@tangle-network/agent-app 4.0.36 → 4.0.37

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.
Files changed (49) hide show
  1. package/dist/assistant/index.js +5 -5
  2. package/dist/chat-react/index.js +3 -3
  3. package/dist/chat-routes/index.js +16 -8
  4. package/dist/chat-routes/index.js.map +1 -1
  5. package/dist/chat-routes/turn-event-stream.d.ts +10 -1
  6. package/dist/chat-routes/turn-execution.d.ts +34 -3
  7. package/dist/chat-routes/turn-intent.d.ts +5 -0
  8. package/dist/chat-routes/turn-progress.d.ts +25 -1
  9. package/dist/chat-routes/turn-route-contracts.d.ts +31 -2
  10. package/dist/chat-routes/turn-settlement.d.ts +23 -0
  11. package/dist/chat-store/index.js +2 -2
  12. package/dist/{chunk-NAMSFODC.js → chunk-4YBNKXUE.js} +54 -4
  13. package/dist/chunk-4YBNKXUE.js.map +1 -0
  14. package/dist/{chunk-K2JPSXKI.js → chunk-6YLVFV3F.js} +39 -3
  15. package/dist/chunk-6YLVFV3F.js.map +1 -0
  16. package/dist/{chunk-23YED7HQ.js → chunk-77UNTK66.js} +355 -288
  17. package/dist/chunk-77UNTK66.js.map +1 -0
  18. package/dist/{chunk-KPCNNFBO.js → chunk-AOSQ5JCO.js} +41 -2
  19. package/dist/{chunk-KPCNNFBO.js.map → chunk-AOSQ5JCO.js.map} +1 -1
  20. package/dist/{chunk-GOKFD7ZZ.js → chunk-BMRKOPL6.js} +2 -2
  21. package/dist/{chunk-E633CJFH.js → chunk-COUT2WD5.js} +2 -2
  22. package/dist/{chunk-7VJCMEEE.js → chunk-DPD7LY3T.js} +11 -6
  23. package/dist/chunk-DPD7LY3T.js.map +1 -0
  24. package/dist/{chunk-MQCAO5VW.js → chunk-MGW25KMR.js} +3 -3
  25. package/dist/{chunk-IAK227OO.js → chunk-Q7NELHRU.js} +2 -2
  26. package/dist/{chunk-4YZKDWMB.js → chunk-SADNHPAY.js} +2 -2
  27. package/dist/operator/index.js +2 -2
  28. package/dist/preset-cloudflare/index.js +5 -5
  29. package/dist/public-consultation/index.d.ts +1 -1
  30. package/dist/public-consultation/index.js +6 -6
  31. package/dist/sandbox/index.js +3 -3
  32. package/dist/turn-stream/cancellation.d.ts +16 -0
  33. package/dist/turn-stream/core.d.ts +4 -0
  34. package/dist/turn-stream/do.d.ts +4 -2
  35. package/dist/turn-stream/hosted-turn.d.ts +20 -0
  36. package/dist/turn-stream/index.js +122 -5
  37. package/dist/turn-stream/index.js.map +1 -1
  38. package/dist/web-react/chat-stream.d.ts +4 -2
  39. package/dist/web-react/index.js +13 -5
  40. package/package.json +1 -1
  41. package/dist/chunk-23YED7HQ.js.map +0 -1
  42. package/dist/chunk-7VJCMEEE.js.map +0 -1
  43. package/dist/chunk-K2JPSXKI.js.map +0 -1
  44. package/dist/chunk-NAMSFODC.js.map +0 -1
  45. /package/dist/{chunk-GOKFD7ZZ.js.map → chunk-BMRKOPL6.js.map} +0 -0
  46. /package/dist/{chunk-E633CJFH.js.map → chunk-COUT2WD5.js.map} +0 -0
  47. /package/dist/{chunk-MQCAO5VW.js.map → chunk-MGW25KMR.js.map} +0 -0
  48. /package/dist/{chunk-IAK227OO.js.map → chunk-Q7NELHRU.js.map} +0 -0
  49. /package/dist/{chunk-4YZKDWMB.js.map → chunk-SADNHPAY.js.map} +0 -0
@@ -7,6 +7,8 @@ import {
7
7
  // src/turn-stream/core.ts
8
8
  var TURN_STREAM_TOKEN_TTL_MS = 6e4;
9
9
  var TURN_STREAM_TOKEN_HEADER = "x-turn-stream-token";
10
+ var TURN_HOST_CANCEL_PATH = "/turn-host/cancel";
11
+ var TURN_HOST_CONTROL_PATH = "/turn-host/control";
10
12
  function encodeTurnStreamClaims(claims) {
11
13
  const { identity, purpose } = claims;
12
14
  if (!["turn-control", "turn-cancel", "turn-recovery"].includes(purpose) || !identity || !["thread", "workspace"].includes(identity.scope) || [identity.workspaceId, identity.threadId, identity.executionId, identity.lockId, identity.turnStreamId].some((value) => typeof value !== "string" || !value.trim())) throw new Error("Invalid turn-stream control claims");
@@ -157,6 +159,37 @@ var TurnControlUnavailableError = class extends Error {
157
159
  this.name = "TurnControlUnavailableError";
158
160
  }
159
161
  };
162
+ async function requestHostedTurnCancellation(namespace, target, auth) {
163
+ const response = await hostedCancellationRequest(namespace, target, auth, false);
164
+ if (!response) return { requested: false, reason: "stale-host" };
165
+ if (!response.ok) throw new Error(`Hosted turn cancellation failed (HTTP ${response.status})`);
166
+ return response.json();
167
+ }
168
+ async function connectHostedTurnCancellation(namespace, target, auth) {
169
+ const response = await hostedCancellationRequest(namespace, target, auth, true);
170
+ if (!response) throw new TurnControlUnavailableError("The host id is invalid");
171
+ return observeCancellationSocket(response);
172
+ }
173
+ async function hostedCancellationRequest(namespace, target, auth, upgrade) {
174
+ let id;
175
+ try {
176
+ id = namespace.idFromString(target.hostId);
177
+ } catch {
178
+ return null;
179
+ }
180
+ const url = new URL(`https://turn-stream.internal${upgrade ? TURN_HOST_CONTROL_PATH : TURN_HOST_CANCEL_PATH}`);
181
+ if (upgrade) {
182
+ for (const [key, value] of Object.entries(target)) if (value !== void 0) url.searchParams.set(key, value);
183
+ }
184
+ return namespace.get(id).fetch(url.href, {
185
+ method: upgrade ? "GET" : "POST",
186
+ headers: {
187
+ ...upgrade ? { Upgrade: "websocket" } : { "Content-Type": "application/json" },
188
+ [TURN_STREAM_TOKEN_HEADER]: await mintTurnStreamToken(turnHostChannelKey(target.hostId), auth.secret)
189
+ },
190
+ ...upgrade ? {} : { body: JSON.stringify(target) }
191
+ });
192
+ }
160
193
  async function cancellationRequest(namespace, identity, auth, upgrade) {
161
194
  const key = turnLockChannelKey(identity.workspaceId, identity.threadId, identity.scope);
162
195
  const url = new URL(`https://turn-stream.internal${upgrade ? "/" : TURN_STREAM_PATHS.lockReleaseInterrupted}`);
@@ -185,7 +218,9 @@ async function requestDurableTurnCancellation(namespace, identity, auth) {
185
218
  return response.json();
186
219
  }
187
220
  async function connectDurableTurnCancellation(namespace, identity, auth) {
188
- const response = await cancellationRequest(namespace, identity, auth, true);
221
+ return observeCancellationSocket(await cancellationRequest(namespace, identity, auth, true));
222
+ }
223
+ async function observeCancellationSocket(response) {
189
224
  if (response.status !== 101 || !response.webSocket) throw new TurnControlUnavailableError(`Turn control connection failed (HTTP ${response.status})`);
190
225
  const socket = response.webSocket;
191
226
  const controller = new AbortController();
@@ -731,6 +766,8 @@ async function forwardTurnToHost(host, request) {
731
766
  export {
732
767
  TURN_STREAM_TOKEN_TTL_MS,
733
768
  TURN_STREAM_TOKEN_HEADER,
769
+ TURN_HOST_CANCEL_PATH,
770
+ TURN_HOST_CONTROL_PATH,
734
771
  mintTurnStreamToken,
735
772
  verifyTurnStreamToken,
736
773
  threadChannelKey,
@@ -753,6 +790,8 @@ export {
753
790
  turnEventStorageKey,
754
791
  TurnCancellationRequestedError,
755
792
  TurnControlUnavailableError,
793
+ requestHostedTurnCancellation,
794
+ connectHostedTurnCancellation,
756
795
  requestDurableTurnCancellation,
757
796
  connectDurableTurnCancellation,
758
797
  DEFAULT_STALE_TURN_LOCK_GRACE_MS,
@@ -773,4 +812,4 @@ export {
773
812
  createTurnStreamUpgradeHandler,
774
813
  forwardTurnToHost
775
814
  };
776
- //# sourceMappingURL=chunk-KPCNNFBO.js.map
815
+ //# sourceMappingURL=chunk-AOSQ5JCO.js.map
@@ -1 +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. 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_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 // 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;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,K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W,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;AAeA,eAAsB,kBAAkB,MAAgB,SAAqC;AAC3F,QAAM,KAAK,KAAK,UAAU,YAAY;AACtC,QAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;AAC3C,UAAQ,IAAI,0BAA0B,MAAM,oBAAoB,mBAAmB,OAAO,EAAE,CAAC,GAAG,KAAK,KAAK,MAAM,CAAC;AACjH,SAAO,KAAK,UAAU,IAAI,IAAI,EAAE,cAAc,KAAK,gBAAgB,gCAAgC,CAAC,EAAE,MAAM,IAAI,QAAQ,SAAS,EAAE,QAAQ,CAAC,CAAC;AAC/I;","names":[]}
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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AY,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;AAeA,eAAsB,kBAAkB,MAAgB,SAAqC;AAC3F,QAAM,KAAK,KAAK,UAAU,YAAY;AACtC,QAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;AAC3C,UAAQ,IAAI,0BAA0B,MAAM,oBAAoB,mBAAmB,OAAO,EAAE,CAAC,GAAG,KAAK,KAAK,MAAM,CAAC;AACjH,SAAO,KAAK,UAAU,IAAI,IAAI,EAAE,cAAc,KAAK,gBAAgB,gCAAgC,CAAC,EAAE,MAAM,IAAI,QAAQ,SAAS,EAAE,QAAQ,CAAC,CAAC;AAC/I;","names":[]}
@@ -2,7 +2,7 @@ import {
2
2
  TURN_USAGE_KEYS,
3
3
  addStepFinishUsage,
4
4
  withoutToolList
5
- } from "./chunk-NAMSFODC.js";
5
+ } from "./chunk-4YBNKXUE.js";
6
6
  import {
7
7
  asRecord,
8
8
  asString,
@@ -447,4 +447,4 @@ export {
447
447
  TOOL_ABORTED_ERROR,
448
448
  observeNativeCompletion
449
449
  };
450
- //# sourceMappingURL=chunk-GOKFD7ZZ.js.map
450
+ //# sourceMappingURL=chunk-BMRKOPL6.js.map
@@ -31,7 +31,7 @@ import {
31
31
  checkAttachmentType,
32
32
  sanitizeAttachmentFileName,
33
33
  sniffBinary
34
- } from "./chunk-IAK227OO.js";
34
+ } from "./chunk-Q7NELHRU.js";
35
35
 
36
36
  // src/web-react/use-dictation.ts
37
37
  import { useCallback, useEffect, useRef, useState } from "react";
@@ -1853,4 +1853,4 @@ export {
1853
1853
  ComposerModeControls,
1854
1854
  EntryComposer
1855
1855
  };
1856
- //# sourceMappingURL=chunk-E633CJFH.js.map
1856
+ //# sourceMappingURL=chunk-COUT2WD5.js.map
@@ -56,7 +56,7 @@ import {
56
56
  } from "./chunk-QM5TPZQY.js";
57
57
  import {
58
58
  attachmentPartsFromMessageParts
59
- } from "./chunk-4YZKDWMB.js";
59
+ } from "./chunk-SADNHPAY.js";
60
60
  import {
61
61
  cancelStatusFor,
62
62
  fieldAcceptsFreeText,
@@ -73,7 +73,7 @@ import {
73
73
  isTurnIntentEvent,
74
74
  isTurnPhaseEvent,
75
75
  settleTurnResponse
76
- } from "./chunk-K2JPSXKI.js";
76
+ } from "./chunk-6YLVFV3F.js";
77
77
  import {
78
78
  parsePlanSubmittedEvent,
79
79
  persistedPartToPlan
@@ -335,10 +335,15 @@ function defaultReconnectDelayMs(attempt, rand = Math.random) {
335
335
  return Math.min(8e3, 500 * 2 ** attempt * (0.5 + rand()));
336
336
  }
337
337
  async function streamChatTurn(opts) {
338
- const res = await settleTurnResponse(await opts.start(), (phase) => opts.callbacks.onPhase?.(phase));
338
+ const res = await settleTurnResponse(
339
+ await opts.start(),
340
+ (phase) => opts.callbacks.onPhase?.(phase),
341
+ opts.callbacks.onIntent,
342
+ opts.callbacks.onHostControl
343
+ );
339
344
  if (!res.ok || !res.body) {
340
- const { error: e } = await res.json().catch(() => ({}));
341
- throw Object.assign(new Error((typeof e === "string" ? e : e?.message) ?? `HTTP ${res.status}`), { code: typeof e === "object" ? e?.code : void 0 });
345
+ const { error: e, code } = await res.json().catch(() => ({}));
346
+ throw Object.assign(new Error((typeof e === "string" ? e : e?.message) ?? `HTTP ${res.status}`), { code: (typeof e === "object" ? e?.code : void 0) ?? code });
342
347
  }
343
348
  let turnId = res.headers.get("x-turn-id")?.trim() || null;
344
349
  const withTurnId = {
@@ -9002,4 +9007,4 @@ export {
9002
9007
  AgentProfileChoices,
9003
9008
  ComposerProfilePill
9004
9009
  };
9005
- //# sourceMappingURL=chunk-7VJCMEEE.js.map
9010
+ //# sourceMappingURL=chunk-DPD7LY3T.js.map