@tangle-network/agent-app 0.60.134 → 0.60.136
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 +5 -5
- package/dist/chat-react/index.js +3 -3
- package/dist/chat-routes/index.js +17 -7
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/wire.d.ts +2 -0
- package/dist/chat-store/index.js +2 -2
- package/dist/{chunk-XZ4M2ZPO.js → chunk-2ZGB4V7I.js} +54 -16
- package/dist/chunk-2ZGB4V7I.js.map +1 -0
- package/dist/{chunk-JEM4BKR4.js → chunk-JTBPQEGM.js} +3 -3
- package/dist/{chunk-2GP6JOWE.js → chunk-N5M7YT6P.js} +3 -3
- package/dist/{chunk-ZBPOWSYN.js → chunk-NFAOHX4Z.js} +2 -2
- package/dist/{chunk-NNNAC3DV.js → chunk-WAMJU3G4.js} +2 -2
- package/dist/{chunk-D52LB6UQ.js → chunk-WTC6AOPL.js} +2 -2
- package/dist/{chunk-2NHJNINW.js → chunk-YHRWZZJN.js} +1 -1
- package/dist/chunk-YHRWZZJN.js.map +1 -0
- package/dist/{chunk-VXWEJ7F2.js → chunk-YR6TZ777.js} +2 -2
- package/dist/public-consultation/index.js +3 -3
- package/dist/runtime/index.js +2 -2
- package/dist/runtime/router-turn.d.ts +22 -0
- package/dist/runtime/router-turn.js +1 -1
- package/dist/web-react/index.js +5 -5
- package/dist/workspace-export/index.js +11 -2
- package/dist/workspace-export/index.js.map +1 -1
- package/dist/workspace-export/types.d.ts +2 -0
- package/package.json +1 -1
- package/dist/chunk-2NHJNINW.js.map +0 -1
- package/dist/chunk-XZ4M2ZPO.js.map +0 -1
- /package/dist/{chunk-JEM4BKR4.js.map → chunk-JTBPQEGM.js.map} +0 -0
- /package/dist/{chunk-2GP6JOWE.js.map → chunk-N5M7YT6P.js.map} +0 -0
- /package/dist/{chunk-ZBPOWSYN.js.map → chunk-NFAOHX4Z.js.map} +0 -0
- /package/dist/{chunk-NNNAC3DV.js.map → chunk-WAMJU3G4.js.map} +0 -0
- /package/dist/{chunk-D52LB6UQ.js.map → chunk-WTC6AOPL.js.map} +0 -0
- /package/dist/{chunk-VXWEJ7F2.js.map → chunk-YR6TZ777.js.map} +0 -0
|
@@ -56,6 +56,8 @@ export interface ProducerToolResultEvent {
|
|
|
56
56
|
ok: boolean;
|
|
57
57
|
result?: unknown;
|
|
58
58
|
message?: string;
|
|
59
|
+
/** Typed reason for a failed call, when the producer knows it. */
|
|
60
|
+
code?: string;
|
|
59
61
|
};
|
|
60
62
|
}
|
|
61
63
|
/** Describe cumulative provider usage reported by a producer. */
|
package/dist/chat-store/index.js
CHANGED
|
@@ -14,9 +14,9 @@ import {
|
|
|
14
14
|
mentionInputToPart,
|
|
15
15
|
mentionPartsFromMessageParts,
|
|
16
16
|
toChatMessageParts
|
|
17
|
-
} from "../chunk-
|
|
17
|
+
} from "../chunk-YR6TZ777.js";
|
|
18
18
|
import "../chunk-ZVEEWGDK.js";
|
|
19
|
-
import "../chunk-
|
|
19
|
+
import "../chunk-YHRWZZJN.js";
|
|
20
20
|
import "../chunk-TXD5HXLE.js";
|
|
21
21
|
import {
|
|
22
22
|
attachmentPartKey
|
|
@@ -376,6 +376,8 @@ function placeRouterTurn(input) {
|
|
|
376
376
|
});
|
|
377
377
|
}
|
|
378
378
|
var DEFAULT_BUDGET_MS = 9e4;
|
|
379
|
+
var RETRY_STATUS = /* @__PURE__ */ new Set([408, 425, 429, 500, 502, 503, 504]);
|
|
380
|
+
var MAX_RETRY_DELAY_MS = 8e3;
|
|
379
381
|
var TOOL_EVENT_LIMIT = 500;
|
|
380
382
|
var TOOL_EVENT = "__routerTurnToolEvent";
|
|
381
383
|
var TOOL_RESULT_LIMIT = 12e3;
|
|
@@ -404,7 +406,7 @@ function defaultToolError(error) {
|
|
|
404
406
|
}
|
|
405
407
|
return null;
|
|
406
408
|
}
|
|
407
|
-
function renderResult(outcome) {
|
|
409
|
+
function renderResult(outcome, limit = TOOL_RESULT_LIMIT) {
|
|
408
410
|
if (!outcome.ok) return `Error (${outcome.code}): ${outcome.message}`;
|
|
409
411
|
let text;
|
|
410
412
|
try {
|
|
@@ -412,7 +414,7 @@ function renderResult(outcome) {
|
|
|
412
414
|
} catch {
|
|
413
415
|
text = String(outcome.result);
|
|
414
416
|
}
|
|
415
|
-
return text.length >
|
|
417
|
+
return text.length > limit ? `${text.slice(0, limit)}\u2026` : text;
|
|
416
418
|
}
|
|
417
419
|
async function runRouterTurn(options) {
|
|
418
420
|
const lastUser = options.continueFrom?.messages.filter((message) => message.role === "user").at(-1)?.content;
|
|
@@ -443,9 +445,37 @@ async function runRouterTurn(options) {
|
|
|
443
445
|
const emit = options.onEvent ?? (() => {
|
|
444
446
|
});
|
|
445
447
|
const { signal } = options;
|
|
446
|
-
const
|
|
447
|
-
|
|
448
|
-
|
|
448
|
+
const attempts = Math.max(1, Math.floor(options.retry?.attempts ?? 1));
|
|
449
|
+
const attemptTimeoutMs = options.retry?.timeoutMs;
|
|
450
|
+
const baseDelayMs = options.retry?.baseDelayMs ?? 500;
|
|
451
|
+
const pause = (ms) => new Promise((resolve, reject) => {
|
|
452
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
453
|
+
const timer = setTimeout(resolve, ms);
|
|
454
|
+
signal?.addEventListener("abort", () => {
|
|
455
|
+
clearTimeout(timer);
|
|
456
|
+
reject(signal.reason);
|
|
457
|
+
}, { once: true });
|
|
458
|
+
});
|
|
459
|
+
const fetchImpl = signal || attempts > 1 || attemptTimeoutMs ? async (input, init) => {
|
|
460
|
+
for (let attempt = 1; ; attempt++) {
|
|
461
|
+
signal?.throwIfAborted();
|
|
462
|
+
const signals = [signal, attemptTimeoutMs ? AbortSignal.timeout(attemptTimeoutMs) : void 0].filter((value) => Boolean(value));
|
|
463
|
+
const attemptSignal = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
|
|
464
|
+
const backoff = () => Math.min(MAX_RETRY_DELAY_MS, baseDelayMs * 2 ** (attempt - 1)) * (0.5 + Math.random() / 2);
|
|
465
|
+
let response;
|
|
466
|
+
try {
|
|
467
|
+
response = await (options.fetchImpl ?? fetch)(input, { ...init, ...attemptSignal ? { signal: attemptSignal } : {} });
|
|
468
|
+
} catch (error) {
|
|
469
|
+
if (signal?.aborted || attempt >= attempts) throw error;
|
|
470
|
+
await pause(backoff());
|
|
471
|
+
continue;
|
|
472
|
+
}
|
|
473
|
+
if (attempt >= attempts || !RETRY_STATUS.has(response.status)) return response;
|
|
474
|
+
const retryAfter = Number(response.headers.get("retry-after"));
|
|
475
|
+
await response.body?.cancel().catch(() => {
|
|
476
|
+
});
|
|
477
|
+
await pause(Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1e3, MAX_RETRY_DELAY_MS) : backoff());
|
|
478
|
+
}
|
|
449
479
|
} : options.fetchImpl;
|
|
450
480
|
const extraBody = {
|
|
451
481
|
...options.maxTokens ? { max_tokens: options.maxTokens } : {},
|
|
@@ -458,10 +488,11 @@ async function runRouterTurn(options) {
|
|
|
458
488
|
if (!byFunction.has(fn)) byFunction.set(fn, tool);
|
|
459
489
|
}
|
|
460
490
|
let servedModel = null;
|
|
461
|
-
const
|
|
491
|
+
const streamTurnFor = (model) => (options.stream === false ? createOpenAICompatCompletionTurn : createOpenAICompatStreamTurn)({
|
|
462
492
|
baseUrl: options.baseUrl ?? DEFAULT_TANGLE_ROUTER_BASE_URL,
|
|
463
493
|
apiKey,
|
|
464
|
-
model
|
|
494
|
+
model,
|
|
495
|
+
...options.temperature !== void 0 ? { temperature: options.temperature } : {},
|
|
465
496
|
tools: [...byFunction.entries()].map(([name, tool]) => ({
|
|
466
497
|
type: "function",
|
|
467
498
|
function: { name, description: tool.description, parameters: tool.inputSchema }
|
|
@@ -484,7 +515,8 @@ async function runRouterTurn(options) {
|
|
|
484
515
|
let toolLimitReached = false;
|
|
485
516
|
const deadline = Date.now() + (options.budgetMs ?? DEFAULT_BUDGET_MS);
|
|
486
517
|
const callIdOf = (id, toolName) => id ?? `${toolName}-${started.size}`;
|
|
487
|
-
const run = async () => {
|
|
518
|
+
const run = async (model) => {
|
|
519
|
+
const streamTurn = streamTurnFor(model);
|
|
488
520
|
for await (const step of streamToolLoop({
|
|
489
521
|
systemPrompt: options.systemPrompt,
|
|
490
522
|
...options.continueFrom ? { priorMessages: options.continueFrom.messages } : { userMessage: options.userMessage, priorMessages: options.history ?? [] },
|
|
@@ -495,7 +527,7 @@ async function runRouterTurn(options) {
|
|
|
495
527
|
deadlineMs: deadline,
|
|
496
528
|
maxToolTurns: options.maxToolTurns ?? 12,
|
|
497
529
|
labelFor: (call) => byFunction.get(call.toolName)?.name ?? call.toolName,
|
|
498
|
-
renderResult: (label, outcome2) => options.renderToolResult ? options.renderToolResult(label, outcome2) : renderResult(outcome2),
|
|
530
|
+
renderResult: (label, outcome2) => options.renderToolResult ? options.renderToolResult(label, outcome2) : renderResult(outcome2, options.toolResultLimit),
|
|
499
531
|
executeToolCall: async (call, context) => {
|
|
500
532
|
const tool = byFunction.get(call.toolName);
|
|
501
533
|
if (!tool) return { ok: false, code: "unknown_tool", message: `No tool named ${call.toolName}` };
|
|
@@ -525,6 +557,8 @@ async function runRouterTurn(options) {
|
|
|
525
557
|
}
|
|
526
558
|
segments[segments.length - 1] += event.text;
|
|
527
559
|
emit({ type: "text", segment: segments.length, delta: event.text });
|
|
560
|
+
} else if (event.type === "reasoning" && event.text) {
|
|
561
|
+
emit({ type: "reasoning", delta: event.text });
|
|
528
562
|
} else if (event.type === "usage") {
|
|
529
563
|
usage.promptTokens += event.usage.promptTokens;
|
|
530
564
|
usage.completionTokens += event.usage.completionTokens;
|
|
@@ -590,18 +624,21 @@ async function runRouterTurn(options) {
|
|
|
590
624
|
...failure ? { failure } : {}
|
|
591
625
|
});
|
|
592
626
|
const repeat = options.repeat !== false;
|
|
627
|
+
const repeats = !repeat ? [] : options.fallbackModels?.length ? [...options.fallbackModels] : [options.model];
|
|
593
628
|
let stop;
|
|
594
629
|
try {
|
|
595
630
|
try {
|
|
596
|
-
stop = await run();
|
|
631
|
+
stop = await run(options.model);
|
|
597
632
|
} catch (error) {
|
|
598
|
-
|
|
599
|
-
|
|
633
|
+
const next = repeats.shift();
|
|
634
|
+
if (next === void 0 || signal?.aborted || toolsRan > 0 || segments.length > 0) throw error;
|
|
635
|
+
stop = await run(next);
|
|
600
636
|
}
|
|
601
637
|
} catch (error) {
|
|
602
638
|
if (signal?.aborted) return outcome({ code: "turn_aborted", message: "The turn was cancelled." });
|
|
603
639
|
const status = error.status;
|
|
604
|
-
|
|
640
|
+
const detail = error instanceof Error ? error.message.match(/\(HTTP \d+\): ([\s\S]*)$/)?.[1]?.slice(0, 200) : void 0;
|
|
641
|
+
return outcome(typeof status === "number" ? { code: `model_http_${status}`, status, message: "The model service did not answer.", ...detail ? { detail } : {} } : { code: "model_unavailable", message: "The model service did not answer." });
|
|
605
642
|
}
|
|
606
643
|
if (stop === "deadline" && checkpoint) {
|
|
607
644
|
return { ...outcome(), continuation: {
|
|
@@ -612,9 +649,10 @@ async function runRouterTurn(options) {
|
|
|
612
649
|
}
|
|
613
650
|
if (stop !== "completed") return outcome({ code: `turn_${stop}`, message: "The reply was stopped before it finished." });
|
|
614
651
|
if (!segments.some((part) => part.trim()) && !options.continueFrom?.text.trim()) {
|
|
615
|
-
|
|
652
|
+
const next = repeats.shift();
|
|
653
|
+
if (toolsRan === 0 && next !== void 0) {
|
|
616
654
|
try {
|
|
617
|
-
stop = await run();
|
|
655
|
+
stop = await run(next);
|
|
618
656
|
} catch {
|
|
619
657
|
stop = "completed";
|
|
620
658
|
}
|
|
@@ -646,4 +684,4 @@ export {
|
|
|
646
684
|
composeRouterTurnPrompt,
|
|
647
685
|
runRouterTurn
|
|
648
686
|
};
|
|
649
|
-
//# sourceMappingURL=chunk-
|
|
687
|
+
//# sourceMappingURL=chunk-2ZGB4V7I.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/runtime/loop.ts","../src/runtime/openai-stream.ts","../src/runtime/turn-knowledge.ts","../src/runtime/reply-language.ts","../src/runtime/router-turn.ts","../src/runtime/turn-continuation.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 /** Provider-specific call data the next request must echo back. Gemini 3\n * sends `{ google: { thought_signature } }` here and answers HTTP 400\n * when a later request's assistant `tool_calls` entry lacks it. */\n extra_content?: unknown\n }>\n }\n finish_reason?: string | null\n }>\n /** Token accounting (requires `stream_options.include_usage`). Cumulative for\n * the call: the Tangle Router can send it on more than one chunk. */\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 extraContent?: unknown\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 * A call's `extra_content` is kept as `providerFields.extra_content`, which the\n * tool loop echoes on the call's assistant `tool_calls` entry in the next request.\n * Usage is cumulative per call and may arrive on several chunks, so it is\n * yielded once, the last value, when the stream ends.\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 let usage: { promptTokens: number; completionTokens: number } | undefined\n for await (const chunk of chunks) {\n // Usage can ride a chunk with an empty choices array — read it before the\n // choice guard. Each report is cumulative, so the last one is the call's.\n if (chunk.usage?.prompt_tokens != null || chunk.usage?.completion_tokens != null) {\n usage = {\n promptTokens: chunk.usage.prompt_tokens ?? 0,\n completionTokens: chunk.usage.completion_tokens ?? 0,\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 if (tc.extra_content !== undefined) cur.extraContent = tc.extra_content\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 if (usage) yield { type: 'usage', usage }\n for (const [, c] of [...calls.entries()].sort((a, b) => a[0] - b[0])) {\n if (!c.name) continue\n yield {\n type: 'tool_call',\n call: {\n toolCallId: c.id,\n toolName: c.name,\n args: safeParse(c.args),\n ...(c.extraContent !== undefined ? { providerFields: { extra_content: c.extraContent } } : {}),\n } satisfies LoopToolCall,\n }\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/**\n * The buffered sibling of {@link createOpenAICompatStreamTurn}: one\n * `/chat/completions` request without `stream`, answered by one JSON\n * completion, yielded as the same `LoopEvent`s (the same tool-call assembly and\n * served-model attribution). For an endpoint or ledger that expects one buffered\n * completion per model call.\n */\nexport function createOpenAICompatCompletionTurn(\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 completionAsChunk(doFetch, `${base}/chat/completions`, opts.apiKey, {\n model: opts.model,\n messages,\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/** One buffered OpenAI-compat completion (structural — no `openai` dep). */\ninterface OpenAICompletion {\n model?: string\n choices?: Array<{\n message?: {\n content?: string | null\n reasoning_content?: string | null\n tool_calls?: Array<{ id?: string; function?: { name?: string; arguments?: string }; extra_content?: unknown }>\n }\n finish_reason?: string | null\n }>\n usage?: { prompt_tokens?: number; completion_tokens?: number } | null\n}\n\nasync function* completionAsChunk(\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: 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) throw await httpFailure(res, 'completion')\n const completion = await res.json() as OpenAICompletion\n if (attribution) {\n const served = servedFromHeader(res, attribution.requestedModel)\n ?? (completion.model ? servedFromBody(completion.model, attribution.requestedModel) : undefined)\n if (served) attribution.report(served)\n }\n const choice = completion.choices?.[0]\n const message = choice?.message\n // The whole completion as one chunk, so `toLoopEvents` assembles it exactly as a stream.\n yield {\n ...(completion.model ? { model: completion.model } : {}),\n choices: [{\n delta: {\n content: message?.content ?? null,\n reasoning_content: message?.reasoning_content ?? null,\n tool_calls: (message?.tool_calls ?? []).map((call, index) => ({\n index,\n ...(call.id ? { id: call.id } : {}),\n function: { name: call.function?.name ?? '', arguments: call.function?.arguments ?? '' },\n ...(call.extra_content !== undefined ? { extra_content: call.extra_content } : {}),\n })),\n },\n finish_reason: choice?.finish_reason ?? null,\n }],\n ...(completion.usage ? { usage: completion.usage } : {}),\n }\n}\n\nasync function httpFailure(res: Response, kind: 'stream' | 'completion'): Promise<Error> {\n const text = res.body ? await res.text().catch(() => '') : ''\n const error = new Error(`OpenAI-compat ${kind} 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 return error\n}\n\nfunction servedFromHeader(res: Response, requestedModel: string): OpenAICompatServedModel | undefined {\n const servedHeader = res.headers.get('x-tangle-served-model')\n if (!servedHeader) return undefined\n return {\n requestedModel,\n servedModel: servedHeader,\n source: 'router_header',\n substituted: normalizeModelId(servedHeader) !== normalizeModelId(requestedModel),\n ...parseFailoverHeader(res.headers.get('x-tangle-failover')),\n }\n}\n\nfunction servedFromBody(model: string, requestedModel: string): OpenAICompatServedModel {\n return {\n requestedModel,\n servedModel: model,\n source: 'response_body',\n substituted: normalizeModelId(model) !== normalizeModelId(requestedModel),\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) throw await httpFailure(res, 'stream')\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 served = servedFromHeader(res, attribution.requestedModel)\n if (served) report(served)\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) report(servedFromBody(chunk.model, attribution.requestedModel))\n yield chunk\n }\n }\n}\n","/**\n * Knowledge in every turn: the index of an app's knowledge files, the full\n * text of the small ones, and the rule that keeps answers on them.\n *\n * Measured on Hospitality production (2026-10-11): a Router turn that had to\n * discover files through list/read tools answered 17/17 correctly but needed\n * 3 tool calls (first words 12-17 s), and a turn that skipped the tools\n * answered from model defaults (\"checkout 11:00\" when the file said 12 pm).\n * Putting the text in the prompt removes both failure modes.\n */\n/** The fields read from an agent-runtime workspace-store entry; structural so older runtimes still type-check. */\ninterface KnowledgeEntry { path: string; kind: string; content?: string; bytes?: { size: number } }\n\n/** One knowledge file a turn carries; `text` is null when it is too large or not readable here. */\nexport interface TurnKnowledgeFile {\n path: string\n size: number\n text: string | null\n}\n\nexport interface TurnKnowledgeBudget {\n /** Files at most this many bytes have their text included. Default 8 000. */\n fileBytes?: number\n /** Total text bytes across files. Default 16 000. */\n textBytes?: number\n /** Most files listed. Default 60. */\n maxFiles?: number\n}\n\nconst DEFAULT_FILE_BYTES = 8_000\nconst DEFAULT_TEXT_BYTES = 16_000\nconst DEFAULT_MAX_FILES = 60\n\n/** Apply the byte budget in path order: small files keep their text until the total is spent. */\nexport function budgetTurnKnowledge(files: readonly TurnKnowledgeFile[], budget: TurnKnowledgeBudget = {}): TurnKnowledgeFile[] {\n const fileBytes = budget.fileBytes ?? DEFAULT_FILE_BYTES\n let remaining = budget.textBytes ?? DEFAULT_TEXT_BYTES\n return [...files].sort((a, b) => a.path.localeCompare(b.path)).slice(0, budget.maxFiles ?? DEFAULT_MAX_FILES)\n .map(file => {\n const fits = file.text !== null && file.size <= fileBytes && file.size <= remaining\n if (fits) remaining -= file.size\n return { path: file.path, size: file.size, text: fits ? file.text : null }\n })\n}\n\n/**\n * The prompt lines for a turn's knowledge. `readTool` names the tool that\n * opens a listed file whose text is not shown; without one, such a file is\n * listed by name only.\n */\nexport function turnKnowledgeInstructions(files: readonly TurnKnowledgeFile[], options: { readTool?: string } = {}): string[] {\n const read = options.readTool\n return [\n 'Answer questions about this business or its work (hours, times, policies, codes, passwords, prices, contacts, amenities, procedures) only from the knowledge in these instructions, the knowledge files below, or a tool result. Never give a typical or assumed value, and do not say something is absent unless a source says so.' +\n (read ? ` When a listed file without its text may cover the question, read it with ${read} before answering.` : '') +\n ' When nothing covers it, say you do not have that information and offer to ask the owner.' +\n ' When two sources disagree, give each value with the source that states it and ask the owner which is current; never pick one silently.',\n ...files.map(file => file.text !== null ? `Knowledge file ${file.path}:\\n${file.text}`\n : `Knowledge file ${file.path} (${file.size} bytes, text not shown)${read ? `: read it with ${read} when the question may be covered by it.` : '.'}`),\n ]\n}\n\n/** A workspace store's knowledge files (kind `file` under `prefix`) as turn knowledge, within the budget. */\nexport async function workspaceKnowledgeForTurn(\n store: { list(workspaceId: string, prefix: string): Promise<readonly KnowledgeEntry[]> },\n workspaceId: string,\n options: TurnKnowledgeBudget & { prefix?: string } = {},\n): Promise<TurnKnowledgeFile[]> {\n const entries = await store.list(workspaceId, options.prefix ?? '/files/')\n return budgetTurnKnowledge(entries.filter(entry => entry.kind === 'file').map(entry => ({\n path: entry.path,\n size: entry.content !== undefined ? new TextEncoder().encode(entry.content).byteLength : entry.bytes?.size ?? 0,\n text: entry.content ?? null,\n })), options)\n}\n","/**\n * The language a Router turn replies in, for every agent app: the sender's current\n * message decides, then the conversation's. It names no language on purpose. On\n * 2026-10-12 a hospitality turn whose context said \"saved language for notices is\n * Spanish\" answered 10 of 19 English questions in Spanish; a model follows any\n * language the prompt names. Saved preferences belong to messages the app starts.\n */\nexport function replyLanguageInstruction(): string {\n return 'Reply in the language of the sender\\'s current message, or in the language they ask for in it. ' +\n 'When its language is unclear (a short acknowledgement, a photo, a voice note), continue in the conversation\\'s language. ' +\n 'Change a saved language only when the sender asks for it in this message; a message written in another language is not that request.'\n}\n\n// ISO 639-1. Names come from Intl, in English, Spanish and the language's own name,\n// so a request for any language is recognised without a hand-kept list.\nconst LANGUAGE_CODES = ('aa ab af ak am an ar as av ay az ba be bg bi bm bn bo br bs ca ce ch co cr cs cu cv cy da de dv dz ee el en eo es ' +\n 'et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu hy hz ia id ie ig ii ik io is it iu ja jv ka kg ki kj kk kl km kn ko kr ' +\n 'ks ku kv kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mr ms mt my na nb nd ne ng nl nn no nr nv ny oc oj om or os pa pi pl ps pt qu ' +\n 'rm rn ro ru rw sa sc sd se sg si sk sl sm sn so sq sr ss st su sv sw ta te tg th ti tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo ' +\n 'xh yi yo za zh zu').split(' ')\n// Always recognised, whatever the runtime's Intl data: generic words and the common\n// languages in English, Spanish and their own names (plus हिंदी beside हिन्दी).\nconst CORE_NAMES = [\n 'language', 'languages', 'idioma', 'idiomas', 'langue', 'lingua', 'língua', 'sprache',\n 'english', 'inglés', 'ingles', 'spanish', 'español', 'espanol', 'castellano', 'french', 'français', 'francés',\n 'portuguese', 'português', 'portugués', 'german', 'deutsch', 'alemán', 'italian', 'italiano', 'japanese', '日本語',\n 'japonés', 'chinese', '中文', '汉语', 'chino', 'korean', '한국어', 'coreano', 'arabic', 'العربية', 'árabe', 'hindi',\n 'हिन्दी', 'हिंदी', 'russian', 'русский', 'ruso', 'dutch', 'nederlands', 'neerlandés', 'hebrew', 'עברית', 'hebreo',\n 'turkish', 'türkçe', 'turco', 'vietnamese', 'tiếng việt', 'vietnamita', 'catalan', 'català', 'catalán',\n]\n// Language names that are everyday words: \"ya he ido\", \"él cree\", \"que me venda\",\n// \"odia\", \"from afar\", \"ewe\", \"Latin America\", \"shoe polish\".\nconst COMMON_WORDS = new Set(['ido', 'cree', 'venda', 'odia', 'afar', 'ewe', 'latin', 'polish'])\n\nlet patterns: RegExp[] | undefined\nfunction languagePatterns(): RegExp[] {\n if (patterns) return patterns\n const names = new Set(CORE_NAMES)\n for (const locale of ['en', 'es', ...LANGUAGE_CODES]) {\n let display: Intl.DisplayNames\n // A runtime without Intl language data still has CORE_NAMES.\n try { display = new Intl.DisplayNames([locale], { type: 'language' }) } catch { continue }\n for (const code of locale === 'en' || locale === 'es' ? LANGUAGE_CODES : [locale]) {\n const name = display.of(code)?.toLowerCase()\n if (name && name !== code && name.length >= 3 && !COMMON_WORDS.has(name)) names.add(name)\n }\n }\n // Latin-script names need word edges (\"pedido\" must not match Ido); scripts written\n // without spaces, such as 日本語, match anywhere.\n return patterns = [...names].map(name => {\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n return /^[\\p{Script=Latin}\\s'-]+$/u.test(name) ? new RegExp(`(?<!\\\\p{L})${escaped}(?!\\\\p{L})`, 'iu') : new RegExp(escaped, 'iu')\n })\n}\n\n/**\n * True when the message names a language. A tool that saves a reply-language\n * preference requires it, using its `context.userMessage`, so the model cannot\n * save a language the sender never asked for.\n */\nexport function asksForLanguage(message: string | undefined): boolean {\n return typeof message === 'string' && languagePatterns().some(pattern => pattern.test(message))\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 *\n * Bounded paid lanes run this same engine inside a protected Router model grant\n * (`runProtectedRouterTurn` in `./protected-router-turn`, outside this entry so a\n * Worker bundle never pulls the grant client).\n */\nimport { streamAppToolLoop, type LoopEvent, type LoopMessage, type LoopToolCall, type ToolLoopStopReason } from './loop'\nimport { DEFAULT_TANGLE_ROUTER_BASE_URL } from './model'\nimport { createOpenAICompatCompletionTurn, createOpenAICompatStreamTurn } from './openai-stream'\nimport { turnKnowledgeInstructions, type TurnKnowledgeFile } from './turn-knowledge'\nimport { replyLanguageInstruction } from './reply-language'\nimport { placeExecution, type PlacementRecord, type VacuousAxis } from '@tangle-network/agent-runtime/placement'\nexport { DURABLE_HOP_BUDGET_MS, turnCheckpointPath, workspaceTurnCheckpoints, type CheckpointWorkspaceStore, type TurnCheckpointStore } from './turn-continuation'\nexport { budgetTurnKnowledge, turnKnowledgeInstructions, workspaceKnowledgeForTurn, type TurnKnowledgeBudget, type TurnKnowledgeFile } from './turn-knowledge'\nexport { asksForLanguage, replyLanguageInstruction } from './reply-language'\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>, context: RouterTurnToolContext): Promise<unknown>\n}\n\n/** What a running tool gets besides its arguments. */\nexport interface RouterTurnToolContext {\n /**\n * Report a typed side event while the tool runs (a graph edit, a file written, a\n * progress step). It streams at once as a `tool_event` and is recorded in the\n * outcome's `toolEvents`. Events sent after the call settles are dropped.\n */\n emit(kind: string, data?: unknown): void\n /** The sender's message this turn answers, so a tool can act only on what was asked (see {@link asksForLanguage}). */\n userMessage: string\n}\n\n/** One side event a tool reported while it ran. */\nexport interface RouterTurnToolEvent {\n callId: string\n toolName: string\n kind: string\n data: unknown\n at: number\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 /** Hidden reasoning the model streamed (`reasoning_content` / `thinking`), for a thinking view. Never part of the answer. */\n | { type: 'reasoning'; 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 | ({ type: 'tool_event' } & RouterTurnToolEvent)\n\nexport interface RouterTurnFailure {\n /** `model_http_<status>`, `model_unavailable`, `model_empty`, `turn_<stopReason>`, `turn_aborted`,\n * `turn_tool_limit` or `router_unconfigured`; under a protected grant also the `grant_*` and\n * `settlement_*` codes of `./protected-router-turn`. */\n code: string\n status?: number\n message: string\n /** The model service's own error text, at most 200 characters (e.g. `key_budget_exhausted`), so an app can\n * tell a spend cap from a missing balance. Never a credential. */\n detail?: 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 /** Every side event the turn's tools reported, in order (at most 500). */\n toolEvents: RouterTurnToolEvent[]\n failure?: RouterTurnFailure\n /**\n * Set instead of a failure when the turn reached its budget at a clean point\n * (every tool call answered). The turn is not over: persist this and call\n * `runRouterTurn` again with `continueFrom` in a durable process to finish it.\n * `text` holds everything the turn has written so far, across hops.\n */\n continuation?: RouterTurnContinuation\n /** Where the turn was placed, when the caller asked for placement. */\n placement?: PlacementRecord\n}\n\n/** A checkpointed Router turn: the conversation after the system prompt, ready to continue. JSON-safe. */\nexport interface RouterTurnContinuation {\n messages: LoopMessage[]\n /** Hops this turn has already run, including this one. */\n hops: number\n /** Reply text every hop so far wrote; the final hop's outcome `text` includes it. */\n text: string\n}\n\n/**\n * What placement reads for a Router turn: the resolved profile, the tools the\n * turn would hold, and a model the sender chose. Declared data only.\n */\nexport interface RouterTurnPlacementInput {\n profile: object\n toolNames?: readonly string[]\n /** A model other than the profile's needs the sandbox to choose between them. */\n requestedModel?: string\n /** Deny-only permissions grant nothing a Router turn lacks. Default: ['permissions']. */\n vacuousAxes?: readonly VacuousAxis[]\n /** The app inlines the profile's skill text into the prompt. */\n inlineSkills?: boolean\n}\n\n/**\n * Where one conversational turn runs: `inference` or `loop` run here in\n * `runRouterTurn`; `sandbox` means the profile or request needs a computer\n * (a harness, files, MCP servers, skills that are not inlined, another model).\n * Throws `PlacementRefusedError` when no tier can meet every requirement.\n */\nexport function placeRouterTurn(input: RouterTurnPlacementInput): PlacementRecord {\n return placeExecution({\n profile: input.profile,\n requirements: {\n ...(input.toolNames?.length ? { tools: [...input.toolNames] } : {}),\n ...(input.requestedModel ? { model: input.requestedModel } : {}),\n },\n context: { interactive: false, inferenceAvailable: true, loopAvailable: true },\n vacuousAxes: input.vacuousAxes ?? ['permissions'],\n ...(input.inlineSkills ? { inlineSkills: true } : {}),\n })\n}\n\n/** One tool call's result as the model reads it. */\nexport type RouterTurnToolOutcome = { ok: true; result: unknown } | { ok: false; code: string; message: string }\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 for this hop. Default 90 s. At the budget the outcome carries a\n * `continuation` instead of failing; the model call or tool already running finishes first. */\n budgetMs?: number\n /** Continue a checkpointed turn; `userMessage` and `history` are ignored. */\n continueFrom?: RouterTurnContinuation\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 /** Cancels the turn: the model call in flight is aborted, no further tool starts, and the\n * outcome carries `turn_aborted`. Effects of tools that already ran are kept. */\n signal?: AbortSignal\n /** Default true: one repeat of a model call that failed before any word or tool, and of a blank\n * answer. Pass false when a second billable call needs the caller's own decision; the failure is\n * then returned as it happened. */\n repeat?: boolean\n /** Default true. False takes each model call as one buffered completion instead of a stream. */\n stream?: boolean\n /** Sent as `reasoning_effort`. */\n reasoningEffort?: string\n /** Sent as `max_completion_tokens`: one model call's visible and reasoning tokens together. */\n maxCompletionTokens?: number\n /** At most this many tool calls run. The next one is refused before it runs and the turn ends\n * with `turn_tool_limit`. */\n maxToolCalls?: number\n /** Replace the text the model reads for one tool result. `toolName` is the app's name. */\n renderToolResult?: (toolName: string, outcome: RouterTurnToolOutcome) => string\n /**\n * Place the turn before any model call. A turn placed in the sandbox returns at once\n * with `placement` and failure `placement_sandbox`, so the app runs it there instead.\n */\n placement?: Omit<RouterTurnPlacementInput, 'toolNames'>\n temperature?: number\n /** Models tried in order when a model call fails before any word or tool, or answers blank. Without it,\n * that safe repeat uses `model` again. `repeat: false` turns both off. */\n fallbackModels?: readonly string[]\n /** Resend one model request that answered 408, 425, 429 or 5xx, or failed to connect, before its stream\n * began, with exponential backoff (a `retry-after` up to 8 s is honoured). `attempts` counts the first\n * send (default 1). `timeoutMs` bounds each attempt, stream included. */\n retry?: { attempts?: number; timeoutMs?: number; baseDelayMs?: number }\n /** Characters of one tool result the model reads when no `renderToolResult` is given. Default 12 000. */\n toolResultLimit?: number\n}\n\nconst DEFAULT_BUDGET_MS = 90_000\nconst RETRY_STATUS = new Set([408, 425, 429, 500, 502, 503, 504])\nconst MAX_RETRY_DELAY_MS = 8_000\nconst TOOL_EVENT_LIMIT = 500\n/** Marks a tool's typed event inside a loop progress update. */\nconst TOOL_EVENT = '__routerTurnToolEvent'\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, the turn's knowledge files, 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: {\n context?: readonly string[]\n toolNames?: readonly string[]\n /** Knowledge files every turn carries; see {@link turnKnowledgeInstructions}. */\n knowledge?: { files: readonly TurnKnowledgeFile[]; readTool?: string }\n } = {},\n): string {\n const knowledge = options.knowledge ? turnKnowledgeInstructions(options.knowledge.files, { readTool: options.knowledge.readTool }) : []\n const text = [profile.prompt?.systemPrompt ?? '', ...(profile.prompt?.instructions ?? []), ...knowledge,\n replyLanguageInstruction(), ...(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\nconst joinText = (parts: string[]) => parts.map(part => part.trim()).filter(Boolean).join('\\n\\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: RouterTurnToolOutcome, limit = TOOL_RESULT_LIMIT): 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 > limit ? `${text.slice(0, limit)}…` : text\n}\n\nexport async function runRouterTurn(options: RouterTurnOptions): Promise<RouterTurnOutcome> {\n // A continued turn answers the last user message in its checkpoint.\n const lastUser = options.continueFrom?.messages.filter(message => message.role === 'user').at(-1)?.content\n const currentUserMessage = options.continueFrom ? (typeof lastUser === 'string' ? lastUser : '') : options.userMessage\n const placement = options.placement\n ? placeRouterTurn({ ...options.placement, toolNames: (options.tools ?? []).map(tool => tool.name) })\n : undefined\n if (placement?.chosen === 'sandbox') {\n return { text: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 }, toolEvents: [], placement,\n failure: { code: 'placement_sandbox', message: placement.reason } }\n }\n const { apiKey } = options\n if (!apiKey) {\n return { text: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 }, toolEvents: [],\n failure: { code: 'router_unconfigured', message: 'The model credential is not configured.' } }\n }\n const emit = options.onEvent ?? (() => {})\n const { signal } = options\n // A cancelled turn sends nothing more, whatever the injected fetch does with the signal.\n const attempts = Math.max(1, Math.floor(options.retry?.attempts ?? 1))\n const attemptTimeoutMs = options.retry?.timeoutMs\n const baseDelayMs = options.retry?.baseDelayMs ?? 500\n const pause = (ms: number) => new Promise<void>((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason)\n const timer = setTimeout(resolve, ms)\n signal?.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason) }, { once: true })\n })\n const fetchImpl: typeof fetch | undefined = signal || attempts > 1 || attemptTimeoutMs\n ? async (input, init) => {\n for (let attempt = 1; ; attempt++) {\n signal?.throwIfAborted()\n const signals = [signal, attemptTimeoutMs ? AbortSignal.timeout(attemptTimeoutMs) : undefined]\n .filter((value): value is AbortSignal => Boolean(value))\n const attemptSignal = signals.length > 1 ? AbortSignal.any(signals) : signals[0]\n const backoff = () => Math.min(MAX_RETRY_DELAY_MS, baseDelayMs * 2 ** (attempt - 1)) * (0.5 + Math.random() / 2)\n let response: Response\n try {\n // A cancelled turn sends nothing more, whatever the injected fetch does with the signal.\n response = await (options.fetchImpl ?? fetch)(input, { ...init, ...(attemptSignal ? { signal: attemptSignal } : {}) })\n } catch (error) {\n if (signal?.aborted || attempt >= attempts) throw error\n await pause(backoff())\n continue\n }\n // Nothing has streamed yet, so a resend repeats no word and no tool.\n if (attempt >= attempts || !RETRY_STATUS.has(response.status)) return response\n const retryAfter = Number(response.headers.get('retry-after'))\n await response.body?.cancel().catch(() => {})\n await pause(Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1000, MAX_RETRY_DELAY_MS) : backoff())\n }\n }\n : options.fetchImpl\n const extraBody = {\n ...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n ...(options.maxCompletionTokens ? { max_completion_tokens: options.maxCompletionTokens } : {}),\n ...(options.reasoningEffort ? { reasoning_effort: options.reasoningEffort } : {}),\n }\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 streamTurnFor = (model: string) => (options.stream === false ? createOpenAICompatCompletionTurn : createOpenAICompatStreamTurn)({\n baseUrl: options.baseUrl ?? DEFAULT_TANGLE_ROUTER_BASE_URL,\n apiKey,\n model,\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n tools: [...byFunction.entries()].map(([name, tool]) => ({\n type: 'function', function: { name, description: tool.description, parameters: tool.inputSchema },\n })),\n ...(Object.keys(extraBody).length ? { extraBody } : {}),\n ...(options.traceId ? { headers: { 'x-tangle-trace-id': options.traceId } } : {}),\n ...(fetchImpl ? { 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 toolEvents: RouterTurnToolEvent[] = []\n const started = new Map<string, number>()\n let segmentOpen = false\n let toolsRan = 0\n let checkpoint: LoopMessage[] | null = null\n let toolLimitReached = false\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 (model: string): Promise<ToolLoopStopReason | 'tool_limit'> => {\n const streamTurn = streamTurnFor(model)\n for await (const step of streamAppToolLoop<LoopEvent>({\n systemPrompt: options.systemPrompt,\n ...(options.continueFrom\n ? { priorMessages: options.continueFrom.messages }\n : { userMessage: options.userMessage, 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 labelFor: call => byFunction.get(call.toolName)?.name ?? call.toolName,\n renderResult: (label, outcome) => options.renderToolResult ? options.renderToolResult(label, outcome) : renderResult(outcome, options.toolResultLimit),\n executeToolCall: async (call: LoopToolCall, context) => {\n const tool = byFunction.get(call.toolName)\n if (!tool) return { ok: false, code: 'unknown_tool', message: `No tool named ${call.toolName}` }\n if (signal?.aborted) return { ok: false, code: 'aborted', message: 'The turn was cancelled before this tool ran.' }\n if (options.maxToolCalls !== undefined && toolsRan >= options.maxToolCalls) {\n toolLimitReached = true\n return { ok: false, code: 'tool_limit', message: 'The turn reached its tool-call limit.' }\n }\n toolsRan++\n // A tool's typed event rides the loop's progress channel, so it streams in order before the result.\n const emitEvent = (kind: string, data?: unknown) => context?.progress({ data: { [TOOL_EVENT]: kind, data } })\n try {\n return { ok: true, result: await tool.run(call.args, { emit: emitEvent, userMessage: currentUserMessage }) }\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 === 'reasoning' && event.text) {\n emit({ type: 'reasoning', 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_progress') {\n const tool = byFunction.get(step.toolName)\n const marked = step.update.data as { [TOOL_EVENT]?: unknown; data?: unknown } | undefined\n // A tool's own emit carries its kind; plain loop progress (a step count, a message) is kind `progress`.\n const typed = typeof marked?.[TOOL_EVENT] === 'string'\n const event: RouterTurnToolEvent = {\n callId: callIdOf(step.toolCallId, step.toolName), toolName: tool?.name ?? step.toolName,\n kind: typed ? marked![TOOL_EVENT] as string : 'progress',\n data: typed ? marked!.data ?? null : step.update, at: Date.now(),\n }\n if (toolEvents.length < TOOL_EVENT_LIMIT) toolEvents.push(event)\n emit({ type: 'tool_event', ...event })\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 // The refused call never ran; the turn ends here rather than asking the model again.\n if (toolLimitReached) return 'tool_limit'\n } else if (step.kind === 'capped') {\n if (step.stopReason === 'deadline' && step.messages) checkpoint = step.messages\n return step.stopReason\n }\n }\n return 'completed'\n }\n\n const outcome = (failure?: RouterTurnFailure): RouterTurnOutcome => ({\n text: joinText([options.continueFrom?.text ?? '', ...segments]),\n servedModel, toolCalls, usage: { ...usage }, toolEvents: [...toolEvents], ...(placement ? { placement } : {}), ...(failure ? { failure } : {}),\n })\n const repeat = options.repeat !== false\n // The safe repeat walks this chain: the next fallback model, or the same model once.\n const repeats = !repeat ? [] : options.fallbackModels?.length ? [...options.fallbackModels] : [options.model]\n let stop: ToolLoopStopReason | 'tool_limit'\n try {\n try {\n stop = await run(options.model)\n } catch (error) {\n // Safe to repeat only while nothing was said and no tool ran.\n const next = repeats.shift()\n if (next === undefined || signal?.aborted || toolsRan > 0 || segments.length > 0) throw error\n stop = await run(next)\n }\n } catch (error) {\n if (signal?.aborted) return outcome({ code: 'turn_aborted', message: 'The turn was cancelled.' })\n const status = (error as { status?: unknown }).status\n // The stream adapter puts the service's own text after the status; keep it, short, for the app's error categories.\n const detail = error instanceof Error ? error.message.match(/\\(HTTP \\d+\\): ([\\s\\S]*)$/)?.[1]?.slice(0, 200) : undefined\n return outcome(typeof status === 'number'\n ? { code: `model_http_${status}`, status, message: 'The model service did not answer.', ...(detail ? { detail } : {}) }\n : { code: 'model_unavailable', message: 'The model service did not answer.' })\n }\n if (stop === 'deadline' && checkpoint) {\n return { ...outcome(), continuation: { messages: checkpoint,\n hops: (options.continueFrom?.hops ?? 0) + 1,\n text: outcome().text } }\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()) && !options.continueFrom?.text.trim()) {\n const next = repeats.shift()\n if (toolsRan === 0 && next !== undefined) {\n try { stop = await run(next) } 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","/**\n * A Router turn never fails because of time. `runRouterTurn` stops at its hop\n * budget at a clean point and returns a `continuation`; the host saves it here\n * and runs the next hop in a durable process (a Durable Object alarm or a Queue\n * consumer: 15 minutes of wall time each), posting into the same conversation.\n *\n * Checkpoints live in the app's workspace store under `/turns/<turnId>/`, which\n * a Files view (`/files/`) never lists.\n */\nimport type { RouterTurnContinuation } from './router-turn'\n\n/** Wall time a durable hop may plan for: a Durable Object alarm or Queue consumer gets 15 minutes. */\nexport const DURABLE_HOP_BUDGET_MS = 14 * 60_000\n\n/** Where a turn's checkpoint waits between hops. */\nexport interface TurnCheckpointStore {\n save(turnId: string, continuation: RouterTurnContinuation): Promise<void>\n load(turnId: string): Promise<RouterTurnContinuation | null>\n clear(turnId: string): Promise<void>\n}\n\ninterface CheckpointEntry { content?: string; revision: number }\n\n/** The fields of an agent-runtime `WorkspaceStore` a checkpoint needs; structural so any adapter fits. */\nexport interface CheckpointWorkspaceStore {\n get(workspaceId: string, path: string): Promise<CheckpointEntry | null>\n put(input: { workspaceId: string; path: string; kind: 'file'; ifRevision: number | null; actor: string; content: string }): Promise<unknown>\n delete(input: { workspaceId: string; path: string; actor: string }): Promise<unknown>\n}\n\nexport function turnCheckpointPath(turnId: string): string {\n return `/turns/${encodeURIComponent(turnId)}/checkpoint.json`\n}\n\n/** Turn checkpoints in a workspace store, written as `actor`. */\nexport function workspaceTurnCheckpoints(store: CheckpointWorkspaceStore, workspaceId: string, actor: string): TurnCheckpointStore {\n return {\n async save(turnId, continuation) {\n const path = turnCheckpointPath(turnId)\n const current = await store.get(workspaceId, path)\n await store.put({ workspaceId, path, kind: 'file', ifRevision: current?.revision ?? null, actor,\n content: JSON.stringify(continuation) })\n },\n async load(turnId) {\n const entry = await store.get(workspaceId, turnCheckpointPath(turnId))\n return entry?.content ? JSON.parse(entry.content) as RouterTurnContinuation : null\n },\n async clear(turnId) {\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MAAI,CAAC,SAAS,KAAK,UAAQ,KAAK,KAAK,CAAC,KAAK,CAAC,QAAQ,cAAc,KAAK,KAAK,GAAG;AAC7E,UAAM,OAAO,QAAQ,MAAM;AAC3B,QAAI,aAAa,KAAK,SAAS,QAAW;AACxC,UAAI;AAAE,eAAO,MAAM,IAAI,IAAI;AAAA,MAAE,QAAQ;AAAE,eAAO;AAAA,MAAY;AAC1D,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"]}
|
|
@@ -33,14 +33,14 @@ import {
|
|
|
33
33
|
} from "./chunk-LSUELMHY.js";
|
|
34
34
|
import {
|
|
35
35
|
attachmentPartsFromMessageParts
|
|
36
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-YR6TZ777.js";
|
|
37
37
|
import {
|
|
38
38
|
TURN_INTENT_EVENT,
|
|
39
39
|
TURN_PHASE_EVENT,
|
|
40
40
|
isTurnIntentEvent,
|
|
41
41
|
isTurnPhaseEvent,
|
|
42
42
|
settleTurnResponse
|
|
43
|
-
} from "./chunk-
|
|
43
|
+
} from "./chunk-YHRWZZJN.js";
|
|
44
44
|
import {
|
|
45
45
|
parsePlanSubmittedEvent,
|
|
46
46
|
persistedPartToPlan
|
|
@@ -6804,4 +6804,4 @@ export {
|
|
|
6804
6804
|
useThinkingSeconds,
|
|
6805
6805
|
ChatMessages
|
|
6806
6806
|
};
|
|
6807
|
-
//# sourceMappingURL=chunk-
|
|
6807
|
+
//# sourceMappingURL=chunk-JTBPQEGM.js.map
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
import {
|
|
8
8
|
mentionInputToPart,
|
|
9
9
|
toChatMessageParts
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-YR6TZ777.js";
|
|
11
11
|
import {
|
|
12
12
|
ChatTurnInputError,
|
|
13
13
|
TURN_INTENT_EVENT,
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
parseChatTurnParts,
|
|
21
21
|
parseFileMentions,
|
|
22
22
|
turnResponseEventFor
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-YHRWZZJN.js";
|
|
24
24
|
import {
|
|
25
25
|
normalizeClientTurnId,
|
|
26
26
|
resolveChatTurn
|
|
@@ -1261,4 +1261,4 @@ export {
|
|
|
1261
1261
|
createChatTurnRoutes,
|
|
1262
1262
|
streamChatRouteAsSandboxEvents
|
|
1263
1263
|
};
|
|
1264
|
-
//# sourceMappingURL=chunk-
|
|
1264
|
+
//# sourceMappingURL=chunk-N5M7YT6P.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
runRouterTurn
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-2ZGB4V7I.js";
|
|
4
4
|
|
|
5
5
|
// src/runtime/protected-model.ts
|
|
6
6
|
import {
|
|
@@ -219,4 +219,4 @@ export {
|
|
|
219
219
|
createRouterProtectedModelPort,
|
|
220
220
|
runProtectedRouterTurn
|
|
221
221
|
};
|
|
222
|
-
//# sourceMappingURL=chunk-
|
|
222
|
+
//# sourceMappingURL=chunk-NFAOHX4Z.js.map
|
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
checkAttachmentType,
|
|
28
28
|
sanitizeAttachmentFileName,
|
|
29
29
|
sniffBinary
|
|
30
|
-
} from "./chunk-
|
|
30
|
+
} from "./chunk-WTC6AOPL.js";
|
|
31
31
|
|
|
32
32
|
// src/web-react/use-dictation.ts
|
|
33
33
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
@@ -1552,4 +1552,4 @@ export {
|
|
|
1552
1552
|
ComposerModeControls,
|
|
1553
1553
|
EntryComposer
|
|
1554
1554
|
};
|
|
1555
|
-
//# sourceMappingURL=chunk-
|
|
1555
|
+
//# sourceMappingURL=chunk-WAMJU3G4.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
formatBytes
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-YHRWZZJN.js";
|
|
4
4
|
|
|
5
5
|
// src/chat-routes/binary-sniff.ts
|
|
6
6
|
var OOXML_WORD_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
|
|
@@ -386,4 +386,4 @@ export {
|
|
|
386
386
|
attachmentSizeErrorMessage,
|
|
387
387
|
attachmentTotalSizeErrorMessage
|
|
388
388
|
};
|
|
389
|
-
//# sourceMappingURL=chunk-
|
|
389
|
+
//# sourceMappingURL=chunk-WTC6AOPL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/chat-routes/turn-progress.ts","../src/chat-routes/wire.ts"],"sourcesContent":["/**\n * Turn progress: the real stage a chat turn is in, on the turn stream.\n *\n * A turn can spend seconds before its first answer token: authorization, the\n * conversation load, the single-flight lock, the product's pre-turn work, a\n * sandbox, the harness and the model's first token. `session.run.phase` events\n * name those stages as they happen, so a chat shows where the turn is instead\n * of a spinner.\n *\n * A client that sends {@link TURN_PROGRESS_HEADER} gets the response stream as\n * soon as the route has parsed the body and `authorize` has admitted the\n * caller. Authorization never runs inside the stream: every refusal it makes\n * (400, 401, 402, 403, 404, 429) is a plain HTTP response, so an unadmitted\n * caller sees no stage, holds no stream and starts no work. After admission,\n * anything the route answers with a non-stream response (a held lock's 409, a\n * gate's own response, a handoff, a failure) arrives as one\n * {@link TURN_RESPONSE_EVENT} carrying that response's status, headers and\n * body, and {@link settleTurnResponse} turns it back into the `Response` the\n * caller already handles. A client that does not send the header gets exactly\n * the responses it got before.\n *\n * Product work that only an admitted turn may do (resolving its profile and\n * model, any write) belongs in `prepareTurn`, which runs after admission and,\n * on a progress-first stream, inside it with its own named stages.\n * `tests/chat-routes/authorize-before-stream.test.ts` is the gate that keeps\n * every shared route behind its `authorize`.\n *\n * Browser-safe and import-free: the server route and the web client share it.\n */\n\n/** Request header that asks for a progress-first turn stream. */\nexport const TURN_PROGRESS_HEADER = 'x-turn-progress'\n/** The only value of {@link TURN_PROGRESS_HEADER}. The route echoes it on a progress-first response. */\nexport const TURN_PROGRESS_FIRST = 'first'\n\n/** Stream event naming the turn's current stage. Non-terminal and never turn content. */\nexport const TURN_PHASE_EVENT = 'session.run.phase'\n\n/**\n * Stages the shared route emits before the producer runs. Products add their\n * own (a sandbox product emits `provisioning`, `starting`,\n * `awaiting-first-token`).\n * - `accepted`: the caller is admitted; the conversation and the lock are loading.\n * - `preparing`: the turn holds its lock; the product's pre-turn work is running.\n */\nexport type TurnRoutePhase = 'accepted' | 'preparing'\n\n/** The data of a {@link TURN_PHASE_EVENT}. */\nexport type TurnPhaseData = {\n /** Stage id: a {@link TurnRoutePhase} or a product's own stage. */\n phase: string\n /** Text the client shows verbatim. */\n message: string\n /** A keepalive for the current stage rather than a new stage. */\n heartbeat?: boolean\n /** Milliseconds since the current wait began. */\n elapsedMs?: number\n /** Milliseconds since the server received the request. */\n sinceRequestMs?: number\n}\n\n/** A {@link TURN_PHASE_EVENT} as it crosses the wire. */\nexport type TurnPhaseEvent = { type: typeof TURN_PHASE_EVENT; data: TurnPhaseData }\n\n/** Default text for the route's own stages. Products override it through `createChatTurnRoutes({ progressMessages })`. */\nexport const TURN_ROUTE_PHASE_MESSAGES: Record<TurnRoutePhase, string> = {\n accepted: 'Loading your conversation…',\n preparing: 'Preparing the agent…',\n}\n\n/** Build a {@link TURN_PHASE_EVENT}. */\nexport function buildTurnPhaseEvent(\n phase: string,\n message: string,\n opts: { heartbeat?: boolean; elapsedMs?: number; sinceRequestMs?: number } = {},\n): TurnPhaseEvent {\n return {\n type: TURN_PHASE_EVENT,\n data: {\n phase,\n message,\n ...(opts.heartbeat ? { heartbeat: true } : {}),\n ...(typeof opts.elapsedMs === 'number' ? { elapsedMs: opts.elapsedMs } : {}),\n ...(typeof opts.sinceRequestMs === 'number' ? { sinceRequestMs: opts.sinceRequestMs } : {}),\n },\n }\n}\n\n/** True for a {@link TURN_PHASE_EVENT} with a usable `phase` and `message`. */\nexport function isTurnPhaseEvent(event: unknown): event is TurnPhaseEvent {\n if (!event || typeof event !== 'object') return false\n const candidate = event as { type?: unknown; data?: { phase?: unknown; message?: unknown } }\n return candidate.type === TURN_PHASE_EVENT\n && typeof candidate.data?.phase === 'string'\n && typeof candidate.data?.message === 'string'\n}\n\n/**\n * Stream event carrying the turn's intent line: one plain sentence, written by\n * a fast model call at admission, saying what the agent is about to do (\"Looking\n * at your three competitors' pricing pages, then I'll draft the comparison.\").\n * A client shows it as a labeled status line, never as the answer, until the\n * turn's first answer text replaces it. It narrates intent; it never answers\n * or acts. Non-terminal and never turn content; at most one per turn.\n */\nexport const TURN_INTENT_EVENT = 'session.run.intent'\n\n/** The data of a {@link TURN_INTENT_EVENT}. */\nexport type TurnIntentData = {\n /** The sentence, shown verbatim. */\n text: string\n /** Milliseconds since the server received the request. */\n sinceRequestMs?: number\n}\n\n/** A {@link TURN_INTENT_EVENT} as it crosses the wire. */\nexport type TurnIntentEvent = { type: typeof TURN_INTENT_EVENT; data: TurnIntentData }\n\n/** True for a {@link TURN_INTENT_EVENT} with non-empty text. */\nexport function isTurnIntentEvent(event: unknown): event is TurnIntentEvent {\n if (!event || typeof event !== 'object') return false\n const candidate = event as { type?: unknown; data?: { text?: unknown } }\n return candidate.type === TURN_INTENT_EVENT\n && typeof candidate.data?.text === 'string'\n && candidate.data.text.trim().length > 0\n}\n\n/** Terminal event of a progress-first stream that ended without a turn: the response the route returned instead. */\nexport const TURN_RESPONSE_EVENT = 'turn.response'\n\n/** The data of a {@link TURN_RESPONSE_EVENT}. */\nexport type TurnResponseData = {\n status: number\n /** Response headers other than `set-cookie` and framing headers. */\n headers: Record<string, string>\n body: string\n}\n\n/** Headers a {@link TURN_RESPONSE_EVENT} cannot carry: cookies cannot be set after the stream opened, and framing belongs to the outer response. */\nconst UNCARRIED_HEADERS = new Set(['set-cookie', 'content-length', 'content-encoding', 'transfer-encoding', 'connection'])\n\n/** Error code {@link settleTurnResponse} reports when a progress-first stream closes before the turn started. */\nexport const TURN_STREAM_LOST_CODE = 'turn_stream_lost'\n\n/** Serialize a non-stream response for a {@link TURN_RESPONSE_EVENT}. */\nexport async function turnResponseEventFor(response: Response): Promise<{ type: typeof TURN_RESPONSE_EVENT; data: TurnResponseData }> {\n const headers: Record<string, string> = {}\n response.headers.forEach((value, key) => {\n if (!UNCARRIED_HEADERS.has(key.toLowerCase())) headers[key.toLowerCase()] = value\n })\n return { type: TURN_RESPONSE_EVENT, data: { status: response.status, headers, body: await response.text() } }\n}\n\n/**\n * Settle a turn response for a client that sent {@link TURN_PROGRESS_HEADER}.\n *\n * Reads the stream's leading progress events, handing each to `onPhase` (and an\n * intent line to `onIntent`, or dropping it when there is none), until the\n * first other event. A {@link TURN_RESPONSE_EVENT} resolves to a `Response`\n * with the original status, headers and body, so the caller's existing error\n * handling runs unchanged. Any other event resolves to a `Response` whose body\n * starts at that event and continues with the rest of the stream. A response\n * that is not progress-first is returned as it is.\n */\nexport async function settleTurnResponse(\n response: Response,\n onPhase: (phase: TurnPhaseData) => void,\n onIntent?: (intent: TurnIntentData) => void,\n): Promise<Response> {\n if (response.headers.get(TURN_PROGRESS_HEADER) !== TURN_PROGRESS_FIRST || !response.body) return response\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n const encoder = new TextEncoder()\n let buffer = ''\n let ended = false\n for (;;) {\n let newline = buffer.indexOf('\\n')\n while (newline < 0) {\n if (ended) {\n // The stream closed inside the progress prefix: the turn never started.\n return Response.json(\n { error: 'The connection closed before the turn started. Try again.', code: TURN_STREAM_LOST_CODE },\n { status: 502 },\n )\n }\n const { done, value } = await reader.read()\n if (done) {\n ended = true\n buffer += decoder.decode()\n // A final line without its newline is still a line.\n if (buffer.trim()) buffer += '\\n'\n } else {\n buffer += decoder.decode(value, { stream: true })\n }\n newline = buffer.indexOf('\\n')\n }\n const line = buffer.slice(0, newline).trim()\n if (!line) {\n buffer = buffer.slice(newline + 1)\n continue\n }\n let event: unknown\n try {\n event = JSON.parse(line)\n } catch {\n event = null\n }\n if (isTurnPhaseEvent(event)) {\n buffer = buffer.slice(newline + 1)\n onPhase(event.data)\n continue\n }\n // An intent line is progress too: a response the route answers after it\n // (a held lock's 409) still settles with its own status.\n if (isTurnIntentEvent(event)) {\n buffer = buffer.slice(newline + 1)\n onIntent?.(event.data)\n continue\n }\n const answered = event as { type?: unknown; data?: Partial<TurnResponseData> } | null\n if (answered?.type === TURN_RESPONSE_EVENT && typeof answered.data?.status === 'number') {\n await reader.cancel().catch(() => {})\n return new Response(answered.data.status === 204 || answered.data.status === 304 ? null : String(answered.data.body ?? ''), {\n status: answered.data.status,\n headers: answered.data.headers ?? {},\n })\n }\n return streamFrom(reader, buffer, encoder, response)\n }\n}\n\n/** The rest of a progress-first stream, starting with bytes already read. */\nfunction streamFrom(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n pending: string,\n encoder: TextEncoder,\n original: Response,\n): Response {\n let first = pending\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n if (first) {\n controller.enqueue(encoder.encode(first))\n first = ''\n return\n }\n const { done, value } = await reader.read()\n if (done) controller.close()\n else controller.enqueue(value)\n },\n cancel(reason) {\n return reader.cancel(reason)\n },\n })\n return new Response(body, { status: original.status, headers: original.headers })\n}\n","import { isWorkspaceFileExportable } from '../web/file-export'\nimport { TURN_PROGRESS_FIRST, TURN_PROGRESS_HEADER } from './turn-progress'\nimport type { ReasoningEffort } from '@tangle-network/agent-interface'\n\n/**\n * Wire contract between the chat client (composer + `streamChatTurn`) and the\n * assembled server vertical (`createChatTurnRoutes`). This module must remain\n * browser-safe: `/web-react` re-exports these types into browser bundles, so\n * imports must not reach a Node builtin or an engine package.\n *\n * The client part shape permits an absolute file path until the server converts\n * it to the URL required by the sandbox SDK. It is derived here, not imported,\n * so the client bundle never touches the SDK.\n */\n\nexport interface ChatTurnTextPartInput {\n type: 'text'\n text: string\n}\n\n/** A non-text prompt part the upload route hands back and the client echoes\n * on send. `url` carries an inline `data:` URI for small files; `path` is a\n * sandbox workspace reference for large ones (the >1 MiB gateway body cap\n * makes the two-step upload mandatory). */\nexport interface ChatTurnFilePartInput {\n type: 'image' | 'file'\n filename?: string\n mediaType?: string\n url?: string\n path?: string\n}\n\n/** Resolve input as either a text part or a file part of a chat turn */\nexport type ChatTurnPartInput = ChatTurnTextPartInput | ChatTurnFilePartInput\n\n/** A chat turn's automatic sentinel plus the canonical agent reasoning levels. */\nexport type ChatReasoningEffort = 'auto' | ReasoningEffort\n\n// ── producer stream vocabulary ───────────────────────────────────────────────\n\n/** Represent a text event produced by a source with a fixed type and associated text content */\nexport interface ProducerTextEvent {\n type: 'text'\n text: string\n}\n\n/** Define an event representing reasoning output with a fixed type and associated text */\nexport interface ProducerReasoningEvent {\n type: 'reasoning'\n text: string\n}\n\n/** Represent an event triggered by a producer tool call with its identifier, name, and arguments */\nexport interface ProducerToolCallEvent {\n type: 'tool_call'\n call: {\n toolCallId: string\n toolName: string\n args: Record<string, unknown>\n }\n}\n\n/** Describe the structure of an event representing the result of a producer tool call */\nexport interface ProducerToolResultEvent {\n type: 'tool_result'\n toolCallId: string\n toolName: string\n outcome: {\n ok: boolean\n result?: unknown\n message?: string\n /** Typed reason for a failed call, when the producer knows it. */\n code?: string\n }\n}\n\n/** Describe cumulative provider usage reported by a producer. */\nexport interface ProducerUsageEvent {\n type: 'usage'\n usage: {\n promptTokens: number\n completionTokens: number\n reasoningTokens?: number\n toolTokens?: number\n toolCallCount?: number\n providerCostUsd?: number\n /** Present only when the provider enforced the complete execution budget. */\n budgetEnforced?: boolean\n }\n}\n\n/** Define the structure for a producer notice event with type, id, kind, and text fields */\nexport interface ProducerNoticeEvent {\n type: 'notice'\n id: string\n /** Kept inline with `/interactions`' `NoticeKind` so this file stays import-free. */\n noticeKind: 'warning' | 'auto-declined' | 'error'\n text: string\n /** Typed reason, on an `error` notice. */\n code?: string\n}\n\n/** Represent an error event emitted by a producer containing message, code, and optional details */\nexport interface ProducerErrorEvent {\n type: 'error'\n data: {\n message: string\n code?: string\n details?: Record<string, unknown>\n }\n}\n\n/** Stable raw lifecycle/interaction/plan/route events forwarded unchanged. */\nexport type ProducerPassthroughEventType =\n | 'turn'\n | 'metadata'\n | 'interaction'\n | 'interaction.cancel'\n | 'plan.submitted'\n | 'done'\n | 'warning'\n /** A tool's typed side event while it runs (`data`: toolCallId, toolName, kind, data, at). */\n | 'tool.event'\n | 'session.run.started'\n | 'session.run.completed'\n | 'session.run.failed'\n | 'turn_status'\n\n/** Define an event carrying passthrough data with flexible properties for producer communication */\nexport interface ProducerPassthroughEvent {\n type: ProducerPassthroughEventType\n data?: Record<string, unknown>\n /** Route markers and raw passthroughs may carry `turnId`, `status`, `seq`, etc. */\n [key: string]: unknown\n}\n\n/** Represent events emitted by a producer during its operation for processing and handling */\nexport type ProducerWireEvent =\n | ProducerTextEvent\n | ProducerReasoningEvent\n | ProducerToolCallEvent\n | ProducerToolResultEvent\n | ProducerUsageEvent\n | ProducerNoticeEvent\n | ProducerErrorEvent\n | ProducerPassthroughEvent\n\n/** The image/file split an attachment is rendered and persisted under — the\n * same discriminant as {@link ChatMentionKind}, but a distinct name because an\n * attachment carries content the product uploaded (`ChatAttachmentInput`)\n * while a mention points at a file the box already has. Defined HERE (the\n * import-free layer) so `ChatAttachmentInput` can reference it and the client\n * composer imports it without pulling the persisted-part vocabulary;\n * `/chat-store`'s parts module re-exports it alongside the attachment helpers. */\nexport type ChatAttachmentKind = 'image' | 'file'\n\n/** `POST` turn-body entry describing a file already uploaded to the product's\n * store (vault/object-store) — distinct from an inline {@link\n * ChatTurnFilePartInput} (which carries bytes) and from a {@link FileMention}\n * (a sandbox path the box already holds). The route resolves this field with\n * {@link resolveChatAttachments}: every path is re-validated and every size is\n * re-derived from the stored body, so nothing here is trusted as sent. */\nexport interface ChatAttachmentInput {\n path: string\n name: string\n size: number\n mediaType: string\n kind: ChatAttachmentKind\n}\n\n/** POST body for the turn route. `content` may be empty when `parts` carry the\n * message (an image-only send). Product routing fields (workspaceId etc.) ride\n * alongside and are read by the product's `authorize` seam. */\nexport interface ChatTurnRequestPayload {\n threadId: string\n content?: string\n /** Non-text parts from the upload route, echoed back verbatim. */\n parts?: ChatTurnFilePartInput[]\n /** `@`-picked file mentions for this turn — path references into the\n * workspace sandbox, NOT uploads, so they travel in their own field rather\n * than as `parts` entries. A product whose `parts` field is already spoken\n * for (an attachment sentinel) can still send mentions, and mentions\n * persist as their own `ChatMentionPart`s so a retry rebuilds them. The\n * route validates this field with {@link parseFileMentions} and replaces it\n * on the payload with the validated, deduped list. */\n mentions?: FileMention[]\n /** Files uploaded to the product's store ahead of the turn — path\n * references, NOT inline bytes (those ride `parts`). Validated and\n * size-re-derived by {@link resolveChatAttachments} into persistable\n * attachment parts; a product whose `parts` field is spoken for by inline\n * uploads still sends store-backed files here. */\n attachments?: ChatAttachmentInput[]\n model?: string\n effort?: ChatReasoningEffort\n harness?: string\n /** Client-generated idempotency key for the logical turn (retry-safe). */\n turnId?: string\n /** New token for a deliberate retry; reuse it for transport retries of that attempt. */\n retryAttemptId?: string\n [key: string]: unknown\n}\n\n/** `fetch` init for the turn route — the one place the client wire shape is\n * serialized, so composer glue and products never drift from the server's\n * parser. */\nexport function chatTurnRequestInit(\n payload: ChatTurnRequestPayload,\n options: { progressFirst?: boolean } = {},\n): RequestInit {\n return {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n // Ask for a progress-first stream (`./turn-progress`); settle the response with `settleTurnResponse`.\n ...(options.progressFirst ? { [TURN_PROGRESS_HEADER]: TURN_PROGRESS_FIRST } : {}),\n },\n body: JSON.stringify(payload),\n }\n}\n\n// ── inline-part byte budget ─────────────────────────────────────────────────\n//\n// The sandbox gateway caps request bodies at 1 MiB; a turn body whose inline\n// `data:` parts exceed it dies at the gateway with an opaque 413. Enforce the\n// budget at the route boundary instead, with headroom for the JSON envelope\n// (same fail-loud-at-the-choke-point style as /sandbox's provision-payload and\n// env-size gates).\n\n/** Define the maximum byte size allowed for inline parts in data processing */\nexport const INLINE_PARTS_MAX_BYTES = 950_000\n\n// ── dispatch (parts[]) budget vocabulary ────────────────────────────────────\n//\n// The default caps `buildDispatchParts` sizes an attachment/mention dispatch\n// against — the sidecar/proxy limits an assembled `parts` array crosses, one\n// step past `INLINE_PARTS_MAX_BYTES` (which gates the raw turn BODY). Grouped\n// here, in the import-free layer, so the numbers are one overridable\n// vocabulary the client can read and a product can tune per call rather than\n// constants buried in the server module. NOTE: these model sidecar/proxy caps,\n// not a product's MIME accept-list or vault bucketing — those are DOMAIN\n// values the product supplies, never defaulted here.\n\n/** Hard cap on the whole `/prompt` request body as it crosses the sandbox\n * proxy — smaller in practice than a raw-file write cap because a dispatch\n * carries several inline parts plus the flattened history in one request. */\nexport const DISPATCH_REQUEST_MAX_BYTES = 1024 * 1024\n\n/** Bytes reserved off the top of {@link DISPATCH_REQUEST_MAX_BYTES} for the\n * JSON structure around the parts array (keys, delimiters, per-part\n * `type`/`filename`/`mediaType` fields) that {@link base64WireLen} does not\n * account for — keeps the inline budget off the exact proxy cap where one\n * stray byte trips the 413. */\nexport const DISPATCH_STRUCTURAL_RESERVE_BYTES = 64 * 1024\n\n/** Sidecar's hard cap on the `parts` array of one prompt request — a dispatch\n * must never assemble more parts than this or the whole turn 400s. */\nexport const DISPATCH_MAX_PARTS = 64\n\n/** Product-side cap on media parts per dispatch (current turn + carried\n * history), well under {@link DISPATCH_MAX_PARTS}. History trimming that keeps\n * a transcript's native media under this is a PRODUCT concern (the pointer\n * block keeps trimmed media reachable); `buildDispatchParts` enforces only the\n * total {@link DISPATCH_MAX_PARTS} cap. */\nexport const DISPATCH_MAX_MEDIA_PARTS = 24\n\n/** Size a base64-encoded string occupies on the wire given the raw\n * (pre-encoding) byte length: base64 packs 3 raw bytes into 4 output\n * characters, rounded up to the next multiple of 4. */\nexport function base64WireLen(byteLen: number): number {\n return Math.ceil(byteLen / 3) * 4\n}\n\n/**\n * Render a raw byte count as a human-readable size (`512B`, `3KB`, `12MB\n * 500KB`). Ported EXACTLY from gtm-agent's `attachment-limits.ts` — byte-\n * identical implementation, not a reinterpretation — so `resolve-attachments`'s\n * and `promote-file-part`'s error strings match gtm's wording verbatim. Lives\n * in the import-free wire layer (not `resolve-attachments.ts` alone) because\n * BOTH the aggregate-cap message here and the per-file oversize message in\n * `promote-file-part.ts` need it; a browser composer wanting the same\n * formatting for a client-side pre-check can also import it with no engine\n * pulled in.\n */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes}B`\n if (bytes >= 1024 * 1024) {\n const megabytes = Math.floor(bytes / (1024 * 1024))\n const remainder = bytes % (1024 * 1024)\n return remainder === 0 ? `${megabytes}MB` : `${megabytes}MB ${formatBytes(remainder)}`\n }\n return `${Math.round(bytes / 1024)}KB`\n}\n\n/** Represent errors for invalid chat turn inputs with status and code properties */\nexport class ChatTurnInputError extends Error {\n constructor(message: string, readonly status = 400, readonly code = 'INVALID_CHAT_TURN') {\n super(message)\n this.name = 'ChatTurnInputError'\n }\n}\n\nfunction partByteSize(part: ChatTurnPartInput): number {\n let bytes = 0\n if (part.type === 'text') return part.text.length\n if (part.url) bytes += part.url.length\n if (part.path) bytes += part.path.length\n return bytes\n}\n\n/** Calculate the total byte size of an array of chat turn parts */\nexport function promptPartsByteSize(parts: ChatTurnPartInput[]): number {\n return parts.reduce((total, part) => total + partByteSize(part), 0)\n}\n\n/** Throws `ChatTurnInputError` (413) when the parts' inline payload would blow\n * the gateway cap. Path-ref parts are tiny by construction and always pass. */\nexport function assertPromptPartsWithinCap(\n parts: ChatTurnPartInput[],\n maxBytes = INLINE_PARTS_MAX_BYTES,\n): void {\n const total = promptPartsByteSize(parts)\n if (total <= maxBytes) return\n const largest = [...parts].sort((a, b) => partByteSize(b) - partByteSize(a))[0]\n const largestName = largest && largest.type !== 'text' ? largest.filename ?? largest.path ?? largest.type : 'text'\n throw new ChatTurnInputError(\n `Inline prompt parts total ${total}B, over the ${maxBytes}B budget (largest: ${largestName}, ${largest ? partByteSize(largest) : 0}B). ` +\n 'Upload large files through the upload route so they travel as sandbox path references.',\n 413,\n 'PROMPT_PARTS_TOO_LARGE',\n )\n}\n\n// ── file mentions ────────────────────────────────────────────────────────\n//\n// A file mention (`@`-picked in the composer, sandbox-ui#184) is a path\n// reference into the workspace sandbox — no byte upload. These helpers turn\n// a resolved mention list into wire parts and the prompt pointer block that\n// tells the agent where to read them from.\n\n/** A file mention resolved from the composer's `@`-picker: the\n * workspace-relative path plus enough metadata to build a prompt part and\n * pointer text. `path` is the canonical identity — the mention pill's\n * `MentionItem.id` for the file kind (`/web-react`'s `useFileMentions`). */\nexport interface FileMention {\n path: string\n name: string\n size?: number\n}\n\nconst MENTION_IMAGE_MEDIA_TYPES: ReadonlyMap<string, string> = new Map([\n ['.png', 'image/png'],\n ['.jpg', 'image/jpeg'],\n ['.jpeg', 'image/jpeg'],\n ['.gif', 'image/gif'],\n ['.webp', 'image/webp'],\n ['.svg', 'image/svg+xml'],\n ['.bmp', 'image/bmp'],\n ['.heic', 'image/heic'],\n ['.heif', 'image/heif'],\n ['.avif', 'image/avif'],\n])\n\nfunction extensionOf(path: string): string {\n const base = path.split('/').filter(Boolean).pop() ?? path\n const dot = base.lastIndexOf('.')\n return dot > 0 ? base.slice(dot).toLowerCase() : ''\n}\n\n/** The `image/*` mime for a mention path by extension, or `undefined` for\n * anything not in the known image set (dispatched as `type: 'file'`). */\nexport function mediaTypeForMentionPath(path: string): string | undefined {\n return MENTION_IMAGE_MEDIA_TYPES.get(extensionOf(path))\n}\n\n/** The image/file split a mention is rendered and persisted under — the\n * composer pill's icon, the dispatched part's `type`, and\n * `ChatMentionPart.mentionKind` are all this one value. */\nexport type ChatMentionKind = 'image' | 'file'\n\n/** `image` when the path's extension is in the known image set (the same table\n * {@link mediaTypeForMentionPath} reads), `file` otherwise. Exported so a\n * client that needs only the discriminant — a pill icon, a persisted part's\n * `mentionKind` — never re-declares the extension table; two frozen copies of\n * one mime table is how one gains a format and the other doesn't. */\nexport function mentionKindForPath(path: string): ChatMentionKind {\n return mediaTypeForMentionPath(path) ? 'image' : 'file'\n}\n\n/** Define options to resolve mention paths when converting file mentions to parts */\nexport interface FileMentionsToPartsOptions {\n /** Resolve a mention's workspace-relative path to the absolute path the\n * dispatched part should carry (e.g. a host prefixing the in-box vault\n * root). Default: identity — the path travels unchanged. */\n resolvePath?: (path: string) => string\n}\n\n/** Maps resolved file mentions to path-only `ChatTurnFilePartInput`s —\n * `image` vs `file` by extension, and always a `path`, never a `url` (the\n * url/path XOR invariant: a mention is a sandbox path reference, never\n * inline bytes). */\nexport function fileMentionsToParts(\n mentions: readonly FileMention[],\n opts: FileMentionsToPartsOptions = {},\n): ChatTurnFilePartInput[] {\n const resolvePath = opts.resolvePath ?? ((path: string) => path)\n return mentions.map((mention) => {\n const mediaType = mediaTypeForMentionPath(mention.path)\n const part: ChatTurnFilePartInput = {\n type: mediaType ? 'image' : 'file',\n filename: mention.name,\n path: resolvePath(mention.path),\n }\n if (mediaType) part.mediaType = mediaType\n return part\n })\n}\n\n/** The agent-facing pointer block appended to the dispatched prompt — never\n * persisted in message `content`. Empty array → `''` so callers can append\n * unconditionally. This is the sole producer of that text: the current\n * turn's dispatch and any history projection built from the same mention\n * list both route through here, so the two can't drift apart. */\nexport function buildMentionPromptBlock(\n mentions: readonly Pick<FileMention, 'name' | 'path'>[],\n): string {\n if (mentions.length === 0) return ''\n const lines = mentions.map((m) => `- ${m.name} (${m.path})`)\n return `\\n\\nMentioned files — read them from these paths:\\n${lines.join('\\n')}`\n}\n\n// ── mention validation ───────────────────────────────────────────────────\n//\n// This package owns BOTH ends of the mention path contract — it emits paths\n// from `createSandboxFileIndexRoute` and consumes them in `fileMentionsToParts`\n// / `buildMentionPromptBlock` — so the validation belongs here rather than in\n// each app that wires the pair up. A mention names a file that already exists\n// in the sandbox, so validation is a pure path/charset/count check with no\n// I/O: existence is proven later, when the agent reads the path and the turn\n// fails loudly if it is gone.\n\n/** Hard cap on mentions per turn. Bounds the prompt pointer block, the\n * persisted parts, and whatever media budget a dispatch draws from them. */\nexport const MENTION_MAX_COUNT = 16\n\n/** Longest mention display name accepted — bounds the pointer-block text and\n * the transcript pill label. */\nconst MAX_MENTION_NAME_LENGTH = 256\n/** Longest mention path accepted. */\nconst MAX_MENTION_PATH_LENGTH = 1024\n\n/** Represent the result of a sandbox mention path check indicating success or failure with an error message */\nexport type SandboxMentionPathCheck =\n | { succeeded: true }\n | { succeeded: false; error: string }\n\n/**\n * Validate a workspace-relative sandbox mention path. Rejects traversal (a\n * `..` path segment), absolute paths (leading `/`), backslashes, and null\n * bytes — the four ways a path picked in a client can escape the root the\n * index route scanned.\n *\n * Spaces and unicode are deliberately ALLOWED: in-box filenames are arbitrary,\n * and an ASCII-only charset would silently drop real files from a feature\n * whose whole job is naming them.\n */\nexport function validateSandboxMentionPath(path: unknown): SandboxMentionPathCheck {\n if (typeof path !== 'string' || path.length === 0) {\n return { succeeded: false, error: 'mention path must be a non-empty string' }\n }\n if (path.length > MAX_MENTION_PATH_LENGTH) {\n return { succeeded: false, error: `mention path must not exceed ${MAX_MENTION_PATH_LENGTH} characters` }\n }\n if (path.includes('\\0')) {\n return { succeeded: false, error: 'mention path must not contain null bytes' }\n }\n if (path.includes('\\\\')) {\n return { succeeded: false, error: 'mention path must not contain backslashes' }\n }\n if (path.startsWith('/')) {\n return { succeeded: false, error: 'mention path must be workspace-relative, not absolute' }\n }\n if (path.split('/').some((segment) => segment === '..')) {\n return { succeeded: false, error: 'mention path must not contain \"..\" segments' }\n }\n return { succeeded: true }\n}\n\nfunction parseFileMention(value: unknown, index: number): FileMention {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ChatTurnInputError(`mentions[${index}] must be an object`)\n }\n const record = value as Record<string, unknown>\n\n const pathCheck = validateSandboxMentionPath(record.path)\n if (!pathCheck.succeeded) throw new ChatTurnInputError(`mentions[${index}]: ${pathCheck.error}`)\n\n if (!isWorkspaceFileExportable(record.path as string)) {\n throw new ChatTurnInputError(`mentions[${index}]: file is not exportable`)\n }\n\n const name = record.name\n if (typeof name !== 'string' || !name.trim()) {\n throw new ChatTurnInputError(`mentions[${index}].name must be a non-empty string`)\n }\n if (name.length > MAX_MENTION_NAME_LENGTH) {\n throw new ChatTurnInputError(`mentions[${index}].name must not exceed ${MAX_MENTION_NAME_LENGTH} characters`)\n }\n\n const size = record.size\n if (size !== undefined) {\n if (typeof size !== 'number' || !Number.isFinite(size)) {\n throw new ChatTurnInputError(`mentions[${index}].size must be a finite number`)\n }\n if (size < 0) {\n throw new ChatTurnInputError(`mentions[${index}].size must not be negative`)\n }\n }\n\n return { path: record.path as string, name, ...(typeof size === 'number' ? { size } : {}) }\n}\n\n/**\n * Validates the untyped `mentions` array off the wire, mirroring\n * {@link parseChatTurnParts}: the typed list, or `ChatTurnInputError` (400)\n * naming the offending entry. Never sanitizes-and-continues — a traversal path\n * is a rejected request, not a trimmed one.\n *\n * A path repeated within one turn is deduped to its first occurrence rather\n * than rejected: mentioning the same file twice is plausible user input, not\n * an attack.\n */\nexport function parseFileMentions(raw: unknown): FileMention[] {\n if (raw === undefined || raw === null) return []\n if (!Array.isArray(raw)) throw new ChatTurnInputError('mentions must be an array')\n if (raw.length > MENTION_MAX_COUNT) {\n throw new ChatTurnInputError(`mentions must not exceed ${MENTION_MAX_COUNT} entries`)\n }\n\n const mentions: FileMention[] = []\n const seenPaths = new Set<string>()\n for (let index = 0; index < raw.length; index += 1) {\n const mention = parseFileMention(raw[index], index)\n if (seenPaths.has(mention.path)) continue\n seenPaths.add(mention.path)\n mentions.push(mention)\n }\n return mentions\n}\n\n/** Validates the untyped `parts` array off the wire. Returns the typed parts\n * or throws `ChatTurnInputError` (400) naming the offending entry. */\nexport function parseChatTurnParts(raw: unknown): ChatTurnFilePartInput[] {\n if (raw === undefined || raw === null) return []\n if (!Array.isArray(raw)) throw new ChatTurnInputError('parts must be an array')\n return raw.map((entry, index) => {\n const part = entry as Record<string, unknown> | null\n if (!part || typeof part !== 'object') {\n throw new ChatTurnInputError(`parts[${index}] must be an object`)\n }\n if (part.type !== 'image' && part.type !== 'file') {\n throw new ChatTurnInputError(`parts[${index}].type must be 'image' or 'file'`)\n }\n for (const key of ['filename', 'mediaType', 'url', 'path'] as const) {\n if (part[key] !== undefined && typeof part[key] !== 'string') {\n throw new ChatTurnInputError(`parts[${index}].${key} must be a string`)\n }\n }\n if (part.content !== undefined) {\n throw new ChatTurnInputError(`parts[${index}].content is not supported; provide a url or path`)\n }\n\n const url = typeof part.url === 'string' && part.url.length > 0 ? part.url : undefined\n const path = typeof part.path === 'string' && part.path.length > 0 ? part.path : undefined\n if (Boolean(url) === Boolean(path)) {\n throw new ChatTurnInputError(`parts[${index}] requires exactly one url or path`)\n }\n if (path && !path.startsWith('/')) {\n throw new ChatTurnInputError(`parts[${index}].path must be absolute`)\n }\n\n const filename = typeof part.filename === 'string' ? part.filename.trim() : undefined\n if (part.type === 'file' && !filename) {\n throw new ChatTurnInputError(`parts[${index}].filename is required for file parts`)\n }\n return {\n type: part.type,\n ...(filename ? { filename } : {}),\n ...(part.mediaType !== undefined ? { mediaType: part.mediaType as string } : {}),\n ...(url ? { url } : { path: path! }),\n }\n })\n}\n"],"mappings":";;;;;AA+BO,IAAM,uBAAuB;AAE7B,IAAM,sBAAsB;AAG5B,IAAM,mBAAmB;AA6BzB,IAAM,4BAA4D;AAAA,EACvE,UAAU;AAAA,EACV,WAAW;AACb;AAGO,SAAS,oBACd,OACA,SACA,OAA6E,CAAC,GAC9D;AAChB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA,GAAI,KAAK,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;AAAA,MAC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M,EAAE,IAAI,IAAI,EAAE,KAAY;AAAA,IACpC;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-ZVEEWGDK.js";
|
|
4
4
|
import {
|
|
5
5
|
mentionKindForPath
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-YHRWZZJN.js";
|
|
7
7
|
import {
|
|
8
8
|
persistedPartToPlan,
|
|
9
9
|
planToPersistedPart
|
|
@@ -135,4 +135,4 @@ export {
|
|
|
135
135
|
buildAttachmentPromptBlock,
|
|
136
136
|
historyContentWithAttachments
|
|
137
137
|
};
|
|
138
|
-
//# sourceMappingURL=chunk-
|
|
138
|
+
//# sourceMappingURL=chunk-YR6TZ777.js.map
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createChatTurnRoutes,
|
|
3
3
|
streamChatRouteAsSandboxEvents
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-N5M7YT6P.js";
|
|
5
5
|
import "../chunk-UTAIRVOK.js";
|
|
6
6
|
import "../chunk-RN4WPTBH.js";
|
|
7
7
|
import "../chunk-Q7WEEN7P.js";
|
|
8
8
|
import "../chunk-3NCPXNBZ.js";
|
|
9
|
-
import "../chunk-
|
|
9
|
+
import "../chunk-YR6TZ777.js";
|
|
10
10
|
import "../chunk-ZVEEWGDK.js";
|
|
11
|
-
import "../chunk-
|
|
11
|
+
import "../chunk-YHRWZZJN.js";
|
|
12
12
|
import "../chunk-TXD5HXLE.js";
|
|
13
13
|
import "../chunk-Z4RD5UF7.js";
|
|
14
14
|
import "../chunk-YG66IHDU.js";
|