@tangle-network/agent-app 4.0.49 → 4.0.51
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/chat-routes/index.js +7 -7
- package/dist/{chunk-EHUSCRLY.js → chunk-476ANSC4.js} +2 -2
- package/dist/{chunk-AOSQ5JCO.js → chunk-6GHEZFOB.js} +50 -35
- package/dist/chunk-6GHEZFOB.js.map +1 -0
- package/dist/{chunk-ORC66WNJ.js → chunk-LDORVR5O.js} +2 -2
- package/dist/{chunk-UQIPRKW4.js → chunk-MRZ63ZR5.js} +2 -2
- package/dist/{chunk-7JR5WWAP.js → chunk-OLUIYJCG.js} +5 -5
- package/dist/{chunk-AFSDGQIV.js → chunk-TWFYDZVA.js} +2 -2
- package/dist/{chunk-FIVFWLX7.js → chunk-YR4OHHQL.js} +12 -8
- package/dist/chunk-YR4OHHQL.js.map +1 -0
- package/dist/preset-cloudflare/index.js +3 -3
- package/dist/public-consultation/index.js +5 -5
- package/dist/runtime/index.js +2 -2
- package/dist/runtime/router-turn.d.ts +4 -0
- package/dist/runtime/router-turn.js +1 -1
- package/dist/sandbox/index.js +2 -2
- package/dist/turn-stream/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-AOSQ5JCO.js.map +0 -1
- package/dist/chunk-FIVFWLX7.js.map +0 -1
- /package/dist/{chunk-EHUSCRLY.js.map → chunk-476ANSC4.js.map} +0 -0
- /package/dist/{chunk-ORC66WNJ.js.map → chunk-LDORVR5O.js.map} +0 -0
- /package/dist/{chunk-UQIPRKW4.js.map → chunk-MRZ63ZR5.js.map} +0 -0
- /package/dist/{chunk-7JR5WWAP.js.map → chunk-OLUIYJCG.js.map} +0 -0
- /package/dist/{chunk-AFSDGQIV.js.map → chunk-TWFYDZVA.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/turn-stream/core.ts","../src/turn-stream/cancellation.ts","../src/chat-routes/stale-turn-lock.ts","../src/turn-stream/adapters.ts"],"sourcesContent":["/**\n * Channel tokens, lock records, workspace signals, and durable event keys.\n * Interactive turn replay belongs to the sandbox session gateway.\n * An optional turn-event backend stores durable rows and a running-turn index.\n * This core uses WebCrypto and plain data without a Cloudflare runtime import.\n */\n\nimport { base64UrlEncodeText, constantTimeEqual, hmacSha256Base64Url } from '../crypto/web-token'\n\n// ── events ──────────────────────────────────────────────────────────────────\n\n/** One event on a turn-stream channel. Workspace-signal events\n * (`thread.created`, `thread.activity`, product events) carry no `seq` —\n * ordering is delivery order on the DO's single-threaded event loop. */\nexport interface TurnStreamEvent {\n type: string\n data?: unknown\n timestamp: number\n seq?: never\n}\n\n// ── channel-bound capability tokens (issue #746) ─────────────────────────────\n//\n// The DO's endpoints are not publicly routed, but \"safe because nothing\n// forwards to it\" is convention, not enforcement: one accidental\n// `stub.fetch(publicRequest)` and every channel's lock, turn events, and\n// signals are cross-tenant writable. Every request the DO serves must now\n// carry a short-lived HMAC capability token minted for THIS DO's channel\n// name — a valid token for one channel is refused by every other, and a\n// token without the secret cannot exist. Worker code mints with the same\n// secret via the adapters (`authSecret`) and the WS upgrade forwarder;\n// nothing else needs to know the format.\n\n/** Default capability lifetime. Tokens are minted per worker request and\n * verified immediately; a WS token gates only the upgrade handshake — an\n * accepted socket lives until it closes. */\nexport const TURN_STREAM_TOKEN_TTL_MS = 60_000\n\n/** Request header the adapters attach (and the DO accepts). The worker also\n * attaches it when forwarding an authorized browser WebSocket handshake. */\nexport const TURN_STREAM_TOKEN_HEADER = 'x-turn-stream-token'\n\n/** Server-only control on an existing unnamed host; never a turn start endpoint. */\nexport const TURN_HOST_CANCEL_PATH = '/turn-host/cancel'\n/** The same host's server-owned connection revokes execution permission on reset. */\nexport const TURN_HOST_CONTROL_PATH = '/turn-host/control'\n\n/** Server control authority is separate from the channel capabilities used by existing viewer forwarders. */\nexport interface TurnStreamTokenClaims {\n purpose: 'turn-control' | 'turn-cancel' | 'turn-recovery'\n identity: TurnLockReleaseInput & { turnStreamId: string }\n}\n\nfunction encodeTurnStreamClaims(claims: TurnStreamTokenClaims): string {\n const { identity, purpose } = claims\n if (!['turn-control', 'turn-cancel', 'turn-recovery'].includes(purpose)\n || !identity || !['thread', 'workspace'].includes(identity.scope)\n || [identity.workspaceId, identity.threadId, identity.executionId, identity.lockId, identity.turnStreamId]\n .some(value => typeof value !== 'string' || !value.trim())) throw new Error('Invalid turn-stream control claims')\n return base64UrlEncodeText(JSON.stringify([purpose, identity.workspaceId, identity.threadId, identity.scope,\n identity.executionId, identity.lockId, identity.turnStreamId]))\n}\n\n/** Legacy v1 channel capabilities remain unchanged. Optional v2 claims bind\n * server-only purpose and exact owner identity inside the same signed payload. */\nexport async function mintTurnStreamToken(\n channelName: string,\n secret: string,\n now: () => number = Date.now,\n ttlMs: number = TURN_STREAM_TOKEN_TTL_MS,\n claims?: TurnStreamTokenClaims,\n): Promise<string> {\n if (!secret || secret.length < 32) throw new Error('turn-stream token secret must be at least 32 characters')\n const expiresAt = now() + ttlMs\n const payload = `${claims ? 'v2' : 'v1'}.${base64UrlEncodeText(channelName)}.${expiresAt.toString(36)}${claims ? `.${encodeTurnStreamClaims(claims)}` : ''}`\n return `${payload}.${await hmacSha256Base64Url(payload, secret)}`\n}\n\n/** Verify a token for `channelName`: constant-time MAC compare with the\n * exact channel name embedded in the signed payload, plus freshness. A\n * token minted for any other channel — or a tampered expiry — is false. */\nexport async function verifyTurnStreamToken(\n channelName: string,\n token: string,\n secret: string,\n now: () => number = Date.now,\n claims?: TurnStreamTokenClaims,\n): Promise<boolean> {\n if (!secret || secret.length < 32) return false\n const parts = token.split('.')\n const version = parts[0]\n if (!(version === 'v1' && parts.length === 4 || version === 'v2' && parts.length === 5)) return false\n const name = parts[1]!\n const expires36 = parts[2]!\n const mac = parts.at(-1)!\n if (claims) {\n try { if (version !== 'v2' || parts[3] !== encodeTurnStreamClaims(claims)) return false }\n catch { return false }\n }\n if (name !== base64UrlEncodeText(channelName)) return false\n if (!/^[0-9a-z]+$/.test(expires36)) return false\n const expiresAt = parseInt(expires36, 36)\n if (!Number.isSafeInteger(expiresAt) || expiresAt <= now()) return false\n const expected = await hmacSha256Base64Url(parts.slice(0, -1).join('.'), secret)\n return constantTimeEqual(mac, expected)\n}\n\n// ── channel keys ────────────────────────────────────────────────────────────\n//\n// One DO instance per channel key. Five families:\n// thread `${workspaceId}:${threadId}` — thread viewer signals.\n// workspace `${workspaceId}` — sidebar activity + thread.created\n// + every turn lock: the workspace-scope lock and each\n// thread-scope lock, under separate storage keys.\n// turn `turn:${turnId}` — durable turn-event rows + status\n// (the TurnEventStore contract; replay survives DO eviction).\n// scope `scope:${scopeId}` — running-turn index for a thread,\n// backing `TurnEventStore.listRunning`.\n// turn host `turn-host:${objectId}` — the capability of an unnamed\n// per-turn object that runs one chat turn (`forwardTurnToHost`).\n\n/** Define the scope level for acquiring a turn lock within thread or workspace contexts */\nexport type TurnLockScope = 'thread' | 'workspace'\n\n/** Channel for a thread's viewer signals. */\nexport function threadChannelKey(workspaceId: string, threadId: string): string {\n return `${workspaceId}:${threadId}`\n}\n\n/** Channel for workspace signals and the workspace-scoped lock. */\nexport function workspaceChannelKey(workspaceId: string): string {\n return workspaceId\n}\n\n/** The channel a lock lives on: the workspace channel, for both scopes.\n * Workspace-scope locks serialize every thread in the workspace (one shared\n * sandbox) and thread-scope locks serialize one thread (router lane); they\n * stay independent because each has its own storage key\n * ({@link turnLockStorageKey}). A thread lock on its own channel created a\n * new Durable Object on every thread's first turn, 0.8-1.9 s inside Creative's\n * admission on staging against an object that already exists. */\nexport function turnLockChannelKey(workspaceId: string, _threadId: string, _scope: TurnLockScope): string {\n return workspaceChannelKey(workspaceId)\n}\n\n/** The storage key a lock lives under inside its channel's instance: the\n * workspace-scope lock under `TURN_STREAM_STORAGE_KEYS.lock`, each thread's\n * lock under `TURN_STREAM_STORAGE_KEYS.threadLockPrefix` + its thread id. */\nexport function turnLockStorageKey(scope: TurnLockScope, threadId: string): string {\n return scope === 'workspace' ? TURN_STREAM_STORAGE_KEYS.lock : `${TURN_STREAM_STORAGE_KEYS.threadLockPrefix}${threadId}`\n}\n\n/** Channel for the optional Durable Object turn-event backend. */\nexport function turnStorageChannelKey(turnId: string): string {\n return `turn:${turnId}`\n}\n\n/** Running-turn index for the optional Durable Object turn-event backend. */\nexport function scopeIndexChannelKey(scopeId: string): string {\n return `scope:${scopeId}`\n}\n\n/** The capability name of a per-turn object, which `newUniqueId` leaves without a channel name. */\nexport function turnHostChannelKey(objectId: string): string {\n return `turn-host:${objectId}`\n}\n\n/** Recent thread-created markers kept for late-connecting sidebars. */\nexport const MAX_RECENT_CREATED = 50\n\n/** A responding marker older than this is treated as stale, so a dropped\n * `end` broadcast can't leave a permanently-stuck \"responding\" dot. */\nexport const ACTIVITY_TTL_MS = 15 * 60 * 1000\n\n/** Remove responding markers older than ttlMs; return their thread IDs. */\nexport function pruneStaleThreads(active: Map<string, number>, now: number, ttlMs: number): string[] {\n const removed: string[] = []\n for (const [threadId, startedAt] of active) {\n if (now - startedAt > ttlMs) {\n active.delete(threadId)\n removed.push(threadId)\n }\n }\n return removed\n}\n\n// ── chat-turn lock record + fences ──────────────────────────────────────────\n\n/** Fallback lifetime for an unreleased lock. Use stale-lock reconciliation to\n * recover earlier when execution state proves that its holder stopped. */\nexport const TURN_LOCK_TTL_MS = 30 * 60 * 1000\n\n/** The stored single-flight lock. Field-compatible with the reference\n * consumer's `ChatTurnLock` so adoption is a swap, not a migration. */\nexport interface DurableTurnLock {\n workspaceId: string\n threadId: string\n scope: TurnLockScope\n executionId: string\n lockId: string\n startedAt: number\n expiresAt: number\n turnId?: string\n /** The turn released this lock, but a product-owned post-turn task (e.g.\n * file persistence reading the box) is still running, so the release is\n * parked on the lock until the task settles. Written only through the DO's\n * defer seam — the base package never sets it on its own. */\n releasePending?: boolean\n /** Optional Router control, owned by this exact lock generation. Stop never releases the lock. */\n cancellation?: { turnStreamId: string; requestedAt?: number }\n}\n\n/** Define input parameters required to acquire a turn-based lock in a workspace thread */\nexport interface TurnLockAcquireInput {\n workspaceId: string\n threadId: string\n scope: TurnLockScope\n executionId: string\n lockId: string\n turnId?: string\n cancellation?: { turnStreamId: string }\n}\n\n/** Resolve the result of attempting to acquire a turn lock indicating success or active lock status */\nexport type TurnLockAcquireResult =\n | { acquired: true; lock: DurableTurnLock }\n | { acquired: false; active: DurableTurnLock }\n\n/** Define input parameters required to release a turn lock in a specific workspace thread */\nexport interface TurnLockReleaseInput {\n workspaceId: string\n threadId: string\n scope: TurnLockScope\n executionId: string\n lockId: string\n}\n\n/** Fenced out-of-band release (stop button, stale-lock reconciliation). The\n * fences make it refuse a SUCCESSOR lock: `interruptedAt` must not precede\n * the lock's own start, and when either side names a turn, both must name\n * the same one. */\nexport interface TurnLockInterruptedReleaseInput {\n workspaceId: string\n threadId: string\n /** Try only this scope; omit to try workspace then thread. */\n scope?: TurnLockScope\n interruptedAt: number\n turnId?: string\n /** Only after the existing stale policy positively proves this exact Router owner and its children abandoned. */\n recovery?: TurnLockReleaseInput & { turnStreamId: string }\n}\n\n/** `stored` is what the DO read from storage; expired locks are dead. */\nexport function activeTurnLock(stored: DurableTurnLock | undefined, now: number): DurableTurnLock | null {\n if (!stored) return null\n // Locks written before the scope field existed default to thread scope.\n const lock = stored.scope ? stored : { ...stored, scope: 'thread' as const }\n return lock.expiresAt > now ? lock : null\n}\n\n/** Create a durable turn lock object with timing and scope based on input parameters */\nexport function createTurnLock(input: TurnLockAcquireInput, now: number, ttlMs = TURN_LOCK_TTL_MS): DurableTurnLock {\n return {\n workspaceId: input.workspaceId,\n threadId: input.threadId,\n scope: input.scope,\n executionId: input.executionId,\n lockId: input.lockId,\n startedAt: now,\n expiresAt: now + ttlMs,\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.cancellation ? { cancellation: { turnStreamId: input.cancellation.turnStreamId } } : {}),\n }\n}\n\n/** A cooperative release matches the execution and, when supplied, lock ID. */\nexport function turnLockMatchesRelease(\n active: DurableTurnLock,\n input: { executionId: string; lockId?: string },\n): boolean {\n if (active.executionId !== input.executionId) return false\n if (input.lockId && active.lockId !== input.lockId) return false\n return true\n}\n\n/**\n * The interrupted/stale release fence. `interruptedAt` is the instant the\n * releasing evidence was observed (the stop click, the stale-lock probe) —\n * a lock STARTED after that instant is a successor the evidence says nothing\n * about, so it survives. When the lock recorded a client turnId, the release\n * must name the same turn; a lock without one refuses a turn-specific\n * release (it cannot prove it is that turn).\n */\nexport function interruptedReleaseApplies(\n active: DurableTurnLock,\n input: { threadId: string; interruptedAt: number; turnId?: string },\n): boolean {\n if (active.threadId !== input.threadId) return false\n if (active.startedAt > input.interruptedAt) return false\n if (active.turnId) {\n if (active.turnId !== input.turnId) return false\n } else if (input.turnId) {\n return false\n }\n return true\n}\n\n// ── wire contract (adapter ↔ DO endpoint paths) ─────────────────────────────\n//\n// Kept byte-identical to the reference consumer's DO where an endpoint\n// existed there, so a product deletes its fork by re-pointing a binding, not\n// by re-speaking a protocol.\n\n/** Provide constant paths for managing chat turn streams and locks */\nexport const TURN_STREAM_PATHS = {\n broadcast: '/broadcast',\n lockAcquire: '/chat-turn-lock/acquire',\n /** Read the active lock without changing it; also brings the object up before a turn needs it. */\n lockPeek: '/chat-turn-lock/peek',\n lockRelease: '/chat-turn-lock/release',\n lockPark: '/chat-turn-lock/park',\n lockReleaseInterrupted: '/chat-turn-lock/release-interrupted',\n turnEventsAppend: '/turn-events/append',\n turnEventsRead: '/turn-events/read',\n turnStatusSet: '/turn-status/set',\n turnStatusGet: '/turn-status/get',\n scopeStatusSet: '/turn-scope/set',\n scopeRunningList: '/turn-scope/running',\n} as const\n\n/** Storage keys inside a DO instance. Exported for subclass coexistence —\n * a product extending the DO must not collide with these. */\nexport const TURN_STREAM_STORAGE_KEYS = {\n lock: 'chatTurnLock',\n threadLockPrefix: 'chatTurnLock:thread:',\n activeThreads: 'activeThreads',\n turnStatus: 'turnStatus',\n turnScope: 'turnScopeIndex',\n turnEventPrefix: 'turnEvent:',\n} as const\n\n/** Zero-padded seq so DO storage `list({ prefix })` returns rows in replay\n * order without a sort. 10 digits holds any realistic turn. */\nexport function turnEventStorageKey(seq: number): string {\n return `${TURN_STREAM_STORAGE_KEYS.turnEventPrefix}${String(seq).padStart(10, '0')}`\n}\n","import type { TurnStreamAuth, TurnStreamNamespaceLike } from './adapters'\nimport { TURN_HOST_CANCEL_PATH, TURN_HOST_CONTROL_PATH, TURN_STREAM_PATHS, TURN_STREAM_TOKEN_HEADER, mintTurnStreamToken, turnHostChannelKey, turnLockChannelKey } from './core'\nimport type { TurnHostControlTarget } from '../chat-routes/turn-progress'\nexport type { TurnHostControlTarget } from '../chat-routes/turn-progress'\nimport type { TurnCancellationIdentity } from './cancellation-do'\nexport type { TurnCancellationIdentity } from './cancellation-do'\n\n/** Per-owner observation only. Closing it never changes or releases the durable lock. */\nexport interface TurnCancellationConnection {\n signal: AbortSignal\n close(): void\n}\n\ninterface ControlSocket extends EventTarget {\n accept(): void\n send(value: string): void\n close(code?: number, reason?: string): void\n}\n\nexport class TurnCancellationRequestedError extends Error {\n readonly code = 'turn_cancel_requested'\n constructor() { super('Cancellation was requested for this turn'); this.name = 'TurnCancellationRequestedError' }\n}\n\nexport class TurnControlUnavailableError extends Error {\n readonly code = 'turn_control_unavailable'\n constructor(message = 'The durable turn control connection was lost') { super(message); this.name = 'TurnControlUnavailableError' }\n}\n\n/** Unique-id reconstruction is required; idFromName(hostId) addresses a different object. */\nexport interface TurnHostControlNamespace extends TurnStreamNamespaceLike {\n idFromString(id: string): unknown\n}\n\n/** Call only after product identity/editor/actual-thread authorization. A positive\n * result accepts intent for this live invocation, not settlement or future replay\n * suppression. A stale/unknown host is never started and cannot select a successor. */\nexport async function requestHostedTurnCancellation(namespace: TurnHostControlNamespace, target: TurnHostControlTarget,\n auth: TurnStreamAuth,\n): Promise<{ requested: boolean; reason?: 'stale-host' }> {\n const response = await hostedCancellationRequest(namespace, target, auth, false)\n if (!response) return { requested: false, reason: 'stale-host' }\n if (!response.ok) throw new Error(`Hosted turn cancellation failed (HTTP ${response.status})`)\n return response.json()\n}\n\n/** Owned by the original hosted request, never its browser. Socket loss revokes\n * permission even when an old storage-free HTTP invocation survives a DO reset. */\nexport async function connectHostedTurnCancellation(namespace: TurnHostControlNamespace, target: TurnHostControlTarget,\n auth: TurnStreamAuth,\n): Promise<TurnCancellationConnection> {\n const response = await hostedCancellationRequest(namespace, target, auth, true)\n if (!response) throw new TurnControlUnavailableError('The host id is invalid')\n return observeCancellationSocket(response)\n}\n\nasync function hostedCancellationRequest(namespace: TurnHostControlNamespace, target: TurnHostControlTarget,\n auth: TurnStreamAuth, upgrade: boolean,\n): Promise<Response | null> {\n let id: unknown\n try { id = namespace.idFromString(target.hostId) }\n catch { return null }\n const url = new URL(`https://turn-stream.internal${upgrade ? TURN_HOST_CONTROL_PATH : TURN_HOST_CANCEL_PATH}`)\n if (upgrade) for (const [key, value] of Object.entries(target)) if (value !== undefined) url.searchParams.set(key, value)\n return namespace.get(id).fetch(url.href, {\n method: upgrade ? 'GET' : 'POST', headers: { ...(upgrade ? { Upgrade: 'websocket' } : { 'Content-Type': 'application/json' }),\n [TURN_STREAM_TOKEN_HEADER]: await mintTurnStreamToken(turnHostChannelKey(target.hostId), auth.secret) },\n ...(upgrade ? {} : { body: JSON.stringify(target) }),\n })\n}\n\nasync function cancellationRequest(namespace: TurnStreamNamespaceLike, identity: TurnCancellationIdentity,\n auth: TurnStreamAuth, upgrade: boolean,\n) {\n const key = turnLockChannelKey(identity.workspaceId, identity.threadId, identity.scope)\n const url = new URL(`https://turn-stream.internal${upgrade ? '/' : TURN_STREAM_PATHS.lockReleaseInterrupted}`)\n const headers = new Headers({ [TURN_STREAM_TOKEN_HEADER]: await mintTurnStreamToken(key, auth.secret, undefined, undefined,\n { purpose: upgrade ? 'turn-control' : 'turn-cancel', identity }) })\n if (upgrade) {\n for (const [name, value] of Object.entries(identity)) url.searchParams.set(name, value)\n url.searchParams.set('sessionId', identity.threadId)\n url.searchParams.set('cancellation', '1')\n headers.set('Upgrade', 'websocket')\n } else headers.set('Content-Type', 'application/json')\n return namespace.get(namespace.idFromName(key)).fetch(url.href, { method: upgrade ? 'GET' : 'POST', headers,\n ...(upgrade ? {} : { body: JSON.stringify({ ...identity, cancel: true }) }) })\n}\n\n/** The product authorizes Stop first. This exact fenced request records intent; it never claims work stopped. */\nexport async function requestDurableTurnCancellation(namespace: TurnStreamNamespaceLike, identity: TurnCancellationIdentity,\n auth: TurnStreamAuth,\n): Promise<{ requested: boolean; reason?: 'stale-owner' }> {\n const response = await cancellationRequest(namespace, identity, auth, false)\n if (!response.ok) throw new Error(`Turn cancellation failed (HTTP ${response.status})`)\n return response.json()\n}\n\n/** One server-owned connection on the existing authenticated DO transport, with retained cancellation replay. */\nexport async function connectDurableTurnCancellation(namespace: TurnStreamNamespaceLike, identity: TurnCancellationIdentity,\n auth: TurnStreamAuth,\n): Promise<TurnCancellationConnection> {\n return observeCancellationSocket(await cancellationRequest(namespace, identity, auth, true))\n}\n\n/** Shared retained-intent handshake and fail-closed socket lifecycle for both existing owners. */\nasync function observeCancellationSocket(response: Response & { webSocket?: ControlSocket }): Promise<TurnCancellationConnection> {\n if (response.status !== 101 || !response.webSocket) throw new TurnControlUnavailableError(`Turn control connection failed (HTTP ${response.status})`)\n const socket = response.webSocket\n const controller = new AbortController()\n let closing = false\n let ready = false\n let resolveReady!: () => void\n let rejectReady!: (error: Error) => void\n const connected = new Promise<void>((resolve, reject) => { resolveReady = resolve; rejectReady = reject })\n const fail = () => {\n if (closing) return\n const error = new TurnControlUnavailableError()\n if (!ready) rejectReady(error)\n controller.abort(error)\n }\n const close = () => { closing = true; clearTimeout(timer); try { socket.close(1000, 'Owner observation ended') } catch { /* Already closed. */ } }\n const timer = setTimeout(() => { if (!ready) { fail(); close() } }, 10_000)\n socket.addEventListener('message', event => {\n let message: { type?: string; cancellationRequested?: boolean }\n try { message = JSON.parse(String((event as MessageEvent).data)) } catch { fail(); close(); return }\n if (message.type === 'turn.control.released') {\n // A normal owner closes before its own cooperative release. Any release\n // still observed here removes this producer's authority to continue I/O.\n fail()\n close(); return\n }\n if (message.type === 'turn.control.ownership-lost') { fail(); close(); return }\n if (message.type !== 'turn.control' || typeof message.cancellationRequested !== 'boolean') { fail(); close(); return }\n if (message.cancellationRequested) controller.abort(new TurnCancellationRequestedError())\n ready = true\n clearTimeout(timer)\n resolveReady()\n })\n socket.addEventListener('close', fail)\n socket.addEventListener('error', fail)\n try { socket.accept(); socket.send(JSON.stringify({ type: 'sync' })); await connected }\n catch (error) { close(); throw error }\n return { signal: controller.signal, close }\n}\n","import type { TurnCancellationIdentity } from '../turn-stream/cancellation'\n\n/**\n * Recovery policy for a `ChatTurnLock` whose holder died.\n *\n * `createChatTurnRoutes` takes the lock as a seam (`acquire`/`release`) and a\n * lock is a single-flight guard: while it is held, a second turn on the same\n * scope is refused. Products give it a TTL measured in tens of minutes, so a\n * turn that dies without releasing wedges chat for that whole window. Every\n * app on the seam inherits that wedge, which is why the way OUT of it is\n * policy this package owns rather than something each app rediscovers.\n *\n * The policy takes PROBES, not clients: it imports no sandbox SDK, opens no\n * connection, and knows nothing about how a product finds its box or talks to\n * a sidecar. That is what makes the rules testable and what keeps the concrete\n * probes — which box key, which session id, which sidecar endpoint — in the\n * product.\n *\n * A supplied exact Router owner probe replaces the native rules: live and\n * unknown hold; positive outer + child abandonment observes the same terminal\n * grace and exact release fence. A native session cannot attest to a Router owner.\n *\n * The native rules, in precedence order:\n *\n * 1. The session probe answered and the execution is TERMINAL ⇒ release, once\n * the lock is past a short grace period. The authority on \"is this turn\n * still running\" is whatever is actually running it; a terminal verdict is\n * proof the lock outlived its turn — but only if the verdict is about THIS\n * turn, which is what the grace buys (see\n * {@link DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS}).\n * 2. The session probe answered and the execution is LIVE ⇒ hold, always.\n * Nothing below may override this. The lock is doing exactly its job.\n * 3. The probes could not reach that authority at all — the sandbox could not\n * be listed, is gone, is not running, or its session probe failed ⇒ fall\n * back on the physical argument: an execution runs INSIDE the box, so a box\n * that is not there is running nothing, and the lock is releasable. Without\n * this fallback the recovery would depend on the very subsystem whose\n * failure produced the stale lock.\n *\n * Rule 3 is gated on a grace period because it is an inference, not an\n * observation — see {@link DEFAULT_STALE_TURN_LOCK_GRACE_MS}.\n */\n\n/** Where the box is, as far as the caller can see. `state` on `not-running`\n * is the platform's own status string, carried through for the log. */\nexport type StaleTurnLockSandboxProbeResult =\n | { status: 'running' }\n | { status: 'absent' }\n | { status: 'not-running'; state?: string }\n\n/** What the thing running the turn says about it. `terminal: false` means an\n * execution is LIVE — the strongest signal in the policy. `diagnostics` rides\n * through to the result and the logs unread. */\nexport type StaleTurnLockSessionProbeResult =\n | { reachable: true; terminal: boolean; diagnostics?: Record<string, unknown> }\n | { reachable: false; reason?: string }\n\n/** A positive abandoned verdict covers the exact outer producer and every registered child/effect owner. */\nexport interface StaleTurnLockOwnerProbeResult {\n identity: TurnCancellationIdentity\n status: 'live' | 'abandoned' | 'unknown'\n diagnostics?: Record<string, unknown>\n}\n\n/**\n * Minimum age a lock must reach before the \"sandbox unreachable ⇒ nothing can\n * be running\" fallback may force-release it.\n *\n * The lock is acquired BEFORE the box is ensured, so during a cold workspace's\n * first turn there is a real window in which the lock is held and no box exists\n * yet — indistinguishable, from a peek, from a box that vanished. The grace\n * period has to outlast that window (create + bootstrap + whatever the product\n * hydrates) or a concurrent request steals the lock from a turn that is merely\n * still provisioning. Five minutes clears observed cold starts with room to\n * spare while cutting the worst case from a TTL-length wedge down to five\n * minutes. Raising it makes recovery slower; lowering it risks stealing a lock\n * mid-provision.\n */\nexport const DEFAULT_STALE_TURN_LOCK_GRACE_MS = 5 * 60 * 1000\n\n/**\n * Minimum age a lock must reach before a TERMINAL session verdict may release\n * it.\n *\n * The session probe is keyed on the THREAD, not on the execution the lock\n * holds: a sidecar that has nothing running reports `terminal` with\n * `activeExecutionId: null`, so there is no id to match the lock against. The\n * lock, meanwhile, is acquired BEFORE the box is ensured and before the\n * execution registers with the sidecar. Between those two moments a second\n * request that reconciles the lock asks the sidecar about a turn it has not\n * heard of yet and gets back the PREVIOUS turn's terminal state — proof about\n * the wrong execution. Releasing on that verdict hands the second request a\n * lock the first one is still using, which is two concurrent turns on a scope\n * whose single-flight guard just voted for itself.\n *\n * One minute covers the acquire → box-ensure → sidecar-registration window on\n * a warm box (the cold-box case is Rule 3's, and has its own, much longer\n * grace). Deliberately NOT\n * {@link DEFAULT_STALE_TURN_LOCK_GRACE_MS}: this branch has a positive\n * observation behind it, so it should recover fast, and stretching it to five\n * minutes would leave a genuinely dead turn wedged for the whole window that\n * the session probe exists to shortcut. Raising it delays recovery from a\n * crashed turn; lowering it narrows the registration window it protects.\n */\nexport const DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS = 60 * 1000\n\n/** Resolve options for probing and releasing stale TURN locks based on lock start time and sandbox state */\nexport interface ReconcileStaleTurnLockOptions {\n /** When the held lock was acquired (epoch ms). The grace period is measured\n * from here, so it must be the LOCK's start, not the turn's. */\n lockStartedAt: number\n /** Router ownership replaces native-only inference. Missing/uncertain outer or child evidence must stay unknown. */\n owner?: {\n identity: TurnCancellationIdentity\n probe(identity: TurnCancellationIdentity): Promise<StaleTurnLockOwnerProbeResult>\n }\n /** Is the box there and running? Never provisions — a peek, not an ensure.\n * A throw is treated as unreachable, same as `absent`. */\n probeSandbox(): Promise<StaleTurnLockSandboxProbeResult>\n /** Ask the running box whether the execution is still live. Only called when\n * `probeSandbox` reported `running`. A throw is treated as unreachable. */\n probeSession(): Promise<StaleTurnLockSessionProbeResult>\n /** Release the lock, fenced by the instant the releasing evidence was\n * observed. `fence.observedAt` is snapshotted BEFORE the probe that\n * justified the release, so a store that can compare it against the held\n * lock's start refuses to delete a SUCCESSOR lock acquired while the probe\n * was in flight. A store that cannot make that comparison may ignore the\n * fence, but must not substitute its own `Date.now()` — that timestamp is\n * by construction newer than any successor and makes the check vacuous.\n *\n * Returns whether the release actually landed — `false` when the lock was\n * already gone (someone else got there first), which is reported, never\n * treated as a release. */\n release(fence: { observedAt: number }): boolean | Promise<boolean>\n /** Override {@link DEFAULT_STALE_TURN_LOCK_GRACE_MS} (Rule 3's fallback). */\n graceMs?: number\n /** Override {@link DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS} (Rule 1's release). */\n terminalGraceMs?: number\n /** Identity fields merged into every log line (workspace, thread, execution\n * id — whatever makes the entry findable in the product's logs). */\n context?: Record<string, unknown>\n /** Defaults to `console.warn`. Both the withheld and the force-released\n * branches log; a force-release is never silent. */\n log?(message: string, meta: Record<string, unknown>): void\n /** Injectable clock, for tests. */\n now?(): number\n}\n\n/** Describe the outcome of reconciling a stale turn lock including release status and diagnostics */\nexport interface ReconcileStaleTurnLockResult {\n released: boolean\n /** Why the policy decided what it did — the probe's own diagnostics on the\n * reachable path, the unreachable reason and lock age on the fallback. */\n diagnostics: Record<string, unknown>\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/**\n * Decide whether a held lock is stale and, if so, release it.\n *\n * Never provisions and never mutates anything but the lock: a reconciliation\n * attempt on a cold workspace leaves it cold.\n */\nexport async function reconcileStaleTurnLock(\n options: ReconcileStaleTurnLockOptions,\n): Promise<ReconcileStaleTurnLockResult> {\n if (options.owner) return reconcileTurnOwner(options)\n // Snapshot the clock BEFORE the probes and use that one instant for BOTH the\n // grace decision and the release fence on every branch: the release is only\n // valid against the lock as it was when the state was observed, not after an\n // arbitrarily slow round trip. Re-reading the clock after a probe would let a\n // slow round trip age the lock past the grace on paper, and would hand the\n // store a fence newer than a successor lock acquired meanwhile.\n const observedAt = (options.now ?? Date.now)()\n let sandbox: StaleTurnLockSandboxProbeResult\n try {\n sandbox = await options.probeSandbox()\n } catch (err) {\n return forceReleaseUnreachable(options, observedAt, {\n unreachableReason: 'SANDBOX_PROBE_FAILED',\n unreachableDetail: messageOf(err),\n })\n }\n if (sandbox.status !== 'running') {\n return forceReleaseUnreachable(options, observedAt, {\n unreachableReason: sandbox.status === 'absent' ? 'SANDBOX_ABSENT' : 'SANDBOX_NOT_RUNNING',\n ...(sandbox.status === 'not-running' && sandbox.state !== undefined\n ? { sandboxState: sandbox.state }\n : {}),\n })\n }\n\n let session: StaleTurnLockSessionProbeResult\n try {\n session = await options.probeSession()\n } catch (err) {\n return forceReleaseUnreachable(options, observedAt, {\n unreachableReason: 'SESSION_PROBE_FAILED',\n unreachableDetail: messageOf(err),\n })\n }\n if (!session.reachable) {\n return forceReleaseUnreachable(options, observedAt, {\n unreachableReason: 'SESSION_UNREACHABLE',\n ...(session.reason !== undefined ? { sessionProbeError: session.reason } : {}),\n })\n }\n\n const diagnostics: Record<string, unknown> = {\n sandboxReachable: true,\n sessionTerminal: session.terminal,\n ...(session.diagnostics ?? {}),\n }\n // The authority answered and says the execution is live: the lock is doing\n // its job. Nothing below this point may override that.\n if (!session.terminal) return { released: false, diagnostics }\n\n // Terminal, but about WHICH execution? The probe is thread-keyed, so a lock\n // younger than the registration window may be reading the previous turn's\n // verdict — hold until it is old enough that the verdict has to be its own.\n const terminalGraceMs = options.terminalGraceMs ?? DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS\n const lockAgeMs = observedAt - options.lockStartedAt\n if (lockAgeMs < terminalGraceMs) {\n const log = options.log ?? ((message, meta) => console.warn(message, meta))\n const withheld = {\n ...diagnostics,\n lockAgeMs,\n terminalReleaseGraceMs: terminalGraceMs,\n terminalReleaseWithheld: 'LOCK_WITHIN_TERMINAL_GRACE_PERIOD',\n }\n log('[chat-routes] stale turn lock held: terminal verdict but lock is younger than the registration window', {\n ...(options.context ?? {}),\n ...withheld,\n })\n return { released: false, diagnostics: withheld }\n }\n\n const released = await options.release({ observedAt })\n return {\n released,\n diagnostics: { ...diagnostics, lockAgeMs, terminalReleaseGraceMs: terminalGraceMs, released, observedAt },\n }\n}\n\nasync function reconcileTurnOwner(options: ReconcileStaleTurnLockOptions): Promise<ReconcileStaleTurnLockResult> {\n const owner = options.owner!\n // The observation fence is captured before the authority read, as on the native path.\n const observedAt = (options.now ?? Date.now)()\n let evidence: StaleTurnLockOwnerProbeResult\n try { evidence = await owner.probe(owner.identity) }\n catch (error) { return { released: false, diagnostics: { ownerStatus: 'unknown', ownerProbeError: messageOf(error) } } }\n const keys = ['workspaceId', 'threadId', 'scope', 'executionId', 'lockId', 'turnStreamId'] as const\n if (!evidence?.identity || keys.some(key => evidence.identity[key] !== owner.identity[key])) {\n return { released: false, diagnostics: { ownerStatus: 'unknown', releaseWithheld: 'OWNER_IDENTITY_MISMATCH' } }\n }\n const status = evidence.status === 'abandoned' || evidence.status === 'live' ? evidence.status : 'unknown'\n const diagnostics = { ...(evidence.diagnostics ?? {}), ownerStatus: status }\n if (status !== 'abandoned') return { released: false, diagnostics }\n const terminalGraceMs = options.terminalGraceMs ?? DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS\n const lockAgeMs = observedAt - options.lockStartedAt\n if (lockAgeMs < terminalGraceMs) return { released: false, diagnostics: {\n ...diagnostics, lockAgeMs, terminalReleaseGraceMs: terminalGraceMs, releaseWithheld: 'LOCK_WITHIN_TERMINAL_GRACE_PERIOD',\n } }\n const released = await options.release({ observedAt })\n return { released, diagnostics: { ...diagnostics, lockAgeMs, terminalReleaseGraceMs: terminalGraceMs, observedAt, released } }\n}\n\n/**\n * The fallback: the session authority could not attest to the execution's\n * state because the box is gone, stopped, or unreachable. Release the lock\n * once it is old enough that it cannot belong to a turn still provisioning its\n * box — and say so either way, with the reason, the lock's age, and the grace\n * period it was measured against.\n *\n * The caller's pre-probe clock read (`observedAt`) serves as the age gate AND\n * the release fence here too, exactly as on the terminal branch.\n */\nasync function forceReleaseUnreachable(\n options: ReconcileStaleTurnLockOptions,\n observedAt: number,\n reason: Record<string, unknown> & { unreachableReason: string },\n): Promise<ReconcileStaleTurnLockResult> {\n const log = options.log ?? ((message, meta) => console.warn(message, meta))\n const graceMs = options.graceMs ?? DEFAULT_STALE_TURN_LOCK_GRACE_MS\n const lockAgeMs = observedAt - options.lockStartedAt\n const diagnostics: Record<string, unknown> = {\n ...reason,\n sandboxReachable: false,\n lockAgeMs,\n forceReleaseGraceMs: graceMs,\n }\n\n if (lockAgeMs < graceMs) {\n log('[chat-routes] stale turn lock held: sandbox unreachable but lock is inside the grace period', {\n ...(options.context ?? {}),\n ...diagnostics,\n })\n return { released: false, diagnostics: { ...diagnostics, forceReleaseWithheld: 'LOCK_WITHIN_GRACE_PERIOD' } }\n }\n\n const released = await options.release({ observedAt })\n log('[chat-routes] force-released stale turn lock: sandbox unreachable, no turn can be executing', {\n ...(options.context ?? {}),\n ...diagnostics,\n released,\n })\n return { released, diagnostics: { ...diagnostics, forceReleased: released } }\n}\n","/**\n * Worker adapters for durable turn storage, single-flight locks, workspace signals, and turns hosted in an object.\n * Namespace interfaces remain structural so Cloudflare bindings and the memory harness\n * run the same authenticated request path.\n * Products provide workspace authorization and their binding's TURN_STREAM_AUTH_SECRET.\n */\n\nimport { connectDurableTurnCancellation, type TurnCancellationConnection, type TurnCancellationIdentity } from './cancellation'\nimport { reconcileStaleTurnLock, type ReconcileStaleTurnLockOptions, type StaleTurnLockOwnerProbeResult } from '../chat-routes/stale-turn-lock'\nimport type { TurnEventStore, TurnStatus } from '../stream/turn-buffer'\nimport {\n TURN_STREAM_PATHS,\n TURN_STREAM_TOKEN_HEADER,\n mintTurnStreamToken,\n scopeIndexChannelKey,\n turnHostChannelKey,\n turnLockChannelKey,\n turnStorageChannelKey,\n workspaceChannelKey,\n type DurableTurnLock,\n type TurnLockAcquireResult,\n type TurnLockReleaseInput,\n type TurnLockInterruptedReleaseInput,\n type TurnLockScope,\n type TurnStreamEvent,\n type TurnStreamTokenClaims,\n} from './core'\n\n// ── structural namespace ────────────────────────────────────────────────────\n\n/** Resolve a stub interface for handling fetch requests with optional initialization parameters */\nexport interface TurnStreamStubLike {\n fetch(input: Request | string, init?: RequestInit): Promise<Response>\n}\n\n/** Cloudflare placement hints. A hint affects only a channel's first creation, never an existing object's location. */\nexport type TurnStreamLocationHint = 'wnam' | 'enam' | 'sam' | 'weur' | 'eeur' | 'apac' | 'apac-ne' | 'apac-se' | 'oc' | 'afr' | 'me'\n\n/** The default matches the application D1 region unless its binding descriptor names another region. */\nexport const DEFAULT_TURN_LOCK_LOCATION_HINT: TurnStreamLocationHint = 'enam'\n\n/** The surface of `DurableObjectNamespace` the adapters use. */\nexport interface TurnStreamNamespaceLike {\n idFromName(name: string): unknown\n get(id: unknown, options?: { locationHint?: string }): TurnStreamStubLike\n}\n\nconst INTERNAL_ORIGIN = 'https://turn-stream.internal'\n\n/** The HMAC secret shared between this worker and its `TurnStreamDO` binding.\n * Every adapter call mints a channel-bound capability token from it; the DO\n * refuses requests without one (issue #746). Products pass the same value\n * the DO resolves — `env.TURN_STREAM_AUTH_SECRET`. */\nexport interface TurnStreamAuth {\n secret: string\n}\n\nasync function postJson<T>(\n namespace: TurnStreamNamespaceLike,\n channelKey: string,\n path: string,\n body: unknown,\n auth: TurnStreamAuth,\n claims?: TurnStreamTokenClaims,\n): Promise<{ status: number; body: T }> {\n const stub = namespace.get(namespace.idFromName(channelKey))\n const response = await stub.fetch(`${INTERNAL_ORIGIN}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n [TURN_STREAM_TOKEN_HEADER]: await mintTurnStreamToken(channelKey, auth.secret, undefined, undefined, claims),\n },\n body: JSON.stringify(body),\n })\n return { status: response.status, body: (await response.json()) as T }\n}\n\nasync function postJsonOk<T>(\n namespace: TurnStreamNamespaceLike,\n channelKey: string,\n path: string,\n body: unknown,\n auth: TurnStreamAuth,\n claims?: TurnStreamTokenClaims,\n): Promise<T> {\n const result = await postJson<T>(namespace, channelKey, path, body, auth, claims)\n if (result.status !== 200) {\n throw new Error(`turn-stream ${path} failed with status ${result.status}`)\n }\n return result.body\n}\n\n// ── TurnEventStore adapter (the real turnStore) ─────────────────────────────\n\n/**\n * Optional Durable Object backend for {@link TurnEventStore}.\n * Each turn has its own named instance; a per-scope index tracks running turns.\n * Products choose this adapter or the D1 backend independently of their lock\n * and workspace-signal transport.\n */\nexport function createDurableObjectTurnEventStore(\n namespace: TurnStreamNamespaceLike,\n auth: TurnStreamAuth,\n): TurnEventStore {\n return {\n async append(turnId, events) {\n if (!events.length) return\n await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnEventsAppend, { events }, auth)\n },\n async read(turnId, fromSeq) {\n const body = await postJsonOk<{ events: Array<{ seq: number; event: string }> }>(\n namespace,\n turnStorageChannelKey(turnId),\n TURN_STREAM_PATHS.turnEventsRead,\n { fromSeq },\n auth,\n )\n return body.events\n },\n async setStatus(turnId, status, scopeId, options) {\n // This store keeps no update time to preserve or compare; refuse rather than write unguarded.\n if (options?.preserveUpdatedAt || options?.onlyIfRunningBefore !== undefined) {\n throw new Error('The turn-stream Durable Object store does not support guarded or time-preserving status writes')\n }\n await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnStatusSet, { status }, auth)\n if (scopeId) {\n await postJsonOk(namespace, scopeIndexChannelKey(scopeId), TURN_STREAM_PATHS.scopeStatusSet, {\n turnId,\n status,\n }, auth)\n }\n },\n async getStatus(turnId) {\n const body = await postJsonOk<{ status: TurnStatus | null }>(\n namespace,\n turnStorageChannelKey(turnId),\n TURN_STREAM_PATHS.turnStatusGet,\n {},\n auth,\n )\n return body.status\n },\n async listRunning(scopeId) {\n const body = await postJsonOk<{ running: string[] }>(\n namespace,\n scopeIndexChannelKey(scopeId),\n TURN_STREAM_PATHS.scopeRunningList,\n {},\n auth,\n )\n return body.running\n },\n }\n}\n\n// ── lock primitives (usable outside the route seam too) ─────────────────────\n\n/** Define input parameters required to acquire a durable turn lock in a workspace thread context */\nexport interface AcquireDurableTurnLockInput {\n workspaceId: string\n threadId: string\n scope: TurnLockScope\n executionId: string\n turnId?: string\n /** Supply to reclaim/retry with a stable id; default mints a UUID. */\n lockId?: string\n cancellation?: { turnStreamId: string }\n}\n\n/** Acquire a durable turn lock in the specified namespace with given input parameters */\nexport async function acquireDurableTurnLock(\n namespace: TurnStreamNamespaceLike,\n input: AcquireDurableTurnLockInput,\n auth: TurnStreamAuth,\n): Promise<TurnLockAcquireResult> {\n const lockId = input.lockId ?? crypto.randomUUID()\n const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope)\n const result = await postJson<TurnLockAcquireResult>(namespace, key, TURN_STREAM_PATHS.lockAcquire, {\n ...input,\n lockId,\n }, auth)\n if (result.status !== 200 && result.status !== 409) {\n throw new Error(`turn-stream lock acquire failed with status ${result.status}`)\n }\n return result.body\n}\n\n/**\n * Read a channel's active turn lock without changing it.\n *\n * The first request to a Durable Object that has never been used creates it,\n * which measured 1.3-2.4 s for a thread's first turn in GTM production\n * against 0.05-0.33 s once it exists; every lock now lives on the\n * workspace channel, which exists after the workspace's first turn. A peek\n * sent as soon as a turn is admitted wakes that object if it was evicted.\n */\nexport async function peekDurableTurnLock(\n namespace: TurnStreamNamespaceLike,\n input: { workspaceId: string } & ({ scope: 'workspace'; threadId?: string } | { scope: TurnLockScope; threadId: string }),\n auth: TurnStreamAuth,\n): Promise<DurableTurnLock | null> {\n const key = turnLockChannelKey(input.workspaceId, input.threadId ?? '', input.scope)\n const result = await postJson<{ active?: DurableTurnLock | null }>(namespace, key, TURN_STREAM_PATHS.lockPeek, {\n scope: input.scope,\n threadId: input.threadId,\n }, auth)\n if (result.status !== 200) throw new Error(`turn-stream lock peek failed with status ${result.status}`)\n return result.body.active ?? null\n}\n\n/** Release a durable turn lock and indicate if the release was successful or deferred */\nexport async function releaseDurableTurnLock(\n namespace: TurnStreamNamespaceLike,\n input: TurnLockReleaseInput,\n auth: TurnStreamAuth,\n): Promise<{ released: boolean; deferred?: boolean }> {\n const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope)\n return postJsonOk(namespace, key, TURN_STREAM_PATHS.lockRelease, input, auth)\n}\n\n/** Park the exact lock's release for its durable owner; any answer but a parked 200 leaves the lock held. */\nexport async function parkDurableTurnLock(namespace: TurnStreamNamespaceLike, input: TurnLockReleaseInput, auth: TurnStreamAuth): Promise<boolean> {\n const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope)\n return (await postJsonOk<{ deferred?: boolean }>(namespace, key, TURN_STREAM_PATHS.lockPark, input, auth)).deferred === true\n}\n\n/** Fenced out-of-band release — the DO refuses a successor lock (started\n * after `interruptedAt`) and a turnId mismatch. Returns whether any scope\n * released. */\nexport async function releaseInterruptedDurableTurnLock(\n namespace: TurnStreamNamespaceLike,\n input: TurnLockInterruptedReleaseInput,\n auth: TurnStreamAuth,\n): Promise<boolean> {\n const scopes: readonly TurnLockScope[] = input.scope ? [input.scope] : ['workspace', 'thread']\n for (const scope of scopes) {\n const key = turnLockChannelKey(input.workspaceId, input.threadId, scope)\n const result = await postJsonOk<{ released: boolean }>(namespace, key, TURN_STREAM_PATHS.lockReleaseInterrupted, {\n scope,\n threadId: input.threadId,\n interruptedAt: input.interruptedAt,\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.recovery ? { recovery: input.recovery } : {}),\n }, auth, input.recovery ? { purpose: 'turn-recovery', identity: input.recovery } : undefined)\n if (result.released) return true\n }\n return false\n}\n\n// ── stale-lock reconciliation against the DO ────────────────────────────────\n\n/** Define options to reconcile stale durable turn locks with context, namespace, workspace, and active lock details */\nexport interface ReconcileStaleDurableTurnLockOptions\n extends Pick<\n ReconcileStaleTurnLockOptions,\n 'probeSandbox' | 'probeSession' | 'graceMs' | 'terminalGraceMs' | 'context' | 'log' | 'now'\n > {\n namespace: TurnStreamNamespaceLike\n auth: TurnStreamAuth\n workspaceId: string\n threadId: string\n /** The lock the acquire attempt was refused on. */\n active: DurableTurnLock\n /** Cancellable Router locks require positive exact outer + child quiescence; native-only probes cannot attest it. */\n probeOwner?(identity: TurnCancellationIdentity): Promise<StaleTurnLockOwnerProbeResult>\n}\n\n/**\n * `/chat-routes`' `reconcileStaleTurnLock` policy wired to the DO: the\n * product supplies the probes (which box, what its session says), the policy\n * decides, and a release lands as a FENCED interrupted release —\n * `interruptedAt` is the policy's `fence.observedAt`, so a successor lock\n * acquired while the probes were in flight survives by construction.\n */\nexport async function reconcileStaleDurableTurnLock(\n options: ReconcileStaleDurableTurnLockOptions,\n): Promise<{ released: boolean; diagnostics: Record<string, unknown> }> {\n const { namespace, auth, workspaceId, threadId, active, probeOwner, ...policy } = options\n const owner = active.cancellation ? { workspaceId: active.workspaceId, threadId: active.threadId, scope: active.scope,\n executionId: active.executionId, lockId: active.lockId, turnStreamId: active.cancellation.turnStreamId } : undefined\n return reconcileStaleTurnLock({\n ...policy,\n lockStartedAt: active.startedAt,\n ...(owner ? { owner: { identity: owner,\n probe: probeOwner ?? (async (identity: TurnCancellationIdentity) => ({ identity, status: 'unknown' as const })) } } : {}),\n release: (fence) =>\n releaseInterruptedDurableTurnLock(namespace, {\n workspaceId,\n threadId: active.threadId,\n scope: active.scope,\n interruptedAt: fence.observedAt,\n ...(active.turnId ? { turnId: active.turnId } : {}),\n ...(owner ? { recovery: owner } : {}),\n }, auth),\n })\n}\n\n/** What the box a held lock's turn ran work on reports: executions still active and sessions seen, or no answer. */\nexport type HolderBoxReport = { live: number; sessions: number } | 'unreachable' | 'timeout'\n\n/** Whether a held lock's turn still runs, in the owner rule's terms; diagnostics are counts and classes only. */\ntype HolderEvidence = { status: 'live' | 'abandoned' | 'unknown'; diagnostics: Record<string, unknown> }\n\n/**\n * The reclaim for a lock whose turn died with its invocation (a closed tab, a runtime limit), which releases nothing,\n * so without it the lock refuses every turn in its scope until its TTL. A live turn renews its running row every 30 s,\n * so a holder thread with an unexpired running turn holds. Box work a turn started (a sandbox turn, a detached computer\n * step) outlives the invocation, so with no running row the box answers next: an active execution there holds. Without\n * `readHolderBox` no box is read. A holder with neither is released past the policy's terminal grace, so a turn must\n * write its running row within that grace of taking the lock. A parked release and a store that cannot answer hold. A\n * box that does not answer sends a lock to the policy's unreachable bound; a durable-Stop lock goes through the owner\n * rule on the same evidence, where an unanswered read is `unknown` and holds. The 409 carries counts and classes only.\n * Enable it through `createDurableTurnLock`'s `turnStore` rather than as a product `reconcile`: only that lock makes the\n * routes write the early running row and hold a handed-off lock, which this evidence relies on.\n */\nexport async function reconcileTurnLockFromStoreAndBox(input: {\n namespace: TurnStreamNamespaceLike\n auth: TurnStreamAuth\n turnStore: Required<Pick<TurnEventStore, 'listRunning'>>\n readHolderBox?(active: DurableTurnLock): Promise<HolderBoxReport>\n active: DurableTurnLock\n /** The policy's clock. Default `Date.now`. */\n now?(): number\n}): Promise<{ released: boolean; diagnostics: Record<string, unknown> }> {\n const { active, turnStore, readHolderBox } = input\n const unknown = (probeError: string): HolderEvidence => ({ status: 'unknown', diagnostics: { probeError } })\n // A failed read is logged here by class; its message never reaches the 409.\n const unreadable = (probeError: string, error: unknown) => {\n console.warn('[turn-lock] held lock evidence unreadable', { class: probeError, error: error instanceof Error ? error.name : typeof error,\n workspaceId: active.workspaceId, lockId: active.lockId })\n return unknown(probeError)\n }\n const evidence = async (): Promise<HolderEvidence> => {\n if (active.releasePending) return { status: 'live', diagnostics: { releasePending: true } }\n let running: string[]\n try { running = await turnStore.listRunning(active.threadId) }\n catch (error) { return unreadable('turn_store_unreadable', error) }\n if (running.length > 0) return { status: 'live', diagnostics: { runningTurns: running.length } }\n let box: HolderBoxReport\n try { box = readHolderBox ? await readHolderBox(active) : { live: 0, sessions: 0 } }\n catch (error) { return unreadable('box_unreachable', error) }\n if (box === 'unreachable' || box === 'timeout') return unknown(box === 'timeout' ? 'box_read_timeout' : 'box_unreachable')\n if (box.live > 0) return { status: 'live', diagnostics: { liveBoxSessions: box.live, boxSessions: box.sessions } }\n return { status: 'abandoned', diagnostics: { runningTurns: 0, liveBoxSessions: 0, boxSessions: box.sessions } }\n }\n return reconcileStaleDurableTurnLock({\n namespace: input.namespace, auth: input.auth, workspaceId: active.workspaceId, threadId: active.threadId, active, now: input.now,\n context: { workspaceId: active.workspaceId, threadId: active.threadId, executionId: active.executionId, lockId: active.lockId },\n probeSandbox: async () => ({ status: 'running' }),\n // A native lock: an unreadable store holds; a box that does not answer goes to the policy's unreachable bound.\n probeSession: async () => {\n const { status, diagnostics } = await evidence()\n if (status === 'unknown' && diagnostics.probeError !== 'turn_store_unreadable') return { reachable: false, reason: String(diagnostics.probeError) }\n return { reachable: true, terminal: status === 'abandoned', diagnostics }\n },\n // A durable-Stop lock: the owner rule judges the same evidence; unknown holds.\n probeOwner: async identity => ({ identity, ...await evidence() }),\n })\n}\n\n// ── ChatTurnLock adapter (the turnLock seam) ────────────────────────────────\n\n/** The subset of `ChatTurnProduceArgs` the lock adapter reads — structural,\n * so this module needs no import from `/chat-routes/turn-routes` (which\n * would drag the `agent-runtime` peer into every `/turn-stream` consumer). */\nexport interface TurnLockSeamArgs<TContext> {\n identity: { tenantId: string; sessionId: string }\n executionId: string\n turnStreamId?: string\n context: TContext\n body: { turnId?: string }\n}\n\n/** Verdict shape of the vertical's `turnLock.acquire`. */\nexport type TurnLockSeamResult =\n | { acquired: true; handle?: unknown; cancellation?: TurnCancellationConnection }\n | { acquired: false; response: Response }\n\n/** Define options for creating a durable turn lock with customizable scope and identification methods */\nexport interface CreateDurableTurnLockOptions<TContext> {\n /** New channels use this hint; existing channel IDs and locations are preserved. */\n locationHint?: TurnStreamLocationHint\n namespace: TurnStreamNamespaceLike\n /** Capability tokens for the DO; pass the worker's\n * `env.TURN_STREAM_AUTH_SECRET`. The DO validates every request. */\n auth: TurnStreamAuth\n /** Which lane serializes this turn: `'workspace'` (shared sandbox — one\n * turn per workspace) or `'thread'` (router lane — one turn per thread). */\n scopeOf(args: TurnLockSeamArgs<TContext>): TurnLockScope\n /** Opt the existing lock into durable Stop. Leave native/durable completion lanes on their existing owner. */\n cancellationOf?(args: TurnLockSeamArgs<TContext>): boolean\n /** The store the routes renew running turns in. Given it and no `reconcile`, a dead holder is reclaimed\n * ({@link reconcileTurnLockFromStoreAndBox}). */\n turnStore?: Required<Pick<TurnEventStore, 'listRunning'>>\n /** Read the box the holder's turn ran work on (`readHolderBoxSessions` from `/sandbox`). Omit when turns run no box\n * work: the default reclaim then reads the turn store alone. */\n readHolderBox?(active: DurableTurnLock): Promise<HolderBoxReport>\n /** The stale-lock policy's clock for the default reclaim, for tests and simulations; the lock's own start stays the\n * Durable Object's wall clock. Default `Date.now`. */\n now?(): number\n /** Override the execution id the lock records (e.g. a follow-up reclaiming\n * the execution it already dispatched). Default: the turn's own. */\n lockExecutionIdOf?(args: TurnLockSeamArgs<TContext>): string | undefined\n /** Client turn id recorded on the lock (fences interrupted releases to the\n * right turn). Default: the request body's `turnId`. */\n clientTurnIdOf?(args: TurnLockSeamArgs<TContext>): string | undefined\n /**\n * Attempt stale-lock recovery after a refused acquire. Return whether the\n * held lock was released (the adapter then retries the acquire once).\n * Products wire {@link reconcileStaleDurableTurnLock} with their sandbox +\n * session probes here. Omit → {@link reconcileTurnLockFromStoreAndBox} when `turnStore` is given, else a refused\n * acquire is final.\n */\n reconcile?(\n args: TurnLockSeamArgs<TContext>,\n active: DurableTurnLock,\n ): Promise<{ released: boolean; diagnostics?: Record<string, unknown> }>\n /** Build the refusal `Response`. Default: a 409 with the shared body shape\n * (`code`, `message`, lock identity + age, reconcile diagnostics). */\n onRefused?(active: DurableTurnLock, diagnostics: Record<string, unknown> | undefined): Response\n}\n\nfunction defaultRefusalResponse(\n active: DurableTurnLock,\n diagnostics: Record<string, unknown> | undefined,\n): Response {\n const workspaceConflict = active.scope === 'workspace'\n return Response.json(\n {\n error: {\n code: workspaceConflict ? 'workspace_turn_in_flight' : 'chat_turn_in_flight',\n message: workspaceConflict\n ? 'A chat turn is already running for this workspace. Wait for it to finish before starting another.'\n : 'A chat turn is already running for this thread. Reconnect to the active response or wait for it to finish.',\n threadId: active.threadId,\n executionId: active.executionId,\n ...(active.turnId ? { turnId: active.turnId } : {}),\n lockStartedAt: active.startedAt,\n lockAgeMs: Date.now() - active.startedAt,\n ...(diagnostics ? { diagnostics } : {}),\n },\n },\n { status: 409 },\n )\n}\n\n/**\n * The vertical's `turnLock` seam on the shared DO: dual-scope single-flight\n * acquire (with one reconcile-then-retry pass when the product supplies a\n * stale-lock reconciler) and cooperative release on settle. The returned\n * object satisfies `createChatTurnRoutes`' `ChatTurnLock<TContext>`\n * structurally.\n */\nexport function createDurableTurnLock<TContext>(options: CreateDurableTurnLockOptions<TContext>): {\n acquire(args: TurnLockSeamArgs<TContext>): Promise<TurnLockSeamResult>\n release(handle: unknown): Promise<void>\n park(handle: unknown): Promise<boolean>\n /** Present only with the default reclaim: a handed-off turn's lock is parked so the reclaim reads it as held. */\n holdForHandoff?(handle: unknown): Promise<boolean>\n warm(target: { tenantId: string; threadId?: string }): Promise<void>\n} {\n const namespace: TurnStreamNamespaceLike = {\n idFromName: name => options.namespace.idFromName(name),\n get: (id, init) => options.namespace.get(id, {\n ...init, locationHint: options.locationHint ?? DEFAULT_TURN_LOCK_LOCATION_HINT,\n }),\n }\n const { turnStore } = options\n const reconcile = options.reconcile ?? (turnStore\n ? (_args: TurnLockSeamArgs<TContext>, active: DurableTurnLock) => reconcileTurnLockFromStoreAndBox({\n namespace, auth: options.auth, turnStore, readHolderBox: options.readHolderBox, active, now: options.now })\n : undefined)\n return {\n // Every lock lives on the workspace channel, so this wakes that object\n // (evicted after idle) before the turn's acquire reaches it.\n async warm(target) {\n await peekDurableTurnLock(namespace, target.threadId\n ? { workspaceId: target.tenantId, threadId: target.threadId, scope: 'thread' }\n : { workspaceId: target.tenantId, scope: 'workspace' }, options.auth)\n },\n async acquire(args) {\n const workspaceId = args.identity.tenantId\n const threadId = args.identity.sessionId\n const scope = options.scopeOf(args)\n const executionId = options.lockExecutionIdOf?.(args) ?? args.executionId\n const turnId = options.clientTurnIdOf ? options.clientTurnIdOf(args) : args.body.turnId\n const cancellable = options.cancellationOf?.(args) === true\n if (cancellable && !args.turnStreamId) throw new Error('Durable cancellation requires the route turnStreamId')\n const input: AcquireDurableTurnLockInput = {\n workspaceId,\n threadId,\n scope,\n executionId,\n ...(turnId ? { turnId } : {}),\n ...(cancellable ? { cancellation: { turnStreamId: args.turnStreamId! } } : {}),\n }\n\n let acquired = await acquireDurableTurnLock(namespace, input, options.auth)\n let diagnostics: Record<string, unknown> | undefined\n if (!acquired.acquired && reconcile) {\n const reconciled = await reconcile(args, acquired.active)\n diagnostics = reconciled.diagnostics\n if (reconciled.released) {\n acquired = await acquireDurableTurnLock(namespace, input, options.auth)\n }\n }\n if (!acquired.acquired) {\n return {\n acquired: false,\n response: (options.onRefused ?? defaultRefusalResponse)(acquired.active, diagnostics),\n }\n }\n const handle: TurnLockReleaseInput = {\n workspaceId,\n threadId,\n scope,\n executionId,\n lockId: acquired.lock.lockId,\n }\n if (!cancellable) return { acquired: true, handle }\n try {\n const cancellation = await connectDurableTurnCancellation(options.namespace,\n { ...handle, turnStreamId: args.turnStreamId! }, options.auth)\n return { acquired: true, handle, cancellation }\n } catch (error) {\n // No producer may run without its control connection. Release only this newly acquired generation.\n await releaseDurableTurnLock(options.namespace, handle, options.auth)\n throw error\n }\n },\n async release(handle) {\n if (!handle) return\n await releaseDurableTurnLock(namespace, handle as TurnLockReleaseInput, options.auth)\n },\n async park(handle) {\n return Boolean(handle) && parkDurableTurnLock(namespace, handle as TurnLockReleaseInput, options.auth)\n },\n // A product reconciler or a lock without the default reads `releasePending` its own way; leave it untouched.\n ...(turnStore && !options.reconcile\n ? { holdForHandoff: async (handle: unknown) => Boolean(handle) && parkDurableTurnLock(namespace, handle as TurnLockReleaseInput, options.auth) }\n : {}),\n }\n}\n\n// ── broadcast helpers (products wire these into onEvent) ────────────────────\n\n/** Coarse per-workspace marker that a thread's turn started / ended — drives\n * a sidebar \"agent responding\" indicator subscribed once per workspace. */\nexport async function broadcastWorkspaceActivity(\n namespace: TurnStreamNamespaceLike,\n workspaceId: string,\n threadId: string,\n phase: 'start' | 'end',\n auth: TurnStreamAuth,\n): Promise<void> {\n try {\n await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {\n type: 'thread.activity',\n timestamp: Date.now(),\n data: { threadId, phase, workspaceId, sessionId: workspaceId },\n } satisfies TurnStreamEvent, auth)\n } catch {\n // Best-effort: the indicator is non-critical UI.\n }\n}\n\n/** Per-workspace marker that a new thread was created, so an already-open\n * history list prepends it without a reload. */\nexport async function broadcastThreadCreated(\n namespace: TurnStreamNamespaceLike,\n workspaceId: string,\n thread: { threadId: string; title: string },\n auth: TurnStreamAuth,\n): Promise<void> {\n try {\n await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {\n type: 'thread.created',\n timestamp: Date.now(),\n data: { threadId: thread.threadId, title: thread.title, workspaceId, sessionId: workspaceId },\n } satisfies TurnStreamEvent, auth)\n } catch {\n // Best-effort: the loader reconciles on the next revalidation.\n }\n}\n\n// ── WebSocket upgrade forwarder (worker entry) ──────────────────────────────\n\n/** Represent success or failure of a TURN stream upgrade authorization with optional response data */\nexport type TurnStreamUpgradeAuthorization = { ok: true } | { ok: false; response: Response }\n\n/** Define options for creating a TURN stream upgrade handler including namespace, path, and authorization logic */\nexport interface CreateTurnStreamUpgradeHandlerOptions {\n namespace: TurnStreamNamespaceLike\n /** HMAC secret shared with the DO binding (`env.TURN_STREAM_AUTH_SECRET`).\n * After the product `authorize` passes, the handler mints a channel-bound\n * capability token and the DO verifies it — the browser never holds it. */\n authSecret: string\n /** The worker route serving the stream. Default `/api/session-stream`. */\n path?: string\n /** Viewer access check (session cookie → workspace membership). */\n authorize(\n request: Request,\n target: { workspaceId: string },\n ): Promise<TurnStreamUpgradeAuthorization>\n}\n\n/**\n * The worker-entry WebSocket forwarder — WORKSPACE channel only; a thread's\n * live turn replay is the sandbox session gateway's job. Call BEFORE the\n * app router (a router loader cannot return a 101); returns `null` for\n * requests that are not a WebSocket upgrade on the configured path.\n *\n * GET {path}?workspaceId=... → workspace channel (sidebar signals)\n *\n * After the 101, the client sends `{type:'sync'}` and receives the\n * current-activity + recent-threads snapshot, then live signals.\n *\n * Security: the product's `authorize` decides whether THIS caller may see the\n * workspace's signals; the channel-bound token this handler then mints is\n * what the DO itself verifies — two independent gates, and the browser never\n * learns the token (it rides the forwarded upgrade request only).\n */\nexport function createTurnStreamUpgradeHandler(\n options: CreateTurnStreamUpgradeHandlerOptions,\n): (request: Request) => Promise<Response | null> {\n const path = options.path ?? '/api/session-stream'\n if (!options.authSecret || options.authSecret.length < 32) {\n throw new Error('createTurnStreamUpgradeHandler requires authSecret (>= 32 chars) — the DO fails closed without tokens')\n }\n return async (request) => {\n const url = new URL(request.url)\n if (url.pathname !== path || request.headers.get('Upgrade')?.toLowerCase() !== 'websocket') return null\n\n if (url.searchParams.has('threadId')) {\n return new Response('Thread replay uses the sandbox session gateway or chat replay route', { status: 400 })\n }\n const workspaceId = url.searchParams.get('workspaceId')\n if (!workspaceId) return new Response('Missing workspaceId', { status: 400 })\n\n const auth = await options.authorize(request, { workspaceId })\n if (!auth.ok) return auth.response\n\n const key = workspaceChannelKey(workspaceId)\n const stub = options.namespace.get(options.namespace.idFromName(key))\n\n const forwardUrl = new URL(request.url)\n forwardUrl.searchParams.set('sessionId', workspaceId)\n forwardUrl.searchParams.set('scope', 'workspace')\n forwardUrl.searchParams.delete('token')\n const headers = new Headers(request.headers)\n headers.set(TURN_STREAM_TOKEN_HEADER, await mintTurnStreamToken(key, options.authSecret))\n return stub.fetch(new Request(new Request(forwardUrl, request), { headers }))\n }\n}\n\n// ── turn host forwarder (worker entry) ──────────────────────────────────────\n\n/** The turn-stream binding chat turns run in (`createChatTurnRoutes`' `turnHost`); its `TurnStreamDO` subclass passes\n * `turnRoutes`. */\nexport interface TurnHost {\n namespace: TurnStreamNamespaceLike & { newUniqueId(): unknown }\n auth: TurnStreamAuth\n /** Placement of each turn's object. Default: the turn lock's region. */\n locationHint?: TurnStreamLocationHint\n}\n\n/** Send a browser's turn request, unread and with its cookies, to a new object of the host binding, and return that\n * object's streamed response. The object's capability names its id, so only this Worker can start a turn there. */\nexport async function forwardTurnToHost(host: TurnHost, request: Request): Promise<Response> {\n const id = host.namespace.newUniqueId()\n const headers = new Headers(request.headers)\n headers.set(TURN_STREAM_TOKEN_HEADER, await mintTurnStreamToken(turnHostChannelKey(String(id)), host.auth.secret))\n return host.namespace.get(id, { locationHint: host.locationHint ?? DEFAULT_TURN_LOCK_LOCATION_HINT }).fetch(new Request(request, { headers }))\n}\n"],"mappings":";;;;;;;AAoCO,IAAM,2BAA2B;AAIjC,IAAM,2BAA2B;AAGjC,IAAM,wBAAwB;AAE9B,IAAM,yBAAyB;AAQtC,SAAS,uBAAuB,QAAuC;AACrE,QAAM,EAAE,UAAU,QAAQ,IAAI;AAC9B,MAAI,CAAC,CAAC,gBAAgB,eAAe,eAAe,EAAE,SAAS,OAAO,KACjE,CAAC,YAAY,CAAC,CAAC,UAAU,WAAW,EAAE,SAAS,SAAS,KAAK,KAC7D,CAAC,SAAS,aAAa,SAAS,UAAU,SAAS,aAAa,SAAS,QAAQ,SAAS,YAAY,EACtG,KAAK,WAAS,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,CAAC,EAAG,OAAM,IAAI,MAAM,oCAAoC;AACpH,SAAO,oBAAoB,KAAK,UAAU;AAAA,IAAC;AAAA,IAAS,SAAS;AAAA,IAAa,SAAS;AAAA,IAAU,SAAS;AAAA,IACpG,SAAS;AAAA,IAAa,SAAS;AAAA,IAAQ,SAAS;AAAA,EAAY,CAAC,CAAC;AAClE;AAIA,eAAsB,oBACpB,aACA,QACA,MAAoB,KAAK,KACzB,QAAgB,0BAChB,QACiB;AACjB,MAAI,CAAC,UAAU,OAAO,SAAS,GAAI,OAAM,IAAI,MAAM,yDAAyD;AAC5G,QAAM,YAAY,IAAI,IAAI;AAC1B,QAAM,UAAU,GAAG,SAAS,OAAO,IAAI,IAAI,oBAAoB,WAAW,CAAC,IAAI,UAAU,SAAS,EAAE,CAAC,GAAG,SAAS,IAAI,uBAAuB,MAAM,CAAC,KAAK,EAAE;AAC1J,SAAO,GAAG,OAAO,IAAI,MAAM,oBAAoB,SAAS,MAAM,C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U,IAAI,IAAI,EAAE,cAAc,KAAK,gBAAgB,gCAAgC,CAAC,EAAE,MAAM,IAAI,QAAQ,SAAS,EAAE,QAAQ,CAAC,CAAC;AAC/I;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/runtime/loop.ts","../src/runtime/gzip-request.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 /** One model call's usage, with why the call ended (`finish_reason`, or a Responses status) when the provider says. */\n | { type: 'usage'; usage: { promptTokens: number; completionTokens: number; cachedPromptTokens?: number; reasoningTokens?: number }\n finishReason?: string }\n | { type: 'other'; event: unknown }\n","/**\n * `fetch` that gzips a large string request body before it leaves the app.\n *\n * A Router turn sends its whole system prompt on every model call. From a\n * Worker in another region, a 37k-token prompt (about 150 kB of JSON) spent\n * 118–672 ms uploading before the Router's first step (tangle-router\n * `body_read`), because each round trip of a new connection carries only a\n * slow-start window. Prompt JSON compresses about tenfold, so the upload fits\n * in fewer round trips. The Tangle Router decodes `Content-Encoding: gzip` on\n * /v1/chat/completions, /v1/messages and /v1/responses; another endpoint may not.\n */\nexport function gzipRequestBodies(base: typeof fetch, minBytes: number): typeof fetch {\n return async (input, init) => {\n const body = init?.body\n if (typeof body !== 'string' || body.length < minBytes / 3) return base(input, init)\n const headers = new Headers(init?.headers)\n if (headers.has('content-encoding')) return base(input, init)\n const bytes = new TextEncoder().encode(body)\n if (bytes.byteLength < minBytes) return base(input, init)\n const compressed = await new Response(new Blob([bytes]).stream().pipeThrough(new CompressionStream('gzip'))).arrayBuffer()\n headers.set('content-encoding', 'gzip')\n headers.delete('content-length')\n return base(input, { ...init, headers, body: compressed })\n }\n}\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 /** A failure the service reports inside the stream (the Tangle Router's\n * `empty_completion`, `reasoning_budget_exhausted`, `stream_idle_timeout`, …). */\n error?: { code?: string | null; message?: string | null; type?: string | null }\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 /** Prompt tokens the provider served from its prompt cache (Gemini implicit caching, OpenAI, Anthropic through the Router). */\n prompt_tokens_details?: { cached_tokens?: number | null } | null\n completion_tokens_details?: { reasoning_tokens?: number | null } | null\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: Extract<LoopEvent, { type: 'usage' }>['usage'] | undefined\n let finishReason: string | 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 // Cumulative like the rest, but a provider may send the details on an earlier chunk only: keep the largest.\n const reported = chunk.usage.prompt_tokens_details?.cached_tokens\n const cached = typeof reported === 'number' ? Math.max(reported, usage?.cachedPromptTokens ?? 0) : usage?.cachedPromptTokens\n const reasoningTokens = chunk.usage.completion_tokens_details?.reasoning_tokens ?? usage?.reasoningTokens\n usage = {\n promptTokens: chunk.usage.prompt_tokens ?? 0,\n completionTokens: chunk.usage.completion_tokens ?? 0,\n ...(typeof cached === 'number' ? { cachedPromptTokens: cached } : {}),\n ...(typeof reasoningTokens === 'number' ? { reasoningTokens } : {}),\n }\n }\n const choice = chunk.choices?.[0]\n if (!choice) continue\n finishReason = choice.finish_reason ?? finishReason\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, ...(finishReason ? { finishReason } : {}) }\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?: OpenAIStreamChunk['usage']\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' | 'responses'): 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, 1000)}` : ''}`)\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 postOpenAIEventStream(doFetch, url, apiKey, body, headers)\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 for await (const data of readOpenAISseFrames(res.body)) {\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 // A failure inside a 200 stream ends the call by name instead of reading as a blank answer.\n if (chunk.error) throw streamFailure(chunk.error)\n yield chunk\n\n }\n}\n\n/** The error a stream's own error frame becomes: its `code` and message, for the caller's failure categories. */\nfunction streamFailure(failure: NonNullable<OpenAIStreamChunk['error']>): Error {\n const code = failure.code || failure.type || 'stream_error'\n return Object.assign(new Error(`OpenAI-compat stream failed: ${code}${failure.message ? `: ${failure.message.slice(0, 1000)}` : ''}`), { code, streamFailure: true })\n}\n\n/** OpenAI models answer reasoning summaries only on the Responses API; chat completions carry none. */\nexport function isOpenAIResponsesModel(model: string): boolean {\n return /^(?:openai\\/)?(?:gpt-|o\\d|chatgpt-)/i.test(model.trim())\n}\n\n/** The chat-completions history the tool loop keeps, as Responses `instructions` and `input` items. */\nexport function toResponsesInput(messages: LoopMessage[]): { instructions?: string; input: Array<Record<string, unknown>> } {\n const instructions: string[] = []\n const input: Array<Record<string, unknown>> = []\n for (const message of messages) {\n const content = typeof message.content === 'string' ? message.content : ''\n if (message.role === 'system') {\n if (content) instructions.push(content)\n } else if (message.role === 'tool') {\n input.push({ type: 'function_call_output', call_id: message.tool_call_id ?? '', output: content })\n } else if (message.role === 'assistant' && message.tool_calls?.length) {\n if (content.trim()) input.push({ role: 'assistant', content })\n for (const call of message.tool_calls) {\n input.push({ type: 'function_call', call_id: call.id, name: call.function.name, arguments: call.function.arguments })\n }\n } else if (message.role === 'user' || message.role === 'assistant') {\n input.push({ role: message.role, content })\n }\n }\n return { ...(instructions.length ? { instructions: instructions.join('\\n\\n') } : {}), input }\n}\n\n/** Chat-completions tool definitions as Responses function tools. */\nfunction toResponsesTools(tools: unknown[] | undefined): Array<Record<string, unknown>> {\n return (tools ?? []).flatMap((tool) => {\n const fn = (tool as { function?: { name?: string; description?: string; parameters?: unknown } }).function\n return fn?.name ? [{ type: 'function', name: fn.name, ...(fn.description ? { description: fn.description } : {}),\n parameters: fn.parameters ?? { type: 'object', properties: {} } }] : []\n })\n}\n\n/**\n * Build a `streamTurn` on the OpenAI Responses API (`POST /responses`, streamed),\n * for OpenAI models whose reasoning reaches a caller only there, as\n * `response.reasoning_summary_text.delta` events. Each Responses event is\n * mapped onto the chat-completions chunk shape {@link toLoopEvents} reads, so\n * text, reasoning, fragmented function calls, usage and served-model\n * attribution behave exactly as on {@link createOpenAICompatStreamTurn}.\n *\n * `extraBody` keys from the chat path are translated: `max_tokens` and\n * `max_completion_tokens` become `max_output_tokens`, and `reasoning_effort`\n * becomes `reasoning.effort` with `summary: 'auto'`. Stateless: earlier tool\n * calls are replayed as `function_call` / `function_call_output` items.\n */\nexport function createOpenAIResponsesTurn(\n opts: OpenAICompatStreamTurnOptions,\n): (messages: LoopMessage[]) => AsyncIterable<LoopEvent> {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const doFetch = opts.fetchImpl ?? fetch\n const { max_tokens: maxTokens, max_completion_tokens: maxCompletion, reasoning_effort: effort, ...rest } = opts.extraBody ?? {}\n const maxOutput = maxCompletion ?? maxTokens\n return (messages) => {\n const { instructions, input } = toResponsesInput(messages)\n const tools = toResponsesTools(opts.tools)\n return toLoopEvents(streamResponses(doFetch, `${base}/responses`, opts.apiKey, {\n model: opts.model,\n ...(instructions ? { instructions } : {}),\n input,\n stream: true,\n store: false,\n ...(tools.length ? { tools } : {}),\n ...(opts.temperature != null ? { temperature: opts.temperature } : {}),\n ...(maxOutput !== undefined ? { max_output_tokens: maxOutput } : {}),\n ...(effort !== undefined ? { reasoning: { effort, summary: 'auto' } } : {}),\n ...rest,\n }, opts.onServedModel ? { requestedModel: opts.model, report: opts.onServedModel } : undefined, opts.headers))\n }\n}\n\ninterface ResponsesItem {\n id?: string; type?: string; call_id?: string; name?: string; arguments?: string; content?: Array<{ type?: string; text?: string }>\n}\n\ninterface ResponsesEvent {\n type?: string\n delta?: string\n text?: string\n arguments?: string\n item_id?: string\n output_index?: number\n content_index?: number\n summary_index?: number\n item?: ResponsesItem\n response?: { model?: string; output?: ResponsesItem[]; error?: { code?: string; message?: string }\n status?: string; incomplete_details?: { reason?: string } | null\n usage?: { input_tokens?: number; output_tokens?: number; input_tokens_details?: { cached_tokens?: number | null } | null\n output_tokens_details?: { reasoning_tokens?: number | null } | null } }\n error?: { code?: string; message?: string }\n message?: string\n}\n\n/** Stream a Responses API call as chat-completions chunks. A failed or errored response throws. */\nasync function* streamResponses(\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 postOpenAIEventStream(doFetch, url, apiKey, body, headers)\n if (!res.ok || !res.body) throw await httpFailure(res, 'responses')\n let reported = false\n const report = (served: OpenAICompatServedModel) => {\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 let lastSummary: string | null = null\n // Output items by id, else output index; an event naming neither belongs to the latest item. Text streams as its deltas\n // arrive, and each done event's final text sends whatever the deltas missed. A function call starts as soon as its name\n // arrives; its arguments go out once, when the response ends, as the final ones: `function_call_arguments.done`, else\n // `output_item.done`, else the response's output, else what `output_item.added` carried, else the deltas.\n const items: Array<{ id?: string; at?: number; named?: boolean; args: string; final: Array<string | undefined>; sent: string[] }> = []\n const itemFor = (id?: string, at?: number) => {\n let item = id === undefined && at === undefined ? items.at(-1)\n : items.find(i => id !== undefined && i.id === id) ?? items.find(i => at !== undefined && i.at === at)\n if (!item) items.push(item = { id, at, args: '', final: [], sent: [] })\n return item\n }\n const text = (id: string | undefined, at: number | undefined, part = 0, delta = '', final?: string): OpenAIStreamChunk[] => {\n const item = itemFor(id, at)\n const sent = item.sent[part] ?? ''\n const next = final === undefined ? sent + delta : final.startsWith(sent) ? final : sent\n item.sent[part] = next\n return next.length > sent.length ? [{ choices: [{ delta: { content: next.slice(sent.length) } }] }] : []\n }\n const sighted = (item: ResponsesItem | undefined, at: number | undefined, rank: number): OpenAIStreamChunk[] => {\n if (item?.type === 'message') {\n return (item.content ?? []).flatMap((part, i) => part.type === 'output_text' ? text(item.id, at, i, '', part.text) : [])\n }\n if (item?.type !== 'function_call') return []\n const call = itemFor(item.id, at)\n call.final[rank] ??= item.arguments\n if (call.named || !item.name) return []\n call.named = true\n return [{ choices: [{ delta: { tool_calls: [{ index: items.indexOf(call), ...(item.call_id ? { id: item.call_id } : {}),\n function: { name: item.name } }] } }] }]\n }\n const settled = (): OpenAIStreamChunk => ({ choices: [{ delta: { tool_calls: items.map((call, index) =>\n ({ index, function: { arguments: call.final.find(args => args) ?? call.args } })) } }] })\n for await (const data of readOpenAISseFrames(res.body)) {\n let event: ResponsesEvent\n try {\n event = JSON.parse(data) as ResponsesEvent\n } catch {\n continue\n }\n switch (event.type) {\n case 'response.output_text.delta':\n yield* text(event.item_id, event.output_index, event.content_index, event.delta)\n break\n case 'response.output_text.done':\n yield* text(event.item_id, event.output_index, event.content_index, '', event.text)\n break\n case 'response.reasoning_summary_text.delta': {\n if (!event.delta) break\n // Separate summary parts the way the model wrote them.\n const part = `${event.output_index ?? 0}:${event.summary_index ?? 0}`\n const lead = lastSummary !== null && lastSummary !== part ? '\\n\\n' : ''\n lastSummary = part\n yield { choices: [{ delta: { reasoning_content: lead + event.delta } }] }\n break\n }\n case 'response.output_item.added':\n yield* sighted(event.item, event.output_index, 3)\n break\n case 'response.output_item.done':\n yield* sighted(event.item, event.output_index, 1)\n break\n case 'response.function_call_arguments.delta':\n if (event.delta) itemFor(event.item_id, event.output_index).args += event.delta\n break\n case 'response.function_call_arguments.done':\n itemFor(event.item_id, event.output_index).final[0] ??= event.arguments\n break\n case 'response.completed':\n case 'response.incomplete':\n case 'response.done': {\n for (const [at, item] of (event.response?.output ?? []).entries()) yield* sighted(item, at, 2)\n yield settled()\n const model = event.response?.model\n if (attribution && !reported && model) report(servedFromBody(model, attribution.requestedModel))\n const usage = event.response?.usage\n // Why the call ended: the reason it is incomplete, else its status.\n const finish = event.response?.incomplete_details?.reason ?? event.response?.status\n yield { ...(model ? { model } : {}), choices: finish ? [{ finish_reason: finish }] : [],\n ...(usage ? { usage: { prompt_tokens: usage.input_tokens ?? 0, completion_tokens: usage.output_tokens ?? 0,\n ...(usage.input_tokens_details ? { prompt_tokens_details: usage.input_tokens_details } : {}),\n ...(usage.output_tokens_details ? { completion_tokens_details: usage.output_tokens_details } : {}) } } : {}) }\n return\n }\n case 'response.failed':\n case 'error': {\n const failure = event.response?.error ?? event.error ?? { message: event.message }\n throw new Error(`OpenAI-compat responses failed: ${(failure?.code ? `${failure.code}: ` : '') + (failure?.message ?? 'no detail')}`.slice(0, 300))\n }\n default:\n break\n }\n\n }\n yield settled()\n}\n\n\n/** The common framing used by both OpenAI SSE protocols; payload parsing stays with each protocol. */\nasync function* readOpenAISseFrames(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n // A consumer that stops reading early unlocks the body, so its caller can cancel it and close the connection.\n try {\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 yield data\n }\n }\n } finally { reader.releaseLock() }\n}\n\n\nfunction postOpenAIEventStream(doFetch: typeof fetch, url: string, apiKey: string, body: Record<string, unknown>, headers?: Record<string, string>): Promise<Response> {\n return 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}\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: 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 // The disagree rule above, read before the files, named a conflict in 10 of 20 bench turns\n // (hospitality, 3 of 5 in production); repeated after the files as a check it named 20 of 20,\n // and 10 of 10 single-file answers stayed unchanged (gemini-3.5-flash-lite, 2026-10-12,\n // hospitality-agent #441).\n ...(files.length > 1 ? ['Before answering from these files, check every file that states the asked fact. When they state different values, give each value with its file name and ask the owner which is current.'] : []),\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 { gzipRequestBodies } from './gzip-request'\nimport { createOpenAICompatCompletionTurn, createOpenAICompatStreamTurn, createOpenAIResponsesTurn, isOpenAIResponsesModel } 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'\nimport { turnTraceId, type TurnSpan, type TurnTrace } from '../turn-trace/recorder'\nimport { nextCallIndex, tracedModelFetch } from '../turn-trace/traced-fetch'\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 /**\n * `'lookup'`: the tool fetches what the answer needs, so text a round writes before calling it narrates\n * the work (\"Let me check your vault\") and is not the answer. A tool that declares nothing (a save, a send,\n * a bridged tool) keeps the text before it as the answer.\n */\n effect?: 'lookup'\n run(args: Record<string, unknown>, context: RouterTurnToolContext): Promise<unknown>\n}\n\n/** Whether text a round writes before calling `tool` narrates the work instead of answering. */\nexport function narratesBefore(tool: Pick<RouterTurnTool, 'effect'> | undefined): boolean {\n return tool?.effect === 'lookup'\n}\n\n/** What a running tool gets besides its arguments. */\nexport interface RouterTurnToolContext {\n /** This call's identity, shared by streamed parts, tool history and a native child execution. */\n callId?: string\n /** The effective turn cancellation signal. Tools must pass it to cancellable I/O. */\n signal?: AbortSignal\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 /** The turn's trace, when the turn records one. A tool that waits on a box or a service adds its own child spans under {@link span}. */\n trace?: TurnTrace\n /** This tool call's `tool.call` span; the parent of any span the tool records. */\n span?: TurnSpan\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 /** The safe repeat is starting a fresh model call on `model`; what the failed call reasoned is finished. */\n | { type: 'repeat'; model: string }\n /** The model named a tool; its arguments are still streaming. Lets a caller start slow work the call will need\n * (the box `sandbox_run` runs in) seconds before the call itself. `toolName` is the app's name. */\n | { type: 'tool_start'; toolName: 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; cachedPromptTokens?: number; reasoningTokens?: number }\n | ({ type: 'tool_event' } & RouterTurnToolEvent)\n\nexport interface RouterTurnFailure {\n /** `model_http_<status>`, `model_stream_<code>` (an error frame inside the stream, e.g. `model_stream_empty_completion`),\n * `model_unavailable`, `model_empty`, `turn_<stopReason>`, `turn_aborted`,\n * `turn_tool_limit`, `router_unconfigured` or `placement_fallback_refused`; 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 1000 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 /**\n * The turn's answer: `text` without its narration, the text a round wrote before calling a tool marked\n * `effect: 'lookup'`. Text before any other tool stays. When everything written was narration, the answer\n * is `text`, so narration that is the turn's only text is still shown. It covers this hop only:\n * `continueFrom.text` from earlier hops is in `text`, never in `answer`.\n */\n answer: 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. `cachedPromptTokens` are the\n * prompt tokens the provider served from its prompt cache; absent when no call reported them. */\n usage: { promptTokens: number; completionTokens: number; modelCalls: number; cachedPromptTokens?: number }\n /** Reasoning the turn streamed (deltas and characters). Zero when the model sent none; absent when no model was called. */\n reasoning?: { deltas: number; chars: 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 watchdog on model turns. Default: the tool loop's own watchdog, far above any legitimate turn, so\n * `budgetMs` bounds the turn. A fixed 12 failed Legal's formation turns, which need 12 tools in 13 model calls\n * (turn_backstop on 2 of 6). */\n maxToolTurns?: number\n maxTokens?: number\n /** Sent as `x-tangle-trace-id` so the router's generation joins the app's trace. Characters the Router\n * refuses in that header (the `:` of an execution id) become `_`; see {@link turnTraceId}. Default: the\n * `trace`'s id. */\n traceId?: string\n /**\n * The turn's trace (`@tangle-network/agent-app/turn-trace`). Every model request is recorded as a\n * `model.call` span with the Router's `Server-Timing` split into network and server time, and every tool\n * call as a `tool.call` span that tool-side spans hang from. Without it nothing is recorded.\n */\n trace?: TurnTrace\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 /**\n * Sent as `reasoning_effort` instead of `reasoningEffort` on a model call that follows a tool round, so a round\n * that only chooses tools reasons less. Such a call that writes a word is cancelled at that word, before it reaches\n * the turn, and sent again at `reasoningEffort` with `tool_choice: \"none\"`: the same tools are listed, so the prompt\n * prefix and its cache are unchanged, but the call must write the answer, and the turn ends after it. One that ends\n * with neither a tool call nor a word is sent again at `reasoningEffort` with tools allowed. The call that opens the\n * turn runs at `reasoningEffort`. Streamed turns only.\n */\n toolRoundEffort?: string\n /**\n * The caller shows the model's reasoning as it streams (`onEvent` `reasoning` events). With `onEvent`, a\n * streamed chat call and the safe repeat on, the Router then releases the stream at the first reasoning frame\n * instead of holding it for the first word, and returns Gemini's thought summaries (gateway\n * `streamReasoningImmediately`). Default false; `createRouterTurnProducer` turns it on.\n */\n showReasoning?: boolean\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 a domain-specific tool result; return undefined to use the shared serialization and limit. */\n renderToolResult?: (toolName: string, outcome: RouterTurnToolOutcome) => string | undefined\n /**\n * Place the turn before any model call, using `model` as the executed model rather than\n * the optional `requestedModel` hint. 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, no resend). With more than one, resends go on past `attempts` until 45 s have passed\n * since the first send, so an outage of that length costs the turn a pause instead of the turn.\n * `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 * Which model API carries the turn. `auto` (default) uses the Responses API for an OpenAI model asked to\n * reason (`reasoningEffort` other than `none`), since OpenAI returns reasoning summaries only there, or given\n * tools, since GPT-6.1 Sol and GPT-6 Astra take function tools only there (the Router refuses them on chat\n * completions with `model_requires_responses_for_tools`), and chat completions otherwise. A buffered turn\n * (`stream: false`) always uses chat completions.\n */\n api?: 'auto' | 'chat' | 'responses'\n /**\n * Gzip a model request body of at least this many bytes (`Content-Encoding: gzip`), so a large system prompt\n * uploads in fewer round trips. Unset defaults to 32 KiB for the origin of DEFAULT_TANGLE_ROUTER_BASE_URL;\n * other origins send bodies as they are. An explicit threshold wins; a negative value disables gzip.\n */\n gzipRequestAboveBytes?: number\n /**\n * Shape each model request's JSON body once, before it is sent, traced and compressed: the product's payload policy,\n * such as a `max_tokens` floor or a model's effort rule. `fetchImpl` cannot do this for a large request, which reaches\n * it already compressed (`gzipRequestAboveBytes`); this hook always reads the decoded body. The body is the wire\n * format of `request.url`'s endpoint (chat completions carries `messages`; the Responses API carries `input` and\n * `reasoning`). It must not change `model`, which the trace and the served-model check read before shaping. A throw\n * fails the call without a resend.\n */\n shapeRequest?(body: Record<string, unknown>, request: { url: string }): Record<string, unknown>\n}\n\nconst DEFAULT_BUDGET_MS = 90_000\nconst RETRY_STATUS = new Set([408, 425, 429, 500, 502, 503, 504])\n// The Router names a refusal no resend of the same model can fix: every\n// credential for it is out of quota, rejected or suspended (tangle-router\n// `X-Tangle-Failure-Category`). The turn moves to its next fallback model at once.\nconst DEAD_CREDENTIAL_CATEGORIES = new Set(['provider_quota_exhausted', 'provider_key_invalid', 'provider_account_suspended'])\nconst MAX_RETRY_DELAY_MS = 8_000\n// How long a request that may resend keeps resending a retryable answer. The Router answers 503 without calling a\n// model while Platform cannot verify the turn's key: Platform's event loop stalled 16 s (10:30) and a\n// Platform deploy restarted it (11:36), and three sends inside 1 to 16 s failed two Legal turns that 45 s\n// would have carried through.\nconst RETRY_WINDOW_MS = 45_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\nexport interface RouterTurnPromptSections {\n /** Every section that is the same on each turn of a workspace, first, so the bytes repeat turn after turn. */\n prefix: string\n /** What this turn adds: its `context`. Empty when there is none. */\n tail: string\n /** `prefix` then `tail`: the system prompt the model reads. */\n text: string\n}\n\nexport interface RouterTurnPromptOptions {\n /** Sections the same on every turn of a workspace (skills, tool guidance, catalogs, references). They go in the\n * prefix, after the profile's prompt, so a provider's prompt cache serves them. */\n stable?: readonly string[]\n /** This turn's own sections (the clock, the board, what changed, ids). They go last, after every stable byte. */\n context?: readonly string[]\n toolNames?: readonly string[]\n /** Knowledge files every turn carries; see {@link turnKnowledgeInstructions}. They change only when the workspace\n * edits them, so they close the prefix. */\n knowledge?: { files: readonly TurnKnowledgeFile[]; readTool?: string }\n /** Under a test runner (Vitest, Jest, `NODE_ENV=test`) the composition throws when the prefix carries a per-turn\n * byte ({@link perTurnPrefixBytes}), so an app's own tests fail before a timestamp costs every turn its prompt\n * cache. It never runs outside a test runner. `false` turns the check off for a prefix that is meant to vary. */\n checkStablePrefix?: boolean\n}\n\n// A clock to the minute is per-turn by construction: ISO (`2026-10-22T08:15`, `2026-10-22 08:15`), `Date#toString`\n// (`Wed Oct 22 2026 08:15:00`) and `Date#toUTCString` (`Wed, 22 Oct 2026 08:15:00`).\nconst PER_TURN_CLOCKS = [\n /\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}/,\n /\\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{2} \\d{4} \\d{2}:\\d{2}/,\n /\\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \\d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{4} \\d{2}:\\d{2}/,\n]\n/** A turn section shorter than this may repeat a stable phrase; only longer ones are looked for in the prefix. */\nconst MIN_REPEATED_CONTEXT = 24\n\n/**\n * The per-turn bytes in a prompt prefix: a clock to the minute, and any of this turn's `context` sections (or the\n * caller's own per-turn values: ids, the member's message) that also appear there. Empty for a cacheable prefix.\n */\nexport function perTurnPrefixBytes(prefix: string, perTurn: readonly string[] = []): string[] {\n const found = PER_TURN_CLOCKS.flatMap(pattern => prefix.match(pattern)?.[0] ?? [])\n for (const value of perTurn) {\n const trimmed = value.trim()\n if (trimmed.length >= MIN_REPEATED_CONTEXT && prefix.includes(trimmed)) found.push(trimmed.slice(0, 80))\n }\n return found\n}\n\nfunction underTestRunner(): boolean {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env\n return Boolean(env && (env.VITEST || env.JEST_WORKER_ID || env.NODE_ENV === 'test'))\n}\n\n/**\n * The lean system prompt for a Router turn, split where its bytes stop repeating. The prefix holds the profile's\n * system prompt, appended prompt and instructions, the reply-language rule, the caller's `stable` sections and the\n * knowledge files; the tail holds the turn's `context`. Tool names are rewritten to the function names the model\n * actually calls.\n *\n * A provider serves a repeated prompt prefix from its cache: through the Router, Gemini served 38,685 of\n * 40,734 prompt tokens from cache on each repeat of a stable 150 kB prefix, and none when a timestamp came first.\n * One per-turn byte early in the prompt therefore costs the whole prompt on every turn, so nothing\n * per-turn belongs in `stable` or the profile's prompt; under a test runner a clock or a repeated `context` section in\n * the prefix throws (`checkStablePrefix`).\n */\nexport function composeRouterTurnPromptSections(\n profile: { prompt?: { systemPrompt?: string; appendSystemPrompt?: string; instructions?: readonly string[] } },\n options: RouterTurnPromptOptions = {},\n): RouterTurnPromptSections {\n const knowledge = options.knowledge ? turnKnowledgeInstructions(options.knowledge.files, { readTool: options.knowledge.readTool }) : []\n const names = [...(options.toolNames ?? [])].sort((a, b) => b.length - a.length)\n const render = (parts: readonly string[]) => names.reduce((out, name) => out.split(name).join(routerFunctionName(name)),\n parts.filter(part => part.trim()).join('\\n\\n'))\n const authored = [profile.prompt?.systemPrompt ?? '', profile.prompt?.appendSystemPrompt ?? '', ...(profile.prompt?.instructions ?? []),\n replyLanguageInstruction(), ...(options.stable ?? [])]\n const prefix = render([...authored, ...knowledge])\n const tail = render(options.context ?? [])\n // The workspace's knowledge files are its own text and may quote a time; the check reads what the app authored.\n if (options.checkStablePrefix !== false && underTestRunner()) {\n const perTurn = perTurnPrefixBytes(render(authored), (options.context ?? []).map(section => render([section])))\n if (perTurn.length) {\n throw new Error(`composeRouterTurnPromptSections: the stable prefix carries per-turn bytes (${perTurn.map(value => JSON.stringify(value)).join(', ')}); `\n + 'move them to `context` so the prompt cache serves the prefix, or pass `checkStablePrefix: false`.')\n }\n }\n return { prefix, tail, text: [prefix, tail].filter(Boolean).join('\\n\\n') }\n}\n\n/** The system prompt {@link composeRouterTurnPromptSections} composes, as one string. */\nexport function composeRouterTurnPrompt(\n profile: { prompt?: { systemPrompt?: string; appendSystemPrompt?: string; instructions?: readonly string[] } },\n options: RouterTurnPromptOptions = {},\n): string {\n return composeRouterTurnPromptSections(profile, options).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\n/** Add one model call's usage to the turn's totals, and it and why the call ended to that call's span. */\nfunction addCallUsage(\n usage: RouterTurnOutcome['usage'],\n call: { promptTokens: number; completionTokens: number; cachedPromptTokens?: number; reasoningTokens?: number },\n span: TurnSpan | undefined,\n finishReason?: string,\n): void {\n usage.promptTokens += call.promptTokens\n usage.completionTokens += call.completionTokens\n usage.modelCalls++\n const cached = call.cachedPromptTokens\n if (cached !== undefined) usage.cachedPromptTokens = (usage.cachedPromptTokens ?? 0) + cached\n span?.set({\n 'gen_ai.usage.input_tokens': call.promptTokens,\n 'gen_ai.usage.output_tokens': call.completionTokens,\n ...(cached !== undefined ? { 'gen_ai.usage.cache_read.input_tokens': cached } : {}),\n ...(call.reasoningTokens !== undefined ? { 'gen_ai.usage.reasoning_tokens': call.reasoningTokens } : {}),\n ...(finishReason ? { 'gen_ai.response.finish_reasons': finishReason } : {}),\n })\n}\n\n/** What each model call wrote, on its span: answer characters and function calls, zero when it wrote neither. */\nfunction callOutput(state: { lastModelSpan: TurnSpan | undefined }) {\n let made = { span: undefined as TurnSpan | undefined, textChars: 0, toolCalls: 0 }\n return (textChars: number, toolCalls: number) => {\n const span = state.lastModelSpan\n if (made.span !== span) made = { span, textChars: 0, toolCalls: 0 }\n made.textChars += textChars\n made.toolCalls += toolCalls\n span?.set({ 'tangle.model.text_chars': made.textChars, 'tangle.model.tool_calls': made.toolCalls })\n }\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, requestedModel: options.model, toolNames: (options.tools ?? []).map(tool => tool.name) })\n : undefined\n if (placement?.chosen === 'sandbox') {\n return { text: '', answer: '', 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: '', answer: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 }, toolEvents: [],\n ...(placement ? { placement } : {}),\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 traceId = options.traceId !== undefined ? turnTraceId(options.traceId) : options.trace?.traceId\n const { trace } = options\n const transportState = { currentModel: options.model, lastModelSpan: undefined as TurnSpan | undefined }\n const wrote = callOutput(transportState)\n const { fetchImpl } = createRouterTurnTransport(options, trace, transportState, signal, attempts, attemptTimeoutMs, baseDelayMs, pause)\n\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 reasoningAsked = Boolean(options.reasoningEffort) && options.reasoningEffort !== 'none'\n // Legal 2026-10-19/20: the Router refused the gpt-6.1-sol fallback's tool turn on chat completions with a 400 in 2\n // of 2 fallbacks, so the fallback that should have saved those turns failed them.\n const responsesForTools = byFunction.size > 0\n const useResponses = (model: string) => options.stream !== false &&\n (options.api === 'responses' || ((options.api ?? 'auto') === 'auto' && (reasoningAsked || responsesForTools) &&\n isOpenAIResponsesModel(model)))\n // A caller that shows reasoning asks the Router to release a streamed chat call at the first reasoning frame\n // rather than hold it for the first word, which also makes it return Gemini's thought summaries (tangle-router\n // gateway option `streamReasoningImmediately`). The cost: once reasoning has been shown the Router no longer\n // switches models silently. A reasoning-only finish or a stall arrives as an error frame (`empty_completion`,\n // `stream_idle_timeout`), which ends the call by name and takes the safe repeat on the next fallback model, so\n // the option is sent only while that repeat is on. The stall timer stays the Router's own (120 s): Gemini sends a\n // tool call whole, so a stream is silent while the model writes the call. On Legal healthy calls went\n // up to 44.6 s from their last word to their tool call and 66 s from their first frame to it, and a 45 s timer cut\n // 2 of 30 turns after their first sentence.\n const bodyFor = (model: string) => options.showReasoning && options.onEvent && options.repeat !== false &&\n options.stream !== false && !useResponses(model)\n ? { ...extraBody, gateway: { streamReasoningImmediately: true } }\n : extraBody\n const streamTurnFor = (model: string, body?: Record<string, unknown>, sent?: (response: Response) => void) => (options.stream === false ? createOpenAICompatCompletionTurn\n : useResponses(model) ? createOpenAIResponsesTurn : 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 extraBody: { ...bodyFor(model), ...body },\n ...(traceId ? { headers: { 'x-tangle-trace-id': traceId } } : {}),\n ...(sent ? { fetchImpl: async (input, init) => { const response = await (fetchImpl ?? fetch)(input, init); sent(response); return response } }\n : fetchImpl ? { fetchImpl } : {}),\n onServedModel: served => {\n servedModel = served.servedModel\n if (served.servedModel) transportState.lastModelSpan?.set({ 'gen_ai.response.model': served.servedModel })\n },\n })\n const segments: string[] = []\n // Indexes of the segments a tool call followed: narration, not the answer.\n const narrated = new Set<number>()\n const usage: RouterTurnOutcome['usage'] = { promptTokens: 0, completionTokens: 0, modelCalls: 0 }\n // How much reasoning the turn streamed: the number an app logs to measure reasoning coverage.\n const reasoning = { deltas: 0, chars: 0 }\n const toolCalls: RouterTurnOutcome['toolCalls'] = []\n const toolEvents: RouterTurnToolEvent[] = []\n const started = new Map<string, number>()\n const priorCallIds = new Set((options.continueFrom?.messages ?? options.history ?? []).flatMap(message => [\n ...('tool_calls' in message ? (message.tool_calls ?? []).map(call => call.id) : []),\n ...('tool_call_id' in message && message.tool_call_id ? [message.tool_call_id] : []),\n ]))\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) => {\n if (id) return id\n let fallback = `${toolName}-${started.size}`\n while (started.has(fallback) || priorCallIds.has(fallback)) fallback += '_'\n return fallback\n }\n\n let placementFailure: RouterTurnFailure | undefined\n const run = async (model: string): Promise<ToolLoopStopReason | 'tool_limit' | 'placement_refused'> => {\n // A safe model retry still cannot change execution tier after this turn began.\n if (placement && options.placement && model !== options.model) {\n const next = placeRouterTurn({ ...options.placement, requestedModel: model,\n toolNames: (options.tools ?? []).map(tool => tool.name) })\n if (next.chosen !== placement.chosen) {\n placementFailure = { code: 'placement_fallback_refused', message: `The fallback model cannot run in this turn's placement: ${next.reason}` }\n return 'placement_refused'\n }\n }\n transportState.currentModel = model\n const { toolRoundEffort } = options\n const streamTurn = toolRoundEffort && options.stream !== false\n ? toolRoundsAt(streamTurnFor(model), streamTurnFor(model, { tool_choice: 'none' }),\n sent => streamTurnFor(model, { reasoning_effort: toolRoundEffort }, sent))\n : 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 ...(options.maxToolTurns !== undefined ? { maxToolTurns: options.maxToolTurns } : {}),\n labelFor: call => byFunction.get(call.toolName)?.name ?? call.toolName,\n renderResult: (label, outcome) => 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 const toolSpan = trace?.start('tool.call', 'tool', {\n 'gen_ai.tool.name': tool.name,\n 'tool.call_id': call.toolCallId ?? '',\n 'call.index': nextCallIndex(trace, 'tool.call'),\n })\n try {\n const result = await tool.run(call.args, {\n ...(call.toolCallId ? { callId: call.toolCallId } : {}),\n emit: emitEvent,\n userMessage: currentUserMessage,\n ...(signal ? { signal } : {}),\n ...(trace && toolSpan ? { trace, span: toolSpan } : {}),\n })\n toolSpan?.end({ 'tool.ok': true })\n return { ok: true, result }\n } catch (error) {\n const mapped = (options.toolError ?? defaultToolError)(error)\n // The span names the failure by its code; a thrown message can carry customer text.\n toolSpan?.end({ 'tool.ok': false }, mapped?.code ?? 'tool_failed')\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 // A turn that owns its trace outside createChatTurnRoutes (a Durable Object turn) gets first_text_ms here.\n trace?.markFirstText()\n if (!segmentOpen) { segments.push(''); segmentOpen = true }\n segments[segments.length - 1] += event.text\n wrote(event.text.length, 0)\n emit({ type: 'text', segment: segments.length, delta: event.text })\n } else if (event.type === 'reasoning' && event.text) {\n reasoning.deltas++\n reasoning.chars += event.text.length\n emit({ type: 'reasoning', delta: event.text })\n } else if (event.type === 'usage') {\n addCallUsage(usage, event.usage, transportState.lastModelSpan, event.finishReason)\n wrote(0, 0)\n emit({ type: 'usage', ...event.usage })\n } else if (event.type === 'tool_call_start') {\n emit({ type: 'tool_start', toolName: byFunction.get(event.toolName)?.name ?? event.toolName })\n } else if (event.type === 'tool_call') {\n const tool = byFunction.get(event.call.toolName)\n if (segmentOpen && narratesBefore(tool)) narrated.add(segments.length - 1)\n segmentOpen = false\n // The loop yields this event before extracting its call. Normalize a missing id once,\n // so execution, progress, result and replay history reuse the displayed identity.\n event.call.toolCallId ||= callIdOf(undefined, event.call.toolName)\n wrote(0, 1)\n const callId = event.call.toolCallId\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 const text = joinText([options.continueFrom?.text ?? '', ...segments])\n const answer = joinText(segments.filter((_segment, index) => !narrated.has(index)))\n return { text, answer: answer || text,\n servedModel, toolCalls, usage: { ...usage }, reasoning: { ...reasoning }, 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' | 'placement_refused'\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 emit({ type: 'repeat', model: next })\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 // An error frame inside a 200 stream (`openai-stream`'s stream failure) keeps the service's code.\n const streamCode = (error as { streamFailure?: unknown; code?: unknown }).streamFailure === true ? (error as { code?: unknown }).code : undefined\n if (typeof streamCode === 'string' && /^[\\w.-]{1,80}$/.test(streamCode)) {\n return outcome({ code: `model_stream_${streamCode}`, message: 'The model service ended the reply with an error.',\n detail: error instanceof Error ? error.message.slice(0, 1000) : streamCode })\n }\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, 1000) : undefined\n // A spent cap (the turn's key or the source it spends through) is the payer's to fix, not an outage.\n const spent = status === 402 && /budget_(exhausted|exceeded)/i.test(detail ?? '')\n return outcome(typeof status === 'number'\n ? { code: `model_http_${status}`, status, ...(detail ? { detail } : {}),\n message: spent ? 'The paying key has spent its budget. Top it up or raise its cap, then retry.' : 'The model service did not answer.' }\n : { code: 'model_unavailable', message: 'The model service did not answer.' })\n }\n if (placementFailure) return outcome(placementFailure)\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). 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 emit({ type: 'repeat', model: next })\n try { stop = await run(next) } catch { stop = 'completed' }\n if (placementFailure) return outcome(placementFailure)\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\ntype StreamTurn = (messages: LoopMessage[]) => AsyncIterable<LoopEvent>\n\n/**\n * `answer` for the call that opens the turn; after a tool round, `toolRound`, kept only when it calls a tool. A call\n * that writes a word is cancelled there, its connection closed so the model writes no more, and `write` is sent in its\n * place: full effort, the same tools listed but `tool_choice: \"none\"`, so it writes the answer, once, and the turn ends\n * after it. A call that ends with neither a tool call nor a word is sent again as `answer`, tools allowed.\n */\nfunction toolRoundsAt(answer: StreamTurn, write: StreamTurn, toolRound: (sent: (response: Response) => void) => StreamTurn): StreamTurn {\n return async function* (messages) {\n if (messages.at(-1)?.role !== 'tool') { yield* answer(messages); return }\n let response: Response | undefined\n let wrote = false\n let calledTool = false\n for await (const event of toolRound(sent => { response = sent })(messages)) {\n if (event.type === 'text' && event.text) { wrote = true; break }\n calledTool ||= event.type === 'tool_call'\n yield event\n }\n if (calledTool) return\n if (!wrote) { yield* answer(messages); return }\n await response?.body?.cancel().catch(() => {})\n yield* write(messages)\n }\n}\n\nfunction createRouterTurnTransport(\n options: RouterTurnOptions,\n trace: RouterTurnOptions['trace'],\n transportState: { currentModel: string; lastModelSpan: TurnSpan | undefined },\n signal: RouterTurnOptions['signal'],\n attempts: number,\n attemptTimeoutMs: number | undefined,\n baseDelayMs: number,\n pause: (ms: number) => Promise<void>,\n) {\n const gzipAbove = options.gzipRequestAboveBytes ?? (\n URL.canParse(options.baseUrl ?? DEFAULT_TANGLE_ROUTER_BASE_URL) &&\n new URL(options.baseUrl ?? DEFAULT_TANGLE_ROUTER_BASE_URL).origin === new URL(DEFAULT_TANGLE_ROUTER_BASE_URL).origin\n ? 32 * 1024 : undefined\n )\n const baseFetch: typeof fetch | undefined = gzipAbove !== undefined && gzipAbove >= 0\n ? gzipRequestBodies(options.fetchImpl ?? fetch, gzipAbove)\n : options.fetchImpl\n // Each HTTP send is its own `model.call` span, so a retried 503 is visible beside the send that answered.\n const sendOnce: typeof fetch | undefined = trace\n ? tracedModelFetch(trace, baseFetch ?? fetch, {\n onSpan: span => { transportState.lastModelSpan = span; span.set({ 'gen_ai.request.model': transportState.currentModel }) },\n })\n : baseFetch\n const fetchImpl: typeof fetch | undefined = signal || attempts > 1 || attemptTimeoutMs\n ? async (input, init) => {\n const firstSentAt = Date.now()\n // Resending stops once the attempts and the retry window are both spent; one attempt never resends.\n const spent = (attempt: number) => attempts === 1 || (attempt >= attempts && Date.now() - firstSentAt >= RETRY_WINDOW_MS)\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 // The wait before a resend is its own span, so the time between two sends is named, not a gap.\n const wait = (ms: number, reason: string) => trace\n ? trace.measure('model.retry_wait', 'other', () => pause(ms), { 'retry.attempt': attempt, 'retry.reason': reason, 'retry.wait_ms': Math.round(ms) })\n : pause(ms)\n let response: Response\n try {\n // A cancelled turn sends nothing more, whatever the injected fetch does with the signal.\n response = await (sendOnce ?? fetch)(input, { ...init, ...(attemptSignal ? { signal: attemptSignal } : {}) })\n } catch (error) {\n if (signal?.aborted || spent(attempt)) throw error\n await wait(backoff(), 'send_failed')\n continue\n }\n // Nothing has streamed yet, so a resend repeats no word and no tool.\n if (spent(attempt) || !RETRY_STATUS.has(response.status)) return response\n if (DEAD_CREDENTIAL_CATEGORIES.has(response.headers.get('x-tangle-failure-category') ?? '')) return response\n const retryAfter = Number(response.headers.get('retry-after'))\n await response.body?.cancel().catch(() => { })\n await wait(Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1000, MAX_RETRY_DELAY_MS) : backoff(), `http_${response.status}`)\n }\n }\n : sendOnce\n // The product shapes the body once, before any send, so every attempt's span and wire carry the request as shaped.\n return { fetchImpl: options.shapeRequest ? shapeRequestBodies(options.shapeRequest, fetchImpl ?? fetch) : fetchImpl }\n}\n\n/** Apply `shapeRequest` to a JSON object body; any other body is sent as it is. */\nfunction shapeRequestBodies(shape: NonNullable<RouterTurnOptions['shapeRequest']>, send: typeof fetch): typeof fetch {\n return (input, init) => {\n const body = init?.body\n if (typeof body !== 'string') return send(input, init)\n let parsed: unknown\n try { parsed = JSON.parse(body) } catch { return send(input, init) }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return send(input, init)\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url\n return send(input, { ...init, body: JSON.stringify(shape(parsed as Record<string, unknown>, { url })) })\n }\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) {\n await store.delete({ workspaceId, path: turnCheckpointPath(turnId), actor })\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA;AAAA,EACiB;AAAA,EACG;AAAA,OACb;;;ACnBA,SAAS,kBAAkB,MAAoB,UAAgC;AACpF,SAAO,OAAO,OAAO,SAAS;AAC5B,UAAM,OAAO,MAAM;AACnB,QAAI,OAAO,SAAS,YAAY,KAAK,SAAS,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