@tangle-network/agent-app 0.60.102 → 0.60.103
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assistant/index.js +2 -2
- package/dist/chat-routes/index.js +6 -4
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/{chunk-K7JI5WY4.js → chunk-DO6JHTJY.js} +5 -5
- package/dist/{chunk-3FH4GZ27.js → chunk-HIFYAQ42.js} +8 -124
- package/dist/chunk-HIFYAQ42.js.map +1 -0
- package/dist/{chunk-KSITU6BQ.js → chunk-PQQYFADL.js} +4 -4
- package/dist/chunk-RN2N75EI.js +119 -0
- package/dist/chunk-RN2N75EI.js.map +1 -0
- package/dist/design-canvas-react/index.js +4 -4
- package/dist/launch-invariants/index.js +8 -8
- package/dist/runtime/index.js +4 -2
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/router-turn.js +13 -0
- package/dist/runtime/router-turn.js.map +1 -0
- package/dist/sandbox/index.js +2 -2
- package/dist/tools/index.js +2 -2
- package/dist/web-react/index.js +14 -14
- package/package.json +6 -1
- package/dist/chunk-3FH4GZ27.js.map +0 -1
- /package/dist/{chunk-K7JI5WY4.js.map → chunk-DO6JHTJY.js.map} +0 -0
- /package/dist/{chunk-KSITU6BQ.js.map → chunk-PQQYFADL.js.map} +0 -0
|
@@ -7,6 +7,10 @@ import {
|
|
|
7
7
|
import {
|
|
8
8
|
stepActivityFlowTrace
|
|
9
9
|
} from "./chunk-FBVLEGEG.js";
|
|
10
|
+
import {
|
|
11
|
+
WorkProductCard,
|
|
12
|
+
workProductPartsFromMessageParts
|
|
13
|
+
} from "./chunk-Y6PRDUFJ.js";
|
|
10
14
|
import {
|
|
11
15
|
joinClasses
|
|
12
16
|
} from "./chunk-L7MB2LLM.js";
|
|
@@ -24,10 +28,6 @@ import {
|
|
|
24
28
|
usePending,
|
|
25
29
|
usePopover
|
|
26
30
|
} from "./chunk-HG4OONJA.js";
|
|
27
|
-
import {
|
|
28
|
-
WorkProductCard,
|
|
29
|
-
workProductPartsFromMessageParts
|
|
30
|
-
} from "./chunk-Y6PRDUFJ.js";
|
|
31
31
|
import {
|
|
32
32
|
AsyncView
|
|
33
33
|
} from "./chunk-LSUELMHY.js";
|
|
@@ -6778,4 +6778,4 @@ export {
|
|
|
6778
6778
|
useThinkingSeconds,
|
|
6779
6779
|
ChatMessages
|
|
6780
6780
|
};
|
|
6781
|
-
//# sourceMappingURL=chunk-
|
|
6781
|
+
//# sourceMappingURL=chunk-DO6JHTJY.js.map
|
|
@@ -5,6 +5,12 @@ import {
|
|
|
5
5
|
normalizeModelId
|
|
6
6
|
} from "./chunk-7YA4QNTU.js";
|
|
7
7
|
|
|
8
|
+
// src/runtime/loop.ts
|
|
9
|
+
import {
|
|
10
|
+
runToolLoop,
|
|
11
|
+
streamToolLoop
|
|
12
|
+
} from "@tangle-network/agent-runtime/tool-loop";
|
|
13
|
+
|
|
8
14
|
// src/runtime/openai-stream.ts
|
|
9
15
|
async function* toLoopEvents(chunks) {
|
|
10
16
|
const calls = /* @__PURE__ */ new Map();
|
|
@@ -143,12 +149,6 @@ async function* streamChatCompletions(doFetch, url, apiKey, body, attribution, h
|
|
|
143
149
|
}
|
|
144
150
|
}
|
|
145
151
|
|
|
146
|
-
// src/runtime/loop.ts
|
|
147
|
-
import {
|
|
148
|
-
runToolLoop,
|
|
149
|
-
streamToolLoop
|
|
150
|
-
} from "@tangle-network/agent-runtime/tool-loop";
|
|
151
|
-
|
|
152
152
|
// src/runtime/router-turn.ts
|
|
153
153
|
var DEFAULT_BUDGET_MS = 9e4;
|
|
154
154
|
var TOOL_RESULT_LIMIT = 12e3;
|
|
@@ -331,120 +331,6 @@ async function runRouterTurn(options) {
|
|
|
331
331
|
return outcome();
|
|
332
332
|
}
|
|
333
333
|
|
|
334
|
-
// src/runtime/protected-model.ts
|
|
335
|
-
import {
|
|
336
|
-
createProtectedAgentCandidateModelPort
|
|
337
|
-
} from "@tangle-network/agent-runtime/candidate-execution";
|
|
338
|
-
var GATEWAY_ORIGIN = "https://candidate-router.tangle.tools";
|
|
339
|
-
var CONTROL_ORIGIN = "https://router.tangle.tools/v1/candidate-model-grants";
|
|
340
|
-
var ACTIVATION_NAMES = [
|
|
341
|
-
"MODEL_GATEWAY_TOKEN",
|
|
342
|
-
"MODEL_GATEWAY_BASE_URL",
|
|
343
|
-
"OPENAI_API_KEY",
|
|
344
|
-
"OPENAI_BASE_URL",
|
|
345
|
-
"ANTHROPIC_API_KEY",
|
|
346
|
-
"ANTHROPIC_AUTH_TOKEN",
|
|
347
|
-
"ANTHROPIC_BASE_URL"
|
|
348
|
-
];
|
|
349
|
-
var ProtectedModelSettlementError = class extends Error {
|
|
350
|
-
constructor(settlement, cause) {
|
|
351
|
-
super("Protected model settled, but its audit record could not be saved", { cause });
|
|
352
|
-
this.settlement = settlement;
|
|
353
|
-
this.name = "ProtectedModelSettlementError";
|
|
354
|
-
}
|
|
355
|
-
settlement;
|
|
356
|
-
};
|
|
357
|
-
function createRouterProtectedModelPort(options) {
|
|
358
|
-
if (!options.apiKey || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0 || !Number.isSafeInteger(Math.round(options.maxCostUsd * 1e9))) {
|
|
359
|
-
throw new Error("Protected Router transport requires a parent key and finite positive cap");
|
|
360
|
-
}
|
|
361
|
-
const receipts = /* @__PURE__ */ new Map();
|
|
362
|
-
async function request(operation, body, settling = false) {
|
|
363
|
-
const timeout = AbortSignal.timeout(settling ? 3e4 : 15e3);
|
|
364
|
-
const signal = !settling && options.signal ? AbortSignal.any([timeout, options.signal]) : timeout;
|
|
365
|
-
let response;
|
|
366
|
-
try {
|
|
367
|
-
response = await fetch(`${CONTROL_ORIGIN}/${operation}`, {
|
|
368
|
-
// Workerd supports manual redirects; non-2xx responses below still fail closed.
|
|
369
|
-
method: "POST",
|
|
370
|
-
redirect: "manual",
|
|
371
|
-
signal,
|
|
372
|
-
headers: {
|
|
373
|
-
Authorization: `Bearer ${options.apiKey}`,
|
|
374
|
-
"Content-Type": "application/json",
|
|
375
|
-
"X-Tangle-Client": options.clientName ?? "agent-app"
|
|
376
|
-
},
|
|
377
|
-
body: JSON.stringify(body)
|
|
378
|
-
});
|
|
379
|
-
} catch {
|
|
380
|
-
if (!settling && options.signal?.aborted) throw options.signal.reason;
|
|
381
|
-
throw new Error(`Protected model ${operation} transport failed`);
|
|
382
|
-
}
|
|
383
|
-
if (!response.ok) {
|
|
384
|
-
const body2 = await response.json().catch(() => null);
|
|
385
|
-
const code = body2?.error?.code;
|
|
386
|
-
const safeCode = typeof code === "string" && /^candidate_[a-z_]{1,80}$/.test(code) ? code : "request_failed";
|
|
387
|
-
throw new Error(`Protected model ${operation}: ${safeCode} (HTTP ${response.status})`);
|
|
388
|
-
}
|
|
389
|
-
return await response.json();
|
|
390
|
-
}
|
|
391
|
-
const client = {
|
|
392
|
-
reserve: (value) => request("reserve", value),
|
|
393
|
-
activate: async (value) => {
|
|
394
|
-
const activation = await request("activate", value);
|
|
395
|
-
const env = activation?.env;
|
|
396
|
-
const token = env?.MODEL_GATEWAY_TOKEN;
|
|
397
|
-
if (typeof token !== "string" || !/^sk-tgr-[A-Za-z0-9_-]{32,}$/.test(token) || env.MODEL_GATEWAY_BASE_URL !== `${GATEWAY_ORIGIN}/v1` || env.OPENAI_BASE_URL !== `${GATEWAY_ORIGIN}/v1` || env.ANTHROPIC_BASE_URL !== GATEWAY_ORIGIN || [env.OPENAI_API_KEY, env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN].some((value2) => value2 !== token)) {
|
|
398
|
-
throw new Error("Protected model activation changed the gateway or credential binding");
|
|
399
|
-
}
|
|
400
|
-
return activation;
|
|
401
|
-
},
|
|
402
|
-
settle: async (value) => {
|
|
403
|
-
const settlement = await request("settle", value, true);
|
|
404
|
-
assertWithinCap(settlement, options.maxCostUsd);
|
|
405
|
-
receipts.set(value.preparationId, settlement);
|
|
406
|
-
return settlement;
|
|
407
|
-
}
|
|
408
|
-
};
|
|
409
|
-
const port = createProtectedAgentCandidateModelPort({
|
|
410
|
-
client,
|
|
411
|
-
resolveModel: (value) => request("resolve", value),
|
|
412
|
-
gatewayDomain: "candidate-router.tangle.tools",
|
|
413
|
-
activationEnvNames: ACTIVATION_NAMES
|
|
414
|
-
});
|
|
415
|
-
return {
|
|
416
|
-
...port,
|
|
417
|
-
settleGrant: async (value) => {
|
|
418
|
-
const settlement = await port.settleGrant(value);
|
|
419
|
-
const receipt = receipts.get(value.preparationId);
|
|
420
|
-
if (receipt) {
|
|
421
|
-
try {
|
|
422
|
-
await options.onSettlement?.(structuredClone(receipt));
|
|
423
|
-
} catch (error) {
|
|
424
|
-
throw new ProtectedModelSettlementError(settlement, error);
|
|
425
|
-
} finally {
|
|
426
|
-
receipts.delete(value.preparationId);
|
|
427
|
-
}
|
|
428
|
-
}
|
|
429
|
-
return settlement;
|
|
430
|
-
}
|
|
431
|
-
};
|
|
432
|
-
}
|
|
433
|
-
function assertWithinCap(settlement, capUsd) {
|
|
434
|
-
if (!Array.isArray(settlement?.calls)) throw new Error("Protected model settlement has no call ledger");
|
|
435
|
-
const capNanos = Math.round(capUsd * 1e9);
|
|
436
|
-
let cost = 0;
|
|
437
|
-
for (const call of settlement.calls) {
|
|
438
|
-
if (!Number.isSafeInteger(call?.costUsdNanos) || call.costUsdNanos < 0) {
|
|
439
|
-
throw new Error("Protected model call cost is invalid");
|
|
440
|
-
}
|
|
441
|
-
cost += call.costUsdNanos;
|
|
442
|
-
if (!Number.isSafeInteger(cost) || cost > capNanos) {
|
|
443
|
-
throw new Error("Protected model settlement exceeds its cost cap");
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
|
|
448
334
|
export {
|
|
449
335
|
toLoopEvents,
|
|
450
336
|
createOpenAICompatStreamTurn,
|
|
@@ -452,8 +338,6 @@ export {
|
|
|
452
338
|
streamToolLoop,
|
|
453
339
|
routerFunctionName,
|
|
454
340
|
composeRouterTurnPrompt,
|
|
455
|
-
runRouterTurn
|
|
456
|
-
ProtectedModelSettlementError,
|
|
457
|
-
createRouterProtectedModelPort
|
|
341
|
+
runRouterTurn
|
|
458
342
|
};
|
|
459
|
-
//# sourceMappingURL=chunk-
|
|
343
|
+
//# sourceMappingURL=chunk-HIFYAQ42.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/runtime/loop.ts","../src/runtime/openai-stream.ts","../src/runtime/router-turn.ts"],"sourcesContent":["/**\n * The bounded agent tool-loop — owned by `@tangle-network/agent-runtime`.\n *\n * A model turn may emit tool calls (integration-hub actions, the app tools from\n * `../tools`, delegation). The loop streams a turn, collects the executable tool\n * calls, dispatches each, appends the results to history in OpenAI\n * function-calling shape, and re-runs so the model reads them — bounded by\n * `maxToolTurns`, a wall-clock `deadlineMs`, and a `maxCostUsd` budget.\n *\n * The history shape is the OpenAI function-calling contract: the assistant turn\n * that emitted tool calls is preserved as an `assistant` message carrying its\n * `tool_calls` array, and each result is its own `{ role: 'tool', tool_call_id,\n * content }` message keyed to the call. A strict model (Claude, and any\n * OpenAI-compatible provider that validates tool history) needs this to read its\n * own tool use back; folding results into a `user` message makes such models\n * re-issue the same call in a loop.\n *\n * The loop is substrate-owned (`runToolLoop` / `streamToolLoop`); the app\n * supplies `streamTurn` (wrapping its model endpoint) and `executeToolCall`\n * (routing to its integration + app-tool executors). The app-facing names below\n * are 1:1 aliases of the canonical symbols, kept so this package's consumers and\n * the in-package `createAgentRuntime` read against a single, stable vocabulary.\n *\n * This is the LEAF the runtime barrel and its children both import — keeping the\n * tool-loop vocabulary out of any import cycle. The barrel re-exports it.\n */\n\nexport {\n runToolLoop as runAppToolLoop,\n streamToolLoop as streamAppToolLoop,\n} from '@tangle-network/agent-runtime/tool-loop'\nexport type {\n ToolLoopCall as LoopToolCall,\n ToolLoopAssistantToolCall as LoopAssistantToolCall,\n ToolLoopMessage as LoopMessage,\n ToolLoopEvent,\n ToolLoopStopReason,\n ToolLoopResult,\n RunToolLoopOptions as AppToolLoopOptions,\n StreamToolLoopOptions as StreamAppToolLoopOptions,\n StreamToolLoopYield as StreamLoopYield,\n} from '@tangle-network/agent-runtime/tool-loop'\n\n/**\n * Events the app's OpenAI-compat stream adapter ({@link toLoopEvents}) yields.\n *\n * This is the app's own `Raw` event type for the streaming loop — the canonical\n * `streamToolLoop<Raw>` is generic over it. It widens the substrate's\n * tool-loop event with `reasoning` (DeepSeek/router `reasoning_content` /\n * `thinking` deltas, rendered as thinking sections) and `usage` (per-message\n * token accounting) — neither belongs in the substrate's loop contract, so they\n * stay here. The adapter maps each into the `streamTurn` seam; `text` and\n * `tool_call` drive the loop, `reasoning` / `usage` pass through to the UI.\n */\nexport type LoopEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n /** The model has begun a tool call: its name is known, its arguments are\n * still streaming. Emitted once per call, before its `tool_call`. Lets a\n * caller start slow work the call will need (resuming a sandbox box for\n * `sandbox_run`) while the arguments arrive. Consumers that do not care\n * ignore it: it never drives the loop. */\n | { type: 'tool_call_start'; toolCallId?: string; toolName: string }\n | {\n type: 'tool_call'\n call: import('@tangle-network/agent-runtime/tool-loop').ToolLoopCall\n }\n | { type: 'usage'; usage: { promptTokens: number; completionTokens: number } }\n | { type: 'other'; event: unknown }\n","/**\n * OpenAI-compatible stream → `LoopEvent` adapter, for NON-sandbox copilots.\n *\n * `streamAppToolLoop` takes a `streamTurn` seam that yields `LoopEvent`s. A\n * sandboxed agent produces those from its container; a browser/edge copilot\n * instead calls a model directly. The Tangle Router, the tcloud SDK, and most\n * providers all speak the OpenAI Chat Completions streaming shape — so the ONE\n * reusable piece is assembling that stream (content deltas + FRAGMENTED\n * tool-call deltas) into `LoopEvent`s. That assembly is the boilerplate every\n * copilot would re-write (and get wrong — OpenAI streams tool-call arguments in\n * pieces across chunks).\n *\n * This does NOT implement an HTTP client beyond a minimal `fetch` + SSE reader\n * (browser/edge/Node-safe, zero deps). For richer transport use the tcloud SDK\n * or the Vercel AI SDK and pipe their stream through {@link toLoopEvents}.\n */\nimport type { LoopEvent, LoopMessage, LoopToolCall } from './loop'\nimport { normalizeModelId } from './model-catalog'\n\n/** Minimal OpenAI Chat Completions streaming chunk (structural — no `openai` dep). */\nexport interface OpenAIStreamChunk {\n /** The model that produced this chunk. The Tangle Router reports the DATED\n * upstream id here (`gpt-5-2025-08-07`) whether or not it substituted, so\n * this is a served-model source only after id folding — see\n * {@link OpenAICompatServedModel}. */\n model?: string\n choices?: Array<{\n delta?: {\n content?: string | null\n /** Reasoning deltas — DeepSeek/router use `reasoning_content`; some proxies use `thinking`. */\n reasoning_content?: string | null\n thinking?: string | null\n tool_calls?: Array<{\n index: number\n id?: string\n function?: { name?: string; arguments?: string }\n }>\n }\n finish_reason?: string | null\n }>\n /** Final-chunk token accounting (requires `stream_options.include_usage`). */\n usage?: {\n prompt_tokens?: number\n completion_tokens?: number\n } | null\n}\n\ninterface PartialToolCall {\n id?: string\n name: string\n args: string\n announced: boolean\n}\n\n/**\n * Map an OpenAI-compat streaming chunk iterator to `LoopEvent`s: each content\n * delta → a `text` event; tool-call deltas are accumulated by index across\n * chunks and emitted as one complete `tool_call` event when the stream finishes\n * (arguments JSON-parsed; an empty/garbled args string yields `{}` rather than\n * throwing). Works for the Tangle Router, tcloud, or any OpenAI-compat source.\n *\n * Each call also yields one `tool_call_start` as soon as its name arrives,\n * while its arguments are still streaming, so a caller can start work the call\n * will need. Providers send the whole name in the call's first delta.\n */\nexport async function* toLoopEvents(chunks: AsyncIterable<OpenAIStreamChunk>): AsyncIterable<LoopEvent> {\n const calls = new Map<number, PartialToolCall>()\n for await (const chunk of chunks) {\n // Usage rides the final chunk, which has an empty choices array — handle\n // it before the choice guard.\n if (chunk.usage?.prompt_tokens != null || chunk.usage?.completion_tokens != null) {\n yield {\n type: 'usage',\n usage: {\n promptTokens: chunk.usage.prompt_tokens ?? 0,\n completionTokens: chunk.usage.completion_tokens ?? 0,\n },\n }\n }\n const choice = chunk.choices?.[0]\n if (!choice) continue\n const content = choice.delta?.content\n if (content) yield { type: 'text', text: content }\n const reasoning = choice.delta?.reasoning_content ?? choice.delta?.thinking\n if (reasoning) yield { type: 'reasoning', text: reasoning }\n for (const tc of choice.delta?.tool_calls ?? []) {\n const cur = calls.get(tc.index) ?? { name: '', args: '', announced: false }\n if (tc.id) cur.id = tc.id\n if (tc.function?.name) cur.name += tc.function.name\n if (tc.function?.arguments) cur.args += tc.function.arguments\n calls.set(tc.index, cur)\n if (!cur.announced && cur.name) {\n cur.announced = true\n yield { type: 'tool_call_start', ...(cur.id ? { toolCallId: cur.id } : {}), toolName: cur.name }\n }\n }\n }\n for (const [, c] of [...calls.entries()].sort((a, b) => a[0] - b[0])) {\n if (!c.name) continue\n yield { type: 'tool_call', call: { toolCallId: c.id, toolName: c.name, args: safeParse(c.args) } satisfies LoopToolCall }\n }\n}\n\nfunction safeParse(s: string): Record<string, unknown> {\n if (!s.trim()) return {}\n try {\n const v = JSON.parse(s)\n return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {}\n } catch {\n return {}\n }\n}\n\n/**\n * Which model actually served one direct-router turn.\n *\n * The router substitutes models on purpose — a quota-walled primary comes back\n * `200` answered by a different model — and says so in response headers. This\n * lane used to drop the whole `Response` after taking `.body`, so a turn\n * requested as `claude-sonnet-4-6` and answered by `openai/gpt-5` was recorded\n * by its caller as Claude: per-model quality scoring blamed the wrong model and\n * cost used the wrong price basis.\n *\n * Map this onto the shell's existing attribution contract rather than inventing\n * a second channel — `ChatTurnRouteProducer.modelAttribution()` (`/chat-routes`):\n *\n * modelAttribution: () => ({ requestedModel, servedModel, echoReceived: true })\n *\n * Leave that contract's `servedSource` unset: its union is sandbox\n * profile-resolution vocabulary with no router analogue.\n */\nexport interface OpenAICompatServedModel {\n /** The model id this turn asked for (`OpenAICompatStreamTurnOptions.model`). */\n requestedModel: string\n /** The model the router/provider reports having actually served. */\n servedModel: string\n /** Where `servedModel` was read from. The header is the router's own\n * substitution signal; the body is the backstop that survives CORS. */\n source: 'router_header' | 'response_body'\n /** True when served differs from requested after id folding. Folded, not\n * compared raw: the body reports a dated id on EVERY turn, so `!==` would\n * claim a substitution every time. */\n substituted: boolean\n /** `x-tangle-failover` `trigger=` — why the router swapped. Absent when the\n * router did not inject the substitute (a caller-supplied fallback chain\n * sets the served-model header without the failover one). */\n trigger?: string\n /** `x-tangle-failover` `degraded=`. */\n degraded?: boolean\n}\n\n/** Parse `from=…; to=…; trigger=…; degraded=…` down to the fields we report.\n * Absent/garbled segments are simply omitted — attribution is best-effort and\n * must never fail a turn that is otherwise streaming fine. */\nfunction parseFailoverHeader(raw: string | null): { trigger?: string; degraded?: boolean } {\n if (!raw) return {}\n const fields = new Map<string, string>()\n for (const segment of raw.split(';')) {\n const eq = segment.indexOf('=')\n if (eq === -1) continue\n fields.set(segment.slice(0, eq).trim().toLowerCase(), segment.slice(eq + 1).trim())\n }\n const trigger = fields.get('trigger')\n const degraded = fields.get('degraded')\n return {\n ...(trigger ? { trigger } : {}),\n ...(degraded != null ? { degraded: degraded === 'true' } : {}),\n }\n}\n\n/** Define options for configuring an OpenAI-compatible streaming chat turn including API details and tools */\nexport interface OpenAICompatStreamTurnOptions {\n /** OpenAI-compat base URL (e.g. the Tangle Router `https://router.tangle.tools/v1`). */\n baseUrl: string\n apiKey: string\n model: string\n /** OpenAI tool definitions — pass `buildAppToolOpenAITools(taxonomy)` so the\n * model can call the app tools. Omit for a tool-free copilot. */\n tools?: unknown[]\n temperature?: number\n fetchImpl?: typeof fetch\n /** Extra body fields (e.g. `max_tokens`). */\n extraBody?: Record<string, unknown>\n /** Extra request headers, e.g. a trace id the router records with the generation. */\n headers?: Record<string, string>\n /**\n * Called at most ONCE per turn, as soon as the serving model is\n * determinable, with what actually answered. Never called when neither the\n * header nor the body names a model — silence means \"learned nothing\", not\n * \"nothing was substituted\".\n *\n * `streamTurn` runs once per TOOL turn, so a multi-turn `runAppToolLoop`\n * fires this once per turn; take the last for row attribution.\n */\n onServedModel?: (served: OpenAICompatServedModel) => void\n}\n\n/**\n * Build a `streamTurn` that calls an OpenAI-compatible `/chat/completions`\n * endpoint (Tangle Router / tcloud / any compat provider) with `stream: true`\n * and yields `LoopEvent`s via {@link toLoopEvents}. Browser/edge/Node-safe —\n * just `fetch` + an SSE reader. Drop straight into `streamAppToolLoop`:\n *\n * const cfg = resolveTangleModelConfig() // or { baseUrl, apiKey, model }\n * streamAppToolLoop({ streamTurn: createOpenAICompatStreamTurn({ ...cfg, tools }), executeToolCall, ... })\n */\nexport function createOpenAICompatStreamTurn(\n opts: OpenAICompatStreamTurnOptions,\n): (messages: LoopMessage[]) => AsyncIterable<LoopEvent> {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const doFetch = opts.fetchImpl ?? fetch\n return (messages) =>\n toLoopEvents(\n streamChatCompletions(doFetch, `${base}/chat/completions`, opts.apiKey, {\n model: opts.model,\n messages,\n stream: true,\n stream_options: { include_usage: true },\n ...(opts.tools && opts.tools.length > 0 ? { tools: opts.tools } : {}),\n ...(opts.temperature != null ? { temperature: opts.temperature } : {}),\n ...opts.extraBody,\n }, opts.onServedModel ? { requestedModel: opts.model, report: opts.onServedModel } : undefined, opts.headers),\n )\n}\n\n/** Stream + parse an OpenAI-compat SSE response into chunks. Tolerates `data:`\n * framing, multi-line buffers, and the terminal `[DONE]`. */\nasync function* streamChatCompletions(\n doFetch: typeof fetch,\n url: string,\n apiKey: string,\n body: Record<string, unknown>,\n attribution?: { requestedModel: string; report: (served: OpenAICompatServedModel) => void },\n headers?: Record<string, string>,\n): AsyncIterable<OpenAIStreamChunk> {\n const res = await doFetch(url, {\n method: 'POST',\n headers: { ...headers, Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'text/event-stream' },\n body: JSON.stringify(body),\n })\n if (!res.ok || !res.body) {\n const text = res.body ? await res.text().catch(() => '') : ''\n const error = new Error(`OpenAI-compat stream failed (HTTP ${res.status})${text ? `: ${text.slice(0, 200)}` : ''}`)\n // Stamp the NUMERIC status. `isUpstreamUnavailable` (`/model-resolution`)\n // reads a numeric field first and prose only as a backstop, and a\n // Cloudflare EDGE 502 gives it nothing else to read: `content-type:\n // text/plain`, a body of `error code: 502`, and none of the router's own\n // `x-tangle-*` headers, because the origin never ran. Carrying the status\n // as data keeps THIS path — the browser/edge copilot lane, which calls the\n // router directly — out of the string-matching business entirely.\n Object.assign(error, { status: res.status })\n throw error\n }\n // Served-model attribution, fired at most once, as early as it is knowable.\n //\n // The header comes first because it is the router's OWN substitution signal:\n // `X-Tangle-Served-Model` is set only when the served model differs from the\n // requested one, so its presence is authoritative and it arrives before the\n // first byte of content. `X-Tangle-Failover` rides along only when the router\n // itself picked the substitute (a caller-supplied fallback chain sets the\n // former without the latter), which is why `trigger`/`degraded` are optional.\n //\n // The body is the backstop for when the header cannot reach us. In a BROWSER,\n // headers are invisible to JS unless the server lists them in\n // `Access-Control-Expose-Headers` — tangle-router#324 added both, but that\n // only helps once it is DEPLOYED, and any other OpenAI-compat endpoint\n // pointed at this client exposes nothing. The chunk `model` field is not\n // subject to CORS, so it keeps the browser lane attributable regardless.\n let reported = false\n const report = (served: OpenAICompatServedModel): void => {\n if (reported || !attribution) return\n reported = true\n attribution.report(served)\n }\n if (attribution) {\n const servedHeader = res.headers.get('x-tangle-served-model')\n if (servedHeader) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: servedHeader,\n source: 'router_header',\n substituted: normalizeModelId(servedHeader) !== normalizeModelId(attribution.requestedModel),\n ...parseFailoverHeader(res.headers.get('x-tangle-failover')),\n })\n }\n }\n const reader = res.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) continue\n const data = trimmed.slice(5).trim()\n if (data === '[DONE]') return\n let chunk: OpenAIStreamChunk\n try {\n chunk = JSON.parse(data) as OpenAIStreamChunk\n } catch {\n continue /* skip a partial/garbled SSE frame */\n }\n // Body fallback: only when the header said nothing. Fold both ids before\n // comparing — the router reports the dated upstream id (`gpt-5-2025-08-07`)\n // for a request of `openai/gpt-5` even with NO substitution, so a raw\n // `!==` would report a swap on literally every turn.\n if (attribution && !reported && chunk.model) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: chunk.model,\n source: 'response_body',\n substituted: normalizeModelId(chunk.model) !== normalizeModelId(attribution.requestedModel),\n })\n }\n yield chunk\n }\n }\n}\n","/**\n * One conversational turn answered by a model through the Tangle Router, with\n * the app's own tools executed in-process — no sandbox in the path.\n *\n * This is the default runtime for conversational turns in an agent app: the\n * product supplies the principal's tools, the profile prompt and the\n * conversation; the engine streams words as the model writes them, runs tool\n * calls through the bounded `streamAppToolLoop`, and returns one outcome.\n * Long, file or code work belongs to the sandbox, reached through a tool the\n * product adds to `tools`.\n *\n * Every failure is an outcome, never a throw. A durable turn owner retries\n * thrown errors, and a retry after a tool ran would repeat that tool's effect\n * (\"never re-run a turn automatically\", docs/agent-app-lessons.md). The only\n * automatic repeat is one model call that failed before any word or tool.\n */\nimport { streamAppToolLoop, type LoopEvent, type LoopMessage, type LoopToolCall, type ToolLoopStopReason } from './loop'\nimport { DEFAULT_TANGLE_ROUTER_BASE_URL } from './model'\nimport { createOpenAICompatStreamTurn } from './openai-stream'\n\n/** A tool the turn may call. Structurally an `McpToolDefinition` whose env is already bound. */\nexport interface RouterTurnTool {\n name: string\n description: string\n /** JSON Schema for the arguments object. */\n inputSchema: Record<string, unknown>\n run(args: Record<string, unknown>): Promise<unknown>\n}\n\n/** What the turn is doing, in the order it happens, for a live view. */\nexport type RouterTurnEvent =\n | { type: 'text'; segment: number; delta: string }\n | { type: 'tool'; callId: string; toolName: string; status: 'running'; input: Record<string, unknown>; startedAt: number }\n | { type: 'tool'; callId: string; toolName: string; status: 'completed'; output: unknown; startedAt: number; endedAt: number }\n | { type: 'tool'; callId: string; toolName: string; status: 'error'; error: { code: string; message: string }; startedAt: number; endedAt: number }\n | { type: 'usage'; promptTokens: number; completionTokens: number }\n\nexport interface RouterTurnFailure {\n /** `model_http_<status>`, `model_unavailable`, `turn_<stopReason>` or `router_unconfigured`. */\n code: string\n status?: number\n message: string\n}\n\nexport interface RouterTurnOutcome {\n /** Every text segment the model wrote, joined by blank lines. */\n text: string\n /** The model the router reports having served, when it said. */\n servedModel: string | null\n toolCalls: Array<{ callId: string; toolName: string; ok: boolean }>\n /** Token use summed over every model call in the turn, as the router reported it. */\n usage: { promptTokens: number; completionTokens: number; modelCalls: number }\n failure?: RouterTurnFailure\n}\n\nexport interface RouterTurnOptions {\n apiKey: string\n model: string\n /** Defaults to the Tangle Router. */\n baseUrl?: string\n systemPrompt: string\n userMessage: string\n /** Earlier turns. Plain text messages, or OpenAI function-calling history (an assistant message\n * carrying `tool_calls` and the `tool` messages answering them) so the model sees what it did. */\n history?: Array<{ role: 'user' | 'assistant'; content: string } | LoopMessage>\n tools?: RouterTurnTool[]\n /** Wall-clock budget in ms. Default 90 s. A caller whose retry window is shorter passes less. */\n budgetMs?: number\n /** Runaway backstop on model turns. Default 12. */\n maxToolTurns?: number\n maxTokens?: number\n /** Sent as `x-tangle-trace-id` so the router's generation joins the app's trace. */\n traceId?: string\n fetchImpl?: typeof fetch\n onEvent?: (event: RouterTurnEvent) => void\n /** Map a thrown tool error to what the model reads. Default: an error carrying string `code`\n * (and numeric `status`) is reported with its message; anything else is a generic failure. */\n toolError?: (error: unknown) => { code: string; message: string; status?: number } | null\n /** Called for a tool failure the default mapping hides from the model, for the app's logs. */\n onToolFailure?: (toolName: string, error: unknown) => void\n}\n\nconst DEFAULT_BUDGET_MS = 90_000\nconst TOOL_RESULT_LIMIT = 12_000\n\n/** OpenAI-compatible function names allow only `[A-Za-z0-9_-]{1,64}`; app tool names often use dots. */\nexport function routerFunctionName(name: string): string {\n return name.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64)\n}\n\n/**\n * The lean system prompt for a Router turn: the profile's system prompt and\n * instructions, then caller context, with tool names rewritten to the function\n * names the model actually calls.\n */\nexport function composeRouterTurnPrompt(\n profile: { prompt?: { systemPrompt?: string; instructions?: readonly string[] } },\n options: { context?: readonly string[]; toolNames?: readonly string[] } = {},\n): string {\n const text = [profile.prompt?.systemPrompt ?? '', ...(profile.prompt?.instructions ?? []), ...(options.context ?? [])]\n .filter(part => part.trim()).join('\\n\\n')\n return [...(options.toolNames ?? [])].sort((a, b) => b.length - a.length)\n .reduce((out, name) => out.split(name).join(routerFunctionName(name)), text)\n}\n\nfunction defaultToolError(error: unknown): { code: string; message: string; status?: number } | null {\n const value = error as { code?: unknown; status?: unknown; message?: unknown; issues?: unknown }\n if (Array.isArray(value?.issues)) {\n return { code: 'invalid_arguments', message: JSON.stringify(value.issues).slice(0, 600) }\n }\n if (typeof value?.code === 'string' && typeof value.message === 'string') {\n return { code: value.code, message: value.message, ...(typeof value.status === 'number' ? { status: value.status } : {}) }\n }\n return null\n}\n\nfunction renderResult(outcome: { ok: true; result: unknown } | { ok: false; code: string; message: string }): string {\n if (!outcome.ok) return `Error (${outcome.code}): ${outcome.message}`\n let text: string\n try { text = typeof outcome.result === 'string' ? outcome.result : JSON.stringify(outcome.result ?? null) }\n catch { text = String(outcome.result) }\n return text.length > TOOL_RESULT_LIMIT ? `${text.slice(0, TOOL_RESULT_LIMIT)}…` : text\n}\n\nexport async function runRouterTurn(options: RouterTurnOptions): Promise<RouterTurnOutcome> {\n if (!options.apiKey) {\n return { text: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 },\n failure: { code: 'router_unconfigured', message: 'The model credential is not configured.' } }\n }\n const emit = options.onEvent ?? (() => {})\n const byFunction = new Map<string, RouterTurnTool>()\n for (const tool of options.tools ?? []) {\n const fn = routerFunctionName(tool.name)\n if (!byFunction.has(fn)) byFunction.set(fn, tool)\n }\n let servedModel: string | null = null\n const streamTurn = createOpenAICompatStreamTurn({\n baseUrl: options.baseUrl ?? DEFAULT_TANGLE_ROUTER_BASE_URL,\n apiKey: options.apiKey,\n model: options.model,\n tools: [...byFunction.entries()].map(([name, tool]) => ({\n type: 'function', function: { name, description: tool.description, parameters: tool.inputSchema },\n })),\n ...(options.maxTokens ? { extraBody: { max_tokens: options.maxTokens } } : {}),\n ...(options.traceId ? { headers: { 'x-tangle-trace-id': options.traceId } } : {}),\n ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),\n onServedModel: served => { servedModel = served.servedModel },\n })\n const segments: string[] = []\n const usage = { promptTokens: 0, completionTokens: 0, modelCalls: 0 }\n const toolCalls: RouterTurnOutcome['toolCalls'] = []\n const started = new Map<string, number>()\n let segmentOpen = false\n let toolsRan = 0\n const deadline = Date.now() + (options.budgetMs ?? DEFAULT_BUDGET_MS)\n const callIdOf = (id: string | undefined, toolName: string) => id ?? `${toolName}-${started.size}`\n\n const run = async (): Promise<ToolLoopStopReason> => {\n for await (const step of streamAppToolLoop<LoopEvent>({\n systemPrompt: options.systemPrompt,\n userMessage: options.userMessage,\n priorMessages: (options.history ?? []) as LoopMessage[],\n streamTurn,\n extractText: event => event.type === 'text' ? event.text : '',\n extractToolCall: event => event.type === 'tool_call' ? event.call : null,\n isExecutableTool: name => byFunction.has(name),\n deadlineMs: deadline,\n maxToolTurns: options.maxToolTurns ?? 12,\n renderResult: (_label, outcome) => renderResult(outcome),\n executeToolCall: async (call: LoopToolCall) => {\n const tool = byFunction.get(call.toolName)\n if (!tool) return { ok: false, code: 'unknown_tool', message: `No tool named ${call.toolName}` }\n toolsRan++\n try {\n return { ok: true, result: await tool.run(call.args) }\n } catch (error) {\n const mapped = (options.toolError ?? defaultToolError)(error)\n if (mapped) return { ok: false, ...mapped }\n options.onToolFailure?.(tool.name, error)\n return { ok: false, code: 'tool_failed', message: 'The tool failed; tell the user what could not be completed.' }\n }\n },\n })) {\n if (step.kind === 'event') {\n const event = step.event\n if (event.type === 'text' && event.text) {\n if (!segmentOpen) { segments.push(''); segmentOpen = true }\n segments[segments.length - 1] += event.text\n emit({ type: 'text', segment: segments.length, delta: event.text })\n } else if (event.type === 'usage') {\n usage.promptTokens += event.usage.promptTokens\n usage.completionTokens += event.usage.completionTokens\n usage.modelCalls++\n emit({ type: 'usage', ...event.usage })\n } else if (event.type === 'tool_call') {\n segmentOpen = false\n const tool = byFunction.get(event.call.toolName)\n const callId = callIdOf(event.call.toolCallId, event.call.toolName)\n started.set(callId, Date.now())\n emit({ type: 'tool', callId, toolName: tool?.name ?? event.call.toolName, status: 'running',\n input: event.call.args, startedAt: started.get(callId)! })\n }\n } else if (step.kind === 'tool_result') {\n const tool = byFunction.get(step.toolName)\n const callId = callIdOf(step.toolCallId, step.toolName)\n const startedAt = started.get(callId) ?? Date.now()\n const toolName = tool?.name ?? step.toolName\n toolCalls.push({ callId, toolName, ok: step.outcome.ok })\n emit(step.outcome.ok\n ? { type: 'tool', callId, toolName, status: 'completed', output: step.outcome.result, startedAt, endedAt: Date.now() }\n : { type: 'tool', callId, toolName, status: 'error', startedAt, endedAt: Date.now(),\n error: { code: step.outcome.code, message: step.outcome.message } })\n } else if (step.kind === 'capped') {\n return step.stopReason\n }\n }\n return 'completed'\n }\n\n const outcome = (failure?: RouterTurnFailure): RouterTurnOutcome => ({\n text: segments.map(part => part.trim()).filter(Boolean).join('\\n\\n'),\n servedModel, toolCalls, usage: { ...usage }, ...(failure ? { failure } : {}),\n })\n let stop: ToolLoopStopReason\n try {\n try {\n stop = await run()\n } catch (error) {\n // Safe to repeat only while nothing was said and no tool ran.\n if (toolsRan > 0 || segments.length > 0) throw error\n stop = await run()\n }\n } catch (error) {\n const status = (error as { status?: unknown }).status\n return outcome(typeof status === 'number'\n ? { code: `model_http_${status}`, status, message: 'The model service did not answer.' }\n : { code: 'model_unavailable', message: 'The model service did not answer.' })\n }\n if (stop !== 'completed') return outcome({ code: `turn_${stop}`, message: 'The reply was stopped before it finished.' })\n // A model can end its turn with neither a word nor a tool call (gemini-2.5-flash did on 8 of\n // 53 \"remember\" turns, 2026-10-11). Nothing was said and nothing ran, so one repeat is safe;\n // an answer still blank is a typed failure, never a successful empty reply.\n if (!segments.some(part => part.trim())) {\n if (toolsRan === 0) {\n try { stop = await run() } catch { stop = 'completed' }\n if (stop !== 'completed') return outcome({ code: `turn_${stop}`, message: 'The reply was stopped before it finished.' })\n }\n if (!segments.some(part => part.trim())) {\n return outcome({ code: 'model_empty', message: 'The model finished without writing a reply.' })\n }\n }\n return outcome()\n}\n"],"mappings":";;;;;;;;AA2BA;AAAA,EACiB;AAAA,EACG;AAAA,OACb;;;ACmCP,gBAAuB,aAAa,QAAoE;AACtG,QAAM,QAAQ,oBAAI,IAA6B;AAC/C,mBAAiB,SAAS,QAAQ;AAGhC,QAAI,MAAM,OAAO,iBAAiB,QAAQ,MAAM,OAAO,qBAAqB,MAAM;AAChF,YAAM;AAAA,QACJ,MAAM;AAAA,QACN,OAAO;AAAA,UACL,cAAc,MAAM,MAAM,iBAAiB;AAAA,UAC3C,kBAAkB,MAAM,MAAM,qBAAqB;AAAA,QACrD;AAAA,MACF;AAAA,IACF;AACA,UAAM,SAAS,MAAM,UAAU,CAAC;AAChC,QAAI,CAAC,OAAQ;AACb,UAAM,UAAU,OAAO,OAAO;AAC9B,QAAI,QAAS,OAAM,EAAE,MAAM,QAAQ,MAAM,QAAQ;AACjD,UAAM,YAAY,OAAO,OAAO,qBAAqB,OAAO,OAAO;AACnE,QAAI,UAAW,OAAM,EAAE,MAAM,aAAa,MAAM,UAAU;AAC1D,eAAW,MAAM,OAAO,OAAO,cAAc,CAAC,GAAG;AAC/C,YAAM,MAAM,MAAM,IAAI,GAAG,KAAK,KAAK,EAAE,MAAM,IAAI,MAAM,IAAI,WAAW,MAAM;AAC1E,UAAI,GAAG,GAAI,KAAI,KAAK,GAAG;AACvB,UAAI,GAAG,UAAU,KAAM,KAAI,QAAQ,GAAG,SAAS;AAC/C,UAAI,GAAG,UAAU,UAAW,KAAI,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,SAAS,KAAK,UAAQ,KAAK,KAAK,CAAC,GAAG;AACvC,QAAI,aAAa,GAAG;AAClB,UAAI;AAAE,eAAO,MAAM,IAAI;AAAA,MAAE,QAAQ;AAAE,eAAO;AAAA,MAAY;AACtD,UAAI,SAAS,YAAa,QAAO,QAAQ,EAAE,MAAM,QAAQ,IAAI,IAAI,SAAS,4CAA4C,CAAC;AAAA,IACzH;AACA,QAAI,CAAC,SAAS,KAAK,UAAQ,KAAK,KAAK,CAAC,GAAG;AACvC,aAAO,QAAQ,EAAE,MAAM,eAAe,SAAS,8CAA8C,CAAC;AAAA,IAChG;AAAA,EACF;AACA,SAAO,QAAQ;AACjB;","names":["outcome"]}
|
|
@@ -2,15 +2,15 @@ import {
|
|
|
2
2
|
authenticateToolRequest,
|
|
3
3
|
createMcpToolHandler
|
|
4
4
|
} from "./chunk-6A7MYOUI.js";
|
|
5
|
-
import {
|
|
6
|
-
assertRenderUiSchema
|
|
7
|
-
} from "./chunk-XMIV374H.js";
|
|
8
5
|
import {
|
|
9
6
|
base64UrlDecodeText,
|
|
10
7
|
base64UrlEncodeText,
|
|
11
8
|
constantTimeEqual,
|
|
12
9
|
hmacSha256Base64Url
|
|
13
10
|
} from "./chunk-S5SRJJQG.js";
|
|
11
|
+
import {
|
|
12
|
+
assertRenderUiSchema
|
|
13
|
+
} from "./chunk-XMIV374H.js";
|
|
14
14
|
import {
|
|
15
15
|
buildAppToolOpenAITools,
|
|
16
16
|
findCustomTool,
|
|
@@ -270,4 +270,4 @@ export {
|
|
|
270
270
|
createAppToolRuntimeExecutor,
|
|
271
271
|
handleAppToolRequest
|
|
272
272
|
};
|
|
273
|
-
//# sourceMappingURL=chunk-
|
|
273
|
+
//# sourceMappingURL=chunk-PQQYFADL.js.map
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// src/runtime/protected-model.ts
|
|
2
|
+
import {
|
|
3
|
+
createProtectedAgentCandidateModelPort
|
|
4
|
+
} from "@tangle-network/agent-runtime/candidate-execution";
|
|
5
|
+
var GATEWAY_ORIGIN = "https://candidate-router.tangle.tools";
|
|
6
|
+
var CONTROL_ORIGIN = "https://router.tangle.tools/v1/candidate-model-grants";
|
|
7
|
+
var ACTIVATION_NAMES = [
|
|
8
|
+
"MODEL_GATEWAY_TOKEN",
|
|
9
|
+
"MODEL_GATEWAY_BASE_URL",
|
|
10
|
+
"OPENAI_API_KEY",
|
|
11
|
+
"OPENAI_BASE_URL",
|
|
12
|
+
"ANTHROPIC_API_KEY",
|
|
13
|
+
"ANTHROPIC_AUTH_TOKEN",
|
|
14
|
+
"ANTHROPIC_BASE_URL"
|
|
15
|
+
];
|
|
16
|
+
var ProtectedModelSettlementError = class extends Error {
|
|
17
|
+
constructor(settlement, cause) {
|
|
18
|
+
super("Protected model settled, but its audit record could not be saved", { cause });
|
|
19
|
+
this.settlement = settlement;
|
|
20
|
+
this.name = "ProtectedModelSettlementError";
|
|
21
|
+
}
|
|
22
|
+
settlement;
|
|
23
|
+
};
|
|
24
|
+
function createRouterProtectedModelPort(options) {
|
|
25
|
+
if (!options.apiKey || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0 || !Number.isSafeInteger(Math.round(options.maxCostUsd * 1e9))) {
|
|
26
|
+
throw new Error("Protected Router transport requires a parent key and finite positive cap");
|
|
27
|
+
}
|
|
28
|
+
const receipts = /* @__PURE__ */ new Map();
|
|
29
|
+
async function request(operation, body, settling = false) {
|
|
30
|
+
const timeout = AbortSignal.timeout(settling ? 3e4 : 15e3);
|
|
31
|
+
const signal = !settling && options.signal ? AbortSignal.any([timeout, options.signal]) : timeout;
|
|
32
|
+
let response;
|
|
33
|
+
try {
|
|
34
|
+
response = await fetch(`${CONTROL_ORIGIN}/${operation}`, {
|
|
35
|
+
// Workerd supports manual redirects; non-2xx responses below still fail closed.
|
|
36
|
+
method: "POST",
|
|
37
|
+
redirect: "manual",
|
|
38
|
+
signal,
|
|
39
|
+
headers: {
|
|
40
|
+
Authorization: `Bearer ${options.apiKey}`,
|
|
41
|
+
"Content-Type": "application/json",
|
|
42
|
+
"X-Tangle-Client": options.clientName ?? "agent-app"
|
|
43
|
+
},
|
|
44
|
+
body: JSON.stringify(body)
|
|
45
|
+
});
|
|
46
|
+
} catch {
|
|
47
|
+
if (!settling && options.signal?.aborted) throw options.signal.reason;
|
|
48
|
+
throw new Error(`Protected model ${operation} transport failed`);
|
|
49
|
+
}
|
|
50
|
+
if (!response.ok) {
|
|
51
|
+
const body2 = await response.json().catch(() => null);
|
|
52
|
+
const code = body2?.error?.code;
|
|
53
|
+
const safeCode = typeof code === "string" && /^candidate_[a-z_]{1,80}$/.test(code) ? code : "request_failed";
|
|
54
|
+
throw new Error(`Protected model ${operation}: ${safeCode} (HTTP ${response.status})`);
|
|
55
|
+
}
|
|
56
|
+
return await response.json();
|
|
57
|
+
}
|
|
58
|
+
const client = {
|
|
59
|
+
reserve: (value) => request("reserve", value),
|
|
60
|
+
activate: async (value) => {
|
|
61
|
+
const activation = await request("activate", value);
|
|
62
|
+
const env = activation?.env;
|
|
63
|
+
const token = env?.MODEL_GATEWAY_TOKEN;
|
|
64
|
+
if (typeof token !== "string" || !/^sk-tgr-[A-Za-z0-9_-]{32,}$/.test(token) || env.MODEL_GATEWAY_BASE_URL !== `${GATEWAY_ORIGIN}/v1` || env.OPENAI_BASE_URL !== `${GATEWAY_ORIGIN}/v1` || env.ANTHROPIC_BASE_URL !== GATEWAY_ORIGIN || [env.OPENAI_API_KEY, env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN].some((value2) => value2 !== token)) {
|
|
65
|
+
throw new Error("Protected model activation changed the gateway or credential binding");
|
|
66
|
+
}
|
|
67
|
+
return activation;
|
|
68
|
+
},
|
|
69
|
+
settle: async (value) => {
|
|
70
|
+
const settlement = await request("settle", value, true);
|
|
71
|
+
assertWithinCap(settlement, options.maxCostUsd);
|
|
72
|
+
receipts.set(value.preparationId, settlement);
|
|
73
|
+
return settlement;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const port = createProtectedAgentCandidateModelPort({
|
|
77
|
+
client,
|
|
78
|
+
resolveModel: (value) => request("resolve", value),
|
|
79
|
+
gatewayDomain: "candidate-router.tangle.tools",
|
|
80
|
+
activationEnvNames: ACTIVATION_NAMES
|
|
81
|
+
});
|
|
82
|
+
return {
|
|
83
|
+
...port,
|
|
84
|
+
settleGrant: async (value) => {
|
|
85
|
+
const settlement = await port.settleGrant(value);
|
|
86
|
+
const receipt = receipts.get(value.preparationId);
|
|
87
|
+
if (receipt) {
|
|
88
|
+
try {
|
|
89
|
+
await options.onSettlement?.(structuredClone(receipt));
|
|
90
|
+
} catch (error) {
|
|
91
|
+
throw new ProtectedModelSettlementError(settlement, error);
|
|
92
|
+
} finally {
|
|
93
|
+
receipts.delete(value.preparationId);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return settlement;
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function assertWithinCap(settlement, capUsd) {
|
|
101
|
+
if (!Array.isArray(settlement?.calls)) throw new Error("Protected model settlement has no call ledger");
|
|
102
|
+
const capNanos = Math.round(capUsd * 1e9);
|
|
103
|
+
let cost = 0;
|
|
104
|
+
for (const call of settlement.calls) {
|
|
105
|
+
if (!Number.isSafeInteger(call?.costUsdNanos) || call.costUsdNanos < 0) {
|
|
106
|
+
throw new Error("Protected model call cost is invalid");
|
|
107
|
+
}
|
|
108
|
+
cost += call.costUsdNanos;
|
|
109
|
+
if (!Number.isSafeInteger(cost) || cost > capNanos) {
|
|
110
|
+
throw new Error("Protected model settlement exceeds its cost cap");
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export {
|
|
116
|
+
ProtectedModelSettlementError,
|
|
117
|
+
createRouterProtectedModelPort
|
|
118
|
+
};
|
|
119
|
+
//# sourceMappingURL=chunk-RN2N75EI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/runtime/protected-model.ts"],"sourcesContent":["import {\n createProtectedAgentCandidateModelPort,\n type AgentCandidateModelGrantClient,\n type AgentCandidateModelPort,\n} from '@tangle-network/agent-runtime/candidate-execution'\n\nconst GATEWAY_ORIGIN = 'https://candidate-router.tangle.tools'\nconst CONTROL_ORIGIN = 'https://router.tangle.tools/v1/candidate-model-grants'\nconst ACTIVATION_NAMES = [\n 'MODEL_GATEWAY_TOKEN', 'MODEL_GATEWAY_BASE_URL', 'OPENAI_API_KEY', 'OPENAI_BASE_URL',\n 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',\n] as const\n\nexport interface RouterProtectedModelPortOptions {\n apiKey: string\n maxCostUsd: number\n clientName?: string\n signal?: AbortSignal\n onSettlement?(receipt: RouterProtectedModelSettlement): Promise<void> | void\n}\n\n/** A validated charge remains authoritative when the product cannot save its audit record. */\nexport class ProtectedModelSettlementError extends Error {\n constructor(readonly settlement: Awaited<ReturnType<AgentCandidateModelPort['settleGrant']>>, cause: unknown) {\n super('Protected model settled, but its audit record could not be saved', { cause })\n this.name = 'ProtectedModelSettlementError'\n }\n}\n\n/** Bind one turn to Router's atomic grant ledger without exposing its parent key. */\nexport function createRouterProtectedModelPort(options: RouterProtectedModelPortOptions): AgentCandidateModelPort {\n if (!options.apiKey || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0\n || !Number.isSafeInteger(Math.round(options.maxCostUsd * 1_000_000_000))) {\n throw new Error('Protected Router transport requires a parent key and finite positive cap')\n }\n const receipts = new Map<string, RouterProtectedModelSettlement>()\n async function request<T>(operation: string, body: unknown, settling = false): Promise<T> {\n const timeout = AbortSignal.timeout(settling ? 30_000 : 15_000)\n const signal = !settling && options.signal ? AbortSignal.any([timeout, options.signal]) : timeout\n let response: Response\n try {\n response = await fetch(`${CONTROL_ORIGIN}/${operation}`, {\n // Workerd supports manual redirects; non-2xx responses below still fail closed.\n method: 'POST', redirect: 'manual', signal,\n headers: {\n Authorization: `Bearer ${options.apiKey}`,\n 'Content-Type': 'application/json', 'X-Tangle-Client': options.clientName ?? 'agent-app',\n },\n body: JSON.stringify(body),\n })\n } catch {\n if (!settling && options.signal?.aborted) throw options.signal.reason\n throw new Error(`Protected model ${operation} transport failed`)\n }\n if (!response.ok) {\n const body = await response.json().catch(() => null) as { error?: { code?: unknown } } | null\n const code = body?.error?.code\n // Preserve Runtime's draining retry contract without echoing server text or credentials.\n const safeCode = typeof code === 'string' && /^candidate_[a-z_]{1,80}$/.test(code) ? code : 'request_failed'\n throw new Error(`Protected model ${operation}: ${safeCode} (HTTP ${response.status})`)\n }\n return await response.json() as T\n }\n\n const client: AgentCandidateModelGrantClient = {\n reserve: (value) => request('reserve', value),\n activate: async (value) => {\n const activation = await request<Awaited<ReturnType<AgentCandidateModelGrantClient['activate']>>>('activate', value)\n const env = activation?.env\n const token = env?.MODEL_GATEWAY_TOKEN\n if (typeof token !== 'string' || !/^sk-tgr-[A-Za-z0-9_-]{32,}$/.test(token)\n || env.MODEL_GATEWAY_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.OPENAI_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.ANTHROPIC_BASE_URL !== GATEWAY_ORIGIN\n || [env.OPENAI_API_KEY, env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN].some((value) => value !== token)) {\n throw new Error('Protected model activation changed the gateway or credential binding')\n }\n return activation\n },\n settle: async (value) => {\n const settlement = await request<RouterProtectedModelSettlement>('settle', value, true)\n assertWithinCap(settlement, options.maxCostUsd)\n receipts.set(value.preparationId, settlement)\n return settlement\n },\n }\n const port = createProtectedAgentCandidateModelPort({\n client, resolveModel: (value) => request('resolve', value),\n gatewayDomain: 'candidate-router.tangle.tools', activationEnvNames: ACTIVATION_NAMES,\n })\n return {\n ...port,\n settleGrant: async (value) => {\n const settlement = await port.settleGrant(value)\n const receipt = receipts.get(value.preparationId)\n if (receipt) {\n try {\n await options.onSettlement?.(structuredClone(receipt))\n } catch (error) {\n throw new ProtectedModelSettlementError(settlement, error)\n } finally {\n receipts.delete(value.preparationId)\n }\n }\n return settlement\n },\n }\n}\n\n/**\n * Router's settle response is Runtime's exact settlement ledger. Router keeps\n * the billing hold and charge behind it and refuses a settlement outside the\n * grant's frozen limits; Runtime rejects unknown or missing ledger fields.\n */\nexport type RouterProtectedModelSettlement = Awaited<ReturnType<AgentCandidateModelGrantClient['settle']>>\n\n/** Bound the ledger's cumulative cost by this turn's cap before anything retains it. */\nfunction assertWithinCap(settlement: RouterProtectedModelSettlement, capUsd: number): void {\n if (!Array.isArray(settlement?.calls)) throw new Error('Protected model settlement has no call ledger')\n const capNanos = Math.round(capUsd * 1_000_000_000)\n let cost = 0\n for (const call of settlement.calls) {\n if (!Number.isSafeInteger(call?.costUsdNanos) || call.costUsdNanos < 0) {\n throw new Error('Protected model call cost is invalid')\n }\n cost += call.costUsdNanos\n if (!Number.isSafeInteger(cost) || cost > capNanos) {\n throw new Error('Protected model settlement exceeds its cost cap')\n }\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAGK;AAEP,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AAAA,EACvB;AAAA,EAAuB;AAAA,EAA0B;AAAA,EAAkB;AAAA,EACnE;AAAA,EAAqB;AAAA,EAAwB;AAC/C;AAWO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACvD,YAAqB,YAAyE,OAAgB;AAC5G,UAAM,oEAAoE,EAAE,MAAM,CAAC;AADhE;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;AAGO,SAAS,+BAA+B,SAAmE;AAChH,MAAI,CAAC,QAAQ,UAAU,CAAC,OAAO,SAAS,QAAQ,UAAU,KAAK,QAAQ,cAAc,KAChF,CAAC,OAAO,cAAc,KAAK,MAAM,QAAQ,aAAa,GAAa,CAAC,GAAG;AAC1E,UAAM,IAAI,MAAM,0EAA0E;AAAA,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M,YAAY,KAAK,KAAK,eAAe,GAAG;AACtE,YAAM,IAAI,MAAM,sCAAsC;AAAA,IACxD;AACA,YAAQ,KAAK;AACb,QAAI,CAAC,OAAO,cAAc,IAAI,KAAK,OAAO,UAAU;AAClD,YAAM,IAAI,MAAM,iDAAiD;AAAA,IACnE;AAAA,EACF;AACF;","names":["body","value"]}
|
|
@@ -84,15 +84,15 @@ import {
|
|
|
84
84
|
setPagePropsCommand,
|
|
85
85
|
ungroupElementCommand
|
|
86
86
|
} from "../chunk-6NYVAURR.js";
|
|
87
|
-
import {
|
|
88
|
-
DesignCanvasChromeLazy,
|
|
89
|
-
DesignCanvasLazy
|
|
90
|
-
} from "../chunk-NRG2YHGY.js";
|
|
91
87
|
import {
|
|
92
88
|
assertSceneMediaSrc,
|
|
93
89
|
bleedAwareExportBounds,
|
|
94
90
|
scaleForPreset
|
|
95
91
|
} from "../chunk-OHWQUKBP.js";
|
|
92
|
+
import {
|
|
93
|
+
DesignCanvasChromeLazy,
|
|
94
|
+
DesignCanvasLazy
|
|
95
|
+
} from "../chunk-NRG2YHGY.js";
|
|
96
96
|
import "../chunk-UTAIRVOK.js";
|
|
97
97
|
import "../chunk-RN4WPTBH.js";
|
|
98
98
|
import "../chunk-3NCPXNBZ.js";
|
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
import {
|
|
2
|
+
D1_MAX_BOUND_PARAMETERS,
|
|
3
|
+
SIZED_READ_BYTES,
|
|
4
|
+
SIZED_READ_COMPOSITE_ROWS,
|
|
5
|
+
SIZED_READ_ROWS,
|
|
6
|
+
readInSizedBatches,
|
|
7
|
+
sizedBatches
|
|
8
|
+
} from "../chunk-5UQJ7F3P.js";
|
|
1
9
|
import {
|
|
2
10
|
LAUNCH_BUDGETS,
|
|
3
11
|
LAUNCH_INVARIANTS,
|
|
@@ -16,14 +24,6 @@ import {
|
|
|
16
24
|
slotsOf,
|
|
17
25
|
withD1LimitAlarms
|
|
18
26
|
} from "../chunk-LLO436QO.js";
|
|
19
|
-
import {
|
|
20
|
-
D1_MAX_BOUND_PARAMETERS,
|
|
21
|
-
SIZED_READ_BYTES,
|
|
22
|
-
SIZED_READ_COMPOSITE_ROWS,
|
|
23
|
-
SIZED_READ_ROWS,
|
|
24
|
-
readInSizedBatches,
|
|
25
|
-
sizedBatches
|
|
26
|
-
} from "../chunk-5UQJ7F3P.js";
|
|
27
27
|
|
|
28
28
|
// src/launch-invariants/auth-lookup-cache.ts
|
|
29
29
|
var AUTH_LOOKUP_TTL_MS = 6e4;
|
package/dist/runtime/index.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ProtectedModelSettlementError,
|
|
3
|
+
createRouterProtectedModelPort
|
|
4
|
+
} from "../chunk-RN2N75EI.js";
|
|
5
|
+
import {
|
|
3
6
|
composeRouterTurnPrompt,
|
|
4
7
|
createOpenAICompatStreamTurn,
|
|
5
|
-
createRouterProtectedModelPort,
|
|
6
8
|
routerFunctionName,
|
|
7
9
|
runRouterTurn,
|
|
8
10
|
runToolLoop,
|
|
9
11
|
streamToolLoop,
|
|
10
12
|
toLoopEvents
|
|
11
|
-
} from "../chunk-
|
|
13
|
+
} from "../chunk-HIFYAQ42.js";
|
|
12
14
|
import {
|
|
13
15
|
DEFAULT_TANGLE_BILLING_ENFORCEMENT_ENV_VAR,
|
|
14
16
|
DEFAULT_TANGLE_ROUTER_BASE_URL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts"],"sourcesContent":["/**\n * Application profile composition using Runtime's certified-guidance source.\n *\n * The shell adapts the prompt source to the application's resolved profile;\n * Runtime owns pulling, cache lifetime, concurrent refresh and retained guidance.\n * Only prompt-compatible guidance is folded here. Tool definitions, execution\n * permissions, MCP servers and files are not installed from certified material.\n * The complete profile remains available through `current()` for inspection and\n * the product's separately authorized materialization path.\n */\nimport {\n createCertifiedPromptSource,\n type CertifiedProfile,\n type CertifiedPromptSourceOptions,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\n/** Pull coordinates, refresh cadence and timeout owned by the shared source. */\nexport type CertifiedDeliveryConfig = CertifiedPromptSourceOptions\n\n/** Adapt certified prompt guidance without granting execution authority. */\nexport interface CertifiedDelivery {\n /** Refresh on the source's cadence and compose the current prompt guidance.\n * Other resolved profile fields pass through unchanged. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now, coalescing with an in-flight pull. Best-effort; not a\n * post-activation revision barrier or a permission-revocation protocol. */\n refresh(): Promise<void>\n /** Last successfully pulled profile, or null before a successful pull. */\n current(): CertifiedProfile | null\n}\n\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const source = createCertifiedPromptSource(config)\n return {\n async composeProfile(base) {\n return { ...base, systemPrompt: await source.compose(base.systemPrompt) }\n },\n refresh: () => source.refresh({ force: true }),\n current: source.current,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value through `SandboxRuntimeConfig.env` at creation or\n * refreshes it through `SandboxRuntimeConfig.runtimeEnv` before retained-box\n * bootstrap. The value remains workspace-scoped because every member and turn\n * shares the box; runtime renewal does not create a per-user secret channel.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_SEVERITY)) {\n throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,OAGK;AAkBA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BAAmB,YAAY,QAAQ,eAAe,KAAK,EAAE,WAAW,GAAG;AAC5F,YAAM,IAAI,MAAM,GAAG,KAAK,2DAA2D;AAAA,IACrF;AAAA,EACF;AACA,MAAI,QAAQ,QAAQ,QAAW;AAC7B,eAAW,CAAC,MAAM,MAAM,KAAK,OAAO,QAAQ,QAAQ,GAAG,GAAG;AACxD,UAAI,KAAK,KAAK,EAAE,WAAW,EAAG,OAAM,IAAI,MAAM,GAAG,KAAK,sCAAsC;AAC5F,UAAI,OAAO,cAAc,QAAQ;AAC/B,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,oCAAoC,KAAK,UAAW,OAAmC,SAAS,CAAC,GAAG;AAAA,MACnJ;AACA,UAAI;AACJ,UAAI;AACF,iBAAS,IAAI,IAAI,OAAO,GAAG;AAAA,MAC7B,QAAQ;AACN,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,sCAAsC,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAClH;AACA,UAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UAAU;AAC/D,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,8BAA8B,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAC1G;AAAA,IACF;AAAA,EACF;AACA,MAAI,QAAQ,gBAAgB,QAAW;AACrC,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,WAAW,GAAG;AAC9D,UAAI,EAAE,SAAS,sBAAsB;AACnC,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,GAAG,2CAA2C,KAAK,UAAU,KAAK,CAAC,GAAG;AAAA,MACjH;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts"],"sourcesContent":["/**\n * Application profile composition using Runtime's certified-guidance source.\n *\n * The shell adapts the prompt source to the application's resolved profile;\n * Runtime owns pulling, cache lifetime, concurrent refresh and retained guidance.\n * Only prompt-compatible guidance is folded here. Tool definitions, execution\n * permissions, MCP servers and files are not installed from certified material.\n * The complete profile remains available through `current()` for inspection and\n * the product's separately authorized materialization path.\n */\nimport {\n createCertifiedPromptSource,\n type CertifiedProfile,\n type CertifiedPromptSourceOptions,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\n/** Pull coordinates, refresh cadence and timeout owned by the shared source. */\nexport type CertifiedDeliveryConfig = CertifiedPromptSourceOptions\n\n/** Adapt certified prompt guidance without granting execution authority. */\nexport interface CertifiedDelivery {\n /** Refresh on the source's cadence and compose the current prompt guidance.\n * Other resolved profile fields pass through unchanged. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now, coalescing with an in-flight pull. Best-effort; not a\n * post-activation revision barrier or a permission-revocation protocol. */\n refresh(): Promise<void>\n /** Last successfully pulled profile, or null before a successful pull. */\n current(): CertifiedProfile | null\n}\n\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const source = createCertifiedPromptSource(config)\n return {\n async composeProfile(base) {\n return { ...base, systemPrompt: await source.compose(base.systemPrompt) }\n },\n refresh: () => source.refresh({ force: true }),\n current: source.current,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value through `SandboxRuntimeConfig.env` at creation or\n * refreshes it through `SandboxRuntimeConfig.runtimeEnv` before retained-box\n * bootstrap. The value remains workspace-scoped because every member and turn\n * shares the box; runtime renewal does not create a per-user secret channel.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_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AAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import {
|
|
2
|
+
composeRouterTurnPrompt,
|
|
3
|
+
routerFunctionName,
|
|
4
|
+
runRouterTurn
|
|
5
|
+
} from "../chunk-HIFYAQ42.js";
|
|
6
|
+
import "../chunk-D6UJEOZQ.js";
|
|
7
|
+
import "../chunk-7YA4QNTU.js";
|
|
8
|
+
export {
|
|
9
|
+
composeRouterTurnPrompt,
|
|
10
|
+
routerFunctionName,
|
|
11
|
+
runRouterTurn
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=router-turn.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/sandbox/index.js
CHANGED
|
@@ -131,10 +131,10 @@ import {
|
|
|
131
131
|
} from "../chunk-4LBCTFBP.js";
|
|
132
132
|
import "../chunk-WVESWAJJ.js";
|
|
133
133
|
import "../chunk-LWSJK546.js";
|
|
134
|
-
import "../chunk-
|
|
134
|
+
import "../chunk-PQQYFADL.js";
|
|
135
135
|
import "../chunk-6A7MYOUI.js";
|
|
136
|
-
import "../chunk-XMIV374H.js";
|
|
137
136
|
import "../chunk-S5SRJJQG.js";
|
|
137
|
+
import "../chunk-XMIV374H.js";
|
|
138
138
|
import "../chunk-BMZTYGKE.js";
|
|
139
139
|
import "../chunk-UGWQLQDS.js";
|
|
140
140
|
import "../chunk-TMOYOMSW.js";
|