Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
338 changes: 338 additions & 0 deletions docs/architecture/ADR-2026-11-12-provider-neutral-agent-runtime.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions foundry/validators/toolchain.lock.v1.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
"implementationPath": "tools/foundry/lib/upstream-conformance.mjs",
"implementationSha256": "195f68ad4546108c78fc1006ea7597063281dbe79461f356fbda13426bc76365",
"sourceClosure": {
"pnpm-lock.yaml": "51b50b5f5eac279135e552c1a453435e208ec8e908f103e59cf29a0c003f0f5a",
"package.json": "ec3391cc3c6e8d1640d32aeef08f01bb8a0fbb81c7ababd7e9a10e0493e09851",
"pnpm-lock.yaml": "e8f534f1081f9a7e0bb5e989669a80924cf40e8e0c0ab9099e9c5d8854c8ca20",
"package.json": "a20e250d95e766003ef08e0c4cd09213f005be20396e0b47bd913868883b3b94",
"tools/foundry/lib/dependency-lock.mjs": "f958ff7a2dd17c41734590c5db2085131dce2693675fd848c412b092e99dce91",
"tools/foundry/lib/io.mjs": "0cbb6aada3bd9072dac68e74f9b0b25f01fcd0e0aa3d502190348afb38b16718",
"tools/foundry/lib/upstream-conformance.mjs": "195f68ad4546108c78fc1006ea7597063281dbe79461f356fbda13426bc76365"
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,8 @@
"test:queen-session": "node --import tsx --test test/queen-session.test.ts",
"eval:deep-reasoning": "node tools/arena/deep-reasoning.mjs",
"build:core": "pnpm --filter @starlight-intelligence/core build",
"build:packages": "turbo run build --filter=@starlight-intelligence/core --filter=@starlight-intelligence/ai-sdk --filter=@starlight-intelligence/mcp --filter=@starlight-intelligence/elevenlabs --concurrency=1",
"test:packages": "pnpm run build:packages && turbo run test --filter=@starlight-intelligence/core --filter=@starlight-intelligence/ai-sdk --filter=@starlight-intelligence/mcp --filter=@starlight-intelligence/elevenlabs --concurrency=1 && node --test test/npm-ecosystem-release.test.mjs test/npm-artifact-audit.test.mjs",
"build:packages": "turbo run build --filter=@starlight-intelligence/core --filter=@starlight-intelligence/ai-sdk --filter=@starlight-intelligence/mcp --filter=@starlight-intelligence/elevenlabs --filter=@starlight-intelligence/agent-runtime --concurrency=1",
"test:packages": "pnpm run build:packages && turbo run test --filter=@starlight-intelligence/core --filter=@starlight-intelligence/ai-sdk --filter=@starlight-intelligence/mcp --filter=@starlight-intelligence/elevenlabs --filter=@starlight-intelligence/agent-runtime --concurrency=1 && node --test test/npm-ecosystem-release.test.mjs test/npm-artifact-audit.test.mjs",
"verify:packages": "pnpm run test:packages && node scripts/verify-npm-ecosystem.mjs",
"changeset": "changeset",
"version:packages": "changeset version",
Expand Down
21 changes: 21 additions & 0 deletions packages/agent-runtime/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Frank Riemer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
150 changes: 150 additions & 0 deletions packages/agent-runtime/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
# Starlight agent runtime

One provider-neutral runtime for every agentic surface in the estate. One call gives you a model,
tools and attribution, so no app assembles the three itself.

```sh
npm install @starlight-intelligence/agent-runtime ai
```

## Why this exists

Five product repositories were each re-deriving the same three layers by hand, which is how model
ids drifted, how tool exposure grew ungoverned, and how nothing ever emitted a cost record. This
package is the shared implementation of those layers.

It follows the accepted Registry decisions: AI SDK 7 for TypeScript, AI Gateway as the default
multi-provider model gateway, MCP as the portable tool interface, and provider-neutral contracts
versioned in Git.

## Usage

```ts
import { createAgentRuntime } from '@starlight-intelligence/agent-runtime';

const runtime = await createAgentRuntime({
route: { kind: 'frontier', tier: 'balanced' },
scope: {
brand_id: 'brand_starlight_intelligence',
product_id: 'product_gencreator',
agent_id: 'agent_studio',
workflow_id: 'workflow_plan_week',
},
mcp: [{ url: 'https://tools.example.com/mcp' }],
// A baseline is REQUIRED when MCP servers are configured: without one there is nothing to
// compare against, so a server that changes a tool after approval could not be detected.
// Persist `runtime.toolFingerprints` after a human approves the tools, and pass it back here.
toolPolicy: { allowlist: ['read_doc', 'search_docs'], baseline: approvedFingerprints },
instructions: 'Plan the week from the creator source material.',
});

const result = await runtime.run({ prompt: 'Plan next week.' });
// `result.attribution` is the record for that run. `runtime.attribution()` returns the same
// record for the run that just finished, which is what you want after a failed one.

await runtime.close();
```

`run()` owns the run's lifecycle, so an aborted, failed or successful run always ends in a
terminal state and always leaves a record. One run at a time: a second `run()` while one is in
flight throws `AgentConcurrencyError` immediately, and the runtime accepts a new run once the
first settles. Use one runtime per concurrent run.

`runtime.agent` is still exposed for streaming. Attribution and the concurrency guard are
guaranteed only for runs started through `run()`; the raw path cannot poison the runtime, but it
is not guarded.

If you are bootstrapping a surface whose servers you trust and whose definitions are versioned
elsewhere, pass `allowUnreviewed: true` instead of a baseline. That is an explicit decision, and
`runtime.toolsUnreviewed` reports it so you can surface it.

## Model routing

A route names a capability, not a vendor call. It resolves through the Vercel AI Gateway, so one
key and one namespace reach every vendor.

```ts
{ kind: 'frontier', tier: 'reasoning-heavy' | 'balanced' | 'fast' }
{ kind: 'explicit', gatewayModelId: 'google/gemini-4-argon' }
```

Reachable today: `anthropic/claude-opus-5.5`, `openai/gpt-6-astra`, `google/gemini-4-argon`,
`spacexai/grok-4.7`. The tier defaults are `anthropic/claude-opus-5.5` for `reasoning-heavy`,
`anthropic/claude-sonnet-5.5` for `balanced` and `openai/gpt-6-luna` for `fast`. No vendor-specific
SDK is a dependency of this package. Note that xAI's Gateway namespace is `spacexai/`, not `xai/`.

An unknown tier, a malformed id, or a namespace the estate does not route to fails at resolution
with a named error. A well-formed id for a routed namespace that the Gateway does not serve
(`anthropic/does-not-exist`) is not checked at resolution, because the only way to know is to ask
the live catalog, and that would make route resolution fail on a network blip. It fails at call
time with the Gateway's own error.

`node scripts/verify-gateway-models.mjs` checks every id the estate resolves to — the four vendor
ids and the `balanced` and `fast` tier defaults — against the live Gateway catalog. It exits 1 when
an id is missing. An unreachable catalog exits 2, and the package's `test` command runs it with
`--allow-offline`, which turns only that case into a loud warning: a network outage is not evidence
about the ids, but a wrong id always fails.

## Tools

MCP tools reach the model through the official AI SDK MCP client, which handles protocol-version
negotiation between `2026-07-28` and the legacy revisions, `Mcp-Param-*` header mirroring, and
elicitation.

Two controls are the application's responsibility, and this package supplies them:

- **Approval.** MCP annotations are untrusted, server-provided hints, and the spec defines their
defaults to be the cautious ones: `readOnlyHint` defaults to false and `openWorldHint` defaults
to **true**. A tool therefore runs unattended only when it says `readOnlyHint: true` AND
`openWorldHint: false`. A destructive or open-world tool never runs unattended, whatever the
hint claims. Everything else requires `toolApproval: 'user-approval'` with a reason that names
the condition that actually triggered it. This policy governs the tools loaded from MCP servers;
the caller's own `tools` are its own code and are not subject to it.
- **Drift.** `fingerprintTools` and `detectToolDrift` detect a server that changed a tool's
description or schema after a human approved it, and added a tool that was not in the baseline.
Pass the approved fingerprints as `toolPolicy.baseline` and drifted tools are refused before
they reach the model.

Tool exposure is bounded by an explicit allowlist. There is no implicit "allow everything".

## Attribution

Every run produces a record carrying the eleven dimensions the estate's observability contract
requires: `brand_id`, `product_id`, `agent_id`, `workflow_id`, `provider`, `model`, `input_tokens`,
`output_tokens`, `estimated_cost`, `latency_ms`, `outcome_status`.

Cost and timing come from the Gateway's own accounting for the generations, not from a local
price table. A price table goes stale the day a vendor changes pricing and then quietly reports
the wrong number, which is worse than reporting nothing. A multi-step run is costed as the **sum**
of its generations, because taking the last one alone understates the run.

`cost_known` says whether `estimated_cost` is a real figure. Completeness is measured against the
number of model calls, not the number of generation ids: a call that produced no id cannot be
priced, so the run's cost is unknown even when every captured id resolves. `estimated_cost` is then
`0`, because a partial sum is not the run's cost and must not be summed by a ledger that ignored
the flag. `cost_known: false` with a zero means unknown; `cost_known: true` with a zero means
genuinely free.

Tokens are complete **per dimension**. If every model call reported input tokens, the summed SDK
count is the run's input count; if any call was silent, the Gateway's per-generation counts are the
source. Output is decided independently, so a call that reported input but not output cannot turn
the run's output count into a zero. `input_tokens_known` and `output_tokens_known` say whether each
count covers the whole run, and an uncovered count is `0` rather than a partial sum.

`latency_ms` is the run's elapsed wall-clock duration: model time, tool execution, retries. It is
deliberately not time-to-first-token, because a TTFT summed over a multi-step run measures nothing
useful. A record built outside a runtime, with no measured duration, falls back to the summed
Gateway `generationTime` — model time only.

Records are validated before they leave the process and passed through a credential redactor,
because they are meant to be committed or shipped to a ledger.

## Boundaries

- Not a state store. Long-lived addressable actors belong on Cloudflare Agents with Durable Objects.
- Not a credential authority. MCP is a tool interface, not an authority layer.
- Not a chat transport. Streaming stays on the AI SDK 7 UI message stream protocol.
- Not a second runtime. ADK, the OpenAI Agents SDK and the Claude Agent SDK are candidates, not
layers under this one.

Code: MIT.
51 changes: 51 additions & 0 deletions packages/agent-runtime/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "@starlight-intelligence/agent-runtime",
"version": "0.1.0",
"private": false,
"type": "module",
"license": "MIT",
"description": "Provider-neutral agent runtime for the Starlight estate: Gateway model routing, MCP tools with approval and drift control, and run attribution.",
"repository": {
"type": "git",
"url": "git+https://github.com/frankxai/Starlight-Intelligence-System.git",
"directory": "packages/agent-runtime"
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist",
"README.md",
"LICENSE"
],
"publishConfig": {
"access": "public"
},
"engines": {
"node": ">=22"
},
"scripts": {
"build": "tsc -p tsconfig.json",
"lint": "tsc -p tsconfig.json --noEmit",
"test": "node --test test/*.test.mjs && node scripts/verify-gateway-models.mjs --allow-offline",
"test:live": "node scripts/verify-gateway-models.mjs",
"prepack": "pnpm run build"
},
"devDependencies": {
"ai": "7.0.170",
"typescript": "5.9.3"
},
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"dependencies": {
"@ai-sdk/mcp": "2.0.97",
"@starlight-intelligence/core": "workspace:^",
"zod": "4.6.5"
},
"peerDependencies": {
"ai": "^7.0.130"
}
}
75 changes: 75 additions & 0 deletions packages/agent-runtime/scripts/verify-gateway-models.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#!/usr/bin/env node
/**
* Verify every Gateway model id the estate resolves to against the LIVE catalog.
*
* Two things resolve to a model id: the tier defaults (`balanced` and `fast` are what most
* surfaces actually call) and the vendor table. Both are checked. A unit test cannot do this:
* asserting a constant against an identical constant proves only that the file was not edited,
* and a namespace check passes for a model id that does not exist.
*
* Usage:
* node scripts/verify-gateway-models.mjs # strict: an unreachable catalog fails
* node scripts/verify-gateway-models.mjs --allow-offline # the package test command: unavailable
* # catalog warns loudly and exits 0
*
* Exit codes: 0 every id is served (or the catalog was unreachable and --allow-offline was
* passed), 1 at least one id is missing, 2 the catalog could not be read in strict mode.
*
* The split is deliberate: an unreachable catalog is not evidence about the ids, so it must not
* turn a correct release red, and it must not pass silently either. A WRONG id is a defect and
* always fails, whatever the flags.
*/
import { estateModelIds, SUPPORTED_VENDORS, TIER_MODELS } from '../dist/model.js';

const CATALOG_URL = 'https://ai-gateway.vercel.sh/v1/models';
const allowOffline = process.argv.includes('--allow-offline');

let payload;
try {
const response = await fetch(CATALOG_URL, { signal: AbortSignal.timeout(30_000) });
if (!response.ok) {
console.error(`Gateway catalog returned HTTP ${response.status}.`);
if (!allowOffline) process.exit(2);
console.warn('WARNING: gateway model ids were NOT verified (catalog unavailable).');
process.exit(0);
}
payload = await response.json();
} catch (error) {
console.error(`Could not read the Gateway catalog: ${error.message}`);
if (!allowOffline) process.exit(2);
console.warn(
'WARNING: gateway model ids were NOT verified (catalog unreachable). ' +
'Run without --allow-offline to make this a failure.',
);
process.exit(0);
}

const ids = new Set((payload?.data ?? []).map(entry => entry.id));
console.log(`Gateway catalog: ${ids.size} models available.`);

const expected = new Map();
for (const [tier, modelId] of Object.entries(TIER_MODELS)) {
expected.set(modelId, `tier:${tier}`);
}
for (const [vendor, modelId] of Object.entries(SUPPORTED_VENDORS)) {
expected.set(modelId, expected.has(modelId) ? `${expected.get(modelId)},vendor:${vendor}` : `vendor:${vendor}`);
}

const missing = [];
for (const modelId of estateModelIds()) {
const label = expected.get(modelId) ?? 'estate';
if (ids.has(modelId)) {
console.log(` ok ${label.padEnd(22)} ${modelId}`);
} else {
console.log(` MISSING ${label.padEnd(22)} ${modelId}`);
missing.push(`${label} (${modelId})`);
}
}

if (missing.length > 0) {
console.error(`\n${missing.length} model id(s) are not served by the Gateway:`);
for (const entry of missing) console.error(` ${entry}`);
process.exit(1);
}

console.log('\nEvery estate model id is served by the Gateway.');
Loading