@tangle-network/agent-app 0.63.2 → 0.63.4
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/agent-profiles/d1.js +3 -3
- package/dist/agent-profiles/index.js +3 -3
- package/dist/chat-routes/cancellation.d.ts +12 -1
- package/dist/chat-routes/index.d.ts +1 -0
- package/dist/chat-routes/index.js +15 -15
- package/dist/chat-routes/route-storage.d.ts +21 -1
- package/dist/chat-routes/stale-turn-lock.d.ts +17 -1
- package/dist/chat-routes/turn-ownership.d.ts +1 -0
- package/dist/chat-routes/turn-route-contracts.d.ts +15 -12
- package/dist/{chunk-ND5XWLRU.js → chunk-72ASTUPN.js} +83 -24
- package/dist/chunk-72ASTUPN.js.map +1 -0
- package/dist/{chunk-XEAZWJ3W.js → chunk-7Y7U7U7X.js} +2 -2
- package/dist/{chunk-5BJHKQ33.js → chunk-ACB7KOQ6.js} +4 -4
- package/dist/{chunk-7TZA2TAM.js → chunk-FCYHDENJ.js} +2 -2
- package/dist/{chunk-WSQFNMIA.js → chunk-HRBF4B5L.js} +5 -5
- package/dist/{chunk-WSQFNMIA.js.map → chunk-HRBF4B5L.js.map} +1 -1
- package/dist/{chunk-SRWQCWLR.js → chunk-IX6UVHXY.js} +3 -3
- package/dist/{chunk-A2NQMVMF.js → chunk-MT6ZTQGD.js} +328 -118
- package/dist/chunk-MT6ZTQGD.js.map +1 -0
- package/dist/{chunk-HG2WVONR.js → chunk-UXK5EBQT.js} +42 -26
- package/dist/chunk-UXK5EBQT.js.map +1 -0
- package/dist/preset-cloudflare/index.js +8 -8
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +8 -8
- package/dist/sandbox/index.js +7 -5
- package/dist/sandbox/prewarm-route.d.ts +7 -0
- package/dist/stream/index.js +17 -17
- package/dist/tools/index.js +4 -4
- package/dist/turn-stream/adapters.d.ts +19 -11
- package/dist/turn-stream/cancellation-do.d.ts +31 -0
- package/dist/turn-stream/cancellation.d.ts +23 -0
- package/dist/turn-stream/core.d.ts +23 -4
- package/dist/turn-stream/do.d.ts +4 -2
- package/dist/turn-stream/index.d.ts +1 -0
- package/dist/turn-stream/index.js +188 -14
- package/dist/turn-stream/index.js.map +1 -1
- package/dist/work-product/index.js +2 -2
- package/package.json +3 -2
- package/dist/chunk-A2NQMVMF.js.map +0 -1
- package/dist/chunk-HG2WVONR.js.map +0 -1
- package/dist/chunk-ND5XWLRU.js.map +0 -1
- /package/dist/{chunk-XEAZWJ3W.js.map → chunk-7Y7U7U7X.js.map} +0 -0
- /package/dist/{chunk-5BJHKQ33.js.map → chunk-ACB7KOQ6.js.map} +0 -0
- /package/dist/{chunk-7TZA2TAM.js.map → chunk-FCYHDENJ.js.map} +0 -0
- /package/dist/{chunk-SRWQCWLR.js.map → chunk-IX6UVHXY.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
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 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. Four 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\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 (2026-10-20) 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/** 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 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_STREAM_PATHS, TURN_STREAM_TOKEN_HEADER, mintTurnStreamToken, turnLockChannelKey } from './core'\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\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 const response = await cancellationRequest(namespace, identity, auth, true) as Response & { webSocket?: ControlSocket }\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 let sandbox: StaleTurnLockSandboxProbeResult\n try {\n sandbox = await options.probeSandbox()\n } catch (err) {\n return forceReleaseUnreachable(options, {\n unreachableReason: 'SANDBOX_PROBE_FAILED',\n unreachableDetail: messageOf(err),\n })\n }\n if (sandbox.status !== 'running') {\n return forceReleaseUnreachable(options, {\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 // Snapshot the clock BEFORE the probe and use that one instant for BOTH the\n // grace decision and the release fence: the release is only valid against the\n // lock as it was when the state was observed, not after an arbitrarily slow\n // round trip. Re-reading the clock after the probe would let a slow round\n // trip age the lock past the grace on paper, and would hand the store a fence\n // newer than a successor lock acquired meanwhile.\n const observedAt = (options.now ?? Date.now)()\n let session: StaleTurnLockSessionProbeResult\n try {\n session = await options.probeSession()\n } catch (err) {\n return forceReleaseUnreachable(options, {\n unreachableReason: 'SESSION_PROBE_FAILED',\n unreachableDetail: messageOf(err),\n })\n }\n if (!session.reachable) {\n return forceReleaseUnreachable(options, {\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 * One clock read (`at`) serves as the age gate AND the release fence here too,\n * for the same reason the terminal branch uses `observedAt` for both.\n */\nasync function forceReleaseUnreachable(\n options: ReconcileStaleTurnLockOptions,\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 at = (options.now ?? Date.now)()\n const lockAgeMs = at - 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: at })\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, and workspace signals.\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 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 * (2026-10-10) 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/** Define input parameters to release an interrupted durable turn lock in a workspace or thread */\nexport type ReleaseInterruptedDurableTurnLockInput = TurnLockInterruptedReleaseInput\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: ReleaseInterruptedDurableTurnLockInput,\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// ── 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 /** 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 → a refused 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 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 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 && options.reconcile) {\n const reconciled = await options.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 }\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 (the\n * per-thread variant went with the deprecated rebroadcast lane; 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"],"mappings":";;;;;;;AAoCO,IAAM,2BAA2B;AAIjC,IAAM,2BAA2B;AAQxC,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,E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AAO,YAAY;AACxB,UAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;AAC/B,QAAI,IAAI,aAAa,QAAQ,QAAQ,QAAQ,IAAI,SAAS,GAAG,YAAY,MAAM,YAAa,QAAO;AAEnG,QAAI,IAAI,aAAa,IAAI,UAAU,GAAG;AACpC,aAAO,IAAI,SAAS,uEAAuE,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC5G;AACA,UAAM,cAAc,IAAI,aAAa,IAAI,aAAa;AACtD,QAAI,CAAC,YAAa,QAAO,IAAI,SAAS,uBAAuB,EAAE,QAAQ,IAAI,CAAC;AAE5E,UAAM,OAAO,MAAM,QAAQ,UAAU,SAAS,EAAE,YAAY,CAAC;AAC7D,QAAI,CAAC,KAAK,GAAI,QAAO,KAAK;AAE1B,UAAM,MAAM,oBAAoB,WAAW;AAC3C,UAAM,OAAO,QAAQ,UAAU,IAAI,QAAQ,UAAU,WAAW,GAAG,CAAC;AAEpE,UAAM,aAAa,IAAI,IAAI,QAAQ,GAAG;AACtC,eAAW,aAAa,IAAI,aAAa,WAAW;AACpD,eAAW,aAAa,IAAI,SAAS,WAAW;AAChD,eAAW,aAAa,OAAO,OAAO;AACtC,UAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;AAC3C,YAAQ,IAAI,0BAA0B,MAAM,oBAAoB,KAAK,QAAQ,UAAU,CAAC;AACxF,WAAO,KAAK,MAAM,IAAI,QAAQ,IAAI,QAAQ,YAAY,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC;AAAA,EAC9E;AACF;","names":[]}
|
|
@@ -18,8 +18,9 @@ import {
|
|
|
18
18
|
import {
|
|
19
19
|
createEscalationSpeculator,
|
|
20
20
|
createSandboxRunTool,
|
|
21
|
-
escalationHints
|
|
22
|
-
|
|
21
|
+
escalationHints,
|
|
22
|
+
resolveTurnStorage
|
|
23
|
+
} from "./chunk-72ASTUPN.js";
|
|
23
24
|
import {
|
|
24
25
|
addStepFinishUsage,
|
|
25
26
|
assistantRowIdForTurn,
|
|
@@ -31,16 +32,6 @@ import {
|
|
|
31
32
|
normalizeClientTurnId,
|
|
32
33
|
resolveChatTurn
|
|
33
34
|
} from "./chunk-YG66IHDU.js";
|
|
34
|
-
import {
|
|
35
|
-
createDurableTurnLock
|
|
36
|
-
} from "./chunk-A2NQMVMF.js";
|
|
37
|
-
import {
|
|
38
|
-
coalesceDeltas,
|
|
39
|
-
createBufferedTurnTap,
|
|
40
|
-
createD1TurnEventStore,
|
|
41
|
-
replayTurnEvents,
|
|
42
|
-
stampReplaySeq
|
|
43
|
-
} from "./chunk-ISP6ZH3G.js";
|
|
44
35
|
import {
|
|
45
36
|
mentionInputToPart,
|
|
46
37
|
toChatMessageParts
|
|
@@ -81,6 +72,12 @@ import {
|
|
|
81
72
|
parseInteractionCancel,
|
|
82
73
|
parseInteractionRequest
|
|
83
74
|
} from "./chunk-6VQCFJWP.js";
|
|
75
|
+
import {
|
|
76
|
+
coalesceDeltas,
|
|
77
|
+
createBufferedTurnTap,
|
|
78
|
+
replayTurnEvents,
|
|
79
|
+
stampReplaySeq
|
|
80
|
+
} from "./chunk-ISP6ZH3G.js";
|
|
84
81
|
import {
|
|
85
82
|
ModelFailoverExhaustedError,
|
|
86
83
|
buildModelChain,
|
|
@@ -1571,6 +1568,10 @@ async function cancelChatTurn(request, options) {
|
|
|
1571
1568
|
return targetChanged();
|
|
1572
1569
|
}
|
|
1573
1570
|
if (target.status === "stopped" || target.status === "answered") return success(false);
|
|
1571
|
+
if (target.control) {
|
|
1572
|
+
const intent = await target.control.request(target.capturedMetadata);
|
|
1573
|
+
return intent.requested ? Response.json({ succeeded: true, sandboxInterrupted: false, cancellationRequested: true }) : targetChanged();
|
|
1574
|
+
}
|
|
1574
1575
|
const markStopped = async () => await target.markStopped(target.capturedMetadata, (/* @__PURE__ */ new Date()).toISOString()) ? null : stateChanged();
|
|
1575
1576
|
if (!target.native) return await markStopped() ?? success(false);
|
|
1576
1577
|
const native = target.native;
|
|
@@ -1844,6 +1845,8 @@ function createChatTurnOwnership(state, log, turnStreamId, options) {
|
|
|
1844
1845
|
turnId: turnStreamId,
|
|
1845
1846
|
error: err instanceof Error ? err.message : String(err)
|
|
1846
1847
|
});
|
|
1848
|
+
} finally {
|
|
1849
|
+
await state.closeCancellation?.();
|
|
1847
1850
|
}
|
|
1848
1851
|
}
|
|
1849
1852
|
})();
|
|
@@ -1853,6 +1856,14 @@ function createChatTurnOwnership(state, log, turnStreamId, options) {
|
|
|
1853
1856
|
const releaseLock = async () => {
|
|
1854
1857
|
if (state.completionHandoff || !state.lockAcquired || state.lockReleased) return;
|
|
1855
1858
|
state.lockReleased = true;
|
|
1859
|
+
try {
|
|
1860
|
+
await state.closeCancellation?.();
|
|
1861
|
+
} catch (err) {
|
|
1862
|
+
log("[chat-routes] turn cancellation close failed", {
|
|
1863
|
+
turnId: turnStreamId,
|
|
1864
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1865
|
+
});
|
|
1866
|
+
}
|
|
1856
1867
|
try {
|
|
1857
1868
|
await options.turnLock.release(state.lockHandle);
|
|
1858
1869
|
} catch (err) {
|
|
@@ -2258,7 +2269,11 @@ async function runAdmittedTurn({
|
|
|
2258
2269
|
request,
|
|
2259
2270
|
waitUntil: ctx?.waitUntil,
|
|
2260
2271
|
earlyResource: early.resource,
|
|
2261
|
-
admissionSignal:
|
|
2272
|
+
admissionSignal: AbortSignal.any([
|
|
2273
|
+
state.executionAbort.signal,
|
|
2274
|
+
...state.cancellationAbort ? [state.cancellationAbort.signal] : [],
|
|
2275
|
+
...ctx?.cancelOnDisconnect ? [request.signal] : []
|
|
2276
|
+
]),
|
|
2262
2277
|
body: payload,
|
|
2263
2278
|
identity,
|
|
2264
2279
|
context,
|
|
@@ -2283,6 +2298,16 @@ async function runAdmittedTurn({
|
|
|
2283
2298
|
if (!acquired.acquired) return acquired.response;
|
|
2284
2299
|
state.lockAcquired = true;
|
|
2285
2300
|
state.lockHandle = acquired.handle;
|
|
2301
|
+
if (acquired.cancellation) {
|
|
2302
|
+
const cancellation = acquired.cancellation;
|
|
2303
|
+
const abort = () => state.executionAbort.abort(cancellation.signal.reason);
|
|
2304
|
+
if (cancellation.signal.aborted) abort();
|
|
2305
|
+
else cancellation.signal.addEventListener("abort", abort, { once: true });
|
|
2306
|
+
state.closeCancellation = async () => {
|
|
2307
|
+
cancellation.signal.removeEventListener("abort", abort);
|
|
2308
|
+
await cancellation.close();
|
|
2309
|
+
};
|
|
2310
|
+
}
|
|
2286
2311
|
}
|
|
2287
2312
|
progress?.("preparing", progressMessages.preparing);
|
|
2288
2313
|
const { endTrace, exportTraceInBackground, fireTerminalLifecycle, assistantRowId, exportTrace, runAfterSettle } = createTurnSettlement(state, trace, options, executionId, traceSink, identity, traceOptions, context, turnStreamId, log, ctx);
|
|
@@ -2424,6 +2449,8 @@ async function runAdmittedTurn({
|
|
|
2424
2449
|
}
|
|
2425
2450
|
function createAdmittedTurnState() {
|
|
2426
2451
|
return {
|
|
2452
|
+
executionAbort: new AbortController(),
|
|
2453
|
+
closeCancellation: void 0,
|
|
2427
2454
|
draft: void 0,
|
|
2428
2455
|
tap: void 0,
|
|
2429
2456
|
nativeTiming: void 0,
|
|
@@ -2658,7 +2685,7 @@ function createTurnEngine(identity, ctx, log, state, dispatched, produceArgs, tr
|
|
|
2658
2685
|
yield* state.producer.stream;
|
|
2659
2686
|
};
|
|
2660
2687
|
let source = producerStream();
|
|
2661
|
-
if (options.cancel && state.cancellationAbort) {
|
|
2688
|
+
if (options.cancel && state.cancellationAbort && !state.closeCancellation) {
|
|
2662
2689
|
source = observeTurnCancellation(source, produceArgs, options.cancel, state.cancellationAbort);
|
|
2663
2690
|
}
|
|
2664
2691
|
if (ctx?.cancelOnDisconnect) {
|
|
@@ -2883,17 +2910,6 @@ function earlyTurnWork(started, log) {
|
|
|
2883
2910
|
};
|
|
2884
2911
|
}
|
|
2885
2912
|
|
|
2886
|
-
// src/chat-routes/route-storage.ts
|
|
2887
|
-
function resolveTurnStorage(options) {
|
|
2888
|
-
const store = options.turnStore;
|
|
2889
|
-
if ("append" in store) return { ...options, turnStore: store };
|
|
2890
|
-
return {
|
|
2891
|
-
...options,
|
|
2892
|
-
turnStore: createD1TurnEventStore(store.db),
|
|
2893
|
-
turnLock: options.turnLock ?? createDurableTurnLock({ ...store.lock, scopeOf: () => "thread" })
|
|
2894
|
-
};
|
|
2895
|
-
}
|
|
2896
|
-
|
|
2897
2913
|
// src/chat-routes/turn-routes.ts
|
|
2898
2914
|
async function admitTurn(request, trace, options, waitUntil) {
|
|
2899
2915
|
const parse = trace.start("admission.parse", "admission");
|
|
@@ -3362,4 +3378,4 @@ export {
|
|
|
3362
3378
|
createChatTurnRoutes,
|
|
3363
3379
|
streamChatRouteAsSandboxEvents
|
|
3364
3380
|
};
|
|
3365
|
-
//# sourceMappingURL=chunk-
|
|
3381
|
+
//# sourceMappingURL=chunk-UXK5EBQT.js.map
|