@tangle-network/agent-app 0.48.1 → 0.48.3

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 (53) hide show
  1. package/dist/DesignCanvas-YLVDCX6H.js +11 -0
  2. package/dist/DesignCanvasEditor-4QWY2LHM.js +14 -0
  3. package/dist/app-auth/index.js +2 -2
  4. package/dist/chat-routes/completed-sandbox-turn.d.ts +3 -3
  5. package/dist/chat-routes/detached-turn.d.ts +2 -2
  6. package/dist/chat-routes/draft-persistence.d.ts +1 -1
  7. package/dist/chat-routes/index.js +33 -37
  8. package/dist/chat-routes/index.js.map +1 -1
  9. package/dist/{chunk-VHMZ3KUH.js → chunk-2WVBGQ2Y.js} +2 -2
  10. package/dist/chunk-3NM4GCAY.js +170 -0
  11. package/dist/chunk-3NM4GCAY.js.map +1 -0
  12. package/dist/{chunk-WYHFHTSQ.js → chunk-BWQPVS7D.js} +2 -2
  13. package/dist/{chunk-IAY2DMKW.js → chunk-EA4UVS4T.js} +61 -2
  14. package/dist/chunk-EA4UVS4T.js.map +1 -0
  15. package/dist/{chunk-AKMQFCDL.js → chunk-FEVVF6JJ.js} +2 -2
  16. package/dist/{chunk-JF423ASS.js → chunk-G2B23BZ6.js} +5 -5
  17. package/dist/{chunk-JAT6SOPK.js → chunk-KWN5PGXM.js} +3 -3
  18. package/dist/{chunk-SYWEMKZR.js → chunk-MFLUDFD3.js} +3 -3
  19. package/dist/chunk-MFLUDFD3.js.map +1 -0
  20. package/dist/{chunk-CSMJM7YT.js → chunk-TWTLQWES.js} +2 -2
  21. package/dist/{chunk-KX2GA3L6.js → chunk-WAMJSZYB.js} +3 -3
  22. package/dist/design-canvas/index.js +2 -2
  23. package/dist/design-canvas-react/engine.js +4 -4
  24. package/dist/design-canvas-react/index.js +7 -7
  25. package/dist/design-canvas-react/lazy.js +1 -1
  26. package/dist/platform/index.js +2 -2
  27. package/dist/preset-cloudflare/detached-turn-workflow.d.ts +6 -20
  28. package/dist/preset-cloudflare/index.js +13 -10
  29. package/dist/preset-cloudflare/index.js.map +1 -1
  30. package/dist/public-consultation/index.js +3 -3
  31. package/dist/sequences/index.js +1 -1
  32. package/dist/stream/index.d.ts +1 -0
  33. package/dist/stream/index.js +7 -1
  34. package/dist/stream/turn-observation.d.ts +32 -0
  35. package/dist/web/api-key-fetch.d.ts +12 -0
  36. package/dist/web/index.d.ts +1 -0
  37. package/dist/web/index.js +3 -1
  38. package/package.json +3 -3
  39. package/dist/DesignCanvas-MWEYD6PR.js +0 -11
  40. package/dist/DesignCanvasEditor-UZ2S6BDD.js +0 -14
  41. package/dist/chunk-IAY2DMKW.js.map +0 -1
  42. package/dist/chunk-JEZJ6HTF.js +0 -77
  43. package/dist/chunk-JEZJ6HTF.js.map +0 -1
  44. package/dist/chunk-SYWEMKZR.js.map +0 -1
  45. /package/dist/{DesignCanvas-MWEYD6PR.js.map → DesignCanvas-YLVDCX6H.js.map} +0 -0
  46. /package/dist/{DesignCanvasEditor-UZ2S6BDD.js.map → DesignCanvasEditor-4QWY2LHM.js.map} +0 -0
  47. /package/dist/{chunk-VHMZ3KUH.js.map → chunk-2WVBGQ2Y.js.map} +0 -0
  48. /package/dist/{chunk-WYHFHTSQ.js.map → chunk-BWQPVS7D.js.map} +0 -0
  49. /package/dist/{chunk-AKMQFCDL.js.map → chunk-FEVVF6JJ.js.map} +0 -0
  50. /package/dist/{chunk-JF423ASS.js.map → chunk-G2B23BZ6.js.map} +0 -0
  51. /package/dist/{chunk-JAT6SOPK.js.map → chunk-KWN5PGXM.js.map} +0 -0
  52. /package/dist/{chunk-CSMJM7YT.js.map → chunk-TWTLQWES.js.map} +0 -0
  53. /package/dist/{chunk-KX2GA3L6.js.map → chunk-WAMJSZYB.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat-routes/draft-persistence.ts","../src/chat-routes/turn-routes.ts","../src/chat-routes/gateway-adapter.ts"],"sourcesContent":["/**\n * Incremental (\"draft\") persistence of the assistant row WHILE a turn streams.\n *\n * Why this exists — the scale argument, not a convenience:\n *\n * A live turn is readable from two places. The hot path is the session\n * gateway's in-memory/Redis event buffer, which exists so a viewer survives a\n * network blip: it is keyed one sorted set per session, refreshed on every\n * push, and expires on a TTL. Its memory cost is `arrival_rate x TTL x\n * bytes_per_session` — strictly LINEAR in the TTL. Stretching that TTL to\n * cover \"a viewer who opens the tab later\" is a category error: it buys memory\n * proportional to the increase and still serves nothing to a viewer who\n * arrives past the new horizon.\n *\n * So the hot buffer must stay SHORT (live delivery + reconnect only), and\n * durable storage must serve history. That only works if durable storage\n * actually HAS the in-flight turn — which, before this module, it did not: the\n * assistant row was written once, after the stream drained. A viewer arriving\n * mid-turn past the hot window read an empty transcript.\n *\n * This module closes that gap: the assistant row is inserted early and patched\n * on a coalesced cadence, so the durable transcript is at most one interval\n * (default 2 s) behind the live stream and the hot buffer never has to be the\n * history tier.\n *\n * Mechanism only. It owns no vocabulary: the caller supplies the snapshot\n * function, the store, and the deterministic row id.\n *\n * Four properties the cadence guarantees:\n * - **Time-floored.** At most one write per `intervalMs`, never one per token.\n * - **Dirty-gated.** Only content-bearing events arm a write; heartbeats,\n * status pings, and lifecycle envelopes never do.\n * - **Single-flight.** A write already in flight suppresses the next trigger\n * instead of queueing; the final write is authoritative regardless of how\n * many drafts landed.\n * - **Best-effort.** A store failure is logged and swallowed — a durability\n * optimization must never kill a healthy stream (the same rule\n * `withDurableChatProjection` already states).\n */\n\nimport { toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport type { ChatTurnUsage } from './turn-routes'\n\n/** Message row shape the writer reads back when re-entering a turn. */\nexport interface DraftStoredMessage extends Pick<AssistantRowValues, keyof ChatTurnUsage> {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n}\n\n/** Values written to the assistant row — the intersection of the append and\n * patch shapes, so one snapshot serves both. */\nexport interface AssistantRowValues {\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n}\n\n/** The store capability incremental persistence needs on top of\n * `appendMessage`. A store without `updateMessage` cannot patch a row, so it\n * cannot draft at all — the caller keeps today's single-write behavior. */\nexport interface AssistantDraftStore {\n listMessages(threadId: string): Promise<DraftStoredMessage[]>\n appendMessage(input: AssistantRowValues & {\n id?: string\n threadId: string\n role: 'user' | 'assistant'\n }): Promise<unknown>\n updateMessage?(id: string, patch: AssistantRowValues): Promise<unknown>\n deleteMessage?(id: string): Promise<unknown>\n}\n\n/** Live snapshot of the assistant body, taken from the producer's own\n * accumulators. `parts` is the DRAFT projection (`draftParts()`), never the\n * finalized one — see `draftAssistantParts`. */\nexport interface AssistantDraftSnapshot {\n content: string\n parts?: Array<Record<string, unknown>>\n usage?: ChatTurnUsage\n model?: string\n}\n\n/** Product-tunable cadence. Defaults are stated on each field; a product with\n * a chattier or heavier workload moves them without forking the writer. */\nexport interface DraftPersistenceTuning {\n /** Minimum wall-clock gap between draft writes, in ms. Default 2000.\n *\n * Justification for 2 s, from a measured tool-heavy production run (517\n * stream events over ~90 s wall = ~5.7 events/s): a 2 s floor with the\n * dirty gate turns 517 candidate writes into <= 45, while leaving the\n * durable row at most 2 s stale — an order of magnitude below the time it\n * takes a viewer to open a tab and render, so a late viewer never perceives\n * the lag. Fleet arithmetic at 10k concurrent 60 s runs: <= 30 updates per\n * run x 167 run-starts/s = ~334 row-updates/s spread over per-tenant\n * shards. Lower it and write amplification grows with no perceptible\n * freshness gain; raise it past ~5 s and a late viewer starts seeing a\n * visibly truncated answer. */\n intervalMs?: number\n /** Serialized-parts size (bytes) past which the interval backs off, so a\n * turn accumulating a megabyte-scale `parts` blob does not rewrite it every\n * interval. Default 262144 (256 KiB) -> interval x 2.5; ten times that ->\n * interval x 5. The final write is never throttled. */\n backoffBytes?: number\n /** Per-tool-part output cap applied to DRAFTS ONLY (bytes). A tool returning\n * a large blob would otherwise be rewritten in full on every draft. The\n * final write always carries the untruncated value. Default 32768 (32 KiB);\n * 0 disables truncation. */\n maxDraftToolOutputBytes?: number\n}\n\n/** Define the inputs required to construct an assistant draft writer */\nexport interface AssistantDraftWriterOptions extends DraftPersistenceTuning {\n store: AssistantDraftStore\n threadId: string\n /** DETERMINISTIC row id for this turn's assistant message — the whole\n * idempotency mechanism. Derived from the turn's existing identity\n * (`deriveExecutionId` in the interactive lane, the turn id in the detached\n * lane), so a re-entered turn addresses the SAME row: the writer looks the\n * id up before its first insert and patches what it finds. */\n messageId: string\n /** Read the producer's live accumulators. Returns null before the producer\n * is resolved (the assembly defers box resolution into the first pull). */\n snapshot(): AssistantDraftSnapshot | null\n /** Pre-persist text transform (`/redact`'s `redactPII`). Applied to the\n * draft's scalar content AND every draft text part — parity with the final\n * write, or incremental persistence would re-open the at-rest PII leak that\n * transform closed, just seconds earlier and on every turn. */\n transformText?(text: string): string | Promise<string>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Coalescing writer that keeps one durable assistant row in step with a\n * streaming turn. Created per turn; not reusable. */\nexport interface AssistantDraftWriter {\n /** Arm/trigger a draft write from one engine event. Synchronous by design —\n * the write itself is fire-and-forget so the stream is never blocked on\n * store latency. */\n notify(event: { type?: unknown }): void\n /** Stop drafting and settle any in-flight write. Called before the final\n * write so a late draft can never clobber the authoritative row. */\n close(): Promise<void>\n /** Write the AUTHORITATIVE completion values onto this turn's row —\n * insert-or-patch under the same deterministic id, un-throttled and\n * un-truncated. Errors propagate: the final write is the one that must not\n * fail silently. Implies {@link close}. */\n finalize(values: AssistantRowValues): Promise<void>\n /** The durable row this turn is writing, once one exists. */\n rowId(): string | undefined\n /** Retract the row for a turn that produced nothing (mirrors the final\n * write's empty-turn skip, which leaves no row at all today). Also retracts\n * a row a PREVIOUS attempt left behind, so a re-entered turn that ends\n * empty converges on \"no row\" rather than a stale partial. */\n discard(): Promise<void>\n /** Diagnostics: how many draft writes actually reached the store. */\n writeCount(): number\n}\n\n/** Event types that carry assistant content and therefore arm a draft write.\n * An allowlist on purpose: an unknown type (a product heartbeat, a bespoke\n * passthrough) must NEVER arm a write, or a silent producer would rewrite the\n * same row forever. */\nconst CONTENT_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'text',\n 'reasoning',\n 'tool_call',\n 'tool_result',\n 'usage',\n 'notice',\n 'error',\n 'file',\n 'interaction',\n 'interaction.cancel',\n 'plan.submitted',\n 'message.part.updated',\n])\n\nconst DEFAULT_INTERVAL_MS = 2000\nconst DEFAULT_BACKOFF_BYTES = 262144\nconst DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES = 32768\n\n/** True when this event should arm a draft write. */\nexport function isDraftContentEvent(event: { type?: unknown }): boolean {\n return typeof event?.type === 'string' && CONTENT_EVENT_TYPES.has(event.type)\n}\n\n/** Caps one tool part's `output` for a DRAFT write. The value is replaced by a\n * truncated string plus a marker, so a reader can tell a clipped draft from a\n * real short output; the final write restores the untruncated value. */\nfunction capDraftToolOutput(part: Record<string, unknown>, maxBytes: number): Record<string, unknown> {\n if (maxBytes <= 0) return part\n if (String(part.type ?? '') !== 'tool') return part\n const state = part.state\n if (!state || typeof state !== 'object') return part\n const record = state as Record<string, unknown>\n const output = record.output\n if (output === undefined || output === null) return part\n const serialized = typeof output === 'string' ? output : safeStringify(output)\n if (serialized.length <= maxBytes) return part\n const metadata = (record.metadata && typeof record.metadata === 'object' ? record.metadata : {}) as Record<string, unknown>\n return {\n ...part,\n state: {\n ...record,\n output: `${serialized.slice(0, maxBytes)}…[draft-truncated ${serialized.length - maxBytes} chars]`,\n metadata: { ...metadata, draftTruncated: true },\n },\n }\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? ''\n } catch {\n return String(value)\n }\n}\n\n/** Build the coalescing draft writer for one turn. */\nexport function createAssistantDraftWriter(options: AssistantDraftWriterOptions): AssistantDraftWriter {\n const log = options.log ?? (() => {})\n const baseIntervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS\n const backoffBytes = options.backoffBytes ?? DEFAULT_BACKOFF_BYTES\n const maxToolOutput = options.maxDraftToolOutputBytes ?? DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES\n\n let dirty = false\n let closed = false\n let inFlight: Promise<void> | undefined\n let lastWriteAt = 0\n let lastBlobBytes = 0\n let rowId: string | undefined\n let writes = 0\n\n /** Interval for the NEXT write, backed off by the size of the last blob\n * written — a turn accumulating a huge parts array rewrites it less often. */\n function currentIntervalMs(): number {\n if (lastBlobBytes >= backoffBytes * 10) return baseIntervalMs * 5\n if (lastBlobBytes >= backoffBytes) return Math.round(baseIntervalMs * 2.5)\n return baseIntervalMs\n }\n\n async function projectValues(snapshot: AssistantDraftSnapshot): Promise<AssistantRowValues> {\n const transform = options.transformText\n const content = transform ? await transform(snapshot.content) : snapshot.content\n let parts: ChatMessagePart[] | undefined\n if (snapshot.parts) {\n const capped = snapshot.parts.map((part) => capDraftToolOutput(part, maxToolOutput))\n const redacted = transform\n ? await Promise.all(\n capped.map(async (part) =>\n String((part as { type?: unknown }).type ?? '') === 'text'\n ? { ...part, text: await transform(String((part as { text?: unknown }).text ?? '')) }\n : part,\n ),\n )\n : capped\n parts = toChatMessageParts(redacted)\n }\n const usage = snapshot.usage ?? {}\n return {\n content,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(snapshot.model ? { model: snapshot.model } : {}),\n ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),\n ...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cacheWriteTokens !== undefined ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),\n ...(usage.costUsd !== undefined ? { costUsd: usage.costUsd } : {}),\n }\n }\n\n /** Adopt the row a PREVIOUS attempt at this turn already inserted, if any.\n * This lookup — by the deterministic id, through the store's ordinary read\n * — is the whole crash-safety mechanism: no new state, no extra column, no\n * second index. */\n async function adoptRow(): Promise<string | undefined> {\n if (rowId) return rowId\n const existing = (await options.store.listMessages(options.threadId)).find(\n (message) => message.id === options.messageId,\n )\n if (existing) rowId = existing.id\n return rowId\n }\n\n /** Insert-or-patch one set of values onto this turn's single row. */\n async function writeOnce(values: AssistantRowValues): Promise<void> {\n if (await adoptRow()) {\n await options.store.updateMessage!(rowId!, values)\n writes += 1\n return\n }\n const inserted = await options.store.appendMessage({\n id: options.messageId,\n threadId: options.threadId,\n role: 'assistant',\n ...values,\n })\n // The `?? options.messageId` tail is valid HERE and only here: this writer\n // supplied the id, so a store that returns nothing still wrote that row.\n // A caller that did not assign an id has no such fallback — which is why\n // `rowIdOf` deliberately stops at the honest read.\n rowId = rowIdOf(inserted) ?? options.messageId\n writes += 1\n }\n\n function trigger(): void {\n if (closed) return\n if (!dirty) return\n // Single-flight: a write already in flight SUPPRESSES this trigger rather\n // than queueing behind it. `dirty` stays armed, so the next event after it\n // lands writes the newer snapshot — one write is never spent on state a\n // later one supersedes.\n if (inFlight) return\n const now = Date.now()\n // The first content event writes immediately (a late viewer sees a row at\n // once); the time floor governs every write after it.\n if (lastWriteAt !== 0 && now - lastWriteAt < currentIntervalMs()) return\n const snapshot = options.snapshot()\n if (!snapshot) return\n // Nothing to persist yet: an armed-but-empty snapshot (first event is a\n // tool call with no text and no parts) would insert a blank row.\n if (!snapshot.content && (!snapshot.parts || snapshot.parts.length === 0)) return\n dirty = false\n lastWriteAt = now\n inFlight = (async () => {\n try {\n const values = await projectValues(snapshot)\n lastBlobBytes = values.parts ? safeStringify(values.parts).length : 0\n await writeOnce(values)\n } catch (err) {\n // Best-effort by contract: a store outage degrades freshness for late\n // viewers, it does not fail a healthy turn.\n log('[chat-routes] incremental assistant persistence failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n } finally {\n inFlight = undefined\n // A trigger that arrived while this write was in flight left `dirty`\n // armed with a NEWER snapshot. Re-run it here or that state would sit\n // unwritten until the next content event — and if this was the last\n // event of a quiet stretch, until the final write.\n if (dirty && !closed) trigger()\n }\n })()\n }\n\n return {\n notify(event) {\n if (closed) return\n if (isDraftContentEvent(event)) dirty = true\n trigger()\n },\n async close() {\n closed = true\n if (inFlight) await inFlight\n },\n async finalize(values) {\n closed = true\n if (inFlight) await inFlight\n await writeOnce(values)\n },\n rowId: () => rowId,\n async discard() {\n closed = true\n if (inFlight) await inFlight\n if (!options.store.deleteMessage) return\n try {\n if (!(await adoptRow())) return\n await options.store.deleteMessage(rowId!)\n rowId = undefined\n } catch (err) {\n log('[chat-routes] draft assistant row discard failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n writeCount: () => writes,\n }\n}\n\n/** True when a store can support incremental persistence at all. Without\n * `updateMessage` a draft row could never be patched, so the caller keeps\n * today's exact single-write behavior. */\nexport function storeSupportsDraftPersistence(store: AssistantDraftStore): boolean {\n return typeof store.updateMessage === 'function'\n}\n\n/** The row id an `appendMessage` actually returned, or `null` when the store\n * returned nothing usable. `ChatTurnMessageStore.appendMessage` is typed\n * `Promise<unknown>` so a product adapter is free to resolve `void`; every\n * caller that wants to NAME the row it just wrote has to read defensively.\n *\n * Deliberately no fallback to a caller-assigned id — see `writeOnce`, which\n * adds its own. A caller that let the store mint the id has nothing to fall\n * back TO, and guessing one would report a row that may not exist. */\nexport function rowIdOf(inserted: unknown): string | null {\n const id = (inserted as { id?: unknown } | null | undefined)?.id\n return typeof id === 'string' && id ? id : null\n}\n\n/** The default deterministic assistant-row id for a turn. Readable on purpose\n * (an operator grepping a transcript row id finds the run), and stable across\n * re-entries because every input already is. */\nexport function assistantRowIdForTurn(turnKey: string): string {\n return `assistant:${turnKey}`\n}\n","/**\n * `createChatTurnRoutes` — the assembled server chat vertical (issue #188\n * Phase 1). One factory composing the pieces every product re-wired by hand:\n *\n * body parse/validate → `/web` `parseJsonObjectBody` + `./wire`\n * turn identity → `/stream` `resolveChatTurn` + agent-runtime `/durable`\n * `deriveExecutionId`\n * producer → injected seam (sandbox lane via\n * `createSandboxChatProducer`; router lane is the\n * product's own `ChatTurnProducer`)\n * turn engine → agent-runtime `/durable` `handleChatTurn` (verbatim)\n * durability → `/stream` turn-buffer tap, wired BY DEFAULT\n * (tee + drain keeps the turn running after a\n * client drop; replay serves the buffered tail)\n * persistence → injected `/chat-store`-shaped store\n * (user row on send, assistant row on completion)\n * interactions answer → `/interactions` `createInteractionAnswerRoute`\n *\n * Handlers are web-standard `Request → Response` (Workers, Node 18+, Deno) —\n * no router import. Auth/access is one injected `authorize` seam, composable\n * with `/app-auth` guards but not coupled to them.\n *\n * Optional product seams let a complex turn-orchestrator compose the vertical\n * instead of hand-rolling a generator — each omittable to the exact behavior\n * above: `turnLock` (single-flight acquire/release around the turn),\n * `contextGate` (pre-producer domain-readiness short-circuit), `beforeTurn`\n * (observe + augment the producer input), `lifecycle` (deterministic\n * start/complete/error telemetry), `heartbeat` (keepalive during silent\n * producer waits), and `onRawEvent` (the raw producer events, for telemetry) —\n * plus the `authorize` result's `insertUserMessage` flag (suppress the user row\n * for a product-dispatched turn). `handleChatTurn` stays the engine — the seams\n * only wrap its input, its producer stream, and its settle.\n *\n * Seam stability: all of the above are STABLE and safe to depend on. They\n * graduated in #227 against the bar this package holds itself to — a seam is\n * provisional until two INDEPENDENT consumers exercise it, because one\n * consumer's shape is indistinguishable from that consumer's assumptions.\n * `turnLock` cleared it with `/turn-stream`'s shared DO adapter (#221);\n * `contextGate`, `beforeTurn`, `onRawEvent` and `insertUserMessage` each\n * cleared it with two product verticals reading them differently — and the\n * review found no leaked assumptions to fix, only `ChatRouteEvent` to export.\n *\n * They stay FLAT top-level options (not grouped under a `hooks` object): that\n * grouping would break every shipped consumer's call for no mechanism gain, and\n * this package's exports are additive-only. For the same reason `onRawEvent`\n * keeps its two-argument `(event, context)` signature rather than being\n * normalized to the single-args shape the other seams take.\n */\n\nimport {\n deriveExecutionId,\n handleChatTurn,\n type ChatTurnIdentity,\n type ChatTurnProducer,\n} from '@tangle-network/agent-runtime/durable'\nimport { mentionInputToPart, toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport {\n assistantRowIdForTurn,\n createAssistantDraftWriter,\n rowIdOf,\n storeSupportsDraftPersistence,\n type AssistantDraftStore,\n type AssistantDraftWriter,\n type DraftPersistenceTuning,\n} from './draft-persistence'\nimport {\n createInteractionAnswerRoute,\n type InteractionAnswerRoute,\n type InteractionAnswerRouteOptions,\n} from '../interactions/route'\nimport {\n coalesceDeltas,\n createBufferedTurnTap,\n normalizeClientTurnId,\n replayTurnEvents,\n resolveChatTurn,\n stampReplaySeq,\n type PersistedChatMessageForTurn,\n type TurnEventStore,\n} from '../stream/index'\nimport type { ModelFailoverAttempt } from '../model-resolution/failover'\nimport { parseJsonObjectBody } from '../web/index'\nimport {\n assertPromptPartsWithinCap,\n ChatTurnInputError,\n parseChatTurnParts,\n parseFileMentions,\n type ChatTurnFilePartInput,\n type ChatTurnPartInput,\n type ChatTurnRequestPayload,\n type FileMention,\n} from './wire'\n\n// ── seams ───────────────────────────────────────────────────────────────────\n\n/** Usage receipt persisted onto the assistant message (the flattened\n * `step-finish` shape `/chat-store`'s columns mirror). */\nexport interface ChatTurnUsage {\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n costUsd?: number\n}\n\n/** What the route persists — a structural subset of `/chat-store`'s\n * `ChatStore`, so `createChatStore(db, tables)` satisfies it directly and a\n * product with its own persistence adapts without importing drizzle. */\nexport interface ChatTurnMessageStore {\n listMessages(threadId: string): Promise<Array<{\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n }>>\n appendMessage(input: {\n /** Caller-assigned row id. Honored by `/chat-store`'s `createChatStore`;\n * a product store free to ignore it (the writer then adopts whatever id\n * the insert returns). Set only by incremental persistence. */\n id?: string\n threadId: string\n role: 'user' | 'assistant'\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n }): Promise<unknown>\n /** Patch an existing row. Its PRESENCE is what enables incremental assistant\n * persistence — a store without it keeps today's exact single-write-on-\n * completion behavior, which is what makes this additive. */\n updateMessage?(id: string, patch: {\n content?: string\n parts?: ChatMessagePart[]\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n }): Promise<unknown>\n /** Remove a row. Used to retract a draft assistant row for a turn that ended\n * producing nothing, so the empty-turn case still leaves no row at all. */\n deleteMessage?(id: string): Promise<unknown>\n}\n\n/** `ChatTurnProducer` plus the persisted projection the assembly reads after\n * drain. `createSandboxChatProducer` returns this; a router-lane producer\n * may omit the optional members (finalText persists as a single text part). */\nexport interface ChatTurnRouteProducer extends ChatTurnProducer {\n assistantParts?(): Array<Record<string, unknown>>\n /** MID-STREAM snapshot of the same projection, safe to call while the turn\n * is running: no dangling-tool terminalization, no pending-ask settlement\n * (see `/stream`'s `draftAssistantParts`). Read by incremental persistence.\n * A producer that omits it still drafts — the scalar text — but persists no\n * parts until the turn completes. */\n draftParts?(): Array<Record<string, unknown>>\n usage?(): ChatTurnUsage\n /** The model that SERVED the turn. With failover wired this is the model that\n * actually answered, which is not necessarily the one the caller preferred —\n * read it after the stream drains, never before. */\n model?: string\n /** Model-failover attribution, when the producer supports it. Reported onto\n * the usage/billing receipt so a downgrade is never silent. */\n modelFailover?(): ChatTurnModelFailover\n /** Requested-versus-served attribution reported by the sandbox sidecar.\n * `echoReceived` distinguishes a missing echo from a partial echo. */\n modelAttribution?(): ChatTurnModelAttribution\n}\n\n/** Which model served, and what it took to get there. */\nexport interface ChatTurnModelFailover {\n /** The model that served the turn. */\n model?: string\n /** Every model tried, in order, with the reason each was abandoned. */\n attempts: ModelFailoverAttempt[]\n /** True when the preferred model did not serve. */\n usedFallback: boolean\n}\n\n/** Requested and effective model attribution for one sandbox turn. */\nexport interface ChatTurnModelAttribution {\n /** The model explicitly requested by the caller, before shell failover. */\n requestedModel?: string\n /** The model the downstream sandbox reports actually served the turn. */\n servedModel?: string\n /** The provider that served the turn, when echoed by the sandbox. */\n servedProvider?: string\n /** How the sandbox selected the served model. */\n servedSource?: 'request' | 'environment' | 'profile'\n /** True when a structurally valid effective-backend echo was observed. */\n echoReceived: boolean\n}\n\n/** Resolve authorization status and context for a chat turn including tenant and user identification */\nexport type ChatTurnAuthorization<TContext> =\n | {\n ok: true\n tenantId: string\n userId: string\n context: TContext\n /** When `false`, skip the `role:'user'` message insert for this turn — for\n * a product-dispatched / synthetic turn (e.g. a follow-up the product\n * raised itself) that must not surface a new user row. Composes with —\n * never overrides — the engine's retry-dedup: `authorize` runs before\n * turn identity is resolved, so it cannot tell a retry from a fresh turn;\n * a turn already deduped stays deduped. Omit / `true` → today's behavior.\n *\n * Settled shape (#227). The validated case in both consumers is the same:\n * a durable plan-approval follow-up re-entering an execution the decision\n * route already enqueued — a decision, not a typed message, so it must\n * not surface a user bubble. Suppressing the insert also propagates:\n * `ChatTurnProduceArgs.userMessageId` is `null` for the rest of the turn\n * when there is no row to reuse, so a seam anchoring to the user row must\n * handle that arm rather than assume a string. */\n insertUserMessage?: boolean\n }\n | { ok: false; response: Response }\n\n/** Define arguments required to authorize a chat turn based on intent and request details */\nexport interface ChatTurnAuthorizeArgs {\n request: Request\n intent: 'turn' | 'replay' | 'running'\n /** Parsed, validated POST body (turn intent only). */\n body?: ChatTurnRequestPayload\n /** The buffered turn id being replayed (replay intent only). */\n turnId?: string\n /** The thread whose running turns are being discovered (running intent only). */\n threadId?: string\n}\n\n/** Trusted per-turn limits supplied by a server adapter, never by the body. */\nexport interface ChatTurnExecutionLimits {\n maxInputTokens?: number\n maxOutputTokens?: number\n maxReasoningTokens?: number\n maxToolTokens?: number\n maxToolCalls?: number\n maxProviderCostUsd?: number\n}\n\n/** Server-only context for one turn request. */\nexport interface ChatTurnRequestContext {\n waitUntil?(p: Promise<unknown>): void\n /** Abort this turn when its HTTP client disconnects. Browser callers omit it. */\n cancelOnDisconnect?: boolean\n /** Limits already authenticated by the server adapter. */\n executionLimits?: ChatTurnExecutionLimits\n}\n\n/** Define the arguments required to produce a chat turn with context and messaging details */\nexport interface ChatTurnProduceArgs<TContext> {\n request: Request\n body: ChatTurnRequestPayload\n identity: ChatTurnIdentity\n context: TContext\n /** The message to send: plain text, or parts when the client attached\n * files (a text part is prepended from `content` when present). */\n prompt: string | ChatTurnPartInput[]\n /** Stable id for cross-process reconnect (`deriveExecutionId`). */\n executionId: string\n /** The turn-buffer id announced to the client for replay. */\n turnStreamId: string\n priorMessages: PersistedChatMessageForTurn[]\n /** Server-authenticated limits for this turn. Never copied from the body. */\n executionLimits?: ChatTurnExecutionLimits\n /** The durable `role:'user'` row this turn is anchored to — the row the\n * factory just inserted, or the one retry-dedup REUSED. Products anchor\n * optimistic-bubble swaps, retry targeting, and stop-polling to it, and it\n * is the only way to name a REUSED row (which `priorMessages` excludes).\n *\n * Three states, all meaningful:\n * - `undefined` — not resolved yet. `turnLock.acquire` is the one seam that\n * sees this: it runs before any side effect by contract, so the row does\n * not exist when it reads the args.\n * - `null` — resolved, no row: `authorize` returned `insertUserMessage:\n * false` on a turn with nothing to reuse, or the store's `appendMessage`\n * resolved without a usable id.\n * - a string — the row id, for `contextGate`, `beforeTurn`, and `produce`. */\n userMessageId?: string | null\n}\n\n/** One event as it crosses the route: the producer's own vocabulary, or an\n * injected keepalive. Same shape the engine forwards verbatim.\n *\n * Public because it IS the vocabulary of two seams — `onRawEvent`'s parameter\n * and `heartbeat.event`'s return. Exported so a product can declare a\n * standalone handler (`function onRawEvent(e: ChatRouteEvent, ctx: T)`) rather\n * than depending on contextual typing from an inline object literal. */\nexport type ChatRouteEvent = { type: string; data?: Record<string, unknown> }\n\n/** Best-effort human-readable cause from a terminal `error` /\n * `session.run.failed` event's `data`. */\nfunction failureReasonOf(data: Record<string, unknown> | undefined): string | undefined {\n if (!data) return undefined\n const message = data.message ?? data.error ?? data.reason\n if (typeof message === 'string' && message.length > 0) return message\n return undefined\n}\n\n/** Keepalive emitted while the producer is quiet (long tool calls, first-token\n * wait) so client watchdogs stay re-armed. One is emitted each time\n * `intervalMs` elapses with no producer event; the window resets on every real\n * event, so a chatty producer never triggers one. The product owns the event\n * shape (`type` + `data`). Omit → no keepalives (today's behavior). */\nexport interface ChatTurnHeartbeat {\n intervalMs: number\n event(info: { elapsedMs: number; tick: number }): ChatRouteEvent\n}\n\n/** Patch a `beforeTurn` hook returns to augment the producer's input. Omitted\n * fields keep the route-assembled value; the product's `produce` still owns\n * the system prompt. */\nexport interface ChatTurnInputPatch {\n prompt?: string | ChatTurnPartInput[]\n priorMessages?: PersistedChatMessageForTurn[]\n}\n\n/** Pre-turn readiness verdict — proceed, short-circuit, or hand off to a\n * product-owned durable turn. Distinct from `authorize`: this gates domain\n * readiness, not access. */\nexport type ChatTurnGateResult =\n | { proceed: true }\n | { proceed: false; response: Response }\n /** The product has accepted the turn and owns execution and lifecycle after\n * the route releases its lock. */\n | { proceed: 'handoff'; response: Response }\n\n/** Single-flight lock verdict — acquired (with an opaque handle passed back to\n * `release`), or already held (short-circuit with the product's 409-style\n * `Response`). */\nexport type ChatTurnLockResult =\n | { acquired: true; handle?: unknown }\n | { acquired: false; response: Response }\n\n/** Async acquire/release wrapped around the turn. `acquire` runs before any\n * side effect; `release` runs once when the turn settles — including on a\n * short-circuit or a throw. */\nexport interface ChatTurnLock<TContext> {\n acquire(args: ChatTurnProduceArgs<TContext>): ChatTurnLockResult | Promise<ChatTurnLockResult>\n release(handle: unknown): void | Promise<void>\n}\n\ninterface ChatTurnLifecycleBase<TContext> {\n identity: ChatTurnIdentity\n executionId: string\n turnStreamId: string\n context: TContext\n}\n/** Define lifecycle start event with context and timestamp for a chat turn */\nexport interface ChatTurnLifecycleStart<TContext> extends ChatTurnLifecycleBase<TContext> {\n startedAt: number\n}\n/** Define the structure representing the completion state of a chat turn lifecycle with usage data */\nexport interface ChatTurnLifecycleComplete<TContext> extends ChatTurnLifecycleBase<TContext> {\n finalText: string\n usage: ChatTurnUsage\n durationMs: number\n /** The model that SERVED the turn — the fallback's id when failover moved it.\n * `usage` is that model's, so telemetry that splits cost or quality by model\n * must key on this and not on the requested one. */\n model?: string\n /** Requested-versus-served attribution. A difference is detectable from\n * this receipt and from the persisted assistant row independently. */\n requestedModel?: string\n servedModel?: string\n servedProvider?: string\n servedSource?: 'request' | 'environment' | 'profile'\n /** Attribution for a downgrade: which models were tried and why each failed.\n * `undefined` when the producer reports no failover support. */\n modelFailover?: ChatTurnModelFailover\n /** The durable `role:'assistant'` row this turn wrote, or `null` when it\n * wrote none (an empty turn leaves no row — a draft started mid-stream is\n * retracted). The detached lane surfaces the same id as\n * `DetachedTurnResult.messageId`; one contract, two lanes. */\n assistantMessageId: string | null\n /** Set when `contextGate` answered this turn and the producer never ran.\n *\n * Present so telemetry can tell \"the model produced nothing\" apart from \"the\n * model was never asked\" — they look identical here (`finalText: ''`,\n * empty `usage`) and mean opposite things. A gated turn writes no assistant\n * row, so `assistantMessageId` is `null`, and the billing/persistence\n * `onTurnComplete` is deliberately NOT fired for it. */\n gated?: true\n}\n/** Represent an error occurring during a chat turn lifecycle with context and duration information */\nexport interface ChatTurnLifecycleError<TContext> extends ChatTurnLifecycleBase<TContext> {\n error: unknown\n durationMs: number\n}\n\n/** Deterministic run telemetry: `onTurnStart` fires before the producer runs;\n * exactly one of `onTurnComplete` / `onTurnError` fires after the turn\n * settles, always after `onTurnStart`. Failure is derived from the turn's own\n * `error` / `session.run.failed` events (or a drain throw), not the engine's\n * lifecycle envelope. Hook errors are swallowed — telemetry never fails a\n * turn. */\nexport interface ChatTurnLifecycle<TContext> {\n onTurnStart?(info: ChatTurnLifecycleStart<TContext>): void | Promise<void>\n onTurnComplete?(info: ChatTurnLifecycleComplete<TContext>): void | Promise<void>\n onTurnError?(info: ChatTurnLifecycleError<TContext>): void | Promise<void>\n}\n\n/** What a settled turn reports to `onTurnComplete` — the product's\n * post-processing seam (billing, titles, audit). */\nexport interface ChatTurnCompleteInput<TContext> {\n identity: ChatTurnIdentity\n finalText: string\n context: TContext\n failed: boolean\n failureReason?: string\n /** The model that SERVED this turn. With failover wired it may differ from\n * the requested one, so a product that bills or scores per model MUST read\n * it here rather than assuming the model it asked for. */\n model?: string\n /** Requested-versus-served attribution. A difference is detectable from\n * this receipt and from the persisted assistant row independently. */\n requestedModel?: string\n servedModel?: string\n servedProvider?: string\n servedSource?: 'request' | 'environment' | 'profile'\n /** Present when the producer supports failover: the full attempt trail, and\n * `usedFallback` — the flag that makes a silent downgrade impossible. */\n modelFailover?: ChatTurnModelFailover\n /** The durable `role:'assistant'` row this turn wrote, or `null` when it\n * wrote none (an empty turn leaves no row).\n *\n * Populated even when `failed` is true — a terminal error event still\n * persists whatever partial answer arrived, and that pairing is exactly\n * what lets a product render an error row against a REAL message instead of\n * hunting for the newest row in the thread. The detached lane surfaces the\n * same id as `DetachedTurnResult.messageId`. */\n assistantMessageId: string | null\n}\n\n/** Define options to configure chat turn routes including authorization, storage, and event buffering */\nexport interface CreateChatTurnRoutesOptions<TContext = void> {\n /** Names the product in `deriveExecutionId` so retries land on the same\n * substrate execution. */\n projectId: string\n /** Authenticate + authorize the caller for a turn or a replay. The only\n * product-supplied access step: session auth, thread/workspace access,\n * seat/balance gates, rate limits all live here. */\n authorize(args: ChatTurnAuthorizeArgs): Promise<ChatTurnAuthorization<TContext>>\n /** Thread/message persistence (`/chat-store`'s store or a product adapter). */\n store: ChatTurnMessageStore\n /** Turn-event buffer (`createD1TurnEventStore(env.DB)` or `/turn-stream`'s\n * `createDurableObjectTurnEventStore(env.TURN_STREAM_DO)` in production,\n * `createMemoryTurnEventStore()` in tests). Wired by default — every turn\n * is buffered and replayable. */\n turnStore: TurnEventStore\n /** Build the turn's event stream. Sandbox lane: `streamSandboxPrompt(...)`\n * wrapped in `createSandboxChatProducer`. Router/openai-compat lane: the\n * product's own producer. May be async (box resolution). */\n produce(args: ChatTurnProduceArgs<TContext>): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>\n /** Single-flight lock acquired before any side effect and released once when\n * the turn settles (including short-circuit/throw). `/turn-stream`'s\n * `createDurableTurnLock` is the shared DO-backed implementation. Omit →\n * no lock. */\n turnLock?: ChatTurnLock<TContext>\n /** Pre-turn readiness gate that can short-circuit with a product `Response`\n * before the producer runs (the user row is already persisted). Runs after\n * `turnLock.acquire`, before `beforeTurn`. Omit → always proceed.\n *\n * Settled shape (#227). What a consumer may depend on:\n * - `args.userMessageId` is RESOLVED here — a string, or `null` when the\n * insert was suppressed with nothing to reuse. (`turnLock.acquire` is the\n * only seam that sees it `undefined`.)\n * - `{proceed:false}` releases the lock and returns the product's `Response`\n * verbatim: `beforeTurn` and `produce` never run, no assistant row is\n * written, and the user row already inserted is KEPT — a real user turn\n * whose assistant side is the gate's own response.\n * - `{proceed:'handoff'}` releases the route-acquired lock, returns the\n * product's accepted `Response`, and transfers execution and lifecycle\n * ownership to the product's durable owner. The route runs no producer\n * or lifecycle hook.\n * - Always returning `{proceed:true}` is supported, not a misuse: the seam\n * doubles as the one place that runs after the user row exists and before\n * the producer, which is where per-turn analytics and readiness\n * precomputation belong. A gate that never gates is a valid consumer. */\n contextGate?(args: ChatTurnProduceArgs<TContext>): ChatTurnGateResult | Promise<ChatTurnGateResult>\n /** Observe the assembled producer input and optionally augment it (rewrite\n * the prompt / prior messages) before the producer runs. Omit → no change.\n *\n * Settled shape (#227). BOTH return arms are contract:\n * - a `ChatTurnInputPatch` shallow-merges over the route-assembled args, so\n * an omitted field keeps the route's value;\n * - `void` means \"no patch\" — and mutating `args.context` in place is the\n * supported way to thread request-scoped state forward to `produce` /\n * `lifecycle` / `onTurnComplete`, which all receive the same object.\n *\n * A throw propagates (the turn fails with the lock released). It runs BEFORE\n * `lifecycle.onTurnStart`, so a throw here fires no terminal lifecycle hook —\n * the span never opened. Telemetry for a failure in this seam belongs in the\n * seam, not in `lifecycle`. */\n beforeTurn?(args: ChatTurnProduceArgs<TContext>): ChatTurnInputPatch | void | Promise<ChatTurnInputPatch | void>\n /** Deterministic run telemetry (start / complete / error) with identity and\n * timing. Omit → no telemetry. */\n lifecycle?: ChatTurnLifecycle<TContext>\n /** Keepalive injected while the producer is quiet. Omit → no keepalives. */\n heartbeat?: ChatTurnHeartbeat\n /** Observe each event the producer emits, before the engine frames it and\n * before any heartbeat injection (the raw sidecar-producer events, for\n * telemetry). Never alters the stream; errors are swallowed. Distinct from\n * `onEvent`, which sees the engine-framed stream incl. lifecycle envelopes.\n *\n * Settled shape (#227). What a consumer may depend on:\n * - it sees EXACTLY the producer's own events — no engine lifecycle\n * envelopes, and no injected keepalives (`heartbeat` wraps the stream\n * downstream of this tap, so a synthetic event never reaches a trace);\n * - a throw is caught and logged, never surfaced: a broken telemetry sink\n * cannot fail a turn or truncate the client's stream;\n * - it is an OBSERVER — the return value is ignored, and the event object\n * continues downstream. Mutating it mutates the stream; don't.\n *\n * Takes `(event, context)` rather than one args object, matching both\n * shipped consumers; see the module header on why it stays that way. */\n onRawEvent?(event: ChatRouteEvent, context: TContext): void | Promise<void>\n /** Pre-persist transform of the final text (e.g. `/redact`'s `redactPII`).\n * Live stream is never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Incremental persistence of the assistant row WHILE the turn streams\n * (`./draft-persistence`), so a viewer arriving mid-run is served from\n * durable storage instead of the streaming gateway's hot event buffer.\n *\n * This is what lets the gateway keep that hot buffer SHORT at scale: its\n * Redis footprint is one sorted set per session refreshed on every push, so\n * memory grows LINEARLY with `ttl x concurrent sessions`. Stretching the\n * TTL to cover late viewers buys memory proportional to the increase and\n * still serves nothing past the new horizon. The buffer stays a reconnect\n * window; durable storage — kept at most one cadence interval stale by this\n * option — is the history tier.\n *\n * Enabled by DEFAULT whenever `store.updateMessage` exists (every\n * `/chat-store` consumer); a store without it keeps today's exact\n * single-write behavior. Pass `false` to opt out, or an object to tune the\n * cadence. Wiring it against a store that cannot patch rows throws at route\n * construction rather than silently no-op'ing. */\n incrementalPersistence?: false | DraftPersistenceTuning\n /** Deterministic durable row id for this turn's assistant message. Default\n * `assistant:<executionId>` — already stable across retries because\n * `deriveExecutionId` is. Override only if the product's message ids have a\n * format constraint; it MUST stay deterministic per turn or a re-entered\n * turn will duplicate its row instead of converging. */\n draftMessageId?(args: { identity: ChatTurnIdentity; executionId: string; threadId: string }): string\n /** Post-processing after a turn settles (billing, titles, audit). Fires with\n * `failed:true` + `failureReason` when the turn carried a terminal error\n * event (model 402 / rate-limit / server error) instead of a clean\n * completion, so products skip the deduct and render an error row rather\n * than billing an empty turn and marking it done. A turn that THROWS never\n * reaches this hook (the engine skips it on a producer throw). Errors are\n * swallowed by the engine — they never fail a streamed turn. */\n onTurnComplete?(input: ChatTurnCompleteInput<TContext>): Promise<void>\n /** Per-event side channel (product broadcast). The turn-buffer tap is\n * already wired; this runs in addition. */\n onEvent?(event: { type: string; data?: Record<string, unknown> }, context: TContext): void | Promise<void>\n /** Trace flush handed to `waitUntil` (OTLP export). */\n traceFlush?(context: TContext): Promise<void>\n /** Compose the interaction-answer endpoints (`/interactions`). Omit when the\n * product has no sidecar ask channel. */\n interactions?: InteractionAnswerRouteOptions\n /** Byte budget for inline prompt parts. Default `INLINE_PARTS_MAX_BYTES`. */\n maxInlinePartBytes?: number\n /** Per-flush coalescer for the turn buffer. Default `coalesceDeltas` (this\n * assembly streams the client vocabulary's `{type:'text'|'reasoning',\n * text}` lines, which it merges). A producer streaming raw\n * `message.part.updated` events passes `coalesceChatStreamEvents`. */\n coalesceTurnEvents?: (events: unknown[]) => unknown[]\n replay?: { pollMs?: number; timeoutMs?: number }\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Define routes to run, replay, and list running chat turns with streaming and reconnect support */\nexport interface ChatTurnRoutes {\n /** POST — run one turn, streaming NDJSON. First line is\n * `{type:'turn', turnId}` (the replay handle); the rest is the engine's\n * event protocol. Pass the platform's `waitUntil` so the turn keeps\n * running (and buffering) after a client disconnect. */\n turn(request: Request, ctx?: ChatTurnRequestContext): Promise<Response>\n /** GET — replay a buffered turn from `?fromSeq=` (0 = everything), then\n * follow it live until it completes. */\n replay(request: Request, params: { turnId: string }): Promise<Response>\n /** GET `?threadId=` — the reconnect-discovery endpoint: the turn ids still\n * running on a thread, so a client that reloaded mid-turn can re-attach to\n * the live stream via {@link replay} instead of losing it. Returns `[]` when\n * the turn store cannot enumerate running turns (`listRunning` unimplemented). */\n running(request: Request): Promise<Response>\n /** list/answer endpoints from `/interactions`; null when not configured. */\n interactions: InteractionAnswerRoute | null\n}\n\n// ── body validation ────────────────────────────────────────────────────────\n\nfunction errorResponse(err: ChatTurnInputError): Response {\n return Response.json({ code: err.code, error: err.message }, { status: err.status })\n}\n\ninterface ParsedTurnBody {\n payload: ChatTurnRequestPayload\n content: string\n fileParts: ChatTurnFilePartInput[]\n mentions: FileMention[]\n turnId: string | undefined\n}\n\nfunction validateTurnBody(body: Record<string, unknown>, maxInlinePartBytes: number | undefined): ParsedTurnBody {\n const threadId = typeof body.threadId === 'string' ? body.threadId.trim() : ''\n if (!threadId) throw new ChatTurnInputError('Missing threadId')\n const rawContent = body.content ?? body.message ?? ''\n if (typeof rawContent !== 'string') throw new ChatTurnInputError('content must be a string')\n const content = rawContent.trim()\n const fileParts = parseChatTurnParts(body.parts)\n // Path references, not bytes — validated for traversal/charset/count, never\n // counted against the inline-parts byte budget below.\n const mentions = parseFileMentions(body.mentions)\n // A mention is a turn's whole payload often enough to count: \"@chart.png\"\n // with no prose is a real ask, and the pointer block the mentions produce is\n // prompt content the model reads.\n const hasAttachments = Array.isArray(body.attachments) && body.attachments.length > 0\n if (!content && fileParts.length === 0 && mentions.length === 0 && !hasAttachments) {\n throw new ChatTurnInputError('Missing content (send text, parts, mentions, attachments, or any combination)')\n }\n assertPromptPartsWithinCap(fileParts, maxInlinePartBytes)\n let turnId: string | undefined\n try {\n turnId = normalizeClientTurnId(body.turnId)\n } catch (err) {\n throw new ChatTurnInputError(err instanceof Error ? err.message : 'Invalid turnId')\n }\n return {\n // The VALIDATED, deduped mention list replaces the raw one on the payload,\n // so every downstream seam (`authorize`, `contextGate`, `beforeTurn`,\n // `produce`) reads checked paths and never the request's own.\n payload: { ...body, threadId, content, mentions } as ChatTurnRequestPayload,\n content,\n fileParts,\n mentions,\n turnId,\n }\n}\n\n/** File parts persist onto the user message verbatim — the wire shape is the\n * persisted `ChatFilePart`/`ChatImagePart` vocabulary already. Mentions get\n * the one mapping step their own vocabulary needs. The typed projection is\n * `/chat-store`'s (same boundary as the assistant hop).\n *\n * Mentions persist as parts rather than being folded into the prompt because\n * the prompt is not readable back: a retry rebuilds the turn from the stored\n * row, and a transcript draws its pills from it. Turning them INTO prompt\n * text stays the product's job — only the product knows how to resolve a\n * workspace-relative path to an in-box one (`fileMentionsToParts`'\n * `resolvePath` seam), so the route never dispatches them itself. */\nfunction userPartsWithFiles(\n userParts: Array<Record<string, unknown>>,\n fileParts: ChatTurnFilePartInput[],\n mentions: FileMention[],\n): ChatMessagePart[] {\n return toChatMessageParts([\n ...userParts,\n ...fileParts.map((part) => ({ ...part })),\n ...mentions.map((mention) => ({ ...mentionInputToPart(mention) })),\n ])\n}\n\n// ── producer-stream wrappers (heartbeat + raw tap) ───────────────────────────\n\n/** Fire `onRawEvent` for each producer event, before the engine frames it.\n * Best-effort — a telemetry throw is logged, never propagated. */\nasync function* tapRawEvents(\n source: AsyncIterable<ChatRouteEvent>,\n onRawEvent: (event: ChatRouteEvent) => void | Promise<void>,\n log: (message: string, meta?: Record<string, unknown>) => void,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n for await (const event of source) {\n try {\n await onRawEvent(event)\n } catch (err) {\n log('[chat-routes] onRawEvent failed', { error: err instanceof Error ? err.message : String(err) })\n }\n yield event\n }\n}\n\n/** Inject a keepalive whenever `intervalMs` elapses with no source event. The\n * silent window (elapsed + tick) resets on every real event, so a producer\n * that keeps emitting never triggers a heartbeat. Closes the source on early\n * return, matching a `for await` over it. */\nasync function* withStreamHeartbeat(\n source: AsyncIterable<ChatRouteEvent>,\n intervalMs: number,\n makeEvent: (info: { elapsedMs: number; tick: number }) => ChatRouteEvent,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n let pending = iterator.next()\n let windowStart = Date.now()\n let tick = 0\n for (;;) {\n let timer: ReturnType<typeof setTimeout> | undefined\n let winner: 'event' | 'heartbeat'\n try {\n const heartbeat = new Promise<'heartbeat'>((resolve) => {\n timer = setTimeout(() => resolve('heartbeat'), intervalMs)\n })\n winner = await Promise.race([pending.then(() => 'event' as const), heartbeat])\n } finally {\n // Clear the pending timer on EVERY exit — including a `pending`\n // rejection — so a rejected source never orphans a setTimeout that\n // keeps the runtime alive for up to `intervalMs`.\n if (timer !== undefined) clearTimeout(timer)\n }\n if (winner === 'heartbeat') {\n tick += 1\n yield makeEvent({ elapsedMs: Date.now() - windowStart, tick })\n continue\n }\n const result = await pending\n if (result.done) return\n yield result.value\n pending = iterator.next()\n windowStart = Date.now()\n tick = 0\n }\n } finally {\n await iterator.return?.()\n }\n}\n\n// ── the factory ────────────────────────────────────────────────────────────\n\n/** Build chat turn routes to handle and validate incoming chat requests with optional logging */\nexport function createChatTurnRoutes<TContext = void>(\n options: CreateChatTurnRoutesOptions<TContext>,\n): ChatTurnRoutes {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n\n // Incremental persistence is on whenever the store can patch a row. An\n // EXPLICIT opt-in against a store that cannot is a wiring bug, so it fails\n // here — at construction — instead of silently degrading every turn.\n const draftStore: AssistantDraftStore = options.store\n if (options.incrementalPersistence && !storeSupportsDraftPersistence(draftStore)) {\n throw new Error(\n 'incrementalPersistence requires a store with updateMessage() — `/chat-store`\\'s createChatStore has it; a product store must implement it or omit the option',\n )\n }\n const draftTuning: DraftPersistenceTuning | null =\n options.incrementalPersistence === false || !storeSupportsDraftPersistence(draftStore)\n ? null\n : (options.incrementalPersistence ?? {})\n\n async function turn(request: Request, ctx?: ChatTurnRequestContext): Promise<Response> {\n const [rawBody, badBody] = await parseJsonObjectBody(request)\n if (badBody) return badBody\n\n let parsed: ParsedTurnBody\n try {\n parsed = validateTurnBody(rawBody, options.maxInlinePartBytes)\n } catch (err) {\n if (err instanceof ChatTurnInputError) return errorResponse(err)\n throw err\n }\n const { payload, content, fileParts, mentions, turnId } = parsed\n\n const auth = await options.authorize({ request, intent: 'turn', body: payload })\n if (!auth.ok) return auth.response\n const { tenantId, userId, context } = auth\n\n // Turn identity: reuse the just-persisted user row on a retry (same\n // turnId or identical trailing content) instead of double-inserting.\n const existingMessages = (await options.store.listMessages(payload.threadId)).map((m) => ({\n id: m.id,\n role: m.role,\n content: m.content,\n parts: (m.parts ?? null) as PersistedChatMessageForTurn['parts'],\n }))\n // An assistant row already trailing the thread is either this turn's\n // in-flight draft (retry — walk past it) or a settled answer (a genuine\n // repeat — new turn). The turn buffer's running index is the discriminator;\n // it is only consulted in the one case that can be ambiguous, so the common\n // path costs nothing.\n let hasRunningTurn = false\n if (draftTuning && existingMessages.at(-1)?.role === 'assistant') {\n try {\n hasRunningTurn = ((await options.turnStore.listRunning?.(payload.threadId)) ?? []).length > 0\n } catch (err) {\n log('[chat-routes] listRunning probe failed; treating the thread as idle', {\n threadId: payload.threadId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n const chatTurn = resolveChatTurn({ existingMessages, userContent: content, turnId, hasRunningTurn })\n\n const identity: ChatTurnIdentity = {\n tenantId,\n sessionId: payload.threadId,\n userId,\n turnIndex: chatTurn.turnIndex,\n }\n const executionId = deriveExecutionId({\n projectId: options.projectId,\n sessionId: payload.threadId,\n turnIndex: chatTurn.turnIndex,\n })\n const turnStreamId = crypto.randomUUID()\n\n const prompt: string | ChatTurnPartInput[] =\n fileParts.length === 0\n ? content\n : content\n ? [{ type: 'text', text: content }, ...fileParts]\n : [...fileParts]\n\n // The producer input every pre-turn seam reads. Replaced — never mutated\n // in place — as later steps resolve more of it (`userMessageId` after the\n // insert, `beforeTurn`'s patch after that), so a seam that captured the\n // object never sees it change underneath. `produce` reads the last\n // version because the engine defers its first pull.\n let produceArgs: ChatTurnProduceArgs<TContext> = {\n request,\n body: payload,\n identity,\n context,\n prompt,\n executionId,\n turnStreamId,\n priorMessages: chatTurn.priorMessages,\n ...(ctx?.executionLimits ? { executionLimits: ctx.executionLimits } : {}),\n }\n\n // Single-flight lock: acquire before any side effect. `release` runs\n // exactly once — in the drain's `finally` on a normal turn, or right here\n // on a short-circuit / throw.\n let lockAcquired = false\n let lockHandle: unknown\n let lockReleased = false\n const releaseLock = async (): Promise<void> => {\n if (!lockAcquired || lockReleased) return\n lockReleased = true\n try {\n await options.turnLock!.release(lockHandle)\n } catch (err) {\n log('[chat-routes] turnLock.release failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n if (options.turnLock) {\n const acquired = await options.turnLock.acquire(produceArgs)\n if (!acquired.acquired) return acquired.response\n lockAcquired = true\n lockHandle = acquired.handle\n }\n\n // Turn state, hoisted so the pre-stream `catch` can settle the lifecycle\n // (fire `onTurnError`, close the span) even when a seam throws\n // synchronously before the drain — the drain would otherwise be the only\n // path that runs the terminal hook.\n let producer: ChatTurnRouteProducer | undefined\n let draft: AssistantDraftWriter | undefined\n // Set once persistence settles; `undefined` means it never ran.\n let assistantMessageId: string | null | undefined\n /** The assistant row this turn ended with. Falls back to the draft writer\n * so a turn whose producer THREW — skipping `persistAssistantMessage`\n * entirely — still names the partial row it left behind. */\n const assistantRowId = (): string | null => assistantMessageId ?? draft?.rowId() ?? null\n let runFailed = false\n // Data of the event that marked the run failed — handed to `onTurnError`\n // when no drain throw supplies a richer cause.\n let lastFailureData: Record<string, unknown> | undefined\n let turnStartedAtMs = 0\n let turnStarted = false\n let lifecycleSettled = false\n // Set when `contextGate` answered the turn without running the producer.\n let gatedTurn = false\n\n // Exactly one terminal lifecycle hook, after the turn settles (idempotent).\n // Failure is this route's own verdict (`runFailed` from error/failed\n // events, or a drain/sync throw), not the engine's envelope.\n const fireTerminalLifecycle = async (failed: boolean, terminalError: unknown): Promise<void> => {\n if (lifecycleSettled) return\n lifecycleSettled = true\n const lifecycle = options.lifecycle\n if (!lifecycle) return\n const durationMs = Date.now() - turnStartedAtMs\n try {\n if (failed) {\n await lifecycle.onTurnError?.({\n identity, executionId, turnStreamId, context, durationMs,\n error: terminalError ?? lastFailureData ?? new Error('chat turn failed'),\n })\n } else {\n const failoverInfo = producer?.modelFailover?.()\n const attribution = producer?.modelAttribution?.()\n await lifecycle.onTurnComplete?.({\n identity, executionId, turnStreamId, context, durationMs,\n finalText: producer?.finalText() ?? '',\n usage: producer?.usage?.() ?? {},\n assistantMessageId: assistantRowId(),\n ...(gatedTurn ? { gated: true } : {}),\n ...(producer?.model ? { model: producer.model } : {}),\n ...(attribution?.requestedModel ? { requestedModel: attribution.requestedModel } : {}),\n ...(attribution?.servedModel ? { servedModel: attribution.servedModel } : {}),\n ...(attribution?.servedProvider ? { servedProvider: attribution.servedProvider } : {}),\n ...(attribution?.servedSource ? { servedSource: attribution.servedSource } : {}),\n ...(failoverInfo ? { modelFailover: failoverInfo } : {}),\n })\n }\n } catch (err) {\n log('[chat-routes] lifecycle terminal hook failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n try {\n // The product (via `authorize`) may suppress the user-row insert for a\n // dispatched/synthetic turn. AND-composition: it can only subtract, never\n // resurrect a turn the engine already deduped as a retry.\n const insertUserMessage = chatTurn.shouldInsertUserMessage && (auth.insertUserMessage ?? true)\n // Name the row this turn is anchored to. Insert and reuse are mutually\n // exclusive (`shouldInsertUserMessage` is false exactly when a reusable\n // row was found), so one source or the other — never both, never a\n // guess. Products used to re-derive this by decorating the store and\n // falling back to the newest row, which mis-resolves under sub-second\n // same-thread turns.\n let userMessageId: string | null = chatTurn.reusedUserMessageId ?? null\n if (insertUserMessage) {\n userMessageId = rowIdOf(\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'user',\n content,\n parts: userPartsWithFiles(chatTurn.userParts, fileParts, mentions),\n }),\n )\n }\n produceArgs = { ...produceArgs, userMessageId }\n\n // Domain-readiness gate: may short-circuit with the product's own\n // response before the producer runs. The user row above is kept (a real\n // user turn); the gate's response is the assistant side of it.\n if (options.contextGate) {\n const gate = await options.contextGate(produceArgs)\n if (gate.proceed === 'handoff') {\n await releaseLock()\n return gate.response\n }\n if (!gate.proceed) {\n await releaseLock()\n // A gated turn is still a TURN, and until now it was the one answer\n // path that fired no lifecycle hook at all — `turnStarted` is set\n // further down, so an early return here left telemetry with no record\n // that anything happened. A product whose gate answers everything\n // therefore looks IDLE rather than broken, which is indistinguishable\n // from healthy on every dashboard.\n //\n // Only the LIFECYCLE hooks fire (telemetry, errors swallowed); the\n // billing/persistence `onTurnComplete` deliberately does not, because\n // no model ran and no assistant row was written. `gated` marks the\n // completion so a consumer counts it without mistaking it for a model\n // turn that produced nothing.\n gatedTurn = true\n turnStartedAtMs = Date.now()\n if (options.lifecycle?.onTurnStart) {\n try {\n await options.lifecycle.onTurnStart({\n identity, executionId, turnStreamId, context, startedAt: turnStartedAtMs,\n })\n } catch (err) {\n log('[chat-routes] lifecycle.onTurnStart failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n await fireTerminalLifecycle(false, undefined)\n return gate.response\n }\n }\n\n // Observe + optionally augment the assembled producer input.\n if (options.beforeTurn) {\n const patch = await options.beforeTurn(produceArgs)\n if (patch) produceArgs = { ...produceArgs, ...patch }\n }\n\n // Durability tap: every engine event buffers (coalesced) so a dropped\n // client replays the tail. Live delivery rides the Response body, not the\n // tap, so `write` is intentionally absent.\n const tap = createBufferedTurnTap({\n store: options.turnStore,\n turnId: turnStreamId,\n scopeId: payload.threadId,\n coalesce: options.coalesceTurnEvents ?? coalesceDeltas,\n })\n const turnMarker = { type: 'turn', turnId: turnStreamId }\n await tap.onEvent(turnMarker)\n\n // Durable projection: the turn buffer above serves LIVE reconnect; this\n // keeps the persisted transcript at most one cadence interval behind, so\n // a viewer arriving after the buffer's (deliberately short) hot window\n // reads the in-flight answer from storage instead of an empty thread.\n // Row identity is the turn's own `executionId`, so a re-entered turn\n // patches the row a previous attempt started instead of duplicating it.\n if (draftTuning) {\n draft = createAssistantDraftWriter({\n ...draftTuning,\n store: draftStore,\n threadId: payload.threadId,\n messageId: options.draftMessageId\n ? options.draftMessageId({ identity, executionId, threadId: payload.threadId })\n : assistantRowIdForTurn(executionId),\n snapshot: () => {\n if (!producer) return null\n return {\n content: producer.finalText(),\n ...(producer.draftParts ? { parts: producer.draftParts() } : {}),\n ...(producer.usage ? { usage: producer.usage() } : {}),\n ...(producer.model ? { model: producer.model } : {}),\n }\n },\n ...(options.transformFinalText ? { transformText: options.transformFinalText } : {}),\n log,\n })\n }\n\n turnStartedAtMs = Date.now()\n turnStarted = true\n if (options.lifecycle?.onTurnStart) {\n try {\n await options.lifecycle.onTurnStart({\n identity, executionId, turnStreamId, context, startedAt: turnStartedAtMs,\n })\n } catch (err) {\n log('[chat-routes] lifecycle.onTurnStart failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n const result = handleChatTurn({\n identity,\n waitUntil: ctx?.waitUntil,\n log,\n hooks: {\n // The engine wants a synchronous producer; box resolution is async —\n // defer it into the generator's first pull.\n produce: () => ({\n stream: (async function* () {\n producer = await options.produce(produceArgs)\n let source: AsyncIterable<ChatRouteEvent> = producer.stream\n if (ctx?.cancelOnDisconnect) {\n source = abortOnSignal(source, request.signal)\n }\n if (options.onRawEvent) {\n source = tapRawEvents(source, (event) => options.onRawEvent!(event, context), log)\n }\n if (options.heartbeat) {\n source = withStreamHeartbeat(source, options.heartbeat.intervalMs, options.heartbeat.event)\n }\n for await (const event of source) yield event\n })(),\n finalText: () => producer?.finalText() ?? '',\n }),\n onEvent: async (event) => {\n if (event.type === 'session.run.failed' || event.type === 'error') {\n runFailed = true\n lastFailureData = event.data\n }\n await tap.onEvent(event)\n // Synchronous bookkeeping; the write it may start is fire-and-\n // forget, so store latency never back-pressures the live stream.\n draft?.notify(event)\n if (options.onEvent) await options.onEvent(event, context)\n },\n ...(options.transformFinalText ? { transformFinalText: options.transformFinalText } : {}),\n persistAssistantMessage: async ({ finalText }) => {\n if (ctx?.cancelOnDisconnect && request.signal.aborted) {\n await draft?.discard()\n assistantMessageId = null\n return\n }\n // The typed boundary: stream-normalizer records → stored vocabulary\n // (validating projection owned by /chat-store — no cast here). The\n // scalar `finalText` arrives already transformed by the engine; the\n // producer's text PARTS are raw, so the same transform must run over\n // each text segment before persistence or a redaction (legal PII)\n // leaks at rest through message.parts.\n const rawParts = producer?.assistantParts ? producer.assistantParts() : undefined\n const projected =\n rawParts && options.transformFinalText\n ? await Promise.all(\n rawParts.map(async (part) =>\n String((part as { type?: unknown }).type ?? '') === 'text'\n ? { ...part, text: await options.transformFinalText!(String((part as { text?: unknown }).text ?? '')) }\n : part,\n ),\n )\n : rawParts\n const parts = projected ? toChatMessageParts(projected) : undefined\n if (!finalText.trim() && (!parts || parts.length === 0)) {\n // Empty turn: today this leaves no assistant row at all, so a\n // draft row started earlier is retracted, not left behind.\n await draft?.discard()\n // Read the writer rather than assuming `null`: `discard` is a\n // no-op on a store without `deleteMessage` (drafting needs only\n // `updateMessage`), and there the draft row genuinely survives.\n assistantMessageId = draft?.rowId() ?? null\n return\n }\n const usage = producer?.usage?.() ?? {}\n const attribution = producer?.modelAttribution?.()\n const values = {\n content: finalText,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(producer?.model ? { model: producer.model } : {}),\n ...(attribution?.requestedModel ? { requestedModel: attribution.requestedModel } : {}),\n ...(attribution?.servedModel ? { servedModel: attribution.servedModel } : {}),\n ...(attribution?.servedProvider ? { servedProvider: attribution.servedProvider } : {}),\n ...(attribution?.servedSource ? { servedSource: attribution.servedSource } : {}),\n ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),\n ...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cacheWriteTokens !== undefined ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),\n ...(usage.costUsd !== undefined ? { costUsd: usage.costUsd } : {}),\n }\n // ONE row per turn either way. With drafting, `finalize` settles\n // any in-flight draft and then insert-or-patches the same\n // deterministic id — so the row this turn ends with is identical to\n // the one the single-write path produces. Without it, today's\n // append is untouched.\n if (draft) {\n await draft.finalize(values)\n assistantMessageId = draft.rowId() ?? null\n return\n }\n assistantMessageId = rowIdOf(\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'assistant',\n ...values,\n }),\n )\n },\n ...(options.onTurnComplete\n ? {\n // Wired into the engine's completion hook, which fires only when\n // the stream ended without throwing. A terminal error EVENT\n // (not a throw) still lands here — so surface `runFailed` so the\n // product skips billing an errored turn instead of marking it\n // complete with empty text.\n onTurnComplete: ({ identity: turnIdentity, finalText }: { identity: ChatTurnIdentity; finalText: string }) => {\n // Read AFTER the drain, so the model reported to billing is\n // the one that actually served — a fallback included.\n const failoverInfo = producer?.modelFailover?.()\n const attribution = producer?.modelAttribution?.()\n return options.onTurnComplete!({\n identity: turnIdentity,\n finalText,\n context,\n failed: runFailed,\n assistantMessageId: assistantRowId(),\n ...(runFailed ? { failureReason: failureReasonOf(lastFailureData) } : {}),\n ...(producer?.model ? { model: producer.model } : {}),\n ...(attribution?.requestedModel ? { requestedModel: attribution.requestedModel } : {}),\n ...(attribution?.servedModel ? { servedModel: attribution.servedModel } : {}),\n ...(attribution?.servedProvider ? { servedProvider: attribution.servedProvider } : {}),\n ...(attribution?.servedSource ? { servedSource: attribution.servedSource } : {}),\n ...(failoverInfo ? { modelFailover: failoverInfo } : {}),\n })\n },\n }\n : {}),\n ...(options.traceFlush ? { traceFlush: () => options.traceFlush!(context) } : {}),\n },\n })\n\n // Tee: one branch to the live client, one drained under waitUntil so the\n // turn (and its buffering via onEvent) runs to completion after a client\n // drop — the engine body executes as it is pulled.\n const [clientBody, drainBody] = result.body.tee()\n const drained = (async () => {\n const reader = drainBody.getReader()\n let drainError: unknown\n try {\n for (;;) {\n const { done } = await reader.read()\n if (done) break\n }\n } catch (err) {\n drainError = err\n log('[chat-routes] turn drain failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n const failed = runFailed || drainError !== undefined\n // Settle any in-flight draft INSIDE the waitUntil-tracked drain. On the\n // path where the producer throws, `persistAssistantMessage` never runs\n // to close the writer, and an unawaited write would race the isolate's\n // teardown — leaving a torn row instead of a clean partial one for a\n // re-entered turn to adopt.\n if (ctx?.cancelOnDisconnect && request.signal.aborted) {\n await draft?.discard()\n } else {\n await draft?.close()\n }\n try {\n await tap.done(failed ? 'error' : 'complete')\n } catch (err) {\n log('[chat-routes] turn buffer finalize failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n await fireTerminalLifecycle(failed, drainError)\n await releaseLock()\n })()\n if (ctx?.waitUntil) ctx.waitUntil(drained)\n else void drained.catch(() => {})\n\n // Announce the replay handle in headers and body before the engine's first event.\n const encoder = new TextEncoder()\n const marker = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(encoder.encode(`${JSON.stringify(turnMarker)}\\n`))\n controller.close()\n },\n })\n const body = concatStreams([marker, clientBody])\n\n return new Response(body, {\n headers: {\n 'Content-Type': result.contentType,\n 'Cache-Control': 'no-cache',\n 'X-Turn-Id': turnStreamId,\n },\n })\n } catch (err) {\n // A throw before the turn began streaming (user-insert, gate, beforeTurn,\n // lifecycle-start, tap setup, engine construction, tee). If the turn had\n // already started, settle the lifecycle with `onTurnError` (close the\n // span) — the drain never ran to do it. Then release the lock, propagate.\n if (turnStarted) await fireTerminalLifecycle(true, err)\n await releaseLock()\n throw err\n }\n }\n\n async function replay(request: Request, params: { turnId: string }): Promise<Response> {\n const turnId = params.turnId?.trim()\n if (!turnId) return Response.json({ error: 'Missing turnId' }, { status: 400 })\n const auth = await options.authorize({ request, intent: 'replay', turnId })\n if (!auth.ok) return auth.response\n\n const fromSeqRaw = new URL(request.url).searchParams.get('fromSeq')\n const fromSeq = fromSeqRaw ? Math.max(0, Math.trunc(Number(fromSeqRaw)) || 0) : 0\n\n const encoder = new TextEncoder()\n const events = replayTurnEvents({\n store: options.turnStore,\n turnId,\n fromSeq,\n ...(options.replay?.pollMs !== undefined ? { pollMs: options.replay.pollMs } : {}),\n ...(options.replay?.timeoutMs !== undefined ? { timeoutMs: options.replay.timeoutMs } : {}),\n })\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n const { done, value } = await events.next()\n if (done) {\n controller.close()\n return\n }\n // Stamp the buffer ordinal so a reconnecting client resumes from\n // `?fromSeq=<lastSeq>` instead of refetching the turn from 0 and\n // re-applying every delta onto already-rendered state.\n controller.enqueue(encoder.encode(`${stampReplaySeq(value)}\\n`))\n },\n cancel() {\n void events.return(undefined)\n },\n })\n return new Response(body, {\n headers: {\n 'Content-Type': 'application/x-ndjson',\n 'Cache-Control': 'no-cache',\n },\n })\n }\n\n async function running(request: Request): Promise<Response> {\n const threadId = new URL(request.url).searchParams.get('threadId')?.trim()\n if (!threadId) return Response.json({ error: 'Missing threadId' }, { status: 400 })\n const auth = await options.authorize({ request, intent: 'running', threadId })\n if (!auth.ok) return auth.response\n // `listRunning` is optional on the store; a store that cannot enumerate\n // running turns simply reports none — the client falls back to the persisted\n // transcript, never to a hang.\n const ids = (await options.turnStore.listRunning?.(threadId)) ?? []\n return Response.json({ running: ids })\n }\n\n return {\n turn,\n replay,\n running,\n interactions: options.interactions ? createInteractionAnswerRoute(options.interactions) : null,\n }\n}\n\n/** Sequential concat of byte streams (marker line, then the engine body). */\nfunction concatStreams(streams: ReadableStream<Uint8Array>[]): ReadableStream<Uint8Array> {\n let index = 0\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n if (!reader) {\n const next = streams[index++]\n if (!next) {\n controller.close()\n return\n }\n reader = next.getReader()\n }\n const { done, value } = await reader.read()\n if (done) {\n reader = null\n continue\n }\n controller.enqueue(value)\n return\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n for (const stream of streams.slice(index)) await stream.cancel(reason)\n },\n })\n}\n\n/**\n * Stop a producer pull as soon as an opted-in caller disconnects.\n * `AsyncIterator.return()` alone cannot interrupt a pending `next()` call, so\n * race each pull with the request signal and close the source in `finally`.\n */\nasync function* abortOnSignal<T>(\n source: AsyncIterable<T>,\n signal: AbortSignal,\n): AsyncGenerator<T, void, unknown> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n for (;;) {\n const next = await nextWithAbort(iterator, signal)\n if (next.done) return\n yield next.value\n }\n } finally {\n await closeIteratorAfterAbort(iterator)\n }\n}\n\nfunction nextWithAbort<T>(\n iterator: AsyncIterator<T>,\n signal: AbortSignal,\n): Promise<IteratorResult<T>> {\n if (signal.aborted) return Promise.reject(new Error('chat turn cancelled'))\n return new Promise((resolve, reject) => {\n let settled = false\n const cleanup = () => signal.removeEventListener('abort', onAbort)\n const onAbort = () => {\n if (settled) return\n settled = true\n cleanup()\n reject(new Error('chat turn cancelled'))\n }\n signal.addEventListener('abort', onAbort, { once: true })\n if (signal.aborted) {\n onAbort()\n return\n }\n Promise.resolve()\n .then(() => iterator.next())\n .then(\n (result) => {\n if (settled) return\n settled = true\n cleanup()\n resolve(result)\n },\n (error: unknown) => {\n if (settled) return\n settled = true\n cleanup()\n reject(error)\n },\n )\n })\n}\n\nconst ABORT_CLEANUP_TIMEOUT_MS = 50\n\nasync function closeIteratorAfterAbort<T>(iterator: AsyncIterator<T>): Promise<void> {\n let closing: PromiseLike<unknown> | undefined\n try {\n const result = iterator.return?.()\n if (result) closing = Promise.resolve(result)\n } catch {\n return\n }\n if (!closing) return\n let timeout: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n Promise.resolve(closing).catch(() => undefined),\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, ABORT_CLEANUP_TIMEOUT_MS)\n }),\n ])\n } finally {\n if (timeout !== undefined) clearTimeout(timeout)\n }\n}\n","import type { SandboxStreamEvent } from '../sandbox/index'\nimport type { ChatTurnExecutionLimits, ChatTurnRoutes } from './turn-routes'\nimport { chatTurnRequestInit, type ChatTurnRequestPayload } from './wire'\n\nexport interface StreamChatRouteAsSandboxOptions {\n routes: ChatTurnRoutes\n request: Request\n payload: ChatTurnRequestPayload\n waitUntil?: (promise: Promise<unknown>) => void\n /** Stop forwarding when the API client disconnects. The persisted turn continues. */\n signal?: AbortSignal\n /** Limits authenticated by the gateway and forwarded to the producer. */\n executionLimits?: ChatTurnExecutionLimits\n}\n\ninterface ParsedChatRouteEvent {\n type?: string\n data?: Record<string, unknown>\n text?: string\n usage?: Record<string, unknown>\n toolName?: string\n}\n\ntype GatewayUsageUpdate = NonNullable<NonNullable<SandboxStreamEvent['data']>['usage']>\n\n/**\n * Drive the normal persisted chat route and expose its events to an\n * agent-gateway sandbox adapter. The route remains the only turn owner: auth,\n * locking, live delivery, transcript writes, and completion hooks run once.\n */\nexport async function* streamChatRouteAsSandboxEvents(\n options: StreamChatRouteAsSandboxOptions,\n): AsyncGenerator<SandboxStreamEvent> {\n const parentSignal = options.signal ?? options.request.signal\n if (parentSignal.aborted) return\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined\n const stopForwarding = () => void reader?.cancel()\n parentSignal.addEventListener('abort', stopForwarding, { once: true })\n\n const request = new Request(options.request.url, {\n ...chatTurnRequestInit(options.payload),\n headers: options.request.headers,\n })\n request.headers.set('Content-Type', 'application/json')\n\n let complete = false\n try {\n const response = await options.routes.turn(\n request,\n {\n ...(options.waitUntil ? { waitUntil: options.waitUntil } : {}),\n ...(options.executionLimits ? { executionLimits: options.executionLimits } : {}),\n },\n )\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined)\n throw new Error(`chat route rejected the gateway turn (${response.status})`)\n }\n if (!response.body) throw new Error('chat route returned no stream')\n\n reader = response.body.getReader()\n if (parentSignal.aborted) {\n await reader.cancel().catch(() => undefined)\n return\n }\n const decoder = new TextDecoder()\n let buffer = ''\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) {\n complete = true\n buffer += decoder.decode()\n const event = toSandboxEvent(parseEvent(buffer))\n if (event) yield event\n break\n }\n buffer += decoder.decode(chunk.value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n const event = toSandboxEvent(parseEvent(line))\n if (event) yield event\n }\n }\n } finally {\n if (!complete) await reader?.cancel().catch(() => undefined)\n reader?.releaseLock()\n parentSignal.removeEventListener('abort', stopForwarding)\n }\n}\n\nfunction parseEvent(line: string): ParsedChatRouteEvent | null {\n if (!line.trim()) return null\n let value: unknown\n try {\n value = JSON.parse(line)\n } catch {\n throw new Error('chat route returned invalid NDJSON')\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('chat route returned a non-object event')\n }\n const event = value as Record<string, unknown>\n if (event.type !== undefined && typeof event.type !== 'string') {\n throw new Error('chat route returned an invalid event type')\n }\n const data = event.data\n if (data !== undefined && (!data || typeof data !== 'object' || Array.isArray(data))) {\n throw new Error('chat route returned invalid event data')\n }\n const dataUsage = data && (data as Record<string, unknown>).usage\n if (dataUsage !== undefined && (!dataUsage || typeof dataUsage !== 'object' || Array.isArray(dataUsage))) {\n throw new Error('chat route returned invalid data.usage')\n }\n if (event.text !== undefined && typeof event.text !== 'string') {\n throw new Error('chat route returned an invalid text event')\n }\n const usage = event.usage\n if (usage !== undefined && (!usage || typeof usage !== 'object' || Array.isArray(usage))) {\n throw new Error('chat route returned invalid usage')\n }\n if (event.toolName !== undefined && typeof event.toolName !== 'string') {\n throw new Error('chat route returned an invalid tool name')\n }\n return {\n ...(typeof event.type === 'string' ? { type: event.type } : {}),\n ...(data ? { data: data as SandboxStreamEvent['data'] } : {}),\n ...(typeof event.text === 'string' ? { text: event.text } : {}),\n ...(usage ? { usage: usage as Record<string, unknown> } : {}),\n ...(typeof event.toolName === 'string' ? { toolName: event.toolName } : {}),\n }\n}\n\nfunction isNonNegativeSafeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nfunction aliasedSafeInteger(\n usage: Record<string, unknown>,\n field: string,\n alias?: string,\n): number | undefined {\n const value = usage[field]\n const aliasValue = alias ? usage[alias] : undefined\n for (const candidate of [value, aliasValue]) {\n if (candidate !== undefined && !isNonNegativeSafeInteger(candidate)) {\n throw new Error(`chat route returned invalid usage.${field}`)\n }\n }\n if (value !== undefined && aliasValue !== undefined && value !== aliasValue) {\n throw new Error(`chat route returned conflicting usage.${field}`)\n }\n return (value ?? aliasValue) as number | undefined\n}\n\nfunction aliasedNonNegativeNumber(\n usage: Record<string, unknown>,\n field: string,\n alias?: string,\n): number | undefined {\n const value = usage[field]\n const aliasValue = alias ? usage[alias] : undefined\n for (const candidate of [value, aliasValue]) {\n if (\n candidate !== undefined &&\n (typeof candidate !== 'number' || !Number.isFinite(candidate) || candidate < 0)\n ) {\n throw new Error(`chat route returned invalid usage.${field}`)\n }\n }\n if (value !== undefined && aliasValue !== undefined && value !== aliasValue) {\n throw new Error(`chat route returned conflicting usage.${field}`)\n }\n return (value ?? aliasValue) as number | undefined\n}\n\n/** Preserve each measured field without inventing the fields the route lacks. */\nfunction providerUsageUpdate(value: unknown): GatewayUsageUpdate | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return null\n const source = value as Record<string, unknown>\n const usage: GatewayUsageUpdate = {}\n const inputTokens = aliasedSafeInteger(source, 'inputTokens', 'promptTokens')\n const outputTokens = aliasedSafeInteger(source, 'outputTokens', 'completionTokens')\n const reasoningTokens = aliasedSafeInteger(source, 'reasoningTokens')\n const toolTokens = aliasedSafeInteger(source, 'toolTokens')\n const toolCallCount = aliasedSafeInteger(source, 'toolCallCount')\n const providerCostUsd = aliasedNonNegativeNumber(source, 'providerCostUsd', 'costUsd')\n if (inputTokens !== undefined) usage.inputTokens = inputTokens\n if (outputTokens !== undefined) usage.outputTokens = outputTokens\n if (reasoningTokens !== undefined) usage.reasoningTokens = reasoningTokens\n if (toolTokens !== undefined) usage.toolTokens = toolTokens\n if (toolCallCount !== undefined) usage.toolCallCount = toolCallCount\n if (providerCostUsd !== undefined) usage.providerCostUsd = providerCostUsd\n if (source.budgetEnforced !== undefined) {\n if (typeof source.budgetEnforced !== 'boolean') {\n throw new Error('chat route returned invalid usage.budgetEnforced')\n }\n usage.budgetEnforced = source.budgetEnforced\n }\n return Object.keys(usage).length > 0 ? usage : null\n}\n\n/** Translate the app route's producer vocabulary to the gateway stream shape. */\nfunction toSandboxEvent(event: ParsedChatRouteEvent | null): SandboxStreamEvent | null {\n if (!event) return null\n\n // `createChatTurnRoutes` emits flattened text events. The gateway's adapter\n // contract uses the sandbox's canonical part-update shape instead.\n if (event.type === 'text') {\n if (event.text === undefined) throw new Error('chat route text event had no text')\n return {\n type: 'message.part.updated',\n data: { part: { type: 'text' }, delta: event.text },\n }\n }\n\n // Reasoning is persisted by the app route but is not public API output.\n // Dropping it also prevents internal thought text from crossing the paid\n // gateway boundary.\n if (event.type === 'reasoning') return null\n\n // Preserve measured fields even when the app route cannot prove a complete\n // provider-enforced receipt. The gateway fills only absent legacy fields and\n // marks that completed receipt as not provider-enforced.\n if (event.type === 'usage' || event.usage || event.data?.usage) {\n const usage = providerUsageUpdate(event.usage ?? event.data?.usage)\n if (!usage) return null\n return { type: 'usage', data: { usage } }\n }\n\n // A producer can announce the same tool call twice while its arguments fill\n // in. The terminal tool result occurs once, so count that event instead.\n if (event.type === 'tool_result') {\n if (!event.toolName) throw new Error('chat route tool result had no tool name')\n return { type: 'tool_result', data: { tool: { name: event.toolName } } }\n }\n\n if (event.type === 'input-required' && !event.data?.inputRequired) {\n const prompt = typeof event.data?.prompt === 'string' ? event.data.prompt : undefined\n return {\n type: 'input-required',\n data: { inputRequired: prompt ? { prompt } : {} },\n }\n }\n\n return {\n ...(event.type ? { type: event.type } : {}),\n ...(event.data ? { data: event.data as SandboxStreamEvent['data'] } : {}),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiLA,IAAM,sBAA2C,oBAAI,IAAI;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,sBAAsB;AAC5B,IAAM,wBAAwB;AAC9B,IAAM,sCAAsC;AAGrC,SAAS,oBAAoB,OAAoC;AACtE,SAAO,OAAO,OAAO,SAAS,YAAY,oBAAoB,IAAI,MAAM,IAAI;AAC9E;AAKA,SAAS,mBAAmB,MAA+B,UAA2C;AACpG,MAAI,YAAY,EAAG,QAAO;AAC1B,MAAI,OAAO,KAAK,QAAQ,EAAE,MAAM,OAAQ,QAAO;AAC/C,QAAM,QAAQ,KAAK;AACnB,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,SAAS;AACf,QAAM,SAAS,OAAO;AACtB,MAAI,WAAW,UAAa,WAAW,KAAM,QAAO;AACpD,QAAM,aAAa,OAAO,WAAW,WAAW,SAAS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
- } from "./chunk-IAY2DMKW.js";
8
+ } from "./chunk-EA4UVS4T.js";
9
9
 
10
10
  // src/platform/sso.ts
11
11
  var DEFAULT_STATE_TTL_SECONDS = 600;
@@ -374,4 +374,4 @@ export {
374
374
  createAdminGuard,
375
375
  assertBillableBalance
376
376
  };
377
- //# sourceMappingURL=chunk-CSMJM7YT.js.map
377
+ //# sourceMappingURL=chunk-TWTLQWES.js.map
@@ -1,14 +1,14 @@
1
1
  // src/design-canvas-react/lazy.tsx
2
2
  import { lazy } from "react";
3
3
  var DesignCanvasLazy = lazy(
4
- () => import("./DesignCanvasEditor-UZ2S6BDD.js").then((m) => ({ default: m.DesignCanvasEditor }))
4
+ () => import("./DesignCanvasEditor-4QWY2LHM.js").then((m) => ({ default: m.DesignCanvasEditor }))
5
5
  );
6
6
  var DesignCanvasChromeLazy = lazy(
7
- () => import("./DesignCanvas-MWEYD6PR.js").then((m) => ({ default: m.DesignCanvas }))
7
+ () => import("./DesignCanvas-YLVDCX6H.js").then((m) => ({ default: m.DesignCanvas }))
8
8
  );
9
9
 
10
10
  export {
11
11
  DesignCanvasLazy,
12
12
  DesignCanvasChromeLazy
13
13
  };
14
- //# sourceMappingURL=chunk-KX2GA3L6.js.map
14
+ //# sourceMappingURL=chunk-WAMJSZYB.js.map
@@ -31,12 +31,12 @@ import {
31
31
  validateSceneOperation,
32
32
  validateSceneOperations,
33
33
  validateSlotValue
34
- } from "../chunk-WYHFHTSQ.js";
34
+ } from "../chunk-BWQPVS7D.js";
35
35
  import {
36
36
  buildScopedMcpServerEntry,
37
37
  createMcpToolHandler
38
38
  } from "../chunk-6A7MYOUI.js";
39
- import "../chunk-IAY2DMKW.js";
39
+ import "../chunk-EA4UVS4T.js";
40
40
  import "../chunk-TXD5HXLE.js";
41
41
 
42
42
  // src/design-canvas/operations.ts
@@ -20,7 +20,7 @@ import {
20
20
  nudgeDelta,
21
21
  resolveExportParams,
22
22
  resolveNodeCachePixelRatio
23
- } from "../chunk-VHMZ3KUH.js";
23
+ } from "../chunk-2WVBGQ2Y.js";
24
24
  import {
25
25
  SCENE_COMMAND_HISTORY_LIMIT,
26
26
  addElementCommand,
@@ -39,12 +39,12 @@ import {
39
39
  setPageGuidesCommand,
40
40
  setPagePropsCommand,
41
41
  ungroupElementCommand
42
- } from "../chunk-AKMQFCDL.js";
42
+ } from "../chunk-FEVVF6JJ.js";
43
43
  import {
44
44
  bleedAwareExportBounds,
45
45
  scaleForPreset
46
- } from "../chunk-WYHFHTSQ.js";
47
- import "../chunk-IAY2DMKW.js";
46
+ } from "../chunk-BWQPVS7D.js";
47
+ import "../chunk-EA4UVS4T.js";
48
48
  import "../chunk-TXD5HXLE.js";
49
49
  export {
50
50
  DEFAULT_INSERT_TEMPLATES,
@@ -12,7 +12,7 @@ import {
12
12
  downloadDataUrl,
13
13
  exportDocumentJson,
14
14
  exportPageDataUrl
15
- } from "../chunk-JF423ASS.js";
15
+ } from "../chunk-G2B23BZ6.js";
16
16
  import {
17
17
  BTN,
18
18
  BTN_ACTIVE,
@@ -41,7 +41,7 @@ import {
41
41
  buildRulerTicks,
42
42
  formatRulerLabel,
43
43
  selectTickStep
44
- } from "../chunk-JAT6SOPK.js";
44
+ } from "../chunk-KWN5PGXM.js";
45
45
  import "../chunk-Q2QKEV6J.js";
46
46
  import "../chunk-ZN5J47UX.js";
47
47
  import {
@@ -65,7 +65,7 @@ import {
65
65
  nudgeDelta,
66
66
  resolveExportParams,
67
67
  resolveNodeCachePixelRatio
68
- } from "../chunk-VHMZ3KUH.js";
68
+ } from "../chunk-2WVBGQ2Y.js";
69
69
  import {
70
70
  SCENE_COMMAND_HISTORY_LIMIT,
71
71
  addElementCommand,
@@ -84,17 +84,17 @@ import {
84
84
  setPageGuidesCommand,
85
85
  setPagePropsCommand,
86
86
  ungroupElementCommand
87
- } from "../chunk-AKMQFCDL.js";
87
+ } from "../chunk-FEVVF6JJ.js";
88
88
  import {
89
89
  assertSceneMediaSrc,
90
90
  bleedAwareExportBounds,
91
91
  scaleForPreset
92
- } from "../chunk-WYHFHTSQ.js";
92
+ } from "../chunk-BWQPVS7D.js";
93
93
  import {
94
94
  DesignCanvasChromeLazy,
95
95
  DesignCanvasLazy
96
- } from "../chunk-KX2GA3L6.js";
97
- import "../chunk-IAY2DMKW.js";
96
+ } from "../chunk-WAMJSZYB.js";
97
+ import "../chunk-EA4UVS4T.js";
98
98
  import "../chunk-TXD5HXLE.js";
99
99
 
100
100
  // src/design-canvas-react/components/CanvasInsertPanel.tsx
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  DesignCanvasChromeLazy,
3
3
  DesignCanvasLazy
4
- } from "../chunk-KX2GA3L6.js";
4
+ } from "../chunk-WAMJSZYB.js";
5
5
  export {
6
6
  DesignCanvasChromeLazy,
7
7
  DesignCanvasLazy
@@ -13,12 +13,12 @@ import {
13
13
  resolveTangleSsoAccount,
14
14
  signSessionCookieValue,
15
15
  verifySignedSsoState
16
- } from "../chunk-CSMJM7YT.js";
16
+ } from "../chunk-TWTLQWES.js";
17
17
  import {
18
18
  resolveTangleDevOrUserKey,
19
19
  resolveTangleExecutionEnvironment
20
20
  } from "../chunk-JML7WKWU.js";
21
- import "../chunk-IAY2DMKW.js";
21
+ import "../chunk-EA4UVS4T.js";
22
22
  import "../chunk-TXD5HXLE.js";
23
23
 
24
24
  // src/platform/hub.ts
@@ -28,33 +28,19 @@ export type DetachedTurnTerminalResult = Exclude<TurnDriveResult, {
28
28
  export type DetachedTurnDriveOutcome = Outcome<TurnDriveResult>;
29
29
  /** Options for one durable detached-turn Workflow run. */
30
30
  export interface DetachedTurnWorkflowTickOptions<TPayload extends DetachedTurnWorkflowIdentity, TSettled> {
31
- /** The Workflow event. Its payload must keep the same session and turn ids. */
32
31
  event: CloudflareWorkflowEventLike<TPayload>;
33
- /** Cloudflare's durable step runner. */
34
32
  step: CloudflareWorkflowStepLike;
35
- /**
36
- * Run exactly one `driveSandboxTurn`/`box.driveTurn` pass.
37
- *
38
- * The callback runs inside one `step.do`. A transport failure is thrown from
39
- * that step so Cloudflare retries the pass with the same deterministic ids.
40
- */
33
+ /** One SDK drive pass. Rejected results must not enter the Workflow cache. */
41
34
  drive: (payload: TPayload) => Promise<DetachedTurnDriveOutcome>;
42
- /**
43
- * Read the completed Sandbox cache/session records and persist the product's
44
- * deterministic assistant row. This callback MUST be idempotent because a
45
- * Worker can stop after the write and before the Workflow step commits.
46
- */
35
+ /** Must be idempotent: the Worker can stop after the write but before commit. */
47
36
  settle: (payload: TPayload, result: DetachedTurnTerminalResult) => Promise<TSettled>;
48
- /** Delay between one-tick drive passes. */
49
37
  pollDelay?: CloudflareWorkflowSleepDuration;
50
- /** Stable prefix for the Workflow's drive and wait step names. */
51
38
  stepName?: string;
52
39
  }
53
40
  /**
54
- * Drive one detached Sandbox turn from a Cloudflare Workflow.
55
- *
56
- * Each drive step makes one prompt admission/status pass and returns promptly.
57
- * A running pass sleeps durably before the next pass. The final settlement is
58
- * also a step, so replayed Workflow execution never holds a live stream open.
41
+ * Drive a detached SDK turn with durable steps, not an HTTP waitUntil lifetime.
42
+ * Stable step names let an evicted Workflow resume without repeating committed
43
+ * passes. Validation belongs inside step.do so a transient malformed response
44
+ * is retried rather than committed permanently as a poisoned checkpoint.
59
45
  */
60
46
  export declare function runDetachedTurnWorkflowTick<TPayload extends DetachedTurnWorkflowIdentity, TSettled>(options: DetachedTurnWorkflowTickOptions<TPayload, TSettled>): Promise<TSettled>;
@@ -35,24 +35,27 @@ function assertIdentity(payload) {
35
35
  function isKnownDriveState(state) {
36
36
  return state === "running" || state === "completed" || state === "failed" || state === "awaiting_plan_decision";
37
37
  }
38
+ function checkedDriveResult(value) {
39
+ const state = value?.state;
40
+ if (!isKnownDriveState(state)) {
41
+ throw new Error(`detached turn drive returned unknown state: ${String(state)}`);
42
+ }
43
+ return value;
44
+ }
38
45
  async function runDetachedTurnWorkflowTick(options) {
39
- const payload = options.event?.payload;
40
- assertIdentity(payload);
46
+ assertIdentity(options.event?.payload);
47
+ const payload = Object.freeze({ ...options.event.payload });
41
48
  const name = options.stepName ?? "detached-turn";
42
49
  const delay = options.pollDelay ?? "5 seconds";
43
50
  let attempt = 0;
44
51
  let terminalResult;
45
52
  while (true) {
46
- const driveResult = await options.step.do(`${name}:drive:${attempt}`, async () => {
53
+ const driveResult = checkedDriveResult(await options.step.do(`${name}:drive:${attempt}`, async () => {
47
54
  const outcome = await options.drive(payload);
48
55
  if (!outcome.succeeded) throw outcome.error;
49
- return outcome.value;
50
- });
51
- const state = driveResult?.state;
52
- if (!isKnownDriveState(state)) {
53
- throw new Error(`detached turn drive returned unknown state: ${String(state)}`);
54
- }
55
- if (state !== "running") {
56
+ return checkedDriveResult(outcome.value);
57
+ }));
58
+ if (driveResult.state !== "running") {
56
59
  terminalResult = driveResult;
57
60
  break;
58
61
  }