@tangle-network/agent-app 4.0.35 → 4.0.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/assistant/index.js +5 -5
  2. package/dist/chat-react/index.js +3 -3
  3. package/dist/chat-routes/index.js +19 -11
  4. package/dist/chat-routes/index.js.map +1 -1
  5. package/dist/chat-routes/turn-event-stream.d.ts +10 -1
  6. package/dist/chat-routes/turn-execution.d.ts +34 -3
  7. package/dist/chat-routes/turn-intent.d.ts +5 -0
  8. package/dist/chat-routes/turn-progress.d.ts +25 -1
  9. package/dist/chat-routes/turn-route-contracts.d.ts +31 -2
  10. package/dist/chat-routes/turn-settlement.d.ts +23 -0
  11. package/dist/chat-store/index.js +2 -2
  12. package/dist/{chunk-NAMSFODC.js → chunk-4YBNKXUE.js} +54 -4
  13. package/dist/chunk-4YBNKXUE.js.map +1 -0
  14. package/dist/{chunk-K2JPSXKI.js → chunk-6YLVFV3F.js} +39 -3
  15. package/dist/chunk-6YLVFV3F.js.map +1 -0
  16. package/dist/{chunk-PZTBXHPE.js → chunk-725RZ5JQ.js} +2 -2
  17. package/dist/{chunk-ONIIKYVV.js → chunk-77UNTK66.js} +357 -290
  18. package/dist/chunk-77UNTK66.js.map +1 -0
  19. package/dist/{chunk-KPCNNFBO.js → chunk-AOSQ5JCO.js} +41 -2
  20. package/dist/{chunk-KPCNNFBO.js.map → chunk-AOSQ5JCO.js.map} +1 -1
  21. package/dist/{chunk-GOKFD7ZZ.js → chunk-BMRKOPL6.js} +2 -2
  22. package/dist/{chunk-E633CJFH.js → chunk-COUT2WD5.js} +2 -2
  23. package/dist/{chunk-7VJCMEEE.js → chunk-DPD7LY3T.js} +11 -6
  24. package/dist/chunk-DPD7LY3T.js.map +1 -0
  25. package/dist/{chunk-5WVGSCBN.js → chunk-MGW25KMR.js} +4 -4
  26. package/dist/{chunk-IAK227OO.js → chunk-Q7NELHRU.js} +2 -2
  27. package/dist/{chunk-QFT2V2OE.js → chunk-RSSK6FUF.js} +2 -2
  28. package/dist/{chunk-4YZKDWMB.js → chunk-SADNHPAY.js} +2 -2
  29. package/dist/{chunk-LTCRS46I.js → chunk-VUI4IUIM.js} +25 -7
  30. package/dist/chunk-VUI4IUIM.js.map +1 -0
  31. package/dist/operator/index.js +2 -2
  32. package/dist/preset-cloudflare/index.js +6 -6
  33. package/dist/public-consultation/index.d.ts +1 -1
  34. package/dist/public-consultation/index.js +8 -8
  35. package/dist/runtime/index.js +3 -3
  36. package/dist/runtime/router-turn.js +2 -2
  37. package/dist/sandbox/index.js +4 -4
  38. package/dist/turn-stream/cancellation.d.ts +16 -0
  39. package/dist/turn-stream/core.d.ts +4 -0
  40. package/dist/turn-stream/do.d.ts +4 -2
  41. package/dist/turn-stream/hosted-turn.d.ts +20 -0
  42. package/dist/turn-stream/index.js +122 -5
  43. package/dist/turn-stream/index.js.map +1 -1
  44. package/dist/turn-trace/index.js +1 -1
  45. package/dist/web-react/chat-stream.d.ts +4 -2
  46. package/dist/web-react/index.js +13 -5
  47. package/package.json +1 -1
  48. package/dist/chunk-7VJCMEEE.js.map +0 -1
  49. package/dist/chunk-K2JPSXKI.js.map +0 -1
  50. package/dist/chunk-LTCRS46I.js.map +0 -1
  51. package/dist/chunk-NAMSFODC.js.map +0 -1
  52. package/dist/chunk-ONIIKYVV.js.map +0 -1
  53. /package/dist/{chunk-PZTBXHPE.js.map → chunk-725RZ5JQ.js.map} +0 -0
  54. /package/dist/{chunk-GOKFD7ZZ.js.map → chunk-BMRKOPL6.js.map} +0 -0
  55. /package/dist/{chunk-E633CJFH.js.map → chunk-COUT2WD5.js.map} +0 -0
  56. /package/dist/{chunk-5WVGSCBN.js.map → chunk-MGW25KMR.js.map} +0 -0
  57. /package/dist/{chunk-IAK227OO.js.map → chunk-Q7NELHRU.js.map} +0 -0
  58. /package/dist/{chunk-QFT2V2OE.js.map → chunk-RSSK6FUF.js.map} +0 -0
  59. /package/dist/{chunk-4YZKDWMB.js.map → chunk-SADNHPAY.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/chat-routes/protected-runtime-producer.ts","../../src/chat-routes/detached-turn.ts","../../src/chat-routes/plan-follow-up.ts","../../src/chat-routes/durable-projection.ts","../../src/chat-routes/attachment-store.ts","../../src/chat-routes/resolve-attachments.ts","../../src/chat-routes/attachment-write-safety.ts","../../src/chat-routes/promote-file-part.ts","../../src/chat-routes/attachment-upload.ts","../../src/chat-routes/intelligence.ts","../../src/chat-routes/stored-attachments.ts"],"sourcesContent":["import type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runProtectedRouterTurn, type RouterTurnGrant } from '../runtime/protected-router-turn'\nimport type { RouterTurnOptions } from '../runtime/router-turn'\nimport type { McpToolDefinition } from '../tools/mcp-rpc'\nimport { createSandboxChatProducer } from './sandbox-producer'\nimport type { ChatTurnRouteProducer, ChatTurnUsage } from './turn-routes'\n\nexport interface ProtectedRuntimeChatOptions {\n profile: AgentProfile\n prompt: string\n priorMessages?: ReadonlyArray<{ role: string; content: string }>\n /** Runtime owns reservation, activation, revocation and authoritative settlement. */\n grant: RouterTurnGrant\n /** Only tools authorized for this execution. Each tool validates its arguments and effects. */\n tools: readonly McpToolDefinition<{ signal: AbortSignal }>[]\n maxToolCalls: number\n signal?: AbortSignal\n}\n\n/** Refuse unsupported profile leaves by name instead of silently dropping them. */\nconst PROTECTED_TURN_AXES: ReadonlySet<string> = new Set([\n 'name', 'description', 'version', 'tags', 'metadata', 'harness', 'tools',\n 'systemPrompt', 'instructions',\n 'modelDefault', 'modelProvider', 'modelReasoningEffort', 'modelMaxVisibleOutputTokens',\n 'modelMaxTotalOutputTokens', 'modelMetadata',\n])\n\nfunction protectedTurnSettings(profile: AgentProfile, toolNames: ReadonlySet<string>,\n profileMaterializationAxes: typeof import('@tangle-network/agent-interface').profileMaterializationAxes): Pick<RouterTurnOptions,\n 'model' | 'systemPrompt' | 'reasoningEffort' | 'maxTokens' | 'maxCompletionTokens'> {\n if (profile.harness && profile.harness !== 'cli-base') throw new Error(`Protected chat runs only the cli-base harness, not ${profile.harness}`)\n if (profile.resources) throw new Error('Protected chat applies prompt text only; run profile resources in the Sandbox lane')\n if (profile.model?.metadata && Object.keys(profile.model.metadata).length > 0) {\n throw new Error('Protected chat does not apply AgentProfile.model.metadata')\n }\n if (profile.model?.maxReasoningTokens !== undefined) throw new Error('Protected chat cannot enforce maxReasoningTokens')\n const unsupported = profileMaterializationAxes(profile).filter(axis => !PROTECTED_TURN_AXES.has(axis))\n if (unsupported.length > 0) {\n throw new Error(`Protected chat does not apply AgentProfile ${unsupported.join(', ')}; run this profile in the Sandbox lane`)\n }\n const declared = profile.model?.default?.trim()\n const provider = profile.model?.provider?.trim()\n const model = declared && provider && declared.startsWith(`${provider}/`) ? declared.slice(provider.length + 1) : declared\n if (!model) throw new Error('Protected chat requires AgentProfile.model.default')\n for (const [name, enabled] of Object.entries(profile.tools ?? {})) {\n if (enabled !== toolNames.has(name)) throw new Error(`Protected tool ${name} does not match AgentProfile.tools`)\n }\n for (const name of toolNames) {\n if (profile.tools?.[name] !== true) throw new Error(`Protected tool ${name} is not enabled by AgentProfile.tools`)\n }\n const { visible, total } = { visible: profile.model?.maxVisibleOutputTokens, total: profile.model?.maxTotalOutputTokens }\n return {\n model,\n systemPrompt: [profile.prompt?.systemPrompt, ...(profile.prompt?.instructions ?? [])]\n .filter((part): part is string => typeof part === 'string' && part.trim().length > 0).join('\\n'),\n ...(profile.model?.reasoningEffort ? { reasoningEffort: profile.model.reasoningEffort } : {}),\n ...(visible !== undefined ? { maxTokens: visible } : {}),\n ...(total !== undefined ? { maxCompletionTokens: total } : {}),\n }\n}\n\n/** Project one protected Router turn, publishing usage only from its settled grant. */\nexport function createProtectedRuntimeChatProducer(options: ProtectedRuntimeChatOptions): ChatTurnRouteProducer {\n if (!Number.isSafeInteger(options.maxToolCalls) || options.maxToolCalls < 0) throw new Error('maxToolCalls must be a non-negative integer')\n options = { ...options,\n grant: { ...options.grant, resolve: structuredClone(options.grant.resolve), reserve: structuredClone(options.grant.reserve) },\n tools: options.tools.map(tool => ({ ...tool, inputSchema: structuredClone(tool.inputSchema) })),\n // Providers reject the storage fields carried by chat history rows.\n priorMessages: options.priorMessages?.map(({ role, content }) => ({ role, content })),\n }\n const tools = new Set(options.tools.map(tool => tool.name))\n if (tools.size !== options.tools.length) throw new Error('Duplicate protected tool name')\n const profile = structuredClone(options.profile)\n let toolCalls = 0\n let usage: ChatTurnUsage = {}\n let started = false\n let model: string | undefined\n const controller = new AbortController()\n const pendingTools = new Set<Promise<unknown>>()\n let execution: Promise<void> | undefined\n let reader: ReadableStreamDefaultReader<unknown> | undefined\n let writer: WritableStreamDefaultWriter<unknown> | undefined\n let terminalObserved = false\n let closing: Promise<void> | undefined\n\n // Local completion requires drained execution and tool effects, not a projected result.\n function close(reason?: unknown): Promise<void> {\n controller.abort(reason)\n closing ??= (async () => {\n const errors: unknown[] = []\n try { await reader?.cancel() } catch (error) { errors.push(error) }\n try { await execution } catch (error) { errors.push(error) }\n while (pendingTools.size) await Promise.allSettled([...pendingTools])\n try { reader?.releaseLock() } catch (error) { errors.push(error) }\n try { writer?.releaseLock() } catch (error) { errors.push(error) }\n terminalObserved = true\n if (errors.length) throw errors[0]\n })()\n return closing\n }\n\n async function* events(): AsyncGenerator<unknown> {\n if (started) throw new Error('A protected chat producer can only execute once')\n started = true\n try {\n controller.signal.throwIfAborted()\n options.signal?.throwIfAborted()\n if (Date.now() >= options.grant.deadlineAtMs) throw new Error('Protected execution deadline expired')\n const signal = AbortSignal.any([\n controller.signal, AbortSignal.timeout(Math.max(1, options.grant.deadlineAtMs - Date.now())),\n ...(options.signal ? [options.signal] : []),\n ])\n const channel = new TransformStream<unknown, unknown>()\n const channelWriter = writer = channel.writable.getWriter()\n reader = channel.readable.getReader()\n const emit = (event: unknown) => channelWriter.write(event)\n // The agent-interface root initializes every schema; only a protected turn needs it, so it loads here.\n const { profileMaterializationAxes } = await import('@tangle-network/agent-interface')\n let settings: ReturnType<typeof protectedTurnSettings>\n // A profile this lane cannot run is a refusal that fails the same way again: the person reads its class sentence.\n try {\n settings = protectedTurnSettings(profile, tools, profileMaterializationAxes)\n } catch (error) {\n throw Object.assign(error as Error, { code: 'profile_unsupported' })\n }\n execution = runProtectedRouterTurn({\n ...settings,\n grant: options.grant,\n userMessage: options.prompt,\n history: [...(options.priorMessages ?? [])],\n signal,\n // The grant's ledger expects one buffered completion per model call.\n stream: false,\n maxToolCalls: options.maxToolCalls,\n maxToolTurns: options.grant.reserve.limits.maxModelCalls,\n // A tool definition here cannot declare an effect, so every tool is a lookup: the lane keeps main's rule.\n tools: options.tools.map(tool => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema, effect: 'lookup' as const,\n run: (args: Record<string, unknown>) => {\n const work = (async () => {\n signal.throwIfAborted()\n toolCalls += 1\n const id = `tool-${toolCalls}`\n await emit({ type: 'tool_call', data: { id, name: tool.name, arguments: args } })\n signal.throwIfAborted()\n try {\n const result = await tool.run(args, { signal })\n await emit({ type: 'tool_result', data: { id, name: tool.name, output: result } })\n return result\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Tool failed'\n await emit({ type: 'tool_result', data: { id, name: tool.name, error: message } })\n throw error\n }\n })()\n pendingTools.add(work)\n void work.then(() => pendingTools.delete(work), () => pendingTools.delete(work))\n return work\n } })),\n toolError: error => ({ code: 'tool_failed', message: error instanceof Error ? error.message : 'Tool failed' }),\n renderToolResult: (_toolName, outcome) => outcome.ok ? JSON.stringify(outcome.result) ?? 'null' : `error: ${outcome.message}`,\n }).then(async outcome => {\n if (outcome.settlement) {\n usage = { ...outcome.settlement.usage }\n model = outcome.settlement.model\n // Tool-result text is billed as input under a grant.\n await emit({ type: 'usage', usage: { promptTokens: usage.inputTokens,\n completionTokens: usage.outputTokens, providerCostUsd: usage.costUsd,\n reasoningTokens: usage.reasoningTokens, toolTokens: 0,\n toolCallCount: toolCalls, budgetEnforced: outcome.settlement.budgetEnforced } })\n }\n // A settlement check fails after the turn answered; the answer stands beside the failure.\n if (!outcome.failure || outcome.failure.code.startsWith('settlement_')) {\n // The Router turn's own answer rule, so this lane and the Router lane store the same final text.\n const finalText = outcome.answer\n if (finalText) await emit({ type: 'message.part.updated', data: { part: { id: 'text_delta', type: 'text' }, delta: finalText } })\n await emit({ type: 'result', data: { finalText } })\n }\n // The code goes with the message, so a refusal reads its class sentence and a runtime failure is withheld.\n if (outcome.failure) throw Object.assign(new Error(outcome.failure.message), { code: outcome.failure.code })\n await channelWriter.close()\n }).catch(error => channelWriter.abort(error))\n for (;;) {\n const next = await reader.read()\n if (next.done) break\n yield next.value\n }\n } finally {\n await close()\n }\n }\n\n const producer = createSandboxChatProducer({ events: events(), model: profile.model?.default, errorNotice: true })\n const stream = producer.stream\n // Even return/throw before the first pull must abort and drain local work.\n const end = stream.return.bind(stream)\n const fail = stream.throw.bind(stream)\n stream.return = async value => {\n const stopped = close(new Error('The chat route stopped reading this turn'))\n void stopped.catch(() => undefined)\n try { return await end(value) } finally { await stopped }\n }\n stream.throw = async error => {\n const stopped = close(error)\n void stopped.catch(() => undefined)\n try { return await fail(error) } finally { await stopped }\n }\n return {\n ...producer,\n stream,\n terminalObserved: () => terminalObserved,\n get model() { return model ?? profile.model?.default },\n usage: () => ({ ...usage }),\n }\n}\n","/**\n * Detached (autonomous) turn → live buffer bridge.\n *\n * The interactive lane (`createChatTurnRoutes`) already streams a user-typed\n * turn to the browser while it runs. An AUTONOMOUS turn — a mission step, a\n * queue job, an inbound-email review — runs detached (`dispatchPrompt`/\n * `streamPrompt` server-side so it survives no one watching) and, historically,\n * only persisted its FINAL message. A browser opening the session mid-run saw a\n * dead screen: the live tokens existed server-side but were never written to\n * the turn-event buffer the client re-attach path (`listRunning` + `/replay`)\n * reads.\n *\n * `runDetachedTurn` is that missing bridge, packaged. It taps the same buffer\n * the interactive lane uses (`createBufferedTurnTap`) with the same producer\n * mapping (`createSandboxChatProducer`), so an autonomous run is watchable\n * token-by-token exactly like an interactive one — while staying durable\n * (a durable driver re-invokes it after a crash; a turn that finished\n * server-side short-circuits instead of re-streaming). Products supply only the\n * domain seams: the raw sandbox event stream, the turn store, and the ids.\n *\n * This is app-shell mechanism (turn durability + live projection), not engine:\n * it owns no loop logic and imports no SDK — the event source is an injected\n * `AsyncIterable`.\n */\n\nimport { toChatMessageParts } from '../chat-store/parts'\nimport type { ModelFailoverAttempt } from '../model-resolution/failover'\nimport {\n coalesceDeltas,\n createBufferedTurnTap,\n type TurnEventStore,\n} from '../stream/index'\nimport {\n assistantRowIdForTurn,\n createAssistantDraftWriter,\n storeSupportsDraftPersistence,\n type AssistantDraftStore,\n type AssistantDraftWriter,\n type AssistantRowValues,\n type DraftStoredMessage,\n type DraftPersistenceTuning,\n} from './draft-persistence'\nimport {\n createSandboxChatProducer,\n type SandboxChatProducerOptions,\n} from './sandbox-producer'\nimport type { ChatTurnUsage } from './turn-routes'\nimport { measuredUsage, TURN_USAGE_KEYS } from './sandbox-turn-usage'\nimport { transformVisibleTextParts } from './visible-text'\n\n/** The normalized structured message body (tool-call / file / plan / interaction\n * parts) that `/chat-store` persists as the durable assistant row — the same\n * shape `createSandboxChatProducer().assistantParts()` returns. */\nexport type DetachedTurnParts = Array<Record<string, unknown>>\n\n/** Authoritative final receipt for a turn that finished server-side, or whose\n * live stream carried no usage (some harness paths only expose tokens via the\n * completed-turn record, e.g. `box.findCompletedTurn(turnId)`). */\nexport interface DetachedTurnFinal {\n text?: string\n usage?: ChatTurnUsage\n /** The structured parts to persist when this receipt is more complete than\n * the live stream (cached, finished server-side, or a fast stream that\n * delivered scalar text before its message-part events). Omitted when the\n * record only carries a usage receipt. */\n parts?: DetachedTurnParts\n}\n\n/** Define options for managing and projecting a detached turn event stream in a session */\nexport interface DetachedTurnOptions {\n store: TurnEventStore\n turnId: string\n /** Thread/session id — recorded as the buffer scope so a browser opening the\n * session mid-run rediscovers this turn via `listRunning(scopeId)` after it\n * has lost the turnId. */\n scopeId: string\n /** The raw sandbox event stream for this turn (e.g. `streamSandboxPrompt`).\n * Ownership of the box, prompt, tooling, and attachments stays with the\n * caller — this only projects the stream.\n *\n * An already-open stream is bound to one model and cannot fail over. Prefer\n * {@link openEvents}; exactly one of the two is required. */\n events?: AsyncIterable<unknown>\n /** Open the raw sandbox stream FOR A GIVEN MODEL — the failover-capable form\n * of {@link events}. Wiring it turns failover on with no further flag\n * whenever {@link fallbackModels} is non-empty. Requires {@link model}.\n *\n * An autonomous run is the case that most needs this: nobody is watching to\n * notice a dead upstream and retry by hand, so without failover the mission\n * step or queue job simply fails. Forwarded to the producer. */\n openEvents?: SandboxChatProducerOptions['openEvents']\n /** Models to try, in order, when `model`'s upstream is dead. Product config —\n * see the producer's note on why a same-family fallback is not automatically\n * safe and why every fallback is surfaced. */\n fallbackModels?: SandboxChatProducerOptions['fallbackModels']\n /** Opt out of failover while still using {@link openEvents}. */\n modelFailover?: false\n /** Maximum time to open/start one model event source through its first event.\n * Forwarded to the producer; default 120 seconds. */\n openTimeoutMs?: SandboxChatProducerOptions['openTimeoutMs']\n /** Hard deadline after the source's first lifecycle event for the first\n * answer-bearing event. Forwarded to the producer; default 60 seconds when\n * the chain has a model to fail over to, none for a one-model chain. */\n firstResponseTimeoutMs?: SandboxChatProducerOptions['firstResponseTimeoutMs']\n /** Fired when a model is abandoned mid-chain (telemetry/alerting). */\n onModelFallback?: SandboxChatProducerOptions['onModelFallback']\n /** The PREFERRED model. Recorded on the persisted assistant message + usage\n * receipt — unless failover moved the turn, in which case the model that\n * actually served is recorded instead and surfaced on the result. */\n model?: string\n /** Per-flush buffer coalescer. Default `coalesceDeltas`. */\n coalesce?: (events: unknown[]) => unknown[]\n /** Which ask kinds the product renders a card for; anything else is\n * auto-declined via {@link declineInteraction}. Forwarded to the producer. */\n isRenderableInteraction?: SandboxChatProducerOptions['isRenderableInteraction']\n /** Resolve a non-renderable ask so the run never hangs in the broker. An\n * autonomous turn has NO human watching to answer an ask, so a caller that\n * omits this risks the run blocking until the broker times out — wire it for\n * any unattended run. Forwarded to the producer. */\n declineInteraction?: SandboxChatProducerOptions['declineInteraction']\n /** Opt-in eager promotion of harness-emitted `file` parts. Forwarded to the\n * producer (see its docs). */\n promoteFilePart?: SandboxChatProducerOptions['promoteFilePart']\n /** What the person reads for a failure whose reason is withheld. Forwarded to the producer. */\n failedTurnText?: SandboxChatProducerOptions['failedTurnText']\n /** Authoritative final receipt, consulted whenever a re-invoke finds a prior\n * buffer: (a) an already-`complete` turn returns it as the cached result,\n * (b) a `running` turn (crash mid-run) uses it to detect a run that finished\n * server-side, and (c) a clean run whose stream carried no usage or only\n * scalar text falls back to it. For Sandbox runs, use\n * `readCompletedSandboxTurn` so the exact completed session message\n * restores tool/file parts as well as text. */\n completedResult?: () => Promise<DetachedTurnFinal | null | undefined>\n /** Own the durable assistant row for this turn instead of returning the body\n * for the caller to insert — and keep it in step with the stream.\n *\n * An autonomous run is exactly the case a late viewer hits: nobody is\n * watching when it starts, so by the time a browser opens the session the\n * streaming gateway's hot event buffer may already have expired it. Keeping\n * that buffer short is what makes it affordable at scale (its Redis\n * footprint is linear in `ttl x concurrent sessions`), so the durable row —\n * written incrementally here — is what serves the late viewer.\n *\n * WIRING THIS TRANSFERS ROW OWNERSHIP: the returned {@link\n * DetachedTurnResult.messageId} names the row this call wrote (draft rows\n * during the stream, authoritative values at the end, retraction when the\n * turn produced nothing). The caller must NOT insert its own assistant row\n * for the turn. Omit the seam and nothing changes — the result is returned\n * and the caller persists it exactly as today.\n *\n * Idempotency reuses the turn's own identity: the row id defaults to\n * `assistant:<turnId>`, so a durable driver re-invoking after a crash\n * patches the same row instead of duplicating parts. */\n persist?: DraftPersistenceTuning & {\n store: AssistantDraftStore\n threadId: string\n /** Deterministic row id. Default `assistant:<turnId>`. */\n messageId?: string\n /** Pre-persist text transform (`/redact`), applied to drafts AND the final\n * write — parity with the interactive lane's `transformFinalText`. */\n transformText?: (text: string) => string | Promise<string>\n }\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Describe the result of a detached turn including state, text, parts, usage, and optional error or cache flag */\nexport interface DetachedTurnResult {\n /** `completed` — clean drain: persist + bill. `failed` — a terminal error\n * event, including the producer's structured `sandbox.stream_failed` event\n * when the raw sandbox stream throws: skip billing, render an error row. */\n state: 'completed' | 'failed'\n text: string\n /** The structured assistant body to persist (tool calls, file/plan/interaction\n * parts). Empty array when the run produced none. */\n parts: DetachedTurnParts\n usage: ChatTurnUsage\n /** Present when `state === 'failed'`. */\n error?: string\n /** True when a prior buffer meant this call returned a cached/finished result\n * WITHOUT re-streaming (durable-driver retry after a crash). */\n cached: boolean\n /** The durable assistant row this call wrote, when `persist` was wired.\n * `null` when the turn produced nothing and the row was retracted. Absent\n * when the caller owns persistence (today's behavior). */\n messageId?: string | null\n /** The model that SERVED the turn — the fallback's id when failover moved it.\n * A caller that bills or scores per model must read this, not the model it\n * requested. */\n model?: string\n /** The caller's explicit model request, before shell failover. */\n requestedModel?: string\n /** The effective model echoed by the downstream sandbox. */\n servedModel?: string\n /** The effective provider echoed by the downstream sandbox. */\n servedProvider?: string\n /** How the downstream sandbox selected the effective model. */\n servedSource?: 'request' | 'environment' | 'profile'\n /** True when the preferred model did not serve. Makes an autonomous\n * downgrade — which no human watched happen — attributable after the fact. */\n usedModelFallback?: boolean\n /** Every model tried, in order. Each attempt's raw `reason` is server-only; never render or send it to a client. */\n modelAttempts?: ModelFailoverAttempt[]\n}\n\n/** Terminal failure event types a producer may forward verbatim. */\nconst TERMINAL_ERROR_TYPES = new Set(['error', 'session.run.failed'])\n\nfunction errorMessageOf(ev: unknown): string {\n const rec = ev as { data?: { message?: unknown; reason?: unknown }; message?: unknown } | null\n const raw = rec?.data?.message ?? rec?.data?.reason ?? rec?.message\n return typeof raw === 'string' && raw ? raw : 'run failed'\n}\n\nfunction hasUsage(usage: ChatTurnUsage): boolean {\n return typeof usage.inputTokens === 'number' && usage.inputTokens > 0\n}\n\nfunction cachedResultFrom(\n final: DetachedTurnFinal | null,\n persisted?: DraftStoredMessage,\n): DetachedTurnResult {\n if (!final && !persisted) {\n throw new Error('Completed turn has no retained result or assistant row; retry exact recovery')\n }\n // A text-only recovery must not erase usage already stored for this turn.\n // Unknown values stay absent; an explicit measured zero is preserved.\n const usage: ChatTurnUsage = {}\n for (const key of TURN_USAGE_KEYS) {\n const value = final?.usage?.[key] ?? persisted?.[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) usage[key] = value\n }\n return {\n state: 'completed',\n text: final?.text ?? persisted?.content ?? '',\n parts:\n final?.parts ??\n (persisted?.parts as DetachedTurnParts | null | undefined) ??\n [],\n usage,\n cached: true,\n }\n}\n\n/**\n * Stream a detached turn into the live turn-event buffer, durably.\n *\n * - Idempotent: an already-`complete` turn returns the cached result without\n * re-streaming (a second event sequence would collide with the buffered one).\n * - Crash-safe: a `running` turn (a prior attempt crashed mid-tap) consults\n * `completedResult` to detect a run that finished server-side; only a run that\n * genuinely did not complete is re-streamed, and then over a buffer the\n * store's `resetEvents` cleared so seqs don't corrupt. A store without\n * `resetEvents` refuses that re-stream and leaves the existing buffer intact.\n * - Marks the turn `running` under `scopeId` so a mid-run browser finds it.\n * - Settles `complete`/`error` so the client stops tailing and billing/render\n * can branch on `state`.\n */\nexport async function runDetachedTurn(opts: DetachedTurnOptions): Promise<DetachedTurnResult> {\n const { store, turnId, scopeId } = opts\n\n // Hoisted so the draft writer's snapshot can read the producer's live\n // accumulators; assigned once the idempotency branches decide to re-stream.\n let producer: ReturnType<typeof createSandboxChatProducer> | undefined\n\n /** The model that actually served. Read LAZILY (never captured up front): on\n * a cached/finished-server-side path no producer exists and the preferred\n * model is the best available answer, but on a live re-stream failover may\n * have moved the turn after the row was first drafted. */\n const servingModel = (): string | undefined => producer?.model ?? opts.model\n\n const persistedRow = async (): Promise<DraftStoredMessage | undefined> => {\n if (!opts.persist) return undefined\n return (await opts.persist.store.listMessages(opts.persist.threadId)).find(\n (message) =>\n message.id ===\n (opts.persist?.messageId ?? assistantRowIdForTurn(turnId)),\n )\n }\n\n // Durable row ownership (opt-in). Built before the idempotency branches so a\n // cached/finished-server-side re-invoke still converges the row instead of\n // leaving whatever partial state a crashed attempt wrote.\n let draft: AssistantDraftWriter | undefined\n if (opts.persist) {\n const { store: persistStore, threadId, messageId, transformText, ...tuning } = opts.persist\n if (!storeSupportsDraftPersistence(persistStore)) {\n throw new Error(\n 'runDetachedTurn persist requires a store with updateMessage() — `/chat-store`\\'s createChatStore has it',\n )\n }\n draft = createAssistantDraftWriter({\n ...tuning,\n store: persistStore,\n threadId,\n messageId: messageId ?? assistantRowIdForTurn(turnId),\n snapshot: () => (producer\n ? {\n content: producer.finalText?.() ?? '',\n ...(producer.draftParts ? { parts: producer.draftParts() } : {}),\n ...(producer.usage ? { usage: producer.usage() } : {}),\n ...(servingModel() ? { model: servingModel() } : {}),\n }\n : null),\n ...(transformText ? { transformText } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n })\n }\n\n /** Settle the durable row with authoritative values (or retract it when the\n * turn produced nothing), and stamp the id onto the result. */\n const settleRow = async (\n base: DetachedTurnResult,\n cachedPersisted?: DraftStoredMessage,\n ): Promise<DetachedTurnResult> => {\n // A cached/reconciled return has no producer to replay the sidecar echo.\n // Preserve the attribution already written by the prior attempt instead\n // of replacing its served `model` with today's requested-model fallback.\n const persisted =\n cachedPersisted ?? (!producer ? await persistedRow() : undefined)\n const info = producer?.modelFailover?.()\n const attribution = producer?.modelAttribution?.()\n const model = producer?.model ?? persisted?.model ?? opts.model\n const requestedModel = attribution?.requestedModel ?? persisted?.requestedModel ?? opts.model\n const servedModel = attribution?.servedModel ?? persisted?.servedModel\n const servedProvider = attribution?.servedProvider ?? persisted?.servedProvider\n const servedSource = attribution?.servedSource ?? (\n persisted?.servedSource === 'request' ||\n persisted?.servedSource === 'environment' ||\n persisted?.servedSource === 'profile'\n ? persisted.servedSource\n : undefined\n )\n const result: DetachedTurnResult = {\n ...base,\n ...(model ? { model } : {}),\n ...(requestedModel ? { requestedModel } : {}),\n ...(servedModel ? { servedModel } : {}),\n ...(servedProvider ? { servedProvider } : {}),\n ...(servedSource ? { servedSource } : {}),\n ...(info ? { usedModelFallback: info.usedFallback, modelAttempts: info.attempts } : {}),\n }\n if (!draft) return result\n const transform = opts.persist?.transformText\n const content = transform ? await transform(result.text) : result.text\n const rawParts = transform ? await transformVisibleTextParts(result.parts, transform) : result.parts\n const parts = toChatMessageParts(rawParts)\n if (!content.trim() && parts.length === 0) {\n await draft.discard()\n return { ...result, messageId: null }\n }\n const values: AssistantRowValues = {\n content,\n ...(parts.length > 0 ? { parts } : {}),\n ...(result.model ? { model: result.model } : {}),\n ...(result.requestedModel ? { requestedModel: result.requestedModel } : {}),\n ...(result.servedModel ? { servedModel: result.servedModel } : {}),\n ...(result.servedProvider ? { servedProvider: result.servedProvider } : {}),\n ...(result.servedSource ? { servedSource: result.servedSource } : {}),\n ...measuredUsage(result.usage),\n }\n await draft.finalize(values)\n return { ...result, messageId: draft.rowId() ?? null }\n }\n\n const completed = async (): Promise<DetachedTurnFinal | null> => {\n if (!opts.completedResult) return null\n // An unavailable authoritative read must not become a fresh stream.\n return (await opts.completedResult()) ?? null\n }\n\n const prior = await store.getStatus(turnId)\n\n if (prior === 'complete') {\n const persisted = await persistedRow()\n return await settleRow(\n cachedResultFrom(await completed(), persisted),\n persisted,\n )\n }\n\n if (prior === 'running') {\n // A prior attempt marked the turn running and then this worker crashed. The\n // detached SESSION may have finished server-side while we were gone — the\n // authoritative check is `completedResult` (findCompletedTurn). If it\n // completed, settle the stuck `running` buffer and return it.\n const final = await completed()\n if (final) {\n await store.setStatus(turnId, 'complete', scopeId)\n const persisted = await persistedRow()\n return await settleRow(cachedResultFrom(final, persisted), persisted)\n }\n // Genuine re-run: clear the partial buffer first, or the fresh tap's seq\n // (restarting at 0) interleaves with the orphaned rows.\n if (!store.resetEvents) {\n throw new Error('Detached turn recovery requires a TurnEventStore with resetEvents before replaying an existing stream')\n }\n await store.resetEvents(turnId)\n }\n\n const tap = createBufferedTurnTap({\n store,\n turnId,\n scopeId,\n coalesce: opts.coalesce ?? coalesceDeltas,\n })\n // Leading turn marker: flips the buffer to `running` (so `listRunning` finds\n // it) and is the browser's `/replay` resume handle.\n await tap.onEvent({ type: 'turn', turnId })\n\n producer = createSandboxChatProducer({\n ...(opts.openEvents ? { openEvents: opts.openEvents } : { events: opts.events }),\n model: opts.model,\n ...(opts.fallbackModels ? { fallbackModels: opts.fallbackModels } : {}),\n ...(opts.modelFailover === false ? { modelFailover: false as const } : {}),\n ...(opts.openTimeoutMs !== undefined ? { openTimeoutMs: opts.openTimeoutMs } : {}),\n ...(opts.firstResponseTimeoutMs !== undefined\n ? { firstResponseTimeoutMs: opts.firstResponseTimeoutMs }\n : {}),\n ...(opts.onModelFallback ? { onModelFallback: opts.onModelFallback } : {}),\n isRenderableInteraction: opts.isRenderableInteraction,\n declineInteraction: opts.declineInteraction,\n promoteFilePart: opts.promoteFilePart,\n failedTurnText: opts.failedTurnText,\n log: opts.log,\n })\n\n let runError: string | undefined\n try {\n for await (const ev of producer.stream) {\n const type = (ev as { type?: unknown }).type\n if (typeof type === 'string' && TERMINAL_ERROR_TYPES.has(type)) runError = errorMessageOf(ev)\n await tap.onEvent(ev)\n // Same coalesced cadence the interactive lane uses: the durable row\n // tracks the run so a viewer arriving after the hot buffer's short window\n // reads it from storage.\n draft?.notify(ev as { type?: unknown })\n }\n await tap.done(runError ? 'error' : 'complete')\n } catch (err) {\n await tap.done('error').catch(() => {})\n // Settle any in-flight draft before propagating so the partial row a\n // re-invoke will adopt is a complete write, not a half-landed one.\n await draft?.close().catch(() => {})\n throw err\n }\n\n const text = producer.finalText?.() ?? ''\n const parts = producer.assistantParts?.() ?? []\n let usage: ChatTurnUsage = producer.usage?.() ?? {}\n\n // A terminal result can supply scalar text even when the event subscriber\n // missed every structured message part. Reconcile that text-only shape with\n // the durable completion record before final persistence.\n const onlyTextParts = parts.every((part) =>\n String((part as { type?: unknown }).type ?? '') === 'text',\n )\n if (!runError && (!hasUsage(usage) || !text || onlyTextParts)) {\n const final = await completed()\n if (final?.usage) usage = { ...usage, ...final.usage }\n return await settleRow({\n state: 'completed',\n text: final?.text ?? text,\n parts: final?.parts?.length ? final.parts : parts,\n usage,\n cached: false,\n })\n }\n\n if (runError) return await settleRow({ state: 'failed', text, parts, usage, error: runError, cached: false })\n return await settleRow({ state: 'completed', text, parts, usage, cached: false })\n}\n","/**\n * The chat turn that attaches to a decided plan's follow-up execution.\n *\n * Deciding a plan does not run anything in the product. The Sandbox platform\n * enqueues the approved (or revision) execution itself under the turn id\n * `planFollowUpTurnId(planId, revision, outcome)`, and the Sidecar names that\n * execution `plan-followup-<sha256(sessionId \\0 turnId)>`. The browser card then\n * re-enters the chat route with a `planFollowUp` descriptor. That attach is a\n * real turn: it streams, persists an assistant row, and bills. It therefore\n * needs the same single-runner protection as a fresh turn.\n *\n * This module owns that attach: the descriptor check against the persisted\n * plan, the execution identity, the exclusive D1 claim on the `turn_status`\n * row, and the replay-then-follow event stream. Products keep their own\n * authorization, billing, and persistence around it.\n */\nimport { createHash, randomUUID } from 'node:crypto'\nimport type { SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport { persistedPartToPlan, planFollowUpTurnId } from '../plans'\n\n/** The decision a follow-up continues. */\nexport type PlanFollowUpOutcome = 'approved' | 'rejected'\n\n/** The descriptor a decided plan card sends back to the chat route. */\nexport interface PlanFollowUpAttach {\n planId: string\n revision: number\n outcome: PlanFollowUpOutcome\n turnId: string\n}\n\n/** Result of checking a follow-up descriptor against the session's persisted plans. */\nexport type PlanFollowUpResolution =\n | { ok: true; attach: PlanFollowUpAttach; executionId: string }\n | { ok: false; status: 400 | 409; code: string; error: string }\n\n/** Result of one exclusive follow-up claim. */\nexport type PlanFollowUpAdmission =\n | { admitted: true; lease: string }\n | { admitted: false; reason: 'in_flight' | 'completed' }\n\n/** Result of settling a claim. `lease_lost` means a stale reclaim superseded it. */\nexport type PlanFollowUpSettlement =\n | { settled: true }\n | { settled: false; reason: 'lease_lost' }\n\n/** A bound D1 statement used by the follow-up gate. */\nexport interface D1BoundForPlanFollowUps {\n run(): Promise<unknown>\n}\n\n/**\n * Structural D1 contract for the follow-up gate. `batch` is required: it is\n * D1's atomic boundary, and the gate confirms ownership from the row read in\n * the same batch instead of from a driver-specific affected-row count.\n */\nexport interface D1LikeForPlanFollowUps {\n prepare(sql: string): { bind(...values: unknown[]): D1BoundForPlanFollowUps }\n batch(statements: D1BoundForPlanFollowUps[]): Promise<unknown[]>\n}\n\n/** Configure the follow-up gate. Clock and lease are injectable for tests. */\nexport interface PlanFollowUpGateOptions {\n now?: () => Date\n createLease?: () => string\n /** How long a `running` claim may sit before another isolate may reclaim it. Default one hour. */\n staleAfterMs?: number\n}\n\n/** Exclusive claim over one follow-up execution's `turn_status` row. */\nexport interface PlanFollowUpGate {\n admit(executionId: string, scopeId: string): Promise<PlanFollowUpAdmission>\n /** Record a completed attach. Only the current lease may settle. */\n settle(executionId: string, scopeId: string, lease: string): Promise<PlanFollowUpSettlement>\n /** Record a failed attach so a retry is admitted immediately. */\n abandon(executionId: string, scopeId: string, lease: string): Promise<PlanFollowUpSettlement>\n}\n\nconst PLAN_FOLLOW_UP_STALE_AFTER_MS = 60 * 60 * 1000\nconst PLAN_FOLLOW_UP_ATTACH_TIMEOUT_MS = 120_000\nconst TERMINAL_SESSION_EVENT_TYPES = new Set(['done', 'error', 'result'])\n\n/** The Sidecar's execution id for a follow-up turn. Keep it byte-identical to the Sidecar. */\nexport function planFollowUpExecutionId(sessionId: string, turnId: string): string {\n return `plan-followup-${createHash('sha256').update(`${sessionId}\\0${turnId}`).digest('hex')}`\n}\n\n/** Parse a follow-up descriptor. The turn id is derived, never trusted. */\nexport function parsePlanFollowUpAttach(value: unknown): PlanFollowUpAttach | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return null\n const record = value as Record<string, unknown>\n const planId = typeof record.planId === 'string' ? record.planId.trim() : ''\n const turnId = typeof record.turnId === 'string' ? record.turnId.trim() : ''\n const revision = record.revision\n const outcome = record.outcome\n if (!planId || !turnId || (outcome !== 'approved' && outcome !== 'rejected')) return null\n if (typeof revision !== 'number' || !Number.isInteger(revision) || revision < 1) return null\n if (turnId !== planFollowUpTurnId(planId, revision, outcome)) return null\n return { planId, revision, outcome, turnId }\n}\n\n/**\n * Validate a follow-up request against what the session actually persisted:\n * the plan must be in this session at this revision and must already carry the\n * claimed decision.\n */\nexport function resolvePlanFollowUpRequest(input: {\n sessionId: string\n planFollowUp: unknown\n messages: ReadonlyArray<{ role: string; parts?: unknown }>\n}): PlanFollowUpResolution {\n const attach = parsePlanFollowUpAttach(input.planFollowUp)\n if (!attach) {\n return { ok: false, status: 400, code: 'invalid_plan_follow_up', error: 'Invalid planFollowUp descriptor' }\n }\n const plan = input.messages\n .filter((message) => message.role === 'assistant' && Array.isArray(message.parts))\n .flatMap((message) => message.parts as unknown[])\n .map((part) => (part && typeof part === 'object' && !Array.isArray(part)\n ? persistedPartToPlan(part as Record<string, unknown>)\n : null))\n .find((candidate) => candidate?.planId === attach.planId && candidate.revision === attach.revision)\n if (!plan) {\n return {\n ok: false,\n status: 409,\n code: 'plan_follow_up_missing',\n error: `Plan ${attach.planId} revision ${attach.revision} is not in this session`,\n }\n }\n if (plan.status !== attach.outcome) {\n return {\n ok: false,\n status: 409,\n code: 'plan_follow_up_not_decided',\n error: `Plan ${attach.planId} is ${plan.status}, not ${attach.outcome}`,\n }\n }\n return { ok: true, attach, executionId: planFollowUpExecutionId(input.sessionId, attach.turnId) }\n}\n\n/**\n * Session events carry two payload shapes: replayed events hold the stream\n * event under `data`, while live events nest it under `data.properties`.\n * Downstream reads `data.<field>`, so a live event is unwrapped. A replayed\n * payload that still carries its own `type` drops it, so `data` holds only the\n * event's fields.\n */\nexport function unwrapSessionEventPayload(event: SandboxEvent): SandboxEvent {\n const data = event.data && typeof event.data === 'object' && !Array.isArray(event.data)\n ? event.data as Record<string, unknown>\n : undefined\n if (!data) return event\n const properties = data.properties && typeof data.properties === 'object' && !Array.isArray(data.properties)\n ? data.properties as Record<string, unknown>\n : undefined\n if (properties) return { ...event, data: properties } as SandboxEvent\n if (typeof data.type === 'string') {\n const { type: _type, ...rest } = data\n return { ...event, data: rest } as SandboxEvent\n }\n return event\n}\n\n/**\n * Attach to the already-enqueued follow-up execution: replay its buffered\n * events from the start, then follow it live to completion. It never sends a\n * new prompt. The session-events iterator has no reconnect, so a stream that\n * ends without a terminal event fails instead of persisting a partial turn.\n */\nexport async function* streamPlanFollowUpEvents(\n box: SandboxInstance,\n sessionId: string,\n executionId: string,\n options: { timeoutMs?: number } = {},\n): AsyncGenerator<SandboxEvent> {\n const timeoutMs = options.timeoutMs ?? PLAN_FOLLOW_UP_ATTACH_TIMEOUT_MS\n const abort = new AbortController()\n const iterator = box.session(sessionId).events({\n executionId,\n since: '0',\n signal: abort.signal,\n })[Symbol.asyncIterator]()\n let timeout: ReturnType<typeof setTimeout> | undefined\n let sawTerminalEvent = false\n const track = (event: SandboxEvent): SandboxEvent => {\n if (TERMINAL_SESSION_EVENT_TYPES.has(String(event.type ?? ''))) sawTerminalEvent = true\n return unwrapSessionEventPayload(event)\n }\n try {\n const first = await Promise.race([\n iterator.next(),\n new Promise<never>((_, reject) => {\n timeout = setTimeout(\n () => reject(new Error(`Plan follow-up ${executionId} did not start within ${Math.round(timeoutMs / 1000)} seconds`)),\n timeoutMs,\n )\n }),\n ])\n if (timeout) clearTimeout(timeout)\n if (first.done) throw new Error(`Plan follow-up ${executionId} ended before emitting an event`)\n yield track(first.value)\n while (true) {\n const next = await iterator.next()\n if (next.done) {\n if (!sawTerminalEvent) {\n throw new Error(`Plan follow-up ${executionId} stream ended without a terminal event`)\n }\n return\n }\n yield track(next.value)\n }\n } finally {\n if (timeout) clearTimeout(timeout)\n abort.abort()\n await iterator.return?.(undefined)\n }\n}\n\ninterface PlanFollowUpStatusRow {\n status: string\n leaseToken: string | null\n}\n\n/**\n * Exclusive claim over a follow-up execution in the shared `turn_status`\n * table. Every claim writes a random lease and confirms ownership from the\n * row returned by the same D1 batch. A running claim older than\n * `staleAfterMs` may be reclaimed; the superseded holder then settles into\n * `lease_lost` instead of overwriting the newer claim. Apply\n * `TURN_STATUS_LEASE_MIGRATION_SQL` (from `/stream`) once after the turn\n * tables: it adds the `leaseToken` column the claim writes.\n */\nexport function createD1PlanFollowUpGate(\n db: D1LikeForPlanFollowUps,\n options: PlanFollowUpGateOptions = {},\n): PlanFollowUpGate {\n const now = options.now ?? (() => new Date())\n const createLease = options.createLease ?? randomUUID\n const staleAfterMs = options.staleAfterMs ?? PLAN_FOLLOW_UP_STALE_AFTER_MS\n const readStatus = (executionId: string) => db.prepare(`\n SELECT status, leaseToken\n FROM turn_status\n WHERE turnId = ?\n LIMIT 1\n `).bind(executionId)\n\n async function readAfterBatch(\n write: D1BoundForPlanFollowUps,\n executionId: string,\n operation: string,\n ): Promise<PlanFollowUpStatusRow> {\n const results = await db.batch([write, readStatus(executionId)])\n const rows = (results[1] as { results?: unknown[] } | undefined)?.results\n const row = rows?.[0] as Partial<PlanFollowUpStatusRow> | undefined\n if (!row || typeof row.status !== 'string') {\n throw new Error(`Plan follow-up ${executionId} has no status after ${operation}`)\n }\n if (row.leaseToken !== null && row.leaseToken !== undefined && typeof row.leaseToken !== 'string') {\n throw new Error(`Plan follow-up ${executionId} has an invalid lease after ${operation}`)\n }\n return { status: row.status, leaseToken: row.leaseToken ?? null }\n }\n\n async function settle(\n executionId: string,\n scopeId: string,\n lease: string,\n status: 'complete' | 'error',\n ): Promise<PlanFollowUpSettlement> {\n const row = await readAfterBatch(\n db.prepare(`\n UPDATE turn_status\n SET status = ?, scopeId = ?, updatedAt = ?\n WHERE turnId = ? AND status = 'running' AND leaseToken = ?\n `).bind(status, scopeId, now().toISOString(), executionId, lease),\n executionId,\n `settling ${status}`,\n )\n if (row.leaseToken !== lease) return { settled: false, reason: 'lease_lost' }\n if (row.status !== status) {\n throw new Error(`Plan follow-up ${executionId} remained ${row.status} while settling ${status}`)\n }\n return { settled: true }\n }\n\n return {\n async admit(executionId, scopeId) {\n const claimedAt = now()\n const lease = createLease()\n const staleBefore = new Date(claimedAt.getTime() - staleAfterMs).toISOString()\n const row = await readAfterBatch(\n db.prepare(`\n INSERT INTO turn_status (turnId, status, scopeId, updatedAt, leaseToken)\n VALUES (?, 'running', ?, ?, ?)\n ON CONFLICT(turnId) DO UPDATE SET\n status = 'running',\n scopeId = excluded.scopeId,\n updatedAt = excluded.updatedAt,\n leaseToken = excluded.leaseToken\n WHERE turn_status.status = 'error'\n OR (turn_status.status = 'running' AND turn_status.updatedAt < ?)\n `).bind(executionId, scopeId, claimedAt.toISOString(), lease, staleBefore),\n executionId,\n 'admission',\n )\n if (row.status === 'running' && row.leaseToken === lease) return { admitted: true, lease }\n if (row.status === 'running') return { admitted: false, reason: 'in_flight' }\n if (row.status === 'complete') return { admitted: false, reason: 'completed' }\n throw new Error(`Plan follow-up ${executionId} has unexpected admission status: ${row.status}`)\n },\n settle: (executionId, scopeId, lease) => settle(executionId, scopeId, lease, 'complete'),\n abandon: (executionId, scopeId, lease) => settle(executionId, scopeId, lease, 'error'),\n }\n}\n","import { getPartKey, mergePersistedPart, type StreamEvent } from '../stream/index'\nimport type { ChatTurnRouteProducer } from './turn-routes'\n\n/** Resolve chat route events and materialize their durable state records */\nexport interface ChatRouteDurableProjection {\n observe(event: unknown): void | Promise<void>\n materialize(): Array<Record<string, unknown>> | Promise<Array<Record<string, unknown>>>\n}\n\n/** Log chat route projection messages with optional metadata for durable processing */\nexport type ChatRouteDurableProjectionLogger =\n (message: string, meta?: Record<string, unknown>) => void\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Adds durable lifecycle projection to any producer lane without moving its\n * transport into agent-app. Purely STRUCTURAL: agent-app ships no implementer\n * of {@link ChatRouteDurableProjection} and deliberately does not — the one it\n * used to ship (`/durable-chat`) was removed in 0.44.0 with zero fleet imports.\n * Pass any `{ observe, materialize }` object backed by your own store. The projection is observed inline and its\n * materialized parts replace same-key pending snapshots after the stream\n * drains. Projection persistence is best-effort for the live lane: a store\n * outage must not terminate an otherwise healthy sandbox stream. Failures are\n * reported through the optional logger so products can retain diagnostics. */\nexport function withDurableChatProjection(\n producer: ChatTurnRouteProducer,\n projection: ChatRouteDurableProjection,\n log: ChatRouteDurableProjectionLogger = (message, meta) => console.error(message, meta ?? ''),\n): ChatTurnRouteProducer {\n let projected: Array<Record<string, unknown>> = []\n async function* stream(): AsyncGenerator<StreamEvent, void, unknown> {\n for await (const event of producer.stream) {\n try {\n await projection.observe(event)\n } catch (error) {\n log('[chat-routes] durable projection observe failed', {\n eventType: event.type,\n error: errorMessage(error),\n })\n }\n yield event\n }\n try {\n projected = await projection.materialize()\n } catch (error) {\n log('[chat-routes] durable projection materialize failed', {\n error: errorMessage(error),\n })\n }\n }\n return {\n ...producer,\n stream: stream(),\n assistantParts: () => {\n const parts = producer.assistantParts?.() ?? []\n const order: string[] = []\n const byKey = new Map<string, Record<string, unknown>>()\n for (const part of [...parts, ...projected]) {\n const key = getPartKey(part)\n if (!byKey.has(key)) order.push(key)\n byKey.set(key, mergePersistedPart(byKey.get(key), part))\n }\n return order.map((key) => byKey.get(key)!)\n },\n }\n}\n","/**\n * Storage seams for the chat-attachment vertical (`resolveChatAttachments`,\n * `buildDispatchParts`, `promoteAgentFilePart`). Structural function ports in\n * the same style as `upload.ts`'s `SandboxUploadSink`: REQUIRED injection, no\n * default implementation — agent-app owns the size/budget/idempotency\n * mechanism, the product owns where the bytes actually live.\n *\n * One reader serves validation, materialization, and dispatch:\n * `resolveChatAttachments` reads only the\n * authoritative `size` (never trusting the client-reported size), while\n * `buildDispatchParts` reads the inline `content` (base64 or raw bytes) to\n * build a `data:` URI. `prepareDispatchAttachments` copies raw bytes when a\n * product opts in. All share `ReadAttachmentFn` so a product\n * wires a single vault/object-store adapter, not two. gtm's KV vault (stores\n * base64 bodies) and `/object-store`'s `ObjectStore` (hands back raw bytes)\n * both satisfy this shape.\n */\n\nimport type { ChatAttachmentPart } from '../chat-store/parts'\nimport { DISPATCH_MAX_MEDIA_PARTS } from './wire'\n\n/**\n * The result of reading one stored attachment. `ok:true` MUST carry the\n * authoritative decoded byte `size` (the cap is meaningless against a\n * client-controlled number) and, when the caller needs to inline the file,\n * its content as `base64` and/or raw `bytes`. `mediaType` is the stored\n * content type when the store knows it (used as the fallback when the wire\n * part carried none). `ok:false` carries a human `reason` that SHOULD name the\n * offending path — it is surfaced verbatim in the caller's typed outcome.\n */\nexport type AttachmentReadResult =\n | {\n ok: true\n /** Authoritative decoded byte length of the stored content. */\n size: number\n /** Inline content as base64 — reused verbatim for a `data:` URI, so a\n * store holding already-base64 bodies never decodes-and-re-encodes. */\n base64?: string\n /** Inline content as raw bytes — base64-encoded by the caller when a\n * `data:` URI is needed. Ignored when `base64` is present. */\n bytes?: Uint8Array\n /** Stored content type, when the store tracks one. */\n mediaType?: string\n }\n | { ok: false; reason: string }\n\n/**\n * Read one stored attachment for `scopeId` (the product's workspace/tenant\n * key) at its store-relative `path`. Missing, deleted, or unreadable content\n * MUST resolve to `{ ok: false, reason }`, never throw — a store failure is a\n * per-attachment outcome the caller folds into its own typed result, not a\n * turn-level exception.\n */\nexport type ReadAttachmentFn = (scopeId: string, path: string) => Promise<AttachmentReadResult>\n\n/** Opt-in copy from the product attachment store to its already-authorized box.\n * Uploads are sequential and their returned byte counts must match the store.\n * The product retains its missing-content sentence and the surrounding trace span. */\nexport interface AttachmentMaterialization {\n upload: (absolutePath: string, bytes: Uint8Array) => Promise<{ size: number }>\n missingBytesMessage: (path: string) => string\n /** The byte sizes of those box files that exist, read in one round trip.\n * Attachment paths are immutable, so a box file whose size equals the\n * part's stored size is already delivered and is neither read nor uploaded\n * again; a missing or different file is copied. Absent: every file is copied. */\n present?: (absolutePaths: readonly string[]) => Promise<ReadonlyMap<string, number>>\n}\n\n/** Prepare carried files before a product constructs its prompt and dispatch input. */\nexport interface PrepareDispatchAttachmentsInput {\n attachments: ChatAttachmentPart[]\n historyAttachments?: readonly ChatAttachmentPart[]\n mentionCount?: number\n scopeId: string\n readAttachment: ReadAttachmentFn\n resolveAttachmentPath: (path: string) => string\n materialize?: AttachmentMaterialization\n}\n\n/** Select carried files and optionally copy them before constructing a prompt.\n * Omitted history and materialization preserve the supplied attachment list.\n * `slice(-0)` intentionally retains the apps' current zero-slot behavior. */\nexport async function prepareDispatchAttachments(input: PrepareDispatchAttachmentsInput): Promise<ChatAttachmentPart[]> {\n const historyBudget = Math.max(\n 0,\n DISPATCH_MAX_MEDIA_PARTS - input.attachments.length - (input.mentionCount ?? 0),\n )\n const attachments = input.historyAttachments === undefined ? input.attachments : [\n ...input.attachments,\n ...input.historyAttachments.slice(-historyBudget),\n ]\n const materialize = input.materialize\n if (!materialize) return attachments\n const copies = attachments.map((part) => ({ part, target: input.resolveAttachmentPath(part.path) }))\n // Only files carried from earlier turns can already be on the box.\n const carried = copies.slice(input.attachments.length).map((copy) => copy.target)\n const delivered = materialize.present && carried.length > 0\n ? await materialize.present([...new Set(carried)])\n : new Map<string, number>()\n const written = new Set<string>()\n for (const { part, target } of copies) {\n if (written.has(target)) continue\n written.add(target)\n if (part.size !== undefined && delivered.get(target) === part.size) continue\n\n const read = await input.readAttachment(input.scopeId, part.path)\n if (!read.ok) throw new Error(read.reason)\n if (!read.bytes) {\n throw new Error(materialize.missingBytesMessage(part.path))\n }\n const result = await materialize.upload(target, read.bytes)\n if (result.size !== read.size) {\n throw new Error(\n `Sandbox attachment size mismatch for ${part.path}: expected ${read.size}, uploaded ${result.size}`,\n )\n }\n }\n return attachments\n}\n\n/** The ownership identity for one attempted write. The upload and promotion\n * routes create a unique path for each attempt, and the product adapter stores\n * this id with it. */\nexport interface AttachmentWriteOwnership {\n readonly id: string\n readonly path: string\n}\n\n/** Public-safe outcome for a storage outage. Backend details belong in logs. */\nexport const ATTACHMENT_STORAGE_FAILURE_MESSAGE = 'Attachment storage is temporarily unavailable. Please try again.'\n\n/** Stable client error code when compensating cleanup did not complete. */\nexport const ATTACHMENT_ROLLBACK_FAILURE_CODE = 'rollback_failed'\n\n/** Public-safe outcome when compensating cleanup did not complete. */\nexport const ATTACHMENT_ROLLBACK_FAILURE_MESSAGE = 'Attachment cleanup failed. Please try again.'\n\n/** Add a path-safe ownership id to a logical path and return an immutable store key. */\nexport function immutableAttachmentPath(logicalPath: string, ownershipId: string): string {\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(ownershipId)) {\n throw new Error('attachment ownership id must be a path-safe identifier')\n }\n return `${logicalPath}--${ownershipId}`\n}\n\n/** Compensation for one attachment write. The adapter MUST compare the stored\n * ownership id before deleting, so an older rollback cannot delete a newer\n * overwrite. */\nexport interface AttachmentWriteReceipt {\n rollback(): void | Promise<void>\n ownership: AttachmentWriteOwnership\n}\n\n/** Clean up a write whose function threw after the store may have committed.\n * The adapter must delete only the supplied ownership, never the logical path\n * unconditionally. */\nexport type AbortAttachmentWriteFn = (\n scopeId: string,\n ownership: AttachmentWriteOwnership,\n) => void | Promise<void>\n\n/**\n * The stable writer result from the original attachment-store contract.\n * Existing products may return this shape and keep using the legacy writer\n * lane. New products should use {@link AtomicAttachmentWriteResult}.\n */\nexport type AttachmentWriteResult = { ok: true } | { ok: false; reason: string }\n\n/** Options from the stable attachment-store contract. */\nexport interface AttachmentWriteOptions {\n mediaType?: string\n name?: string\n originalName?: string\n size?: number\n}\n\n/**\n * The stable writer port. It is intentionally unchanged so products released\n * before the ownership receipt contract continue to compile.\n *\n * The legacy lane does not promise batch rollback. Use\n * {@link createAtomicAttachmentWriter} for ownership-safe writes.\n */\nexport type WriteAttachmentFn = (\n scopeId: string,\n path: string,\n content: Uint8Array | string,\n opts: AttachmentWriteOptions,\n) => Promise<AttachmentWriteResult>\n\n/** Options for a streamed write. `size` is the exact byte count `content`\n * yields. `mediaType` is decided from the file name and its first bytes,\n * before the route has read the rest: an archive's central directory sits at\n * its end, so the route's response, not this value, carries the final type. */\nexport interface AttachmentStreamWriteOptions extends AttachmentWriteOptions {\n size: number\n mediaType: string\n}\n\n/**\n * Streamed writer port for an upload too large to hold in memory. `content`\n * yields exactly `opts.size` bytes. The route checks the file while it\n * streams and withholds the final bytes until the whole file has passed, so\n * on a refusal `content` errors instead of ending. The adapter must make the\n * bytes readable at `path` only when `content` ends cleanly, and must leave\n * whatever was stored at `path` before untouched when it errors. A store put\n * of a fixed-length stream (R2 `put` behind `FixedLengthStream`) does both.\n */\nexport type WriteAttachmentStreamFn = (\n scopeId: string,\n path: string,\n content: ReadableStream<Uint8Array>,\n opts: AttachmentStreamWriteOptions,\n) => Promise<AttachmentWriteResult>\n\n/** Options for an ownership-safe writer. */\nexport interface AtomicAttachmentWriteOptions extends AttachmentWriteOptions {\n ownership: AttachmentWriteOwnership\n}\n\n/** Result for an ownership-safe writer. A receipt is required on both paths. */\nexport type AtomicAttachmentWriteResult =\n | { ok: true; receipt: AttachmentWriteReceipt }\n | { ok: false; reason: string; receipt: AttachmentWriteReceipt }\n\n/** Ownership-safe writer port used by the atomic upload and promotion lanes. */\nexport type AtomicWriteAttachmentFn = (\n scopeId: string,\n path: string,\n content: Uint8Array | string,\n opts: AtomicAttachmentWriteOptions,\n) => Promise<AtomicAttachmentWriteResult>\n\n/** A complete ownership-safe attachment store adapter. */\nexport interface AtomicAttachmentWriter {\n write: AtomicWriteAttachmentFn\n abort: AbortAttachmentWriteFn\n}\n\n/**\n * Build the explicit atomic adapter used by new routes.\n *\n * Keeping the write and abort functions together prevents a caller from\n * enabling ownership paths while forgetting the ambiguous-write cleanup.\n */\nexport function createAtomicAttachmentWriter(input: AtomicAttachmentWriter): AtomicAttachmentWriter {\n return {\n write: input.write.bind(input),\n abort: input.abort.bind(input),\n }\n}\n","/**\n * `resolveChatAttachments` — validate a turn body's `attachments` field into\n * persistable {@link ChatAttachmentPart}s. Every path is re-validated (a path\n * off the wire is never trusted to stay inside the store root) and every size\n * is re-derived from the STORED body via the injected {@link ReadAttachmentFn},\n * never the client-reported `size` — the upload path lets a caller rewrite its\n * own frontmatter, so a stored size cannot bound anything and the wire size can\n * be anything. Both the aggregate cap and the size carried on the returned part\n * come from the authoritative read.\n *\n * Storage-parameterized: the frontmatter parsing / base64 sizing that derives\n * the authoritative size lives BEHIND `readAttachment` (a product's vault or\n * object-store adapter), so this module is a pure validator + budget gate with\n * no store knowledge. Lifted from gtm-agent's `resolve-attachments.ts`\n * (workspaceId → scopeId, the vault read → the injected reader) and kept\n * behavior-identical for gtm-agent#618 adoption.\n */\n\nimport { attachmentInputToPart, type ChatAttachmentPart } from '../chat-store/parts'\nimport type { ReadAttachmentFn } from './attachment-store'\nimport {\n MAX_ATTACHMENT_TOTAL_BYTES,\n attachmentTotalSizeErrorMessage,\n parseChatAttachmentInputs,\n type AttachmentPathCheck,\n} from './attachment-validation'\n\n/** Resolve the result of chat attachment processing with success status and corresponding data or error */\nexport type ResolveChatAttachmentsResult =\n | { succeeded: true; value: ChatAttachmentPart[] }\n | { succeeded: false; error: string }\n\n/** Define options to resolve and validate chat attachments with size, count, and path constraints */\nexport interface ResolveChatAttachmentsOptions {\n /** The product's workspace/tenant key, passed to `readAttachment`. */\n scopeId: string\n /** Authoritative size + content reader — see {@link ReadAttachmentFn}. */\n readAttachment: ReadAttachmentFn\n /** Most attachments one request may carry. Default {@link ATTACHMENT_MAX_COUNT}. */\n maxCount?: number\n /** Aggregate raw-byte ceiling. Default {@link MAX_ATTACHMENT_TOTAL_BYTES}. */\n maxTotalBytes?: number\n /** Path validator override. Default {@link defaultValidateAttachmentPath}. */\n validatePath?: (path: string) => AttachmentPathCheck\n}\n\n/**\n * Validate and resolve a turn body's `attachments` field into persistable\n * parts. Every path is confirmed present (and not deleted) in the caller's own\n * store by `readAttachment` before it is trusted, and size is derived from the\n * authoritative read for both the aggregate cap and the returned part's size.\n */\nexport async function resolveChatAttachments(\n value: unknown,\n options: ResolveChatAttachmentsOptions,\n): Promise<ResolveChatAttachmentsResult> {\n const maxTotalBytes = options.maxTotalBytes ?? MAX_ATTACHMENT_TOTAL_BYTES\n const parsed = parseChatAttachmentInputs(value, options)\n if (!parsed.succeeded) return parsed\n const inputs = parsed.value\n\n // Advisory only: client-controlled, so a dishonest caller can slip past it —\n // but an honest oversized request should fail before it costs a single store\n // read. The authoritative check runs per-attachment below, against the\n // body-derived size.\n const advisoryTotal = inputs.reduce((sum, input) => sum + input.size, 0)\n if (advisoryTotal > maxTotalBytes) {\n return { succeeded: false, error: attachmentTotalSizeErrorMessage(advisoryTotal, maxTotalBytes) }\n }\n\n // One attachment is read, sized, and dropped at a time rather than via\n // Promise.all — that would materialize every attachment's body in memory\n // simultaneously (ten truthful 10 MiB references is ~134 MiB of base64, over\n // a Workers heap) before the cap ever gets a chance to reject the request.\n // Sequential reads bound resident bytes to one attachment at a time and bail\n // the moment the running total exceeds the cap, at the cost of up to\n // `maxCount` serial reads instead of one parallel batch.\n let totalStoredBytes = 0\n for (const input of inputs) {\n const read = await options.readAttachment(options.scopeId, input.path)\n if (!read.ok) return { succeeded: false, error: read.reason }\n totalStoredBytes += read.size\n if (totalStoredBytes > maxTotalBytes) {\n return { succeeded: false, error: attachmentTotalSizeErrorMessage(totalStoredBytes, maxTotalBytes) }\n }\n input.size = read.size\n }\n\n return { succeeded: true, value: inputs.map(attachmentInputToPart) }\n}\n","import { redactErrorMessage } from '../redact'\nimport type {\n AtomicAttachmentWriteResult,\n AttachmentWriteOwnership,\n AttachmentWriteReceipt,\n AttachmentWriteResult,\n} from './attachment-store'\n\ntype ObjectLike = Record<PropertyKey, unknown>\n\nfunction objectLike(value: unknown): value is ObjectLike {\n return value !== null && (typeof value === 'object' || typeof value === 'function')\n}\n\n/** Read an injected writer result without allowing hostile getters to escape. */\nexport function inspectLegacyAttachmentWriteResult(\n value: unknown,\n): AttachmentWriteResult | undefined {\n try {\n if (!objectLike(value)) return undefined\n const ok = value.ok\n if (ok === true) return { ok: true }\n if (ok === false && typeof value.reason === 'string') {\n return { ok: false, reason: value.reason }\n }\n } catch {\n // A malformed or hostile adapter result is a storage failure.\n }\n return undefined\n}\n\n/**\n * Read an ownership-aware writer result with strict runtime checks.\n *\n * The public types protect TypeScript callers only. The product adapter is an\n * injection boundary, so a proxy, malformed value, or truthy non-boolean must\n * fail closed before the route invokes cleanup or publishes a path.\n */\nexport function inspectAtomicAttachmentWriteResult(\n value: unknown,\n ownership: AttachmentWriteOwnership,\n): AtomicAttachmentWriteResult | undefined {\n try {\n if (!objectLike(value)) return undefined\n const receiptValue = value.receipt\n if (!objectLike(receiptValue)) return undefined\n const receiptOwnership = receiptValue.ownership\n if (!objectLike(receiptOwnership)) return undefined\n if (\n receiptOwnership.id !== ownership.id ||\n receiptOwnership.path !== ownership.path ||\n typeof receiptOwnership.id !== 'string' ||\n typeof receiptOwnership.path !== 'string' ||\n typeof receiptValue.rollback !== 'function'\n ) {\n return undefined\n }\n if (value.ok === true) {\n return { ok: true, receipt: receiptValue as unknown as AttachmentWriteReceipt }\n }\n if (value.ok === false && typeof value.reason === 'string') {\n return {\n ok: false,\n reason: value.reason,\n receipt: receiptValue as unknown as AttachmentWriteReceipt,\n }\n }\n } catch {\n // A malformed or hostile adapter result is a storage failure.\n }\n return undefined\n}\n\n/** Sanitize adapter diagnostics and keep storage failures typed when the logger itself fails. */\nexport function logAttachmentStorageError(\n logger: { error(message: string, fields: Record<string, unknown>): void },\n message: string,\n fields: Record<string, unknown>,\n): void {\n try {\n const safeFields = Object.fromEntries(\n Object.entries(fields).map(([key, value]) => [\n key,\n typeof value === 'string' ? redactErrorMessage(value) : value,\n ]),\n )\n logger.error(message, safeFields)\n } catch {\n // Logging must not turn a typed storage failure into a thrown response.\n }\n}\n","/**\n * `promoteAgentFilePart` — turn a harness-emitted `type:\"file\"` stream part\n * into a store-backed {@link ChatAttachmentPart}. The harness hands back a URL\n * pointing at bytes it produced (a `data:` URI, or a path inside the sandbox);\n * nothing durable survives past the turn unless it is written into the\n * product's store, the same way a user upload is. Typed outcomes throughout:\n * every failure mode (unsupported scheme, no sandbox, oversize, store-write\n * failure, malformed part) resolves to `{ succeeded: false, filename, reason }`\n * rather than throwing past this boundary, so the caller folds a visible notice\n * instead of losing the file silently.\n *\n * Storage-parameterized port of gtm-agent's `promote-file-parts.ts` with the\n * refactor gtm never made: persistence goes through an injected stable writer\n * or ownership-safe adapter, the path strategy is the injected\n * `buildAttachmentPath` (neutral `uploads/agent/<date>/` default, no domain\n * bucket taxonomy baked), the MIME map is an injectable hook, and the date\n * segment reads an injectable clock. The logical `hash8(id ?? url ?? filename)`\n * naming is preserved. Atomic callers also receive a fresh ownership suffix so\n * an ambiguous write cannot overwrite an older object.\n */\n\nimport {\n statSandboxFileSize,\n readSandboxBinaryBytes,\n type SandboxExecChannel,\n} from '../sandbox/binary-read'\nimport { attachmentKindForMime, type ChatAttachmentKind, type ChatAttachmentPart } from '../chat-store/parts'\nimport { redactErrorMessage } from '../redact'\nimport {\n ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n immutableAttachmentPath,\n type AtomicAttachmentWriter,\n type AttachmentWriteOwnership,\n type AttachmentWriteReceipt,\n type WriteAttachmentFn,\n} from './attachment-store'\nimport {\n logAttachmentStorageError,\n inspectAtomicAttachmentWriteResult,\n inspectLegacyAttachmentWriteResult,\n} from './attachment-write-safety'\nimport { sanitizeAttachmentFileName } from './attachment-validation'\nimport { formatBytes } from './wire'\nimport { sniffMimeFromName } from '../web/mime'\n\nexport { sniffMimeFromName }\n\n/** Default ceiling on a promoted file's raw (pre-encoding) byte size. */\nexport const PROMOTE_MAX_FILE_BYTES = 10 * 1024 * 1024\n\n/** Define the structure for a raw file part with optional metadata and media type information */\nexport interface RawAgentFilePart {\n type: 'file'\n id?: string\n filename?: string\n /** AI-SDK-shaped parts carry the MIME type here… */\n mediaType?: string\n /** …but OpenCode's native FilePart calls the same field `mime`. */\n mime?: string\n url?: string\n}\n\n/** Resolve the result of promoting a file part with success status and relevant data or error details */\nexport type PromoteFilePartResult =\n | { succeeded: true; part: ChatAttachmentPart }\n | { succeeded: false; filename: string; reason: string }\n\ntype ByteResolution =\n | { succeeded: true; bytes: Uint8Array }\n | { succeeded: false; reason: string }\n\n/** Arguments handed to a {@link PromoteAgentFilePartOptions.buildAttachmentPath}\n * override — everything needed to place the file deterministically. */\nexport interface AttachmentPathArgs {\n /** Sanitized display filename (basename, safe charset). */\n filename: string\n /** First 8 hex chars of the SHA-256 idempotency digest. */\n hash8: string\n /** `YYYY-MM-DD` from the injected clock. */\n date: string\n /** Resolved media type. */\n mediaType: string\n /** `image`/`file` split of the media type. */\n kind: ChatAttachmentKind\n}\n\n/** Decode base64 with `atob` (not `Buffer.from`, which SKIPS out-of-alphabet\n * characters and would decode a corrupt payload to something plausible). */\nfunction base64ToBytes(base64: string): Uint8Array {\n const binary = atob(base64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)\n return bytes\n}\n\nfunction parseDataUrl(url: string): { base64: boolean; data: string } | null {\n const match = /^data:[^,]*,([\\s\\S]*)$/i.exec(url)\n if (!match) return null\n return { base64: /;base64,/i.test(url), data: match[1] ?? '' }\n}\n\n/** The MIME type embedded in a `data:` URI's header, if any — the last-resort\n * signal when the part itself carries no mediaType/mime field. */\nfunction dataUrlMime(url: string | undefined): string | undefined {\n if (!url) return undefined\n const match = /^data:([^;,]+)[;,]/i.exec(url)\n return match ? match[1] : undefined\n}\n\nfunction basenameFromUrl(url: string | undefined): string | undefined {\n if (!url || /^data:/i.test(url)) return undefined\n const withoutQuery = url.split(/[?#]/)[0] ?? url\n const segments = withoutQuery.split('/').filter(Boolean)\n return segments[segments.length - 1] || undefined\n}\n\n/** `file://<path>` strips to `<path>`; a bare absolute path passes through\n * unchanged. The remainder is percent-decoded — sidecar file URLs encode\n * spaces and other reserved characters. */\nfunction resolveFileUrlPath(url: string): { succeeded: true; path: string } | { succeeded: false; reason: string } {\n const withoutScheme = /^file:\\/\\//i.test(url) ? url.slice('file://'.length) : url\n try {\n return { succeeded: true, path: decodeURIComponent(withoutScheme) }\n } catch (err) {\n return { succeeded: false, reason: `malformed file path: ${redactErrorMessage(err)}` }\n }\n}\n\n/** Matches gtm's `attachmentSizeErrorMessage` (attachment-limits.ts:87-89)\n * verbatim, via the shared {@link formatBytes} — e.g. \"report.pdf is 10MB;\n * attachments are limited to 10MB\" — so an oversize promotion notice reads\n * identically whether gtm's original composed it or agent-app's promoter did. */\nfunction oversizeReason(filename: string, actual: number, limit: number): string {\n return `${filename} is ${formatBytes(actual)}; attachments are limited to ${formatBytes(limit)}`\n}\n\nfunction resolveDataUrlBytes(url: string, filename: string, maxBytes: number): ByteResolution {\n const parsed = parseDataUrl(url)\n if (!parsed) return { succeeded: false, reason: 'malformed data URI' }\n let bytes: Uint8Array\n try {\n bytes = parsed.base64 ? base64ToBytes(parsed.data) : new TextEncoder().encode(decodeURIComponent(parsed.data))\n } catch (err) {\n return { succeeded: false, reason: `failed to decode data URI: ${redactErrorMessage(err)}` }\n }\n if (bytes.byteLength > maxBytes) {\n return { succeeded: false, reason: oversizeReason(filename, bytes.byteLength, maxBytes) }\n }\n return { succeeded: true, bytes }\n}\n\nasync function resolveSandboxFileBytes(input: {\n path: string\n box: SandboxExecChannel\n sessionId: string\n filename: string\n maxBytes: number\n}): Promise<ByteResolution> {\n // exec can reject outright (box teardown, timeout, transport failure) — that\n // is a per-file failure, not a turn failure, so it must resolve to a typed\n // outcome like a nonzero exit code does.\n const stat = await statSandboxFileSize(input.box, input.path, { sessionId: input.sessionId })\n if (!stat.succeeded) {\n return { succeeded: false, reason: `could not stat agent file: ${redactErrorMessage(stat.error)}` }\n }\n // Rejected before the bytes are ever pulled — a base64 exec of an oversize\n // file would waste a full sandbox round trip only to be discarded.\n if (stat.value > input.maxBytes) {\n return { succeeded: false, reason: oversizeReason(input.filename, stat.value, input.maxBytes) }\n }\n\n const read = await readSandboxBinaryBytes(input.box, input.path, stat.value, { sessionId: input.sessionId })\n if (!read.succeeded) {\n return { succeeded: false, reason: `could not read agent file: ${redactErrorMessage(read.error)}` }\n }\n return { succeeded: true, bytes: read.value.bytes }\n}\n\nasync function resolveBytes(input: {\n raw: RawAgentFilePart\n box: SandboxExecChannel | undefined\n sessionId: string\n filename: string\n maxBytes: number\n}): Promise<ByteResolution> {\n const url = input.raw.url\n if (!url) return { succeeded: false, reason: 'the file part carries no url' }\n\n if (/^data:/i.test(url)) return resolveDataUrlBytes(url, input.filename, input.maxBytes)\n\n const isSandboxPath = /^file:\\/\\//i.test(url) || url.startsWith('/')\n if (!isSandboxPath) {\n const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(url)?.[1]?.toLowerCase() ?? 'unknown'\n return { succeeded: false, reason: `unsupported file URL scheme: ${scheme}` }\n }\n if (!input.box) return { succeeded: false, reason: 'no sandbox to read agent file' }\n\n const resolvedPath = resolveFileUrlPath(url)\n if (!resolvedPath.succeeded) return resolvedPath\n return resolveSandboxFileBytes({\n path: resolvedPath.path,\n box: input.box,\n sessionId: input.sessionId,\n filename: input.filename,\n maxBytes: input.maxBytes,\n })\n}\n\n/** First 8 hex chars of the SHA-256 of `seed` — deterministic (no\n * `Math.random`) so promoting the same source part twice, even across\n * requests, resolves to the same store path and overwrites in place. */\nasync function hash8(seed: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seed))\n return Array.from(new Uint8Array(digest).slice(0, 4))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/** Neutral default placement: everything under `uploads/agent/<date>/`, named\n * `<base>-<hash8><ext>`. No domain bucket taxonomy (assets/audio/videos…) —\n * a product that wants one supplies `buildAttachmentPath`. */\nfunction defaultBuildAttachmentPath(args: AttachmentPathArgs): string {\n const extensionMatch = /\\.[A-Za-z0-9]+$/.exec(args.filename)\n const extension = extensionMatch ? extensionMatch[0] : ''\n const base = extension ? args.filename.slice(0, -extension.length) : args.filename\n return `uploads/agent/${args.date}/${base}-${args.hash8}${extension}`\n}\n\ntype PromoteFilePartLogger = Pick<Console, 'error'>\n\n\n\nasync function compensatePromotionWrite(\n writer: AtomicAttachmentWriter,\n scopeId: string,\n ownership: AttachmentWriteOwnership,\n receipt: AttachmentWriteReceipt,\n): Promise<{ rollbackError?: unknown; abortError?: unknown }> {\n try {\n await receipt.rollback()\n return {}\n } catch (rollbackError) {\n try {\n await writer.abort(scopeId, ownership)\n return { rollbackError }\n } catch (abortError) {\n return { rollbackError, abortError }\n }\n }\n}\n\ninterface PromoteFilePartCommonOptions {\n raw: RawAgentFilePart\n /** The turn's box — required only to promote a sandbox-path part; a `data:`\n * URI needs none. */\n box?: SandboxExecChannel\n /** The product's workspace/tenant key, passed to `writeAttachment`. */\n scopeId: string\n /** The turn's session id, used for the sandbox stat/read exec calls. */\n sessionId: string\n /** Store-path strategy. Default {@link defaultBuildAttachmentPath}. */\n buildAttachmentPath?: (args: AttachmentPathArgs) => string\n /** Raw-byte ceiling. Default {@link PROMOTE_MAX_FILE_BYTES}. */\n maxBytes?: number\n /** Last-resort media-type hook. Default {@link sniffMimeFromName}. */\n sniffMime?: (filename: string) => string\n /** Clock for the date path segment. Default `() => new Date()`. */\n now?: () => Date\n /** Unique id source for tests or a product's id service. */\n createWriteId?: () => string\n /** Server-side sink for redacted storage details. */\n logger?: PromoteFilePartLogger\n}\n\n/** Stable promotion options from the original writer contract. */\nexport interface PromoteAgentFilePartOptions extends PromoteFilePartCommonOptions {\n /** REQUIRED store writer — no default (the product owns its store). */\n writeAttachment: WriteAttachmentFn\n}\n\n/** Ownership-safe promotion options for new products. */\nexport interface AtomicPromoteAgentFilePartOptions extends PromoteFilePartCommonOptions {\n /** Complete writer + ambiguous-write cleanup adapter. */\n attachmentWriter: AtomicAttachmentWriter\n}\n\nfunction isAtomicPromotionOptions(\n options: PromoteAgentFilePartOptions | AtomicPromoteAgentFilePartOptions,\n): options is AtomicPromoteAgentFilePartOptions {\n return 'attachmentWriter' in options\n}\n\n/** Promote a part using the stable writer contract. */\nexport function promoteAgentFilePart(options: PromoteAgentFilePartOptions): Promise<PromoteFilePartResult>\n\n/** Promote a part using an ownership-safe writer and cleanup adapter. */\nexport function promoteAgentFilePart(options: AtomicPromoteAgentFilePartOptions): Promise<PromoteFilePartResult>\n\n/** Promote a part when the caller selects the writer contract at runtime. */\nexport function promoteAgentFilePart(\n options: PromoteAgentFilePartOptions | AtomicPromoteAgentFilePartOptions,\n): Promise<PromoteFilePartResult>\n\n/** Promote a part of an agent file with optional byte limits and MIME type detection. */\nexport async function promoteAgentFilePart(\n options: PromoteAgentFilePartOptions | AtomicPromoteAgentFilePartOptions,\n): Promise<PromoteFilePartResult> {\n const atomic = isAtomicPromotionOptions(options)\n const maxBytes = options.maxBytes ?? PROMOTE_MAX_FILE_BYTES\n const sniffMime = options.sniffMime ?? sniffMimeFromName\n const buildAttachmentPath = options.buildAttachmentPath ?? defaultBuildAttachmentPath\n const now = options.now ?? (() => new Date())\n const logger = options.logger ?? console\n const createWriteId = atomic\n ? options.createWriteId ?? (() => {\n if (typeof crypto === 'undefined' || typeof crypto.randomUUID !== 'function') {\n throw new Error('attachment promotion requires crypto.randomUUID')\n }\n return crypto.randomUUID()\n })\n : undefined\n\n const filename = sanitizeAttachmentFileName(\n options.raw.filename ?? basenameFromUrl(options.raw.url) ?? 'agent-file',\n )\n\n const resolved = await resolveBytes({\n raw: options.raw,\n box: options.box,\n sessionId: options.sessionId,\n filename,\n maxBytes,\n })\n if (!resolved.succeeded) return { succeeded: false, filename, reason: resolved.reason }\n\n let mediaType: string\n let kind: ChatAttachmentKind\n let logicalPath: string\n try {\n mediaType = (options.raw.mediaType ?? options.raw.mime ?? dataUrlMime(options.raw.url) ?? sniffMime(filename)).toLowerCase()\n kind = attachmentKindForMime(mediaType)\n const digest = await hash8(options.raw.id ?? options.raw.url ?? filename)\n const date = now().toISOString().split('T')[0] ?? ''\n logicalPath = buildAttachmentPath({ filename, hash8: digest, date, mediaType, kind })\n } catch (error) {\n logAttachmentStorageError(logger, '[promote-file-part] path planning failed', {\n error: redactErrorMessage(error),\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n\n if (!atomic) {\n let written: unknown\n try {\n written = await options.writeAttachment(options.scopeId, logicalPath, resolved.bytes, {\n mediaType,\n name: filename,\n originalName: options.raw.filename ?? filename,\n size: resolved.bytes.byteLength,\n })\n } catch (error) {\n const reason = redactErrorMessage(error)\n logAttachmentStorageError(logger, '[promote-file-part] legacy writer failed', {\n path: logicalPath,\n error: reason,\n })\n return { succeeded: false, filename, reason }\n }\n const result = inspectLegacyAttachmentWriteResult(written)\n if (!result) {\n logAttachmentStorageError(logger, '[promote-file-part] legacy writer returned an invalid result', {\n path: logicalPath,\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n if (!result.ok) {\n const reason = redactErrorMessage(result.reason)\n logAttachmentStorageError(logger, '[promote-file-part] legacy write rejected', {\n path: logicalPath,\n error: reason,\n })\n return { succeeded: false, filename, reason }\n }\n\n return {\n succeeded: true,\n part: {\n type: kind,\n path: logicalPath,\n name: filename,\n size: resolved.bytes.byteLength,\n mediaType,\n },\n }\n }\n\n let ownershipId: string\n let path: string\n try {\n ownershipId = createWriteId!()\n path = immutableAttachmentPath(logicalPath, ownershipId)\n } catch (error) {\n logAttachmentStorageError(logger, '[promote-file-part] could not allocate ownership key', {\n path: logicalPath,\n error: redactErrorMessage(error),\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n const ownership: AttachmentWriteOwnership = Object.freeze({ id: ownershipId, path })\n\n // `name` is the sanitized filename already computed above; `originalName`\n // is the pre-sanitization source name (gtm's frontmatter `originalName`) —\n // the one field sanitization would otherwise destroy with no way back.\n let written: Awaited<ReturnType<AtomicAttachmentWriter['write']>>\n try {\n written = await options.attachmentWriter.write(options.scopeId, path, resolved.bytes, {\n mediaType,\n name: filename,\n originalName: options.raw.filename ?? filename,\n size: resolved.bytes.byteLength,\n ownership,\n })\n } catch (err) {\n let abortError: unknown\n try {\n await options.attachmentWriter.abort(options.scopeId, ownership)\n } catch (error) {\n abortError = error\n }\n logAttachmentStorageError(logger, '[promote-file-part] write failed', {\n path,\n ownershipId: ownership.id,\n error: redactErrorMessage(err),\n ...(abortError === undefined ? {} : { abortError: redactErrorMessage(abortError) }),\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n const result = inspectAtomicAttachmentWriteResult(written, ownership)\n if (!result) {\n let abortError: unknown\n try {\n await options.attachmentWriter.abort(options.scopeId, ownership)\n } catch (error) {\n abortError = error\n }\n logAttachmentStorageError(logger, '[promote-file-part] writer returned a mismatched ownership receipt', {\n path,\n ownershipId: ownership.id,\n ...(abortError === undefined ? {} : { abortError: redactErrorMessage(abortError) }),\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n if (!result.ok) {\n const compensation = await compensatePromotionWrite(\n options.attachmentWriter,\n options.scopeId,\n ownership,\n result.receipt,\n )\n logAttachmentStorageError(logger, '[promote-file-part] write rejected', {\n path,\n ownershipId: ownership.id,\n error: redactErrorMessage(result.reason),\n ...(compensation.rollbackError === undefined\n ? {}\n : { rollbackError: redactErrorMessage(compensation.rollbackError) }),\n ...(compensation.abortError === undefined\n ? {}\n : { abortError: redactErrorMessage(compensation.abortError) }),\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n\n return {\n succeeded: true,\n part: {\n type: kind,\n path,\n name: filename,\n size: resolved.bytes.byteLength,\n mediaType,\n },\n }\n}\n","/**\n * `createAttachmentUploadRoute` — the fleet-primitive durable-store upload\n * route: a two-phase batch (every file is validated before any file is written),\n * with a stable legacy lane and an ownership-safe receipt lane for new callers,\n * a content-sniffed type gate\n * (`checkAttachmentType` over `sniffBinary`'s magic-byte read, not the\n * extension or the browser-reported MIME), binary/text caps with optional\n * per-sniffed-mime overrides, an aggregate byte cap, and sanitized filenames.\n * Storage is fully seamed through the injected\n * `WriteAttachmentFn` or `AtomicAttachmentWriter` (`./attachment-store`) — no\n * default store, the product owns where bytes actually live (vault, object\n * store, …), and auth/rate limiting is entirely the injected `authorize`\n * seam's job: this factory\n * never invents a 401 or 429 response, it only returns `auth.response`\n * verbatim on failure.\n *\n * Two body shapes: a `multipart/form-data` batch, parsed whole, and one raw\n * file body named by the `filename` query parameter. A raw body larger than\n * the sniff head streams to `writeAttachmentStream` when the product supplies\n * one: the Worker never holds the file whole, which is what lets a product\n * admit data files of tens of MB inside a 128 MB isolate.\n *\n * Lifted from gtm-agent's `src/routes/api.vault.upload.ts` (the hardening\n * lineage other lifted modules in this vertical cite: gtm#584 binary\n * corruption, gtm#592 sniff gate/caps, gtm#593 batch-atomic writes) and\n * generalized the way `resolve-attachments.ts` generalized gtm's read path —\n * the vault-specific pieces (KV vault paths, frontmatter, per-user rate\n * limiting) are all injected seams here, while the validate-then-write phase\n * split and the type/size gate ordering survive byte-for-byte.\n *\n * @remarks Sibling to, NOT an extension of, `./upload.ts`'s\n * `createUploadRoute` — a different persistence model (durable product store\n * vs. inline-`data:`-or-ephemeral-sandbox-workspace). See that module's doc\n * comment for the up-to-date framing between the two.\n */\n\nimport { formatBytes, type ChatAttachmentInput, type ChatAttachmentKind } from './wire'\nimport { attachmentKindForMime } from '../chat-store/parts'\nimport { redactErrorMessage } from '../redact'\nimport {\n ATTACHMENT_ROLLBACK_FAILURE_CODE,\n ATTACHMENT_ROLLBACK_FAILURE_MESSAGE,\n ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n type AtomicAttachmentWriter,\n immutableAttachmentPath,\n type AttachmentWriteOwnership,\n type AttachmentWriteReceipt,\n type WriteAttachmentFn,\n type WriteAttachmentStreamFn,\n} from './attachment-store'\nimport {\n logAttachmentStorageError,\n inspectAtomicAttachmentWriteResult,\n inspectLegacyAttachmentWriteResult,\n} from './attachment-write-safety'\nimport {\n ALLOWED_ATTACHMENT_SNIFFED_MIMES,\n ATTACHMENT_MAX_COUNT,\n MAX_ATTACHMENT_TOTAL_BYTES,\n MAX_BINARY_ATTACHMENT_BYTES,\n MAX_TEXT_ATTACHMENT_BYTES,\n attachmentSizeErrorMessage,\n attachmentTotalSizeErrorMessage,\n checkAttachmentType,\n defaultValidateAttachmentPath,\n sanitizeAttachmentFileName,\n sniffedMimeImpliedByName,\n type AttachmentPathCheck,\n} from './attachment-validation'\nimport { createStreamingSniffer, sniffBinary, STREAM_SNIFF_HEAD_BYTES, type SniffResult } from './binary-sniff'\nimport { sniffMimeFromName } from './promote-file-part'\n\n/** Stable authorization result for the original writer contract. */\nexport type AttachmentUploadAuthorization =\n | {\n ok: true\n scopeId: string\n writeAttachment?: WriteAttachmentFn\n writeAttachmentStream?: WriteAttachmentStreamFn\n }\n | { ok: false; response: Response }\n\n/** Authorization result for an ownership-safe attachment writer. */\nexport type AtomicAttachmentUploadAuthorization =\n | {\n ok: true\n scopeId: string\n attachmentWriter?: AtomicAttachmentWriter\n }\n | { ok: false; response: Response }\n\n/** The logger receives only sanitized backend details. The client receives the\n * opaque message below, regardless of the store's failure text. */\nexport type AttachmentUploadLogger = Pick<Console, 'error'>\n\n\n\ninterface AttachmentUploadRouteCommonOptions {\n /** Overridable caps. Defaults come from `./attachment-validation`. */\n limits?: {\n /** Most files one request may carry. Default {@link ATTACHMENT_MAX_COUNT}. */\n maxCount?: number\n /** Ceiling on a binary file's raw size. Default {@link MAX_BINARY_ATTACHMENT_BYTES}. */\n maxBinaryBytes?: number\n /** Optional binary-file ceilings keyed by the content-sniffed mime. */\n maxBytesBySniffedMime?: ReadonlyMap<string, number>\n /** Ceiling on a text file's raw size. Default {@link MAX_TEXT_ATTACHMENT_BYTES}. */\n maxTextBytes?: number\n /** Aggregate raw-byte ceiling. Default {@link MAX_ATTACHMENT_TOTAL_BYTES}. */\n maxTotalBytes?: number\n /** Largest `multipart/form-data` body this route parses. A form body is\n * held whole while it parses, at about three copies at peak, so a\n * product that admits files too large for that sets this and takes them\n * as raw bodies (see {@link createAttachmentUploadRoute}). Default: no\n * limit beyond the per-file and aggregate caps. */\n maxFormBytes?: number\n }\n /** Attachment kinds this route accepts. Default `['image', 'file']`. */\n allowedKinds?: ChatAttachmentKind[]\n /** Sniffed-mime allowlist fed to `checkAttachmentType`. */\n allowedSniffedMimes?: ReadonlySet<string>\n /** Sanitized-name → logical store path. */\n pathFor?: (name: string) => string\n /** Store-path validator. Default {@link defaultValidateAttachmentPath}. */\n validatePath?: (path: string) => AttachmentPathCheck\n /** Last-resort media-type hook for text content the sniffer cannot type. */\n sniffMime?: (name: string) => string\n /** Unique id source for atomic ownership keys. */\n createWriteId?: () => string\n /** Server-side error sink. Backend text is sanitized before it is logged. */\n logger?: AttachmentUploadLogger\n}\n\n/** Stable route options for products using the original writer contract. */\nexport interface CreateLegacyAttachmentUploadRouteOptions extends AttachmentUploadRouteCommonOptions {\n /** Authenticate the caller, rate-limit, and resolve the store scope\n * (workspace/tenant id) — never a query param. */\n authorize(args: { request: Request }): Promise<AttachmentUploadAuthorization>\n /** Stable writer. `authorize` may override it per-request. */\n writeAttachment: WriteAttachmentFn\n /** Writer for a raw-body upload larger than {@link STREAM_SNIFF_HEAD_BYTES}:\n * the route checks the file while it streams to this writer, so the file\n * is never held whole. Without it, a raw body is read whole and goes\n * through `writeAttachment` under the same caps. */\n writeAttachmentStream?: WriteAttachmentStreamFn\n}\n\n/**\n * The original public route-options interface remains available for consumers\n * that extend it. Ownership-safe callers use the atomic interface below.\n */\nexport interface CreateAttachmentUploadRouteOptions extends CreateLegacyAttachmentUploadRouteOptions {}\n\n/** Ownership-safe route options for new products. */\nexport interface CreateAtomicAttachmentUploadRouteOptions extends AttachmentUploadRouteCommonOptions {\n /** Authenticate the caller, rate-limit, and resolve the store scope. */\n authorize(args: { request: Request }): Promise<AtomicAttachmentUploadAuthorization>\n /** Complete writer + ambiguous-write cleanup adapter. */\n attachmentWriter: AtomicAttachmentWriter\n}\n\nfunction attachmentUploadError(status: number, code: string, message: string, path?: string): Response {\n return Response.json(\n { error: path === undefined ? { code, message } : { code, message, path } },\n { status },\n )\n}\n\nfunction atomicAttachmentFailure(path: string, cleanupFailures = 0): Response {\n return attachmentUploadError(\n 503,\n cleanupFailures > 0 ? ATTACHMENT_ROLLBACK_FAILURE_CODE : 'attachment_store_unavailable',\n cleanupFailures > 0 ? ATTACHMENT_ROLLBACK_FAILURE_MESSAGE : ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n path,\n )\n}\n\n/** Longest raw-upload `filename` accepted. */\nconst MAX_RAW_FILENAME_LENGTH = 255\n\ntype RawUploadTarget =\n | { succeeded: true; filename: string; declaredBytes: number }\n | { succeeded: false; response: Response }\n\n/**\n * A raw upload is one file as the request body, named by the `filename`\n * query parameter, with its size in `Content-Length` or `X-Upload-Length`\n * (the browser's `File.size`), as in `/object-store`'s upload route. Knowing\n * the size up front is what lets a store receive a fixed-length stream.\n */\nfunction rawUploadTarget(request: Request): RawUploadTarget {\n const filename = new URL(request.url).searchParams.get('filename')\n if (!filename || filename.length > MAX_RAW_FILENAME_LENGTH) {\n return {\n succeeded: false,\n response: attachmentUploadError(\n 400,\n 'invalid_upload',\n 'Expected a multipart/form-data body with file fields, or one raw file body named by the filename query parameter',\n ),\n }\n }\n const uploadLength = request.headers.get('X-Upload-Length')\n const transportLength = request.headers.get('Content-Length')\n if (uploadLength !== null && transportLength !== null && uploadLength !== transportLength) {\n return { succeeded: false, response: attachmentUploadError(400, 'invalid_length', 'Conflicting upload lengths') }\n }\n const declared = uploadLength ?? transportLength\n if (declared === null) {\n return {\n succeeded: false,\n response: attachmentUploadError(411, 'length_required', 'A raw upload declares its size in Content-Length or X-Upload-Length'),\n }\n }\n const declaredBytes = Number(declared)\n if (!/^(0|[1-9]\\d*)$/.test(declared) || !Number.isSafeInteger(declaredBytes)) {\n return { succeeded: false, response: attachmentUploadError(400, 'invalid_length', 'Invalid upload length') }\n }\n return { succeeded: true, filename, declaredBytes }\n}\n\nconst LENGTH_MISMATCH_MESSAGE = 'Upload length does not match the file body'\n\n/** Read a small raw body whole, refusing one longer or shorter than declared. */\nasync function readRawBody(\n request: Request,\n declaredBytes: number,\n): Promise<{ succeeded: true; value: Uint8Array<ArrayBuffer> } | { succeeded: false; response: Response }> {\n const mismatch = { succeeded: false as const, response: attachmentUploadError(400, 'invalid_length', LENGTH_MISMATCH_MESSAGE) }\n const bytes = new Uint8Array(declaredBytes)\n if (!request.body) return declaredBytes === 0 ? { succeeded: true, value: bytes } : mismatch\n const reader = request.body.getReader()\n let offset = 0\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (offset + value.length > declaredBytes) {\n await reader.cancel().catch(() => undefined)\n return mismatch\n }\n bytes.set(value, offset)\n offset += value.length\n }\n } catch {\n return { succeeded: false, response: attachmentUploadError(400, 'invalid_upload', 'The upload body ended early') }\n }\n return offset === declaredBytes ? { succeeded: true, value: bytes } : mismatch\n}\n\n/** Read a body of at most `maxBytes`, refusing a longer one as soon as it\n * passes the cap. A declared `Content-Length` over the cap is refused before\n * any byte is read. */\nasync function readBodyUpTo(\n request: Request,\n maxBytes: number,\n): Promise<{ succeeded: true; value: Uint8Array<ArrayBuffer> } | { succeeded: false; tooLarge: boolean }> {\n const declared = Number(request.headers.get('Content-Length') ?? Number.NaN)\n if (Number.isFinite(declared) && declared > maxBytes) return { succeeded: false, tooLarge: true }\n if (!request.body) return { succeeded: true, value: new Uint8Array(0) }\n const reader = request.body.getReader()\n const chunks: Uint8Array[] = []\n let length = 0\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n length += value.length\n if (length > maxBytes) {\n await reader.cancel().catch(() => undefined)\n return { succeeded: false, tooLarge: true }\n }\n chunks.push(value)\n }\n } catch {\n return { succeeded: false, tooLarge: false }\n }\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.length\n }\n return { succeeded: true, value: bytes }\n}\n\n/** The media type a streamed write records before the whole file is read.\n * The head decides every family except a zip container, whose Office\n * subtype lives in the central directory at the end; for that, the\n * extension's implied type stands in, and the route's response carries the\n * final one. */\nfunction provisionalMediaType(name: string, head: SniffResult, sniffMime: (name: string) => string): string {\n if (!head.binary) return sniffMime(name)\n if (head.mime === 'application/zip') return sniffedMimeImpliedByName(name) ?? head.mime\n return head.mime ?? 'application/octet-stream'\n}\n\ninterface SuccessfulAttachmentWrite {\n path: string\n ownership: AttachmentWriteOwnership\n receipt: AttachmentWriteReceipt\n}\n\n/** Run every available compensation, from the newest write to the oldest. The\n * receipt owns the compare-and-delete operation; this route never deletes a\n * logical path itself. */\nasync function rollbackSuccessfulWrites(\n writes: readonly SuccessfulAttachmentWrite[],\n scopeId: string,\n writer: AtomicAttachmentWriter,\n logger: AttachmentUploadLogger,\n): Promise<number> {\n let failures = 0\n for (let index = writes.length - 1;index >= 0;index -= 1) {\n const write = writes[index]!\n try {\n await write.receipt.rollback()\n } catch (error) {\n failures += 1\n logAttachmentStorageError(logger, '[attachment-upload] cleanup failed', {\n path: write.path,\n ownershipId: write.ownership.id,\n error: redactErrorMessage(error),\n })\n failures += await abortOwnership(writer, scopeId, write.ownership, logger)\n }\n }\n return failures\n}\n\nasync function abortOwnership(\n writer: AtomicAttachmentWriter,\n scopeId: string,\n ownership: AttachmentWriteOwnership,\n logger: AttachmentUploadLogger,\n): Promise<number> {\n try {\n await writer.abort(scopeId, ownership)\n return 0\n } catch (error) {\n logAttachmentStorageError(logger, '[attachment-upload] ambiguous write cleanup failed', {\n path: ownership.path,\n ownershipId: ownership.id,\n error: redactErrorMessage(error),\n })\n return 1\n }\n}\n\nfunction isAtomicRouteOptions(\n options: CreateAttachmentUploadRouteOptions | CreateAtomicAttachmentUploadRouteOptions,\n): options is CreateAtomicAttachmentUploadRouteOptions {\n return 'attachmentWriter' in options\n}\n\n/** Resolve an attachment upload route handler with customizable limits and validation options. */\nexport function createAttachmentUploadRoute(\n options: CreateAttachmentUploadRouteOptions | CreateAtomicAttachmentUploadRouteOptions,\n): (request: Request) => Promise<Response> {\n const atomic = isAtomicRouteOptions(options)\n const maxCount = options.limits?.maxCount ?? ATTACHMENT_MAX_COUNT\n const maxBinaryBytes = options.limits?.maxBinaryBytes ?? MAX_BINARY_ATTACHMENT_BYTES\n const maxBytesBySniffedMime = options.limits?.maxBytesBySniffedMime\n const maxTextBytes = options.limits?.maxTextBytes ?? MAX_TEXT_ATTACHMENT_BYTES\n const maxTotalBytes = options.limits?.maxTotalBytes ?? MAX_ATTACHMENT_TOTAL_BYTES\n const allowedKinds: ChatAttachmentKind[] = options.allowedKinds ?? ['image', 'file']\n const allowedSniffedMimes = options.allowedSniffedMimes ?? ALLOWED_ATTACHMENT_SNIFFED_MIMES\n const pathFor = options.pathFor ?? ((name: string) => name)\n const validatePath = options.validatePath ?? defaultValidateAttachmentPath\n const sniffMime = options.sniffMime ?? sniffMimeFromName\n const createWriteId = atomic\n ? options.createWriteId ?? (() => {\n if (typeof crypto === 'undefined' || typeof crypto.randomUUID !== 'function') {\n throw new Error('attachment upload requires crypto.randomUUID')\n }\n return crypto.randomUUID()\n })\n : undefined\n const logger = options.logger ?? console\n const maxFormBytes = options.limits?.maxFormBytes\n const streamWriter = atomic ? undefined : options.writeAttachmentStream\n const limitFor = (sniff: SniffResult): number => {\n if (!sniff.binary) return maxTextBytes\n return sniff.mime === null ? maxBinaryBytes : maxBytesBySniffedMime?.get(sniff.mime) ?? maxBinaryBytes\n }\n // The most any admitted type may weigh, checked against a raw upload's\n // declared size before a byte is read; the type's own cap is checked once\n // the content is known.\n const largestFileBytes = Math.max(maxTextBytes, maxBinaryBytes, ...(maxBytesBySniffedMime?.values() ?? []))\n\n /**\n * The streamed lane: one raw body larger than the sniff head, written as it\n * arrives. The sniffer keeps only the head and tail, and the last chunk is\n * withheld until the whole file passes the type, kind and size gates, so a\n * refused file never reaches the store in full and its write fails.\n */\n const { streamRawUpload } = createRawUploadStream(sniffMime, allowedSniffedMimes, allowedKinds, limitFor, logger)\n\n return async function attachmentUpload(request: Request): Promise<Response> {\n const auth = await options.authorize({ request })\n if (!auth.ok) return auth.response\n const atomicWriter = atomic\n ? (auth as Extract<AtomicAttachmentUploadAuthorization, { ok: true }>).attachmentWriter ?? options.attachmentWriter\n : undefined\n const legacyWriter = atomic\n ? undefined\n : (auth as Extract<AttachmentUploadAuthorization, { ok: true }>).writeAttachment ?? options.writeAttachment\n if (atomic && !atomicWriter) {\n return attachmentUploadError(503, 'attachment_store_unavailable', ATTACHMENT_STORAGE_FAILURE_MESSAGE)\n }\n\n const files: File[] = []\n const contentType = request.headers.get('Content-Type')?.toLowerCase() ?? ''\n if (!contentType.startsWith('multipart/form-data')) {\n const target = rawUploadTarget(request)\n if (!target.succeeded) return target.response\n const { filename, declaredBytes } = target\n const name = sanitizeAttachmentFileName(filename)\n if (declaredBytes > largestFileBytes) {\n return attachmentUploadError(413, 'attachment_too_large', attachmentSizeErrorMessage(name, declaredBytes, largestFileBytes))\n }\n if (declaredBytes > maxTotalBytes) {\n return attachmentUploadError(413, 'attachments_total_too_large', attachmentTotalSizeErrorMessage(declaredBytes, maxTotalBytes))\n }\n if (streamWriter && declaredBytes > STREAM_SNIFF_HEAD_BYTES) {\n const path = pathFor(name)\n const pathCheck = validatePath(path)\n if (!pathCheck.succeeded) return attachmentUploadError(400, 'invalid_attachment_path', pathCheck.error, path)\n const writer = (auth as Extract<AttachmentUploadAuthorization, { ok: true }>).writeAttachmentStream ?? streamWriter\n return streamRawUpload({ request, scopeId: auth.scopeId, writer, filename, name, path, declaredBytes })\n }\n // A small raw body takes the batch path below as a one-file batch.\n const body = await readRawBody(request, declaredBytes)\n if (!body.succeeded) return body.response\n files.push(new File([body.value], filename))\n } else {\n let formSource: Request | Response = request\n if (maxFormBytes !== undefined) {\n // Read at most the cap before parsing, whether or not the client sent\n // a Content-Length, so an oversized form is refused while small.\n const bounded = await readBodyUpTo(request, maxFormBytes)\n if (!bounded.succeeded && !bounded.tooLarge) {\n return attachmentUploadError(400, 'invalid_upload', 'The upload body ended early')\n }\n if (!bounded.succeeded) {\n return attachmentUploadError(\n 413,\n 'form_upload_too_large',\n `Form uploads are limited to ${formatBytes(maxFormBytes)}; send a larger file as a raw request body named by the filename query parameter`,\n )\n }\n formSource = new Response(bounded.value, { headers: { 'Content-Type': request.headers.get('Content-Type') ?? '' } })\n }\n let form: FormData\n try {\n form = await formSource.formData()\n } catch {\n return attachmentUploadError(400, 'invalid_upload', 'Expected a multipart/form-data body with file fields')\n }\n // Collect every File value regardless of field name — the client may\n // send one field per file or a single repeated field.\n form.forEach((value) => {\n if (value instanceof File) files.push(value)\n })\n }\n if (files.length === 0) {\n return attachmentUploadError(400, 'invalid_upload', 'No files in the upload body')\n }\n\n if (files.length > maxCount) {\n return attachmentUploadError(\n 400,\n 'attachment_count_exceeded',\n `Too many files — the ${maxCount}-file limit was exceeded`,\n )\n }\n\n // Advisory only: client-controlled `file.size`, so a dishonest caller can\n // slip past it — but an honest oversized batch should fail before a\n // single byte is read. The authoritative aggregate check (against the\n // sniffed/decoded byte length) runs per-file in phase 1, below.\n const advisoryTotal = files.reduce((sum, file) => sum + file.size, 0)\n if (advisoryTotal > maxTotalBytes) {\n return attachmentUploadError(\n 413,\n 'attachments_total_too_large',\n attachmentTotalSizeErrorMessage(advisoryTotal, maxTotalBytes),\n )\n }\n\n const preparedBatch = await prepareUploadBatch(files, allowedSniffedMimes, allowedKinds, limitFor, pathFor, atomic, createWriteId, logger, validatePath, maxTotalBytes, sniffMime)\n if (preparedBatch instanceof Response) return preparedBatch\n const { prepared } = preparedBatch\n\n return await commitUploadBatch(prepared, legacyWriter, auth, atomicWriter, atomic, logger)\n }\n}\n\ninterface PreparedWrite {\n path: string\n ownershipId?: string\n name: string\n bytes: Uint8Array\n originalName: string\n size: number\n mediaType: string\n kind: ChatAttachmentKind\n}\n\n\nfunction createRawUploadStream(\n sniffMime: (name: string) => string,\n allowedSniffedMimes: ReadonlySet<string>,\n allowedKinds: ChatAttachmentKind[],\n limitFor: (sniff: SniffResult) => number,\n logger: AttachmentUploadLogger,\n) {\n async function streamRawUpload(input: {\n request: Request\n scopeId: string\n writer: WriteAttachmentStreamFn\n filename: string\n name: string\n path: string\n declaredBytes: number\n }): Promise<Response> {\n const { request, declaredBytes, name, path } = input\n if (!request.body) return attachmentUploadError(400, 'invalid_length', LENGTH_MISMATCH_MESSAGE)\n const reader = request.body.getReader()\n const sniffer = createStreamingSniffer()\n const head: Uint8Array[] = []\n let refusal: Response | undefined\n const tooLong = () => attachmentUploadError(400, 'invalid_length', LENGTH_MISMATCH_MESSAGE)\n\n try {\n while (sniffer.size < STREAM_SNIFF_HEAD_BYTES) {\n const { done, value } = await reader.read()\n if (done) break\n if (sniffer.size + value.length > declaredBytes) {\n await reader.cancel().catch(() => undefined)\n return tooLong()\n }\n sniffer.push(value)\n head.push(value)\n }\n } catch {\n return attachmentUploadError(400, 'invalid_upload', 'The upload body ended early')\n }\n const mediaTypeBeforeEnd = provisionalMediaType(name, sniffBinary(sniffer.head()), sniffMime)\n\n let held = head.pop()\n let finalSniff: SniffResult | undefined\n const refuse = (controller: ReadableStreamDefaultController<Uint8Array>, response: Response) => {\n refusal = response\n controller.error(new Error('attachment upload refused'))\n }\n const content = new ReadableStream<Uint8Array>({\n start(controller) {\n for (const chunk of head) controller.enqueue(chunk)\n },\n async pull(controller) {\n let next: ReadableStreamReadResult<Uint8Array>\n try {\n next = await reader.read()\n } catch {\n refuse(controller, attachmentUploadError(400, 'invalid_upload', 'The upload body ended early'))\n return\n }\n if (!next.done) {\n if (sniffer.size + next.value.length > declaredBytes) {\n await reader.cancel().catch(() => undefined)\n refuse(controller, tooLong())\n return\n }\n sniffer.push(next.value)\n if (held) controller.enqueue(held)\n held = next.value\n return\n }\n if (sniffer.size !== declaredBytes) {\n refuse(controller, tooLong())\n return\n }\n const sniff = sniffer.finish()\n const typeCheck = checkAttachmentType(name, sniff, allowedSniffedMimes)\n if (!typeCheck.succeeded) {\n refuse(controller, attachmentUploadError(\n typeCheck.code === 'attachment_type_mismatch' ? 400 : 415,\n typeCheck.code,\n typeCheck.message,\n ))\n return\n }\n const kind = attachmentKindForMime(sniff.mime ?? '')\n if (!allowedKinds.includes(kind)) {\n refuse(controller, attachmentUploadError(\n 415,\n 'attachment_kind_not_allowed',\n `${name} is a \"${kind}\" attachment, which this upload route does not accept`,\n ))\n return\n }\n const limit = limitFor(sniff)\n if (declaredBytes > limit) {\n refuse(controller, attachmentUploadError(413, 'attachment_too_large', attachmentSizeErrorMessage(name, declaredBytes, limit)))\n return\n }\n finalSniff = sniff\n if (held) controller.enqueue(held)\n held = undefined\n controller.close()\n },\n cancel(reason) {\n return reader.cancel(reason).catch(() => undefined)\n },\n }, { highWaterMark: 0 })\n\n let written: unknown\n try {\n written = await input.writer(input.scopeId, path, content, {\n mediaType: mediaTypeBeforeEnd,\n name,\n originalName: input.filename,\n size: declaredBytes,\n })\n } catch (error) {\n if (!finalSniff) await reader.cancel().catch(() => undefined)\n if (refusal) return refusal\n logAttachmentStorageError(logger, '[attachment-upload] stream writer failed', { path, error: redactErrorMessage(error) })\n return attachmentUploadError(503, 'attachment_store_unavailable', ATTACHMENT_STORAGE_FAILURE_MESSAGE, path)\n }\n if (!finalSniff) await reader.cancel().catch(() => undefined)\n if (refusal) return refusal\n const result = inspectLegacyAttachmentWriteResult(written)\n if (!result || (result.ok && !finalSniff)) {\n // A writer that reports success without reading the file to its end\n // stored something the route never checked.\n logAttachmentStorageError(logger, '[attachment-upload] stream writer returned without a checked file', { path })\n return attachmentUploadError(503, 'attachment_store_unavailable', ATTACHMENT_STORAGE_FAILURE_MESSAGE, path)\n }\n if (!result.ok) {\n const reason = redactErrorMessage(result.reason)\n logAttachmentStorageError(logger, '[attachment-upload] stream write rejected', { path, error: reason })\n return attachmentUploadError(413, 'attachment_write_failed', reason, path)\n }\n const sniff = finalSniff!\n const uploaded: ChatAttachmentInput = {\n path,\n name,\n size: declaredBytes,\n mediaType: sniff.mime ?? sniffMime(name),\n kind: attachmentKindForMime(sniff.mime ?? ''),\n }\n return Response.json({ files: [uploaded] })\n }\n return { streamRawUpload }\n}\n\nasync function prepareUploadBatch(\n files: File[],\n allowedSniffedMimes: ReadonlySet<string>,\n allowedKinds: ChatAttachmentKind[],\n limitFor: (sniff: SniffResult) => number,\n pathFor: (name: string) => string,\n atomic: boolean,\n createWriteId: (() => string) | undefined,\n logger: AttachmentUploadLogger,\n validatePath: (path: string) => AttachmentPathCheck,\n maxTotalBytes: number,\n sniffMime: (name: string) => string,\n) {\n // Phase 1: validate every file and prepare its write input WITHOUT\n // writing anything. A batch fails atomically — any file's validation\n // error must reject the whole request before an earlier file in the\n // same batch is persisted.\n const prepared: PreparedWrite[] = []\n const seenLogicalPaths = new Set<string>()\n let totalBytes = 0\n\n for (const file of files) {\n const bytes = new Uint8Array(await file.arrayBuffer())\n const sniff = sniffBinary(bytes)\n // Attachment paths double as store keys, so the stored name must fit\n // the store charset; the as-uploaded name survives as `originalName`.\n const name = sanitizeAttachmentFileName(file.name)\n\n const typeCheck = checkAttachmentType(name, sniff, allowedSniffedMimes)\n if (!typeCheck.succeeded) {\n return attachmentUploadError(\n typeCheck.code === 'attachment_type_mismatch' ? 400 : 415,\n typeCheck.code,\n typeCheck.message,\n )\n }\n\n const kind = attachmentKindForMime(sniff.mime ?? '')\n if (!allowedKinds.includes(kind)) {\n return attachmentUploadError(\n 415,\n 'attachment_kind_not_allowed',\n `${name} is a \"${kind}\" attachment, which this upload route does not accept`,\n )\n }\n\n const limit = limitFor(sniff)\n if (bytes.length > limit) {\n return attachmentUploadError(\n 413,\n 'attachment_too_large',\n attachmentSizeErrorMessage(name, bytes.length, limit),\n )\n }\n\n const logicalPath = pathFor(name)\n let ownershipId: string | undefined\n let path = logicalPath\n if (atomic) {\n try {\n ownershipId = createWriteId!()\n path = immutableAttachmentPath(logicalPath, ownershipId)\n } catch (error) {\n logAttachmentStorageError(logger, '[attachment-upload] could not allocate ownership key', {\n path: logicalPath,\n error: redactErrorMessage(error),\n })\n return attachmentUploadError(\n 503,\n 'attachment_store_unavailable',\n ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n logicalPath,\n )\n }\n }\n const pathCheck = validatePath(path)\n if (!pathCheck.succeeded) {\n return attachmentUploadError(400, 'invalid_attachment_path', pathCheck.error, path)\n }\n // Small hardening over gtm: a batch whose sanitized names collide onto\n // the same store path (e.g. two variously-cased \"Report.PDF\" uploads)\n // would otherwise silently overwrite one with the other in phase 2.\n const duplicatePath = atomic ? logicalPath : path\n if (seenLogicalPaths.has(duplicatePath)) {\n return attachmentUploadError(\n 400,\n 'attachment_duplicate_path',\n `attachments must not repeat a path within one upload: ${duplicatePath}`,\n path,\n )\n }\n seenLogicalPaths.add(duplicatePath)\n\n // Authoritative aggregate check, against the actual decoded byte\n // length rather than the client-reported `file.size` checked above.\n totalBytes += bytes.length\n if (totalBytes > maxTotalBytes) {\n return attachmentUploadError(\n 413,\n 'attachments_total_too_large',\n attachmentTotalSizeErrorMessage(totalBytes, maxTotalBytes),\n )\n }\n\n const mediaType = sniff.mime ?? sniffMime(name)\n prepared.push({ path, ownershipId, name, bytes, originalName: file.name, size: bytes.length, mediaType, kind })\n }\n return { prepared }\n}\n\nasync function commitUploadBatch(\n prepared: PreparedWrite[],\n legacyWriter: WriteAttachmentFn | undefined,\n auth: { ok: true; scopeId: string; writeAttachment?: WriteAttachmentFn; writeAttachmentStream?: WriteAttachmentStreamFn } | { ok: true; scopeId: string; attachmentWriter?: AtomicAttachmentWriter },\n atomicWriter: AtomicAttachmentWriter | undefined,\n atomic: boolean,\n logger: AttachmentUploadLogger,\n) {\n // Phase 2: every file in the batch passed validation — write them all.\n const uploaded: ChatAttachmentInput[] = []\n const successfulWrites: SuccessfulAttachmentWrite[] = []\n for (const input of prepared) {\n if (!atomic) {\n let written: unknown\n try {\n written = await legacyWriter!(auth.scopeId, input.path, input.bytes, {\n mediaType: input.mediaType,\n name: input.name,\n originalName: input.originalName,\n size: input.size,\n })\n } catch (error) {\n logAttachmentStorageError(logger, '[attachment-upload] legacy writer failed', {\n path: input.path,\n error: redactErrorMessage(error),\n })\n return attachmentUploadError(\n 503,\n 'attachment_store_unavailable',\n ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n input.path,\n )\n }\n const result = inspectLegacyAttachmentWriteResult(written)\n if (!result) {\n logAttachmentStorageError(logger, '[attachment-upload] legacy writer returned an invalid result', {\n path: input.path,\n })\n return attachmentUploadError(\n 503,\n 'attachment_store_unavailable',\n ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n input.path,\n )\n }\n if (!result.ok) {\n const reason = redactErrorMessage(result.reason)\n logAttachmentStorageError(logger, '[attachment-upload] legacy write rejected', {\n path: input.path,\n error: reason,\n })\n return attachmentUploadError(413, 'attachment_write_failed', reason, input.path)\n }\n uploaded.push({\n path: input.path,\n name: input.name,\n size: input.size,\n mediaType: input.mediaType,\n kind: input.kind,\n })\n continue\n }\n\n const ownershipId = input.ownershipId\n if (!ownershipId) {\n return attachmentUploadError(503, 'attachment_store_unavailable', ATTACHMENT_STORAGE_FAILURE_MESSAGE, input.path)\n }\n const ownership: AttachmentWriteOwnership = Object.freeze({ id: ownershipId, path: input.path })\n let written: Awaited<ReturnType<AtomicAttachmentWriter['write']>>\n try {\n written = await atomicWriter!.write(auth.scopeId, input.path, input.bytes, {\n mediaType: input.mediaType,\n name: input.name,\n originalName: input.originalName,\n size: input.size,\n ownership,\n })\n } catch (error) {\n const cleanupFailures = (await abortOwnership(atomicWriter!, auth.scopeId, ownership, logger)) +\n await rollbackSuccessfulWrites(successfulWrites, auth.scopeId, atomicWriter!, logger)\n logAttachmentStorageError(logger, '[attachment-upload] write failed', {\n path: input.path,\n ownershipId: ownership.id,\n cleanupFailures,\n error: redactErrorMessage(error),\n })\n return atomicAttachmentFailure(input.path, cleanupFailures)\n }\n const result = inspectAtomicAttachmentWriteResult(written, ownership)\n if (!result) {\n const cleanupFailures = (await abortOwnership(atomicWriter!, auth.scopeId, ownership, logger)) +\n await rollbackSuccessfulWrites(successfulWrites, auth.scopeId, atomicWriter!, logger)\n logAttachmentStorageError(logger, '[attachment-upload] writer returned a mismatched ownership receipt', {\n path: input.path,\n ownershipId: ownership.id,\n cleanupFailures,\n })\n return atomicAttachmentFailure(input.path, cleanupFailures)\n }\n if (!result.ok) {\n const cleanupFailures = (await rollbackSuccessfulWrites([\n { path: input.path, ownership, receipt: result.receipt },\n ], auth.scopeId, atomicWriter!, logger)) + await rollbackSuccessfulWrites(\n successfulWrites,\n auth.scopeId,\n atomicWriter!,\n logger,\n )\n logAttachmentStorageError(logger, '[attachment-upload] write rejected', {\n path: input.path,\n ownershipId: ownership.id,\n cleanupFailures,\n error: redactErrorMessage(result.reason),\n })\n return atomicAttachmentFailure(input.path, cleanupFailures)\n }\n successfulWrites.push({ path: input.path, ownership, receipt: result.receipt })\n uploaded.push({\n path: input.path,\n name: input.name,\n size: input.size,\n mediaType: input.mediaType,\n kind: input.kind,\n })\n }\n\n return Response.json({ files: uploaded })\n}\n","import type { IntelligenceClient } from '@tangle-network/agent-runtime/intelligence'\nimport type { ChatTurnRouteProducer } from './turn-routes'\nimport { withProducerStream } from './producer-stream'\n\n/** Host-resolved metadata only. Neither input nor output content is exported. */\nexport interface ChatTurnIntelligenceOptions {\n client: () => Pick<IntelligenceClient, 'traceRun'>\n sessionId: string\n userId?: string\n workspaceId?: string\n /** Exact execution identity, when retained by the execution owner. */\n runId?: string\n traceId?: string\n /** Requested model. This is not a receipt for the model that served. */\n model?: string\n /** Existing transport cancellation evidence; grants no new abort authority. */\n signal?: AbortSignal\n /** Receives no exception text, which may contain private customer material. */\n onObservationError?: () => void\n}\n\n/**\n * Observe the source iterator without an execution loop, relay, queue or eager\n * pull. The source still owns cancellation and serializes its own operations.\n * Stream termination is not task correctness, reviewer acceptance or delivery.\n */\nexport function observeChatTurnStream<TEvent>(\n source: AsyncGenerator<TEvent, void, unknown>,\n options: ChatTurnIntelligenceOptions,\n): AsyncGenerator<TEvent, void, unknown> {\n const { client, sessionId, userId, workspaceId, runId, traceId, model, signal, onObservationError } = options\n let state: 'idle' | 'running' | 'terminal' = 'idle'\n let startedAt = 0\n let interrupted = false\n let observation: Promise<void> | undefined\n\n const finish = (termination: 'exhausted' | 'interrupted' | 'failed'): Promise<void> => {\n if (state !== 'running') return observation ?? Promise.resolve()\n state = 'terminal'\n const completedAt = Date.now()\n const observedTermination = signal?.aborted ? 'interrupted' : termination\n observation = Promise.resolve().then(async () => {\n await client().traceRun({\n ...(runId !== undefined ? { runId } : {}),\n ...(traceId !== undefined ? { traceId } : {}),\n ...(model !== undefined ? { model } : {}),\n labels: {\n 'tangle.sessionId': sessionId,\n ...(userId !== undefined ? { 'tangle.userId': userId } : {}),\n ...(workspaceId !== undefined ? { 'tangle.workspaceId': workspaceId } : {}),\n 'tangle.observation.kind': 'stream-lifecycle',\n 'tangle.stream.termination': observedTermination,\n 'tangle.started_at_ms': startedAt,\n 'tangle.completed_at_ms': completedAt,\n 'tangle.duration_ms': Math.max(0, completedAt - startedAt),\n },\n }, async () => undefined)\n }).catch(() => {\n // Even a diagnostic callback must not replace an execution error.\n try { onObservationError?.() } catch { /* Best-effort telemetry only. */ }\n })\n return observation\n }\n\n const invoke = async (\n method: 'next' | 'return' | 'throw',\n operation: () => ReturnType<typeof source.next>,\n ): Promise<Awaited<ReturnType<typeof source.next>>> => {\n if (state === 'idle') {\n // A pre-start close still reaches the source to release factory-owned\n // resources, but does not manufacture an executed-turn observation.\n if (method === 'next') {\n state = 'running'\n startedAt = Date.now()\n } else {\n state = 'terminal'\n }\n }\n try {\n const result = await operation()\n // Apply return intent in source settlement order. A queued return must\n // not relabel an earlier naturally completed next() as cancellation.\n if (method === 'return' && state === 'running') interrupted = true\n if (result.done) await finish(interrupted ? 'interrupted' : 'exhausted')\n return result\n } catch (error) {\n await finish('failed')\n throw error\n }\n }\n\n return {\n [Symbol.asyncIterator]() { return this },\n next(...args) { return invoke('next', () => source.next(...args)) },\n return(value) { return invoke('return', () => source.return(value)) },\n throw(error) { return invoke('throw', () => source.throw(error)) },\n async [Symbol.asyncDispose]() { await this.return(undefined) },\n }\n}\n\n/**\n * Adapter for product producer factories. It preserves every declared\n * ChatTurnRouteProducer projection, lazily bound to the original receiver,\n * including class-backed or frozen producers. No output is read.\n */\nexport async function produceChatTurnWithIntelligence(\n options: ChatTurnIntelligenceOptions & {\n produce: () => ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>\n },\n): Promise<ChatTurnRouteProducer> {\n // Freeze scalar metadata before an asynchronous producer can change context.\n const snapshot: ChatTurnIntelligenceOptions = { ...options }\n const producer = await options.produce()\n const stream = observeChatTurnStream(producer.stream, snapshot)\n return withProducerStream(producer, stream)\n}\n","import { assertSafeKeySegment, type ObjectBody, type ObjectStore } from '../object-store'\nimport type { ReadAttachmentFn, WriteAttachmentFn } from './attachment-store'\nimport { defaultValidateAttachmentPath } from './attachment-validation'\n\n/** A product supplies its private object store after its request bindings are ready. */\nexport interface StoredChatAttachmentsOptions {\n store: ObjectStore | (() => ObjectStore)\n}\n\n/** Scoped stored bytes behind the existing chat attachment reader and writer ports.\n * Authorization remains in the product's routes; these functions validate storage keys.\n * The writer preserves the stable non-atomic port and does not promise batch rollback.\n */\nexport interface StoredChatAttachments {\n readAttachment: ReadAttachmentFn\n writeAttachment: WriteAttachmentFn\n getAttachmentObject(scopeId: string, path: string): Promise<ObjectBody | null>\n attachmentObjectKey(scopeId: string, path: string): string\n}\n\nfunction decodeAttachmentBase64(value: string): Uint8Array {\n const binary = atob(value)\n return Uint8Array.from(binary, (character) => character.charCodeAt(0))\n}\n\n/** Bind durable object storage without capturing an uninitialized request binding. */\nexport function createStoredChatAttachments(options: StoredChatAttachmentsOptions): StoredChatAttachments {\n const store = (): ObjectStore => typeof options.store === 'function' ? options.store() : options.store\n const attachmentObjectKey = (scopeId: string, path: string): string => {\n const scope = assertSafeKeySegment(scopeId)\n const checked = defaultValidateAttachmentPath(path)\n if (!checked.succeeded) throw new Error(checked.error)\n return `${scope}/${path}`\n }\n const getAttachmentObject = async (scopeId: string, path: string): Promise<ObjectBody | null> =>\n store().get(attachmentObjectKey(scopeId, path))\n\n const writeAttachment: WriteAttachmentFn = async (scopeId, path, content, opts) => {\n let bytes: Uint8Array\n let key: string\n try {\n bytes = typeof content === 'string' ? decodeAttachmentBase64(content) : content\n if (opts.size !== undefined && opts.size !== bytes.byteLength) {\n return { ok: false, reason: `Attachment size mismatch for ${path}: expected ${opts.size}, received ${bytes.byteLength}` }\n }\n key = attachmentObjectKey(scopeId, path)\n } catch (error) {\n return { ok: false, reason: `Attachment write failed for ${path}: ${error instanceof Error ? error.message : String(error)}` }\n }\n // Validation refusals use the legacy result; storage outages must reach\n // the route's opaque, retryable 503 response rather than its 413 refusal.\n await store().put(key, bytes, {\n ...(opts.mediaType ? { contentType: opts.mediaType } : {}),\n contentLength: bytes.byteLength,\n })\n return { ok: true }\n }\n\n const readAttachment: ReadAttachmentFn = async (scopeId, path) => {\n try {\n const object = await getAttachmentObject(scopeId, path)\n if (!object) return { ok: false, reason: `Attachment not found: ${path}` }\n const bytes = new Uint8Array(await new Response(object.stream()).arrayBuffer())\n if (bytes.byteLength !== object.size) {\n return { ok: false, reason: `Attachment size mismatch for ${path}: metadata ${object.size}, body ${bytes.byteLength}` }\n }\n return {\n ok: true,\n size: bytes.byteLength,\n bytes,\n ...(object.contentType ? { mediaType: object.contentType } : {}),\n }\n } catch (error) {\n return { ok: false, reason: `Attachment read failed for ${path}: ${error instanceof Error ? error.message : String(error)}` }\n }\n }\n return { readAttachment, writeAttachment, getAttachmentObject, attachmentObjectKey }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAM,sBAA2C,o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AI,KAAK;AAAA,EACpB;AAEA,QAAM,iBAAmC,OAAO,SAAS,SAAS;AAChE,QAAI;AACF,YAAM,SAAS,MAAM,oBAAoB,SAAS,IAAI;AACtD,UAAI,CAAC,OAAQ,QAAO,EAAE,IAAI,OAAO,QAAQ,yBAAyB,IAAI,GAAG;AACzE,YAAM,QAAQ,IAAI,WAAW,MAAM,IAAI,SAAS,OAAO,OAAO,CAAC,EAAE,YAAY,CAAC;AAC9E,UAAI,MAAM,eAAe,OAAO,MAAM;AACpC,eAAO,EAAE,IAAI,OAAO,QAAQ,gCAAgC,IAAI,cAAc,OAAO,IAAI,UAAU,MAAM,UAAU,GAAG;AAAA,MACxH;AACA,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM,MAAM;AAAA,QACZ;AAAA,QACA,GAAI,OAAO,cAAc,EAAE,WAAW,OAAO,YAAY,IAAI,CAAC;AAAA,MAChE;AAAA,IACF,SAAS,OAAO;AACd,aAAO,EAAE,IAAI,OAAO,QAAQ,8BAA8B,IAAI,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,GAAG;AAAA,IAC9H;AAAA,EACF;AACA,SAAO,EAAE,gBAAgB,iBAAiB,qBAAqB,oBAAoB;AACrF;","names":["parts","written","result","sniff","written","result"]}
1
+ {"version":3,"sources":["../../src/chat-routes/protected-runtime-producer.ts","../../src/chat-routes/detached-turn.ts","../../src/chat-routes/plan-follow-up.ts","../../src/chat-routes/durable-projection.ts","../../src/chat-routes/attachment-store.ts","../../src/chat-routes/resolve-attachments.ts","../../src/chat-routes/attachment-write-safety.ts","../../src/chat-routes/promote-file-part.ts","../../src/chat-routes/attachment-upload.ts","../../src/chat-routes/intelligence.ts","../../src/chat-routes/stored-attachments.ts"],"sourcesContent":["import type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runProtectedRouterTurn, type RouterTurnGrant } from '../runtime/protected-router-turn'\nimport type { RouterTurnOptions } from '../runtime/router-turn'\nimport type { McpToolDefinition } from '../tools/mcp-rpc'\nimport { createSandboxChatProducer } from './sandbox-producer'\nimport type { ChatTurnRouteProducer, ChatTurnUsage } from './turn-routes'\n\nexport interface ProtectedRuntimeChatOptions {\n profile: AgentProfile\n prompt: string\n priorMessages?: ReadonlyArray<{ role: string; content: string }>\n /** Runtime owns reservation, activation, revocation and authoritative settlement. */\n grant: RouterTurnGrant\n /** Only tools authorized for this execution. Each tool validates its arguments and effects. */\n tools: readonly McpToolDefinition<{ signal: AbortSignal }>[]\n maxToolCalls: number\n signal?: AbortSignal\n}\n\n/** Refuse unsupported profile leaves by name instead of silently dropping them. */\nconst PROTECTED_TURN_AXES: ReadonlySet<string> = new Set([\n 'name', 'description', 'version', 'tags', 'metadata', 'harness', 'tools',\n 'systemPrompt', 'instructions',\n 'modelDefault', 'modelProvider', 'modelReasoningEffort', 'modelMaxVisibleOutputTokens',\n 'modelMaxTotalOutputTokens', 'modelMetadata',\n])\n\nfunction protectedTurnSettings(profile: AgentProfile, toolNames: ReadonlySet<string>,\n profileMaterializationAxes: typeof import('@tangle-network/agent-interface').profileMaterializationAxes): Pick<RouterTurnOptions,\n 'model' | 'systemPrompt' | 'reasoningEffort' | 'maxTokens' | 'maxCompletionTokens'> {\n if (profile.harness && profile.harness !== 'cli-base') throw new Error(`Protected chat runs only the cli-base harness, not ${profile.harness}`)\n if (profile.resources) throw new Error('Protected chat applies prompt text only; run profile resources in the Sandbox lane')\n if (profile.model?.metadata && Object.keys(profile.model.metadata).length > 0) {\n throw new Error('Protected chat does not apply AgentProfile.model.metadata')\n }\n if (profile.model?.maxReasoningTokens !== undefined) throw new Error('Protected chat cannot enforce maxReasoningTokens')\n const unsupported = profileMaterializationAxes(profile).filter(axis => !PROTECTED_TURN_AXES.has(axis))\n if (unsupported.length > 0) {\n throw new Error(`Protected chat does not apply AgentProfile ${unsupported.join(', ')}; run this profile in the Sandbox lane`)\n }\n const declared = profile.model?.default?.trim()\n const provider = profile.model?.provider?.trim()\n const model = declared && provider && declared.startsWith(`${provider}/`) ? declared.slice(provider.length + 1) : declared\n if (!model) throw new Error('Protected chat requires AgentProfile.model.default')\n for (const [name, enabled] of Object.entries(profile.tools ?? {})) {\n if (enabled !== toolNames.has(name)) throw new Error(`Protected tool ${name} does not match AgentProfile.tools`)\n }\n for (const name of toolNames) {\n if (profile.tools?.[name] !== true) throw new Error(`Protected tool ${name} is not enabled by AgentProfile.tools`)\n }\n const { visible, total } = { visible: profile.model?.maxVisibleOutputTokens, total: profile.model?.maxTotalOutputTokens }\n return {\n model,\n systemPrompt: [profile.prompt?.systemPrompt, ...(profile.prompt?.instructions ?? [])]\n .filter((part): part is string => typeof part === 'string' && part.trim().length > 0).join('\\n'),\n ...(profile.model?.reasoningEffort ? { reasoningEffort: profile.model.reasoningEffort } : {}),\n ...(visible !== undefined ? { maxTokens: visible } : {}),\n ...(total !== undefined ? { maxCompletionTokens: total } : {}),\n }\n}\n\n/** Project one protected Router turn, publishing usage only from its settled grant. */\nexport function createProtectedRuntimeChatProducer(options: ProtectedRuntimeChatOptions): ChatTurnRouteProducer {\n if (!Number.isSafeInteger(options.maxToolCalls) || options.maxToolCalls < 0) throw new Error('maxToolCalls must be a non-negative integer')\n options = { ...options,\n grant: { ...options.grant, resolve: structuredClone(options.grant.resolve), reserve: structuredClone(options.grant.reserve) },\n tools: options.tools.map(tool => ({ ...tool, inputSchema: structuredClone(tool.inputSchema) })),\n // Providers reject the storage fields carried by chat history rows.\n priorMessages: options.priorMessages?.map(({ role, content }) => ({ role, content })),\n }\n const tools = new Set(options.tools.map(tool => tool.name))\n if (tools.size !== options.tools.length) throw new Error('Duplicate protected tool name')\n const profile = structuredClone(options.profile)\n let toolCalls = 0\n let usage: ChatTurnUsage = {}\n let started = false\n let model: string | undefined\n const controller = new AbortController()\n const pendingTools = new Set<Promise<unknown>>()\n let execution: Promise<void> | undefined\n let reader: ReadableStreamDefaultReader<unknown> | undefined\n let writer: WritableStreamDefaultWriter<unknown> | undefined\n let terminalObserved = false\n let closing: Promise<void> | undefined\n\n // Local completion requires drained execution and tool effects, not a projected result.\n function close(reason?: unknown): Promise<void> {\n controller.abort(reason)\n closing ??= (async () => {\n const errors: unknown[] = []\n try { await reader?.cancel() } catch (error) { errors.push(error) }\n try { await execution } catch (error) { errors.push(error) }\n while (pendingTools.size) await Promise.allSettled([...pendingTools])\n try { reader?.releaseLock() } catch (error) { errors.push(error) }\n try { writer?.releaseLock() } catch (error) { errors.push(error) }\n terminalObserved = true\n if (errors.length) throw errors[0]\n })()\n return closing\n }\n\n async function* events(): AsyncGenerator<unknown> {\n if (started) throw new Error('A protected chat producer can only execute once')\n started = true\n try {\n controller.signal.throwIfAborted()\n options.signal?.throwIfAborted()\n if (Date.now() >= options.grant.deadlineAtMs) throw new Error('Protected execution deadline expired')\n const signal = AbortSignal.any([\n controller.signal, AbortSignal.timeout(Math.max(1, options.grant.deadlineAtMs - Date.now())),\n ...(options.signal ? [options.signal] : []),\n ])\n const channel = new TransformStream<unknown, unknown>()\n const channelWriter = writer = channel.writable.getWriter()\n reader = channel.readable.getReader()\n const emit = (event: unknown) => channelWriter.write(event)\n // The agent-interface root initializes every schema; only a protected turn needs it, so it loads here.\n const { profileMaterializationAxes } = await import('@tangle-network/agent-interface')\n let settings: ReturnType<typeof protectedTurnSettings>\n // A profile this lane cannot run is a refusal that fails the same way again: the person reads its class sentence.\n try {\n settings = protectedTurnSettings(profile, tools, profileMaterializationAxes)\n } catch (error) {\n throw Object.assign(error as Error, { code: 'profile_unsupported' })\n }\n execution = runProtectedRouterTurn({\n ...settings,\n grant: options.grant,\n userMessage: options.prompt,\n history: [...(options.priorMessages ?? [])],\n signal,\n // The grant's ledger expects one buffered completion per model call.\n stream: false,\n maxToolCalls: options.maxToolCalls,\n maxToolTurns: options.grant.reserve.limits.maxModelCalls,\n // A tool definition here cannot declare an effect, so every tool is a lookup: the lane keeps main's rule.\n tools: options.tools.map(tool => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema, effect: 'lookup' as const,\n run: (args: Record<string, unknown>) => {\n const work = (async () => {\n signal.throwIfAborted()\n toolCalls += 1\n const id = `tool-${toolCalls}`\n await emit({ type: 'tool_call', data: { id, name: tool.name, arguments: args } })\n signal.throwIfAborted()\n try {\n const result = await tool.run(args, { signal })\n await emit({ type: 'tool_result', data: { id, name: tool.name, output: result } })\n return result\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Tool failed'\n await emit({ type: 'tool_result', data: { id, name: tool.name, error: message } })\n throw error\n }\n })()\n pendingTools.add(work)\n void work.then(() => pendingTools.delete(work), () => pendingTools.delete(work))\n return work\n } })),\n toolError: error => ({ code: 'tool_failed', message: error instanceof Error ? error.message : 'Tool failed' }),\n renderToolResult: (_toolName, outcome) => outcome.ok ? JSON.stringify(outcome.result) ?? 'null' : `error: ${outcome.message}`,\n }).then(async outcome => {\n if (outcome.settlement) {\n usage = { ...outcome.settlement.usage }\n model = outcome.settlement.model\n // Tool-result text is billed as input under a grant.\n await emit({ type: 'usage', usage: { promptTokens: usage.inputTokens,\n completionTokens: usage.outputTokens, providerCostUsd: usage.costUsd,\n reasoningTokens: usage.reasoningTokens, toolTokens: 0,\n toolCallCount: toolCalls, budgetEnforced: outcome.settlement.budgetEnforced } })\n }\n // A settlement check fails after the turn answered; the answer stands beside the failure.\n if (!outcome.failure || outcome.failure.code.startsWith('settlement_')) {\n // The Router turn's own answer rule, so this lane and the Router lane store the same final text.\n const finalText = outcome.answer\n if (finalText) await emit({ type: 'message.part.updated', data: { part: { id: 'text_delta', type: 'text' }, delta: finalText } })\n await emit({ type: 'result', data: { finalText } })\n }\n // The code goes with the message, so a refusal reads its class sentence and a runtime failure is withheld.\n if (outcome.failure) throw Object.assign(new Error(outcome.failure.message), { code: outcome.failure.code })\n await channelWriter.close()\n }).catch(error => channelWriter.abort(error))\n for (;;) {\n const next = await reader.read()\n if (next.done) break\n yield next.value\n }\n } finally {\n await close()\n }\n }\n\n const producer = createSandboxChatProducer({ events: events(), model: profile.model?.default, errorNotice: true })\n const stream = producer.stream\n // Even return/throw before the first pull must abort and drain local work.\n const end = stream.return.bind(stream)\n const fail = stream.throw.bind(stream)\n stream.return = async value => {\n const stopped = close(new Error('The chat route stopped reading this turn'))\n void stopped.catch(() => undefined)\n try { return await end(value) } finally { await stopped }\n }\n stream.throw = async error => {\n const stopped = close(error)\n void stopped.catch(() => undefined)\n try { return await fail(error) } finally { await stopped }\n }\n return {\n ...producer,\n stream,\n terminalObserved: () => terminalObserved,\n get model() { return model ?? profile.model?.default },\n usage: () => ({ ...usage }),\n }\n}\n","/**\n * Detached (autonomous) turn → live buffer bridge.\n *\n * The interactive lane (`createChatTurnRoutes`) already streams a user-typed\n * turn to the browser while it runs. An AUTONOMOUS turn — a mission step, a\n * queue job, an inbound-email review — runs detached (`dispatchPrompt`/\n * `streamPrompt` server-side so it survives no one watching) and, historically,\n * only persisted its FINAL message. A browser opening the session mid-run saw a\n * dead screen: the live tokens existed server-side but were never written to\n * the turn-event buffer the client re-attach path (`listRunning` + `/replay`)\n * reads.\n *\n * `runDetachedTurn` is that missing bridge, packaged. It taps the same buffer\n * the interactive lane uses (`createBufferedTurnTap`) with the same producer\n * mapping (`createSandboxChatProducer`), so an autonomous run is watchable\n * token-by-token exactly like an interactive one — while staying durable\n * (a durable driver re-invokes it after a crash; a turn that finished\n * server-side short-circuits instead of re-streaming). Products supply only the\n * domain seams: the raw sandbox event stream, the turn store, and the ids.\n *\n * This is app-shell mechanism (turn durability + live projection), not engine:\n * it owns no loop logic and imports no SDK — the event source is an injected\n * `AsyncIterable`.\n */\n\nimport { toChatMessageParts } from '../chat-store/parts'\nimport type { ModelFailoverAttempt } from '../model-resolution/failover'\nimport {\n coalesceDeltas,\n createBufferedTurnTap,\n type TurnEventStore,\n} from '../stream/index'\nimport {\n assistantRowIdForTurn,\n createAssistantDraftWriter,\n storeSupportsDraftPersistence,\n type AssistantDraftStore,\n type AssistantDraftWriter,\n type AssistantRowValues,\n type DraftStoredMessage,\n type DraftPersistenceTuning,\n} from './draft-persistence'\nimport {\n createSandboxChatProducer,\n type SandboxChatProducerOptions,\n} from './sandbox-producer'\nimport type { ChatTurnUsage } from './turn-routes'\nimport { measuredUsage, TURN_USAGE_KEYS } from './sandbox-turn-usage'\nimport { transformVisibleTextParts } from './visible-text'\n\n/** The normalized structured message body (tool-call / file / plan / interaction\n * parts) that `/chat-store` persists as the durable assistant row — the same\n * shape `createSandboxChatProducer().assistantParts()` returns. */\nexport type DetachedTurnParts = Array<Record<string, unknown>>\n\n/** Authoritative final receipt for a turn that finished server-side, or whose\n * live stream carried no usage (some harness paths only expose tokens via the\n * completed-turn record, e.g. `box.findCompletedTurn(turnId)`). */\nexport interface DetachedTurnFinal {\n text?: string\n usage?: ChatTurnUsage\n /** The structured parts to persist when this receipt is more complete than\n * the live stream (cached, finished server-side, or a fast stream that\n * delivered scalar text before its message-part events). Omitted when the\n * record only carries a usage receipt. */\n parts?: DetachedTurnParts\n}\n\n/** Define options for managing and projecting a detached turn event stream in a session */\nexport interface DetachedTurnOptions {\n store: TurnEventStore\n turnId: string\n /** Thread/session id — recorded as the buffer scope so a browser opening the\n * session mid-run rediscovers this turn via `listRunning(scopeId)` after it\n * has lost the turnId. */\n scopeId: string\n /** The raw sandbox event stream for this turn (e.g. `streamSandboxPrompt`).\n * Ownership of the box, prompt, tooling, and attachments stays with the\n * caller — this only projects the stream.\n *\n * An already-open stream is bound to one model and cannot fail over. Prefer\n * {@link openEvents}; exactly one of the two is required. */\n events?: AsyncIterable<unknown>\n /** Open the raw sandbox stream FOR A GIVEN MODEL — the failover-capable form\n * of {@link events}. Wiring it turns failover on with no further flag\n * whenever {@link fallbackModels} is non-empty. Requires {@link model}.\n *\n * An autonomous run is the case that most needs this: nobody is watching to\n * notice a dead upstream and retry by hand, so without failover the mission\n * step or queue job simply fails. Forwarded to the producer. */\n openEvents?: SandboxChatProducerOptions['openEvents']\n /** Models to try, in order, when `model`'s upstream is dead. Product config —\n * see the producer's note on why a same-family fallback is not automatically\n * safe and why every fallback is surfaced. */\n fallbackModels?: SandboxChatProducerOptions['fallbackModels']\n /** Opt out of failover while still using {@link openEvents}. */\n modelFailover?: false\n /** Maximum time to open/start one model event source through its first event.\n * Forwarded to the producer; default 120 seconds. */\n openTimeoutMs?: SandboxChatProducerOptions['openTimeoutMs']\n /** Hard deadline after the source's first lifecycle event for the first\n * answer-bearing event. Forwarded to the producer; default 60 seconds when\n * the chain has a model to fail over to, none for a one-model chain. */\n firstResponseTimeoutMs?: SandboxChatProducerOptions['firstResponseTimeoutMs']\n /** Fired when a model is abandoned mid-chain (telemetry/alerting). */\n onModelFallback?: SandboxChatProducerOptions['onModelFallback']\n /** The PREFERRED model. Recorded on the persisted assistant message + usage\n * receipt — unless failover moved the turn, in which case the model that\n * actually served is recorded instead and surfaced on the result. */\n model?: string\n /** Per-flush buffer coalescer. Default `coalesceDeltas`. */\n coalesce?: (events: unknown[]) => unknown[]\n /** Which ask kinds the product renders a card for; anything else is\n * auto-declined via {@link declineInteraction}. Forwarded to the producer. */\n isRenderableInteraction?: SandboxChatProducerOptions['isRenderableInteraction']\n /** Resolve a non-renderable ask so the run never hangs in the broker. An\n * autonomous turn has NO human watching to answer an ask, so a caller that\n * omits this risks the run blocking until the broker times out — wire it for\n * any unattended run. Forwarded to the producer. */\n declineInteraction?: SandboxChatProducerOptions['declineInteraction']\n /** Opt-in eager promotion of harness-emitted `file` parts. Forwarded to the\n * producer (see its docs). */\n promoteFilePart?: SandboxChatProducerOptions['promoteFilePart']\n /** What the person reads for a failure whose reason is withheld. Forwarded to the producer. */\n failedTurnText?: SandboxChatProducerOptions['failedTurnText']\n /** Authoritative final receipt, consulted whenever a re-invoke finds a prior\n * buffer: (a) an already-`complete` turn returns it as the cached result,\n * (b) a `running` turn (crash mid-run) uses it to detect a run that finished\n * server-side, and (c) a clean run whose stream carried no usage or only\n * scalar text falls back to it. For Sandbox runs, use\n * `readCompletedSandboxTurn` so the exact completed session message\n * restores tool/file parts as well as text. */\n completedResult?: () => Promise<DetachedTurnFinal | null | undefined>\n /** Own the durable assistant row for this turn instead of returning the body\n * for the caller to insert — and keep it in step with the stream.\n *\n * An autonomous run is exactly the case a late viewer hits: nobody is\n * watching when it starts, so by the time a browser opens the session the\n * streaming gateway's hot event buffer may already have expired it. Keeping\n * that buffer short is what makes it affordable at scale (its Redis\n * footprint is linear in `ttl x concurrent sessions`), so the durable row —\n * written incrementally here — is what serves the late viewer.\n *\n * WIRING THIS TRANSFERS ROW OWNERSHIP: the returned {@link\n * DetachedTurnResult.messageId} names the row this call wrote (draft rows\n * during the stream, authoritative values at the end, retraction when the\n * turn produced nothing). The caller must NOT insert its own assistant row\n * for the turn. Omit the seam and nothing changes — the result is returned\n * and the caller persists it exactly as today.\n *\n * Idempotency reuses the turn's own identity: the row id defaults to\n * `assistant:<turnId>`, so a durable driver re-invoking after a crash\n * patches the same row instead of duplicating parts. */\n persist?: DraftPersistenceTuning & {\n store: AssistantDraftStore\n threadId: string\n /** Deterministic row id. Default `assistant:<turnId>`. */\n messageId?: string\n /** Pre-persist text transform (`/redact`), applied to drafts AND the final\n * write — parity with the interactive lane's `transformFinalText`. */\n transformText?: (text: string) => string | Promise<string>\n }\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Describe the result of a detached turn including state, text, parts, usage, and optional error or cache flag */\nexport interface DetachedTurnResult {\n /** `completed` — clean drain: persist + bill. `failed` — a terminal error\n * event, including the producer's structured `sandbox.stream_failed` event\n * when the raw sandbox stream throws: skip billing, render an error row. */\n state: 'completed' | 'failed'\n text: string\n /** The structured assistant body to persist (tool calls, file/plan/interaction\n * parts). Empty array when the run produced none. */\n parts: DetachedTurnParts\n usage: ChatTurnUsage\n /** Present when `state === 'failed'`. */\n error?: string\n /** True when a prior buffer meant this call returned a cached/finished result\n * WITHOUT re-streaming (durable-driver retry after a crash). */\n cached: boolean\n /** The durable assistant row this call wrote, when `persist` was wired.\n * `null` when the turn produced nothing and the row was retracted. Absent\n * when the caller owns persistence (today's behavior). */\n messageId?: string | null\n /** The model that SERVED the turn — the fallback's id when failover moved it.\n * A caller that bills or scores per model must read this, not the model it\n * requested. */\n model?: string\n /** The caller's explicit model request, before shell failover. */\n requestedModel?: string\n /** The effective model echoed by the downstream sandbox. */\n servedModel?: string\n /** The effective provider echoed by the downstream sandbox. */\n servedProvider?: string\n /** How the downstream sandbox selected the effective model. */\n servedSource?: 'request' | 'environment' | 'profile'\n /** True when the preferred model did not serve. Makes an autonomous\n * downgrade — which no human watched happen — attributable after the fact. */\n usedModelFallback?: boolean\n /** Every model tried, in order. Each attempt's raw `reason` is server-only; never render or send it to a client. */\n modelAttempts?: ModelFailoverAttempt[]\n}\n\n/** Terminal failure event types a producer may forward verbatim. */\nconst TERMINAL_ERROR_TYPES = new Set(['error', 'session.run.failed'])\n\nfunction errorMessageOf(ev: unknown): string {\n const rec = ev as { data?: { message?: unknown; reason?: unknown }; message?: unknown } | null\n const raw = rec?.data?.message ?? rec?.data?.reason ?? rec?.message\n return typeof raw === 'string' && raw ? raw : 'run failed'\n}\n\nfunction hasUsage(usage: ChatTurnUsage): boolean {\n return typeof usage.inputTokens === 'number' && usage.inputTokens > 0\n}\n\nfunction cachedResultFrom(\n final: DetachedTurnFinal | null,\n persisted?: DraftStoredMessage,\n): DetachedTurnResult {\n if (!final && !persisted) {\n throw new Error('Completed turn has no retained result or assistant row; retry exact recovery')\n }\n // A text-only recovery must not erase usage already stored for this turn.\n // Unknown values stay absent; an explicit measured zero is preserved.\n const usage: ChatTurnUsage = {}\n for (const key of TURN_USAGE_KEYS) {\n const value = final?.usage?.[key] ?? persisted?.[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) usage[key] = value\n }\n return {\n state: 'completed',\n text: final?.text ?? persisted?.content ?? '',\n parts:\n final?.parts ??\n (persisted?.parts as DetachedTurnParts | null | undefined) ??\n [],\n usage,\n cached: true,\n }\n}\n\n/**\n * Stream a detached turn into the live turn-event buffer, durably.\n *\n * - Idempotent: an already-`complete` turn returns the cached result without\n * re-streaming (a second event sequence would collide with the buffered one).\n * - Crash-safe: a `running` turn (a prior attempt crashed mid-tap) consults\n * `completedResult` to detect a run that finished server-side; only a run that\n * genuinely did not complete is re-streamed, and then over a buffer the\n * store's `resetEvents` cleared so seqs don't corrupt. A store without\n * `resetEvents` refuses that re-stream and leaves the existing buffer intact.\n * - Marks the turn `running` under `scopeId` so a mid-run browser finds it.\n * - Settles `complete`/`error` so the client stops tailing and billing/render\n * can branch on `state`.\n */\nexport async function runDetachedTurn(opts: DetachedTurnOptions): Promise<DetachedTurnResult> {\n const { store, turnId, scopeId } = opts\n\n // Hoisted so the draft writer's snapshot can read the producer's live\n // accumulators; assigned once the idempotency branches decide to re-stream.\n let producer: ReturnType<typeof createSandboxChatProducer> | undefined\n\n /** The model that actually served. Read LAZILY (never captured up front): on\n * a cached/finished-server-side path no producer exists and the preferred\n * model is the best available answer, but on a live re-stream failover may\n * have moved the turn after the row was first drafted. */\n const servingModel = (): string | undefined => producer?.model ?? opts.model\n\n const persistedRow = async (): Promise<DraftStoredMessage | undefined> => {\n if (!opts.persist) return undefined\n return (await opts.persist.store.listMessages(opts.persist.threadId)).find(\n (message) =>\n message.id ===\n (opts.persist?.messageId ?? assistantRowIdForTurn(turnId)),\n )\n }\n\n // Durable row ownership (opt-in). Built before the idempotency branches so a\n // cached/finished-server-side re-invoke still converges the row instead of\n // leaving whatever partial state a crashed attempt wrote.\n let draft: AssistantDraftWriter | undefined\n if (opts.persist) {\n const { store: persistStore, threadId, messageId, transformText, ...tuning } = opts.persist\n if (!storeSupportsDraftPersistence(persistStore)) {\n throw new Error(\n 'runDetachedTurn persist requires a store with updateMessage() — `/chat-store`\\'s createChatStore has it',\n )\n }\n draft = createAssistantDraftWriter({\n ...tuning,\n store: persistStore,\n threadId,\n messageId: messageId ?? assistantRowIdForTurn(turnId),\n snapshot: () => (producer\n ? {\n content: producer.finalText?.() ?? '',\n ...(producer.draftParts ? { parts: producer.draftParts() } : {}),\n ...(producer.usage ? { usage: producer.usage() } : {}),\n ...(servingModel() ? { model: servingModel() } : {}),\n }\n : null),\n ...(transformText ? { transformText } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n })\n }\n\n /** Settle the durable row with authoritative values (or retract it when the\n * turn produced nothing), and stamp the id onto the result. */\n const settleRow = async (\n base: DetachedTurnResult,\n cachedPersisted?: DraftStoredMessage,\n ): Promise<DetachedTurnResult> => {\n // A cached/reconciled return has no producer to replay the sidecar echo.\n // Preserve the attribution already written by the prior attempt instead\n // of replacing its served `model` with today's requested-model fallback.\n const persisted =\n cachedPersisted ?? (!producer ? await persistedRow() : undefined)\n const info = producer?.modelFailover?.()\n const attribution = producer?.modelAttribution?.()\n const model = producer?.model ?? persisted?.model ?? opts.model\n const requestedModel = attribution?.requestedModel ?? persisted?.requestedModel ?? opts.model\n const servedModel = attribution?.servedModel ?? persisted?.servedModel\n const servedProvider = attribution?.servedProvider ?? persisted?.servedProvider\n const servedSource = attribution?.servedSource ?? (\n persisted?.servedSource === 'request' ||\n persisted?.servedSource === 'environment' ||\n persisted?.servedSource === 'profile'\n ? persisted.servedSource\n : undefined\n )\n const result: DetachedTurnResult = {\n ...base,\n ...(model ? { model } : {}),\n ...(requestedModel ? { requestedModel } : {}),\n ...(servedModel ? { servedModel } : {}),\n ...(servedProvider ? { servedProvider } : {}),\n ...(servedSource ? { servedSource } : {}),\n ...(info ? { usedModelFallback: info.usedFallback, modelAttempts: info.attempts } : {}),\n }\n if (!draft) return result\n const transform = opts.persist?.transformText\n const content = transform ? await transform(result.text) : result.text\n const rawParts = transform ? await transformVisibleTextParts(result.parts, transform) : result.parts\n const parts = toChatMessageParts(rawParts)\n if (!content.trim() && parts.length === 0) {\n await draft.discard()\n return { ...result, messageId: null }\n }\n const values: AssistantRowValues = {\n content,\n ...(parts.length > 0 ? { parts } : {}),\n ...(result.model ? { model: result.model } : {}),\n ...(result.requestedModel ? { requestedModel: result.requestedModel } : {}),\n ...(result.servedModel ? { servedModel: result.servedModel } : {}),\n ...(result.servedProvider ? { servedProvider: result.servedProvider } : {}),\n ...(result.servedSource ? { servedSource: result.servedSource } : {}),\n ...measuredUsage(result.usage),\n }\n await draft.finalize(values)\n return { ...result, messageId: draft.rowId() ?? null }\n }\n\n const completed = async (): Promise<DetachedTurnFinal | null> => {\n if (!opts.completedResult) return null\n // An unavailable authoritative read must not become a fresh stream.\n return (await opts.completedResult()) ?? null\n }\n\n const prior = await store.getStatus(turnId)\n\n if (prior === 'complete') {\n const persisted = await persistedRow()\n return await settleRow(\n cachedResultFrom(await completed(), persisted),\n persisted,\n )\n }\n\n if (prior === 'running') {\n // A prior attempt marked the turn running and then this worker crashed. The\n // detached SESSION may have finished server-side while we were gone — the\n // authoritative check is `completedResult` (findCompletedTurn). If it\n // completed, settle the stuck `running` buffer and return it.\n const final = await completed()\n if (final) {\n await store.setStatus(turnId, 'complete', scopeId)\n const persisted = await persistedRow()\n return await settleRow(cachedResultFrom(final, persisted), persisted)\n }\n // Genuine re-run: clear the partial buffer first, or the fresh tap's seq\n // (restarting at 0) interleaves with the orphaned rows.\n if (!store.resetEvents) {\n throw new Error('Detached turn recovery requires a TurnEventStore with resetEvents before replaying an existing stream')\n }\n await store.resetEvents(turnId)\n }\n\n const tap = createBufferedTurnTap({\n store,\n turnId,\n scopeId,\n coalesce: opts.coalesce ?? coalesceDeltas,\n })\n // Leading turn marker: flips the buffer to `running` (so `listRunning` finds\n // it) and is the browser's `/replay` resume handle.\n await tap.onEvent({ type: 'turn', turnId })\n\n producer = createSandboxChatProducer({\n ...(opts.openEvents ? { openEvents: opts.openEvents } : { events: opts.events }),\n model: opts.model,\n ...(opts.fallbackModels ? { fallbackModels: opts.fallbackModels } : {}),\n ...(opts.modelFailover === false ? { modelFailover: false as const } : {}),\n ...(opts.openTimeoutMs !== undefined ? { openTimeoutMs: opts.openTimeoutMs } : {}),\n ...(opts.firstResponseTimeoutMs !== undefined\n ? { firstResponseTimeoutMs: opts.firstResponseTimeoutMs }\n : {}),\n ...(opts.onModelFallback ? { onModelFallback: opts.onModelFallback } : {}),\n isRenderableInteraction: opts.isRenderableInteraction,\n declineInteraction: opts.declineInteraction,\n promoteFilePart: opts.promoteFilePart,\n failedTurnText: opts.failedTurnText,\n log: opts.log,\n })\n\n let runError: string | undefined\n try {\n for await (const ev of producer.stream) {\n const type = (ev as { type?: unknown }).type\n if (typeof type === 'string' && TERMINAL_ERROR_TYPES.has(type)) runError = errorMessageOf(ev)\n await tap.onEvent(ev)\n // Same coalesced cadence the interactive lane uses: the durable row\n // tracks the run so a viewer arriving after the hot buffer's short window\n // reads it from storage.\n draft?.notify(ev as { type?: unknown })\n }\n await tap.done(runError ? 'error' : 'complete')\n } catch (err) {\n await tap.done('error').catch(() => {})\n // Settle any in-flight draft before propagating so the partial row a\n // re-invoke will adopt is a complete write, not a half-landed one.\n await draft?.close().catch(() => {})\n throw err\n }\n\n const text = producer.finalText?.() ?? ''\n const parts = producer.assistantParts?.() ?? []\n let usage: ChatTurnUsage = producer.usage?.() ?? {}\n\n // A terminal result can supply scalar text even when the event subscriber\n // missed every structured message part. Reconcile that text-only shape with\n // the durable completion record before final persistence.\n const onlyTextParts = parts.every((part) =>\n String((part as { type?: unknown }).type ?? '') === 'text',\n )\n if (!runError && (!hasUsage(usage) || !text || onlyTextParts)) {\n const final = await completed()\n if (final?.usage) usage = { ...usage, ...final.usage }\n return await settleRow({\n state: 'completed',\n text: final?.text ?? text,\n parts: final?.parts?.length ? final.parts : parts,\n usage,\n cached: false,\n })\n }\n\n if (runError) return await settleRow({ state: 'failed', text, parts, usage, error: runError, cached: false })\n return await settleRow({ state: 'completed', text, parts, usage, cached: false })\n}\n","/**\n * The chat turn that attaches to a decided plan's follow-up execution.\n *\n * Deciding a plan does not run anything in the product. The Sandbox platform\n * enqueues the approved (or revision) execution itself under the turn id\n * `planFollowUpTurnId(planId, revision, outcome)`, and the Sidecar names that\n * execution `plan-followup-<sha256(sessionId \\0 turnId)>`. The browser card then\n * re-enters the chat route with a `planFollowUp` descriptor. That attach is a\n * real turn: it streams, persists an assistant row, and bills. It therefore\n * needs the same single-runner protection as a fresh turn.\n *\n * This module owns that attach: the descriptor check against the persisted\n * plan, the execution identity, the exclusive D1 claim on the `turn_status`\n * row, and the replay-then-follow event stream. Products keep their own\n * authorization, billing, and persistence around it.\n */\nimport { createHash, randomUUID } from 'node:crypto'\nimport type { SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport { persistedPartToPlan, planFollowUpTurnId } from '../plans'\n\n/** The decision a follow-up continues. */\nexport type PlanFollowUpOutcome = 'approved' | 'rejected'\n\n/** The descriptor a decided plan card sends back to the chat route. */\nexport interface PlanFollowUpAttach {\n planId: string\n revision: number\n outcome: PlanFollowUpOutcome\n turnId: string\n}\n\n/** Result of checking a follow-up descriptor against the session's persisted plans. */\nexport type PlanFollowUpResolution =\n | { ok: true; attach: PlanFollowUpAttach; executionId: string }\n | { ok: false; status: 400 | 409; code: string; error: string }\n\n/** Result of one exclusive follow-up claim. */\nexport type PlanFollowUpAdmission =\n | { admitted: true; lease: string }\n | { admitted: false; reason: 'in_flight' | 'completed' }\n\n/** Result of settling a claim. `lease_lost` means a stale reclaim superseded it. */\nexport type PlanFollowUpSettlement =\n | { settled: true }\n | { settled: false; reason: 'lease_lost' }\n\n/** A bound D1 statement used by the follow-up gate. */\nexport interface D1BoundForPlanFollowUps {\n run(): Promise<unknown>\n}\n\n/**\n * Structural D1 contract for the follow-up gate. `batch` is required: it is\n * D1's atomic boundary, and the gate confirms ownership from the row read in\n * the same batch instead of from a driver-specific affected-row count.\n */\nexport interface D1LikeForPlanFollowUps {\n prepare(sql: string): { bind(...values: unknown[]): D1BoundForPlanFollowUps }\n batch(statements: D1BoundForPlanFollowUps[]): Promise<unknown[]>\n}\n\n/** Configure the follow-up gate. Clock and lease are injectable for tests. */\nexport interface PlanFollowUpGateOptions {\n now?: () => Date\n createLease?: () => string\n /** How long a `running` claim may sit before another isolate may reclaim it. Default one hour. */\n staleAfterMs?: number\n}\n\n/** Exclusive claim over one follow-up execution's `turn_status` row. */\nexport interface PlanFollowUpGate {\n admit(executionId: string, scopeId: string): Promise<PlanFollowUpAdmission>\n /** Record a completed attach. Only the current lease may settle. */\n settle(executionId: string, scopeId: string, lease: string): Promise<PlanFollowUpSettlement>\n /** Record a failed attach so a retry is admitted immediately. */\n abandon(executionId: string, scopeId: string, lease: string): Promise<PlanFollowUpSettlement>\n}\n\nconst PLAN_FOLLOW_UP_STALE_AFTER_MS = 60 * 60 * 1000\nconst PLAN_FOLLOW_UP_ATTACH_TIMEOUT_MS = 120_000\nconst TERMINAL_SESSION_EVENT_TYPES = new Set(['done', 'error', 'result'])\n\n/** The Sidecar's execution id for a follow-up turn. Keep it byte-identical to the Sidecar. */\nexport function planFollowUpExecutionId(sessionId: string, turnId: string): string {\n return `plan-followup-${createHash('sha256').update(`${sessionId}\\0${turnId}`).digest('hex')}`\n}\n\n/** Parse a follow-up descriptor. The turn id is derived, never trusted. */\nexport function parsePlanFollowUpAttach(value: unknown): PlanFollowUpAttach | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return null\n const record = value as Record<string, unknown>\n const planId = typeof record.planId === 'string' ? record.planId.trim() : ''\n const turnId = typeof record.turnId === 'string' ? record.turnId.trim() : ''\n const revision = record.revision\n const outcome = record.outcome\n if (!planId || !turnId || (outcome !== 'approved' && outcome !== 'rejected')) return null\n if (typeof revision !== 'number' || !Number.isInteger(revision) || revision < 1) return null\n if (turnId !== planFollowUpTurnId(planId, revision, outcome)) return null\n return { planId, revision, outcome, turnId }\n}\n\n/**\n * Validate a follow-up request against what the session actually persisted:\n * the plan must be in this session at this revision and must already carry the\n * claimed decision.\n */\nexport function resolvePlanFollowUpRequest(input: {\n sessionId: string\n planFollowUp: unknown\n messages: ReadonlyArray<{ role: string; parts?: unknown }>\n}): PlanFollowUpResolution {\n const attach = parsePlanFollowUpAttach(input.planFollowUp)\n if (!attach) {\n return { ok: false, status: 400, code: 'invalid_plan_follow_up', error: 'Invalid planFollowUp descriptor' }\n }\n const plan = input.messages\n .filter((message) => message.role === 'assistant' && Array.isArray(message.parts))\n .flatMap((message) => message.parts as unknown[])\n .map((part) => (part && typeof part === 'object' && !Array.isArray(part)\n ? persistedPartToPlan(part as Record<string, unknown>)\n : null))\n .find((candidate) => candidate?.planId === attach.planId && candidate.revision === attach.revision)\n if (!plan) {\n return {\n ok: false,\n status: 409,\n code: 'plan_follow_up_missing',\n error: `Plan ${attach.planId} revision ${attach.revision} is not in this session`,\n }\n }\n if (plan.status !== attach.outcome) {\n return {\n ok: false,\n status: 409,\n code: 'plan_follow_up_not_decided',\n error: `Plan ${attach.planId} is ${plan.status}, not ${attach.outcome}`,\n }\n }\n return { ok: true, attach, executionId: planFollowUpExecutionId(input.sessionId, attach.turnId) }\n}\n\n/**\n * Session events carry two payload shapes: replayed events hold the stream\n * event under `data`, while live events nest it under `data.properties`.\n * Downstream reads `data.<field>`, so a live event is unwrapped. A replayed\n * payload that still carries its own `type` drops it, so `data` holds only the\n * event's fields.\n */\nexport function unwrapSessionEventPayload(event: SandboxEvent): SandboxEvent {\n const data = event.data && typeof event.data === 'object' && !Array.isArray(event.data)\n ? event.data as Record<string, unknown>\n : undefined\n if (!data) return event\n const properties = data.properties && typeof data.properties === 'object' && !Array.isArray(data.properties)\n ? data.properties as Record<string, unknown>\n : undefined\n if (properties) return { ...event, data: properties } as SandboxEvent\n if (typeof data.type === 'string') {\n const { type: _type, ...rest } = data\n return { ...event, data: rest } as SandboxEvent\n }\n return event\n}\n\n/**\n * Attach to the already-enqueued follow-up execution: replay its buffered\n * events from the start, then follow it live to completion. It never sends a\n * new prompt. The session-events iterator has no reconnect, so a stream that\n * ends without a terminal event fails instead of persisting a partial turn.\n */\nexport async function* streamPlanFollowUpEvents(\n box: SandboxInstance,\n sessionId: string,\n executionId: string,\n options: { timeoutMs?: number } = {},\n): AsyncGenerator<SandboxEvent> {\n const timeoutMs = options.timeoutMs ?? PLAN_FOLLOW_UP_ATTACH_TIMEOUT_MS\n const abort = new AbortController()\n const iterator = box.session(sessionId).events({\n executionId,\n since: '0',\n signal: abort.signal,\n })[Symbol.asyncIterator]()\n let timeout: ReturnType<typeof setTimeout> | undefined\n let sawTerminalEvent = false\n const track = (event: SandboxEvent): SandboxEvent => {\n if (TERMINAL_SESSION_EVENT_TYPES.has(String(event.type ?? ''))) sawTerminalEvent = true\n return unwrapSessionEventPayload(event)\n }\n try {\n const first = await Promise.race([\n iterator.next(),\n new Promise<never>((_, reject) => {\n timeout = setTimeout(\n () => reject(new Error(`Plan follow-up ${executionId} did not start within ${Math.round(timeoutMs / 1000)} seconds`)),\n timeoutMs,\n )\n }),\n ])\n if (timeout) clearTimeout(timeout)\n if (first.done) throw new Error(`Plan follow-up ${executionId} ended before emitting an event`)\n yield track(first.value)\n while (true) {\n const next = await iterator.next()\n if (next.done) {\n if (!sawTerminalEvent) {\n throw new Error(`Plan follow-up ${executionId} stream ended without a terminal event`)\n }\n return\n }\n yield track(next.value)\n }\n } finally {\n if (timeout) clearTimeout(timeout)\n abort.abort()\n await iterator.return?.(undefined)\n }\n}\n\ninterface PlanFollowUpStatusRow {\n status: string\n leaseToken: string | null\n}\n\n/**\n * Exclusive claim over a follow-up execution in the shared `turn_status`\n * table. Every claim writes a random lease and confirms ownership from the\n * row returned by the same D1 batch. A running claim older than\n * `staleAfterMs` may be reclaimed; the superseded holder then settles into\n * `lease_lost` instead of overwriting the newer claim. Apply\n * `TURN_STATUS_LEASE_MIGRATION_SQL` (from `/stream`) once after the turn\n * tables: it adds the `leaseToken` column the claim writes.\n */\nexport function createD1PlanFollowUpGate(\n db: D1LikeForPlanFollowUps,\n options: PlanFollowUpGateOptions = {},\n): PlanFollowUpGate {\n const now = options.now ?? (() => new Date())\n const createLease = options.createLease ?? randomUUID\n const staleAfterMs = options.staleAfterMs ?? PLAN_FOLLOW_UP_STALE_AFTER_MS\n const readStatus = (executionId: string) => db.prepare(`\n SELECT status, leaseToken\n FROM turn_status\n WHERE turnId = ?\n LIMIT 1\n `).bind(executionId)\n\n async function readAfterBatch(\n write: D1BoundForPlanFollowUps,\n executionId: string,\n operation: string,\n ): Promise<PlanFollowUpStatusRow> {\n const results = await db.batch([write, readStatus(executionId)])\n const rows = (results[1] as { results?: unknown[] } | undefined)?.results\n const row = rows?.[0] as Partial<PlanFollowUpStatusRow> | undefined\n if (!row || typeof row.status !== 'string') {\n throw new Error(`Plan follow-up ${executionId} has no status after ${operation}`)\n }\n if (row.leaseToken !== null && row.leaseToken !== undefined && typeof row.leaseToken !== 'string') {\n throw new Error(`Plan follow-up ${executionId} has an invalid lease after ${operation}`)\n }\n return { status: row.status, leaseToken: row.leaseToken ?? null }\n }\n\n async function settle(\n executionId: string,\n scopeId: string,\n lease: string,\n status: 'complete' | 'error',\n ): Promise<PlanFollowUpSettlement> {\n const row = await readAfterBatch(\n db.prepare(`\n UPDATE turn_status\n SET status = ?, scopeId = ?, updatedAt = ?\n WHERE turnId = ? AND status = 'running' AND leaseToken = ?\n `).bind(status, scopeId, now().toISOString(), executionId, lease),\n executionId,\n `settling ${status}`,\n )\n if (row.leaseToken !== lease) return { settled: false, reason: 'lease_lost' }\n if (row.status !== status) {\n throw new Error(`Plan follow-up ${executionId} remained ${row.status} while settling ${status}`)\n }\n return { settled: true }\n }\n\n return {\n async admit(executionId, scopeId) {\n const claimedAt = now()\n const lease = createLease()\n const staleBefore = new Date(claimedAt.getTime() - staleAfterMs).toISOString()\n const row = await readAfterBatch(\n db.prepare(`\n INSERT INTO turn_status (turnId, status, scopeId, updatedAt, leaseToken)\n VALUES (?, 'running', ?, ?, ?)\n ON CONFLICT(turnId) DO UPDATE SET\n status = 'running',\n scopeId = excluded.scopeId,\n updatedAt = excluded.updatedAt,\n leaseToken = excluded.leaseToken\n WHERE turn_status.status = 'error'\n OR (turn_status.status = 'running' AND turn_status.updatedAt < ?)\n `).bind(executionId, scopeId, claimedAt.toISOString(), lease, staleBefore),\n executionId,\n 'admission',\n )\n if (row.status === 'running' && row.leaseToken === lease) return { admitted: true, lease }\n if (row.status === 'running') return { admitted: false, reason: 'in_flight' }\n if (row.status === 'complete') return { admitted: false, reason: 'completed' }\n throw new Error(`Plan follow-up ${executionId} has unexpected admission status: ${row.status}`)\n },\n settle: (executionId, scopeId, lease) => settle(executionId, scopeId, lease, 'complete'),\n abandon: (executionId, scopeId, lease) => settle(executionId, scopeId, lease, 'error'),\n }\n}\n","import { getPartKey, mergePersistedPart, type StreamEvent } from '../stream/index'\nimport type { ChatTurnRouteProducer } from './turn-routes'\n\n/** Resolve chat route events and materialize their durable state records */\nexport interface ChatRouteDurableProjection {\n observe(event: unknown): void | Promise<void>\n materialize(): Array<Record<string, unknown>> | Promise<Array<Record<string, unknown>>>\n}\n\n/** Log chat route projection messages with optional metadata for durable processing */\nexport type ChatRouteDurableProjectionLogger =\n (message: string, meta?: Record<string, unknown>) => void\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Adds durable lifecycle projection to any producer lane without moving its\n * transport into agent-app. Purely STRUCTURAL: agent-app ships no implementer\n * of {@link ChatRouteDurableProjection} and deliberately does not — the one it\n * used to ship (`/durable-chat`) was removed in 0.44.0 with zero fleet imports.\n * Pass any `{ observe, materialize }` object backed by your own store. The projection is observed inline and its\n * materialized parts replace same-key pending snapshots after the stream\n * drains. Projection persistence is best-effort for the live lane: a store\n * outage must not terminate an otherwise healthy sandbox stream. Failures are\n * reported through the optional logger so products can retain diagnostics. */\nexport function withDurableChatProjection(\n producer: ChatTurnRouteProducer,\n projection: ChatRouteDurableProjection,\n log: ChatRouteDurableProjectionLogger = (message, meta) => console.error(message, meta ?? ''),\n): ChatTurnRouteProducer {\n let projected: Array<Record<string, unknown>> = []\n async function* stream(): AsyncGenerator<StreamEvent, void, unknown> {\n for await (const event of producer.stream) {\n try {\n await projection.observe(event)\n } catch (error) {\n log('[chat-routes] durable projection observe failed', {\n eventType: event.type,\n error: errorMessage(error),\n })\n }\n yield event\n }\n try {\n projected = await projection.materialize()\n } catch (error) {\n log('[chat-routes] durable projection materialize failed', {\n error: errorMessage(error),\n })\n }\n }\n return {\n ...producer,\n stream: stream(),\n assistantParts: () => {\n const parts = producer.assistantParts?.() ?? []\n const order: string[] = []\n const byKey = new Map<string, Record<string, unknown>>()\n for (const part of [...parts, ...projected]) {\n const key = getPartKey(part)\n if (!byKey.has(key)) order.push(key)\n byKey.set(key, mergePersistedPart(byKey.get(key), part))\n }\n return order.map((key) => byKey.get(key)!)\n },\n }\n}\n","/**\n * Storage seams for the chat-attachment vertical (`resolveChatAttachments`,\n * `buildDispatchParts`, `promoteAgentFilePart`). Structural function ports in\n * the same style as `upload.ts`'s `SandboxUploadSink`: REQUIRED injection, no\n * default implementation — agent-app owns the size/budget/idempotency\n * mechanism, the product owns where the bytes actually live.\n *\n * One reader serves validation, materialization, and dispatch:\n * `resolveChatAttachments` reads only the\n * authoritative `size` (never trusting the client-reported size), while\n * `buildDispatchParts` reads the inline `content` (base64 or raw bytes) to\n * build a `data:` URI. `prepareDispatchAttachments` copies raw bytes when a\n * product opts in. All share `ReadAttachmentFn` so a product\n * wires a single vault/object-store adapter, not two. gtm's KV vault (stores\n * base64 bodies) and `/object-store`'s `ObjectStore` (hands back raw bytes)\n * both satisfy this shape.\n */\n\nimport type { ChatAttachmentPart } from '../chat-store/parts'\nimport { DISPATCH_MAX_MEDIA_PARTS } from './wire'\n\n/**\n * The result of reading one stored attachment. `ok:true` MUST carry the\n * authoritative decoded byte `size` (the cap is meaningless against a\n * client-controlled number) and, when the caller needs to inline the file,\n * its content as `base64` and/or raw `bytes`. `mediaType` is the stored\n * content type when the store knows it (used as the fallback when the wire\n * part carried none). `ok:false` carries a human `reason` that SHOULD name the\n * offending path — it is surfaced verbatim in the caller's typed outcome.\n */\nexport type AttachmentReadResult =\n | {\n ok: true\n /** Authoritative decoded byte length of the stored content. */\n size: number\n /** Inline content as base64 — reused verbatim for a `data:` URI, so a\n * store holding already-base64 bodies never decodes-and-re-encodes. */\n base64?: string\n /** Inline content as raw bytes — base64-encoded by the caller when a\n * `data:` URI is needed. Ignored when `base64` is present. */\n bytes?: Uint8Array\n /** Stored content type, when the store tracks one. */\n mediaType?: string\n }\n | { ok: false; reason: string }\n\n/**\n * Read one stored attachment for `scopeId` (the product's workspace/tenant\n * key) at its store-relative `path`. Missing, deleted, or unreadable content\n * MUST resolve to `{ ok: false, reason }`, never throw — a store failure is a\n * per-attachment outcome the caller folds into its own typed result, not a\n * turn-level exception.\n */\nexport type ReadAttachmentFn = (scopeId: string, path: string) => Promise<AttachmentReadResult>\n\n/** Opt-in copy from the product attachment store to its already-authorized box.\n * Uploads are sequential and their returned byte counts must match the store.\n * The product retains its missing-content sentence and the surrounding trace span. */\nexport interface AttachmentMaterialization {\n upload: (absolutePath: string, bytes: Uint8Array) => Promise<{ size: number }>\n missingBytesMessage: (path: string) => string\n /** The byte sizes of those box files that exist, read in one round trip.\n * Attachment paths are immutable, so a box file whose size equals the\n * part's stored size is already delivered and is neither read nor uploaded\n * again; a missing or different file is copied. Absent: every file is copied. */\n present?: (absolutePaths: readonly string[]) => Promise<ReadonlyMap<string, number>>\n}\n\n/** Prepare carried files before a product constructs its prompt and dispatch input. */\nexport interface PrepareDispatchAttachmentsInput {\n attachments: ChatAttachmentPart[]\n historyAttachments?: readonly ChatAttachmentPart[]\n mentionCount?: number\n scopeId: string\n readAttachment: ReadAttachmentFn\n resolveAttachmentPath: (path: string) => string\n materialize?: AttachmentMaterialization\n}\n\n/** Select carried files and optionally copy them before constructing a prompt.\n * Omitted history and materialization preserve the supplied attachment list.\n * `slice(-0)` intentionally retains the apps' current zero-slot behavior. */\nexport async function prepareDispatchAttachments(input: PrepareDispatchAttachmentsInput): Promise<ChatAttachmentPart[]> {\n const historyBudget = Math.max(\n 0,\n DISPATCH_MAX_MEDIA_PARTS - input.attachments.length - (input.mentionCount ?? 0),\n )\n const attachments = input.historyAttachments === undefined ? input.attachments : [\n ...input.attachments,\n ...input.historyAttachments.slice(-historyBudget),\n ]\n const materialize = input.materialize\n if (!materialize) return attachments\n const copies = attachments.map((part) => ({ part, target: input.resolveAttachmentPath(part.path) }))\n // Only files carried from earlier turns can already be on the box.\n const carried = copies.slice(input.attachments.length).map((copy) => copy.target)\n const delivered = materialize.present && carried.length > 0\n ? await materialize.present([...new Set(carried)])\n : new Map<string, number>()\n const written = new Set<string>()\n for (const { part, target } of copies) {\n if (written.has(target)) continue\n written.add(target)\n if (part.size !== undefined && delivered.get(target) === part.size) continue\n\n const read = await input.readAttachment(input.scopeId, part.path)\n if (!read.ok) throw new Error(read.reason)\n if (!read.bytes) {\n throw new Error(materialize.missingBytesMessage(part.path))\n }\n const result = await materialize.upload(target, read.bytes)\n if (result.size !== read.size) {\n throw new Error(\n `Sandbox attachment size mismatch for ${part.path}: expected ${read.size}, uploaded ${result.size}`,\n )\n }\n }\n return attachments\n}\n\n/** The ownership identity for one attempted write. The upload and promotion\n * routes create a unique path for each attempt, and the product adapter stores\n * this id with it. */\nexport interface AttachmentWriteOwnership {\n readonly id: string\n readonly path: string\n}\n\n/** Public-safe outcome for a storage outage. Backend details belong in logs. */\nexport const ATTACHMENT_STORAGE_FAILURE_MESSAGE = 'Attachment storage is temporarily unavailable. Please try again.'\n\n/** Stable client error code when compensating cleanup did not complete. */\nexport const ATTACHMENT_ROLLBACK_FAILURE_CODE = 'rollback_failed'\n\n/** Public-safe outcome when compensating cleanup did not complete. */\nexport const ATTACHMENT_ROLLBACK_FAILURE_MESSAGE = 'Attachment cleanup failed. Please try again.'\n\n/** Add a path-safe ownership id to a logical path and return an immutable store key. */\nexport function immutableAttachmentPath(logicalPath: string, ownershipId: string): string {\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(ownershipId)) {\n throw new Error('attachment ownership id must be a path-safe identifier')\n }\n return `${logicalPath}--${ownershipId}`\n}\n\n/** Compensation for one attachment write. The adapter MUST compare the stored\n * ownership id before deleting, so an older rollback cannot delete a newer\n * overwrite. */\nexport interface AttachmentWriteReceipt {\n rollback(): void | Promise<void>\n ownership: AttachmentWriteOwnership\n}\n\n/** Clean up a write whose function threw after the store may have committed.\n * The adapter must delete only the supplied ownership, never the logical path\n * unconditionally. */\nexport type AbortAttachmentWriteFn = (\n scopeId: string,\n ownership: AttachmentWriteOwnership,\n) => void | Promise<void>\n\n/**\n * The stable writer result from the original attachment-store contract.\n * Existing products may return this shape and keep using the legacy writer\n * lane. New products should use {@link AtomicAttachmentWriteResult}.\n */\nexport type AttachmentWriteResult = { ok: true } | { ok: false; reason: string }\n\n/** Options from the stable attachment-store contract. */\nexport interface AttachmentWriteOptions {\n mediaType?: string\n name?: string\n originalName?: string\n size?: number\n}\n\n/**\n * The stable writer port. It is intentionally unchanged so products released\n * before the ownership receipt contract continue to compile.\n *\n * The legacy lane does not promise batch rollback. Use\n * {@link createAtomicAttachmentWriter} for ownership-safe writes.\n */\nexport type WriteAttachmentFn = (\n scopeId: string,\n path: string,\n content: Uint8Array | string,\n opts: AttachmentWriteOptions,\n) => Promise<AttachmentWriteResult>\n\n/** Options for a streamed write. `size` is the exact byte count `content`\n * yields. `mediaType` is decided from the file name and its first bytes,\n * before the route has read the rest: an archive's central directory sits at\n * its end, so the route's response, not this value, carries the final type. */\nexport interface AttachmentStreamWriteOptions extends AttachmentWriteOptions {\n size: number\n mediaType: string\n}\n\n/**\n * Streamed writer port for an upload too large to hold in memory. `content`\n * yields exactly `opts.size` bytes. The route checks the file while it\n * streams and withholds the final bytes until the whole file has passed, so\n * on a refusal `content` errors instead of ending. The adapter must make the\n * bytes readable at `path` only when `content` ends cleanly, and must leave\n * whatever was stored at `path` before untouched when it errors. A store put\n * of a fixed-length stream (R2 `put` behind `FixedLengthStream`) does both.\n */\nexport type WriteAttachmentStreamFn = (\n scopeId: string,\n path: string,\n content: ReadableStream<Uint8Array>,\n opts: AttachmentStreamWriteOptions,\n) => Promise<AttachmentWriteResult>\n\n/** Options for an ownership-safe writer. */\nexport interface AtomicAttachmentWriteOptions extends AttachmentWriteOptions {\n ownership: AttachmentWriteOwnership\n}\n\n/** Result for an ownership-safe writer. A receipt is required on both paths. */\nexport type AtomicAttachmentWriteResult =\n | { ok: true; receipt: AttachmentWriteReceipt }\n | { ok: false; reason: string; receipt: AttachmentWriteReceipt }\n\n/** Ownership-safe writer port used by the atomic upload and promotion lanes. */\nexport type AtomicWriteAttachmentFn = (\n scopeId: string,\n path: string,\n content: Uint8Array | string,\n opts: AtomicAttachmentWriteOptions,\n) => Promise<AtomicAttachmentWriteResult>\n\n/** A complete ownership-safe attachment store adapter. */\nexport interface AtomicAttachmentWriter {\n write: AtomicWriteAttachmentFn\n abort: AbortAttachmentWriteFn\n}\n\n/**\n * Build the explicit atomic adapter used by new routes.\n *\n * Keeping the write and abort functions together prevents a caller from\n * enabling ownership paths while forgetting the ambiguous-write cleanup.\n */\nexport function createAtomicAttachmentWriter(input: AtomicAttachmentWriter): AtomicAttachmentWriter {\n return {\n write: input.write.bind(input),\n abort: input.abort.bind(input),\n }\n}\n","/**\n * `resolveChatAttachments` — validate a turn body's `attachments` field into\n * persistable {@link ChatAttachmentPart}s. Every path is re-validated (a path\n * off the wire is never trusted to stay inside the store root) and every size\n * is re-derived from the STORED body via the injected {@link ReadAttachmentFn},\n * never the client-reported `size` — the upload path lets a caller rewrite its\n * own frontmatter, so a stored size cannot bound anything and the wire size can\n * be anything. Both the aggregate cap and the size carried on the returned part\n * come from the authoritative read.\n *\n * Storage-parameterized: the frontmatter parsing / base64 sizing that derives\n * the authoritative size lives BEHIND `readAttachment` (a product's vault or\n * object-store adapter), so this module is a pure validator + budget gate with\n * no store knowledge. Lifted from gtm-agent's `resolve-attachments.ts`\n * (workspaceId → scopeId, the vault read → the injected reader) and kept\n * behavior-identical for gtm-agent#618 adoption.\n */\n\nimport { attachmentInputToPart, type ChatAttachmentPart } from '../chat-store/parts'\nimport type { ReadAttachmentFn } from './attachment-store'\nimport {\n MAX_ATTACHMENT_TOTAL_BYTES,\n attachmentTotalSizeErrorMessage,\n parseChatAttachmentInputs,\n type AttachmentPathCheck,\n} from './attachment-validation'\n\n/** Resolve the result of chat attachment processing with success status and corresponding data or error */\nexport type ResolveChatAttachmentsResult =\n | { succeeded: true; value: ChatAttachmentPart[] }\n | { succeeded: false; error: string }\n\n/** Define options to resolve and validate chat attachments with size, count, and path constraints */\nexport interface ResolveChatAttachmentsOptions {\n /** The product's workspace/tenant key, passed to `readAttachment`. */\n scopeId: string\n /** Authoritative size + content reader — see {@link ReadAttachmentFn}. */\n readAttachment: ReadAttachmentFn\n /** Most attachments one request may carry. Default {@link ATTACHMENT_MAX_COUNT}. */\n maxCount?: number\n /** Aggregate raw-byte ceiling. Default {@link MAX_ATTACHMENT_TOTAL_BYTES}. */\n maxTotalBytes?: number\n /** Path validator override. Default {@link defaultValidateAttachmentPath}. */\n validatePath?: (path: string) => AttachmentPathCheck\n}\n\n/**\n * Validate and resolve a turn body's `attachments` field into persistable\n * parts. Every path is confirmed present (and not deleted) in the caller's own\n * store by `readAttachment` before it is trusted, and size is derived from the\n * authoritative read for both the aggregate cap and the returned part's size.\n */\nexport async function resolveChatAttachments(\n value: unknown,\n options: ResolveChatAttachmentsOptions,\n): Promise<ResolveChatAttachmentsResult> {\n const maxTotalBytes = options.maxTotalBytes ?? MAX_ATTACHMENT_TOTAL_BYTES\n const parsed = parseChatAttachmentInputs(value, options)\n if (!parsed.succeeded) return parsed\n const inputs = parsed.value\n\n // Advisory only: client-controlled, so a dishonest caller can slip past it —\n // but an honest oversized request should fail before it costs a single store\n // read. The authoritative check runs per-attachment below, against the\n // body-derived size.\n const advisoryTotal = inputs.reduce((sum, input) => sum + input.size, 0)\n if (advisoryTotal > maxTotalBytes) {\n return { succeeded: false, error: attachmentTotalSizeErrorMessage(advisoryTotal, maxTotalBytes) }\n }\n\n // One attachment is read, sized, and dropped at a time rather than via\n // Promise.all — that would materialize every attachment's body in memory\n // simultaneously (ten truthful 10 MiB references is ~134 MiB of base64, over\n // a Workers heap) before the cap ever gets a chance to reject the request.\n // Sequential reads bound resident bytes to one attachment at a time and bail\n // the moment the running total exceeds the cap, at the cost of up to\n // `maxCount` serial reads instead of one parallel batch.\n let totalStoredBytes = 0\n for (const input of inputs) {\n const read = await options.readAttachment(options.scopeId, input.path)\n if (!read.ok) return { succeeded: false, error: read.reason }\n totalStoredBytes += read.size\n if (totalStoredBytes > maxTotalBytes) {\n return { succeeded: false, error: attachmentTotalSizeErrorMessage(totalStoredBytes, maxTotalBytes) }\n }\n input.size = read.size\n }\n\n return { succeeded: true, value: inputs.map(attachmentInputToPart) }\n}\n","import { redactErrorMessage } from '../redact'\nimport type {\n AtomicAttachmentWriteResult,\n AttachmentWriteOwnership,\n AttachmentWriteReceipt,\n AttachmentWriteResult,\n} from './attachment-store'\n\ntype ObjectLike = Record<PropertyKey, unknown>\n\nfunction objectLike(value: unknown): value is ObjectLike {\n return value !== null && (typeof value === 'object' || typeof value === 'function')\n}\n\n/** Read an injected writer result without allowing hostile getters to escape. */\nexport function inspectLegacyAttachmentWriteResult(\n value: unknown,\n): AttachmentWriteResult | undefined {\n try {\n if (!objectLike(value)) return undefined\n const ok = value.ok\n if (ok === true) return { ok: true }\n if (ok === false && typeof value.reason === 'string') {\n return { ok: false, reason: value.reason }\n }\n } catch {\n // A malformed or hostile adapter result is a storage failure.\n }\n return undefined\n}\n\n/**\n * Read an ownership-aware writer result with strict runtime checks.\n *\n * The public types protect TypeScript callers only. The product adapter is an\n * injection boundary, so a proxy, malformed value, or truthy non-boolean must\n * fail closed before the route invokes cleanup or publishes a path.\n */\nexport function inspectAtomicAttachmentWriteResult(\n value: unknown,\n ownership: AttachmentWriteOwnership,\n): AtomicAttachmentWriteResult | undefined {\n try {\n if (!objectLike(value)) return undefined\n const receiptValue = value.receipt\n if (!objectLike(receiptValue)) return undefined\n const receiptOwnership = receiptValue.ownership\n if (!objectLike(receiptOwnership)) return undefined\n if (\n receiptOwnership.id !== ownership.id ||\n receiptOwnership.path !== ownership.path ||\n typeof receiptOwnership.id !== 'string' ||\n typeof receiptOwnership.path !== 'string' ||\n typeof receiptValue.rollback !== 'function'\n ) {\n return undefined\n }\n if (value.ok === true) {\n return { ok: true, receipt: receiptValue as unknown as AttachmentWriteReceipt }\n }\n if (value.ok === false && typeof value.reason === 'string') {\n return {\n ok: false,\n reason: value.reason,\n receipt: receiptValue as unknown as AttachmentWriteReceipt,\n }\n }\n } catch {\n // A malformed or hostile adapter result is a storage failure.\n }\n return undefined\n}\n\n/** Sanitize adapter diagnostics and keep storage failures typed when the logger itself fails. */\nexport function logAttachmentStorageError(\n logger: { error(message: string, fields: Record<string, unknown>): void },\n message: string,\n fields: Record<string, unknown>,\n): void {\n try {\n const safeFields = Object.fromEntries(\n Object.entries(fields).map(([key, value]) => [\n key,\n typeof value === 'string' ? redactErrorMessage(value) : value,\n ]),\n )\n logger.error(message, safeFields)\n } catch {\n // Logging must not turn a typed storage failure into a thrown response.\n }\n}\n","/**\n * `promoteAgentFilePart` — turn a harness-emitted `type:\"file\"` stream part\n * into a store-backed {@link ChatAttachmentPart}. The harness hands back a URL\n * pointing at bytes it produced (a `data:` URI, or a path inside the sandbox);\n * nothing durable survives past the turn unless it is written into the\n * product's store, the same way a user upload is. Typed outcomes throughout:\n * every failure mode (unsupported scheme, no sandbox, oversize, store-write\n * failure, malformed part) resolves to `{ succeeded: false, filename, reason }`\n * rather than throwing past this boundary, so the caller folds a visible notice\n * instead of losing the file silently.\n *\n * Storage-parameterized port of gtm-agent's `promote-file-parts.ts` with the\n * refactor gtm never made: persistence goes through an injected stable writer\n * or ownership-safe adapter, the path strategy is the injected\n * `buildAttachmentPath` (neutral `uploads/agent/<date>/` default, no domain\n * bucket taxonomy baked), the MIME map is an injectable hook, and the date\n * segment reads an injectable clock. The logical `hash8(id ?? url ?? filename)`\n * naming is preserved. Atomic callers also receive a fresh ownership suffix so\n * an ambiguous write cannot overwrite an older object.\n */\n\nimport {\n statSandboxFileSize,\n readSandboxBinaryBytes,\n type SandboxExecChannel,\n} from '../sandbox/binary-read'\nimport { attachmentKindForMime, type ChatAttachmentKind, type ChatAttachmentPart } from '../chat-store/parts'\nimport { redactErrorMessage } from '../redact'\nimport {\n ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n immutableAttachmentPath,\n type AtomicAttachmentWriter,\n type AttachmentWriteOwnership,\n type AttachmentWriteReceipt,\n type WriteAttachmentFn,\n} from './attachment-store'\nimport {\n logAttachmentStorageError,\n inspectAtomicAttachmentWriteResult,\n inspectLegacyAttachmentWriteResult,\n} from './attachment-write-safety'\nimport { sanitizeAttachmentFileName } from './attachment-validation'\nimport { formatBytes } from './wire'\nimport { sniffMimeFromName } from '../web/mime'\n\nexport { sniffMimeFromName }\n\n/** Default ceiling on a promoted file's raw (pre-encoding) byte size. */\nexport const PROMOTE_MAX_FILE_BYTES = 10 * 1024 * 1024\n\n/** Define the structure for a raw file part with optional metadata and media type information */\nexport interface RawAgentFilePart {\n type: 'file'\n id?: string\n filename?: string\n /** AI-SDK-shaped parts carry the MIME type here… */\n mediaType?: string\n /** …but OpenCode's native FilePart calls the same field `mime`. */\n mime?: string\n url?: string\n}\n\n/** Resolve the result of promoting a file part with success status and relevant data or error details */\nexport type PromoteFilePartResult =\n | { succeeded: true; part: ChatAttachmentPart }\n | { succeeded: false; filename: string; reason: string }\n\ntype ByteResolution =\n | { succeeded: true; bytes: Uint8Array }\n | { succeeded: false; reason: string }\n\n/** Arguments handed to a {@link PromoteAgentFilePartOptions.buildAttachmentPath}\n * override — everything needed to place the file deterministically. */\nexport interface AttachmentPathArgs {\n /** Sanitized display filename (basename, safe charset). */\n filename: string\n /** First 8 hex chars of the SHA-256 idempotency digest. */\n hash8: string\n /** `YYYY-MM-DD` from the injected clock. */\n date: string\n /** Resolved media type. */\n mediaType: string\n /** `image`/`file` split of the media type. */\n kind: ChatAttachmentKind\n}\n\n/** Decode base64 with `atob` (not `Buffer.from`, which SKIPS out-of-alphabet\n * characters and would decode a corrupt payload to something plausible). */\nfunction base64ToBytes(base64: string): Uint8Array {\n const binary = atob(base64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)\n return bytes\n}\n\nfunction parseDataUrl(url: string): { base64: boolean; data: string } | null {\n const match = /^data:[^,]*,([\\s\\S]*)$/i.exec(url)\n if (!match) return null\n return { base64: /;base64,/i.test(url), data: match[1] ?? '' }\n}\n\n/** The MIME type embedded in a `data:` URI's header, if any — the last-resort\n * signal when the part itself carries no mediaType/mime field. */\nfunction dataUrlMime(url: string | undefined): string | undefined {\n if (!url) return undefined\n const match = /^data:([^;,]+)[;,]/i.exec(url)\n return match ? match[1] : undefined\n}\n\nfunction basenameFromUrl(url: string | undefined): string | undefined {\n if (!url || /^data:/i.test(url)) return undefined\n const withoutQuery = url.split(/[?#]/)[0] ?? url\n const segments = withoutQuery.split('/').filter(Boolean)\n return segments[segments.length - 1] || undefined\n}\n\n/** `file://<path>` strips to `<path>`; a bare absolute path passes through\n * unchanged. The remainder is percent-decoded — sidecar file URLs encode\n * spaces and other reserved characters. */\nfunction resolveFileUrlPath(url: string): { succeeded: true; path: string } | { succeeded: false; reason: string } {\n const withoutScheme = /^file:\\/\\//i.test(url) ? url.slice('file://'.length) : url\n try {\n return { succeeded: true, path: decodeURIComponent(withoutScheme) }\n } catch (err) {\n return { succeeded: false, reason: `malformed file path: ${redactErrorMessage(err)}` }\n }\n}\n\n/** Matches gtm's `attachmentSizeErrorMessage` (attachment-limits.ts:87-89)\n * verbatim, via the shared {@link formatBytes} — e.g. \"report.pdf is 10MB;\n * attachments are limited to 10MB\" — so an oversize promotion notice reads\n * identically whether gtm's original composed it or agent-app's promoter did. */\nfunction oversizeReason(filename: string, actual: number, limit: number): string {\n return `${filename} is ${formatBytes(actual)}; attachments are limited to ${formatBytes(limit)}`\n}\n\nfunction resolveDataUrlBytes(url: string, filename: string, maxBytes: number): ByteResolution {\n const parsed = parseDataUrl(url)\n if (!parsed) return { succeeded: false, reason: 'malformed data URI' }\n let bytes: Uint8Array\n try {\n bytes = parsed.base64 ? base64ToBytes(parsed.data) : new TextEncoder().encode(decodeURIComponent(parsed.data))\n } catch (err) {\n return { succeeded: false, reason: `failed to decode data URI: ${redactErrorMessage(err)}` }\n }\n if (bytes.byteLength > maxBytes) {\n return { succeeded: false, reason: oversizeReason(filename, bytes.byteLength, maxBytes) }\n }\n return { succeeded: true, bytes }\n}\n\nasync function resolveSandboxFileBytes(input: {\n path: string\n box: SandboxExecChannel\n sessionId: string\n filename: string\n maxBytes: number\n}): Promise<ByteResolution> {\n // exec can reject outright (box teardown, timeout, transport failure) — that\n // is a per-file failure, not a turn failure, so it must resolve to a typed\n // outcome like a nonzero exit code does.\n const stat = await statSandboxFileSize(input.box, input.path, { sessionId: input.sessionId })\n if (!stat.succeeded) {\n return { succeeded: false, reason: `could not stat agent file: ${redactErrorMessage(stat.error)}` }\n }\n // Rejected before the bytes are ever pulled — a base64 exec of an oversize\n // file would waste a full sandbox round trip only to be discarded.\n if (stat.value > input.maxBytes) {\n return { succeeded: false, reason: oversizeReason(input.filename, stat.value, input.maxBytes) }\n }\n\n const read = await readSandboxBinaryBytes(input.box, input.path, stat.value, { sessionId: input.sessionId })\n if (!read.succeeded) {\n return { succeeded: false, reason: `could not read agent file: ${redactErrorMessage(read.error)}` }\n }\n return { succeeded: true, bytes: read.value.bytes }\n}\n\nasync function resolveBytes(input: {\n raw: RawAgentFilePart\n box: SandboxExecChannel | undefined\n sessionId: string\n filename: string\n maxBytes: number\n}): Promise<ByteResolution> {\n const url = input.raw.url\n if (!url) return { succeeded: false, reason: 'the file part carries no url' }\n\n if (/^data:/i.test(url)) return resolveDataUrlBytes(url, input.filename, input.maxBytes)\n\n const isSandboxPath = /^file:\\/\\//i.test(url) || url.startsWith('/')\n if (!isSandboxPath) {\n const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(url)?.[1]?.toLowerCase() ?? 'unknown'\n return { succeeded: false, reason: `unsupported file URL scheme: ${scheme}` }\n }\n if (!input.box) return { succeeded: false, reason: 'no sandbox to read agent file' }\n\n const resolvedPath = resolveFileUrlPath(url)\n if (!resolvedPath.succeeded) return resolvedPath\n return resolveSandboxFileBytes({\n path: resolvedPath.path,\n box: input.box,\n sessionId: input.sessionId,\n filename: input.filename,\n maxBytes: input.maxBytes,\n })\n}\n\n/** First 8 hex chars of the SHA-256 of `seed` — deterministic (no\n * `Math.random`) so promoting the same source part twice, even across\n * requests, resolves to the same store path and overwrites in place. */\nasync function hash8(seed: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seed))\n return Array.from(new Uint8Array(digest).slice(0, 4))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/** Neutral default placement: everything under `uploads/agent/<date>/`, named\n * `<base>-<hash8><ext>`. No domain bucket taxonomy (assets/audio/videos…) —\n * a product that wants one supplies `buildAttachmentPath`. */\nfunction defaultBuildAttachmentPath(args: AttachmentPathArgs): string {\n const extensionMatch = /\\.[A-Za-z0-9]+$/.exec(args.filename)\n const extension = extensionMatch ? extensionMatch[0] : ''\n const base = extension ? args.filename.slice(0, -extension.length) : args.filename\n return `uploads/agent/${args.date}/${base}-${args.hash8}${extension}`\n}\n\ntype PromoteFilePartLogger = Pick<Console, 'error'>\n\n\n\nasync function compensatePromotionWrite(\n writer: AtomicAttachmentWriter,\n scopeId: string,\n ownership: AttachmentWriteOwnership,\n receipt: AttachmentWriteReceipt,\n): Promise<{ rollbackError?: unknown; abortError?: unknown }> {\n try {\n await receipt.rollback()\n return {}\n } catch (rollbackError) {\n try {\n await writer.abort(scopeId, ownership)\n return { rollbackError }\n } catch (abortError) {\n return { rollbackError, abortError }\n }\n }\n}\n\ninterface PromoteFilePartCommonOptions {\n raw: RawAgentFilePart\n /** The turn's box — required only to promote a sandbox-path part; a `data:`\n * URI needs none. */\n box?: SandboxExecChannel\n /** The product's workspace/tenant key, passed to `writeAttachment`. */\n scopeId: string\n /** The turn's session id, used for the sandbox stat/read exec calls. */\n sessionId: string\n /** Store-path strategy. Default {@link defaultBuildAttachmentPath}. */\n buildAttachmentPath?: (args: AttachmentPathArgs) => string\n /** Raw-byte ceiling. Default {@link PROMOTE_MAX_FILE_BYTES}. */\n maxBytes?: number\n /** Last-resort media-type hook. Default {@link sniffMimeFromName}. */\n sniffMime?: (filename: string) => string\n /** Clock for the date path segment. Default `() => new Date()`. */\n now?: () => Date\n /** Unique id source for tests or a product's id service. */\n createWriteId?: () => string\n /** Server-side sink for redacted storage details. */\n logger?: PromoteFilePartLogger\n}\n\n/** Stable promotion options from the original writer contract. */\nexport interface PromoteAgentFilePartOptions extends PromoteFilePartCommonOptions {\n /** REQUIRED store writer — no default (the product owns its store). */\n writeAttachment: WriteAttachmentFn\n}\n\n/** Ownership-safe promotion options for new products. */\nexport interface AtomicPromoteAgentFilePartOptions extends PromoteFilePartCommonOptions {\n /** Complete writer + ambiguous-write cleanup adapter. */\n attachmentWriter: AtomicAttachmentWriter\n}\n\nfunction isAtomicPromotionOptions(\n options: PromoteAgentFilePartOptions | AtomicPromoteAgentFilePartOptions,\n): options is AtomicPromoteAgentFilePartOptions {\n return 'attachmentWriter' in options\n}\n\n/** Promote a part using the stable writer contract. */\nexport function promoteAgentFilePart(options: PromoteAgentFilePartOptions): Promise<PromoteFilePartResult>\n\n/** Promote a part using an ownership-safe writer and cleanup adapter. */\nexport function promoteAgentFilePart(options: AtomicPromoteAgentFilePartOptions): Promise<PromoteFilePartResult>\n\n/** Promote a part when the caller selects the writer contract at runtime. */\nexport function promoteAgentFilePart(\n options: PromoteAgentFilePartOptions | AtomicPromoteAgentFilePartOptions,\n): Promise<PromoteFilePartResult>\n\n/** Promote a part of an agent file with optional byte limits and MIME type detection. */\nexport async function promoteAgentFilePart(\n options: PromoteAgentFilePartOptions | AtomicPromoteAgentFilePartOptions,\n): Promise<PromoteFilePartResult> {\n const atomic = isAtomicPromotionOptions(options)\n const maxBytes = options.maxBytes ?? PROMOTE_MAX_FILE_BYTES\n const sniffMime = options.sniffMime ?? sniffMimeFromName\n const buildAttachmentPath = options.buildAttachmentPath ?? defaultBuildAttachmentPath\n const now = options.now ?? (() => new Date())\n const logger = options.logger ?? console\n const createWriteId = atomic\n ? options.createWriteId ?? (() => {\n if (typeof crypto === 'undefined' || typeof crypto.randomUUID !== 'function') {\n throw new Error('attachment promotion requires crypto.randomUUID')\n }\n return crypto.randomUUID()\n })\n : undefined\n\n const filename = sanitizeAttachmentFileName(\n options.raw.filename ?? basenameFromUrl(options.raw.url) ?? 'agent-file',\n )\n\n const resolved = await resolveBytes({\n raw: options.raw,\n box: options.box,\n sessionId: options.sessionId,\n filename,\n maxBytes,\n })\n if (!resolved.succeeded) return { succeeded: false, filename, reason: resolved.reason }\n\n let mediaType: string\n let kind: ChatAttachmentKind\n let logicalPath: string\n try {\n mediaType = (options.raw.mediaType ?? options.raw.mime ?? dataUrlMime(options.raw.url) ?? sniffMime(filename)).toLowerCase()\n kind = attachmentKindForMime(mediaType)\n const digest = await hash8(options.raw.id ?? options.raw.url ?? filename)\n const date = now().toISOString().split('T')[0] ?? ''\n logicalPath = buildAttachmentPath({ filename, hash8: digest, date, mediaType, kind })\n } catch (error) {\n logAttachmentStorageError(logger, '[promote-file-part] path planning failed', {\n error: redactErrorMessage(error),\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n\n if (!atomic) {\n let written: unknown\n try {\n written = await options.writeAttachment(options.scopeId, logicalPath, resolved.bytes, {\n mediaType,\n name: filename,\n originalName: options.raw.filename ?? filename,\n size: resolved.bytes.byteLength,\n })\n } catch (error) {\n const reason = redactErrorMessage(error)\n logAttachmentStorageError(logger, '[promote-file-part] legacy writer failed', {\n path: logicalPath,\n error: reason,\n })\n return { succeeded: false, filename, reason }\n }\n const result = inspectLegacyAttachmentWriteResult(written)\n if (!result) {\n logAttachmentStorageError(logger, '[promote-file-part] legacy writer returned an invalid result', {\n path: logicalPath,\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n if (!result.ok) {\n const reason = redactErrorMessage(result.reason)\n logAttachmentStorageError(logger, '[promote-file-part] legacy write rejected', {\n path: logicalPath,\n error: reason,\n })\n return { succeeded: false, filename, reason }\n }\n\n return {\n succeeded: true,\n part: {\n type: kind,\n path: logicalPath,\n name: filename,\n size: resolved.bytes.byteLength,\n mediaType,\n },\n }\n }\n\n let ownershipId: string\n let path: string\n try {\n ownershipId = createWriteId!()\n path = immutableAttachmentPath(logicalPath, ownershipId)\n } catch (error) {\n logAttachmentStorageError(logger, '[promote-file-part] could not allocate ownership key', {\n path: logicalPath,\n error: redactErrorMessage(error),\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n const ownership: AttachmentWriteOwnership = Object.freeze({ id: ownershipId, path })\n\n // `name` is the sanitized filename already computed above; `originalName`\n // is the pre-sanitization source name (gtm's frontmatter `originalName`) —\n // the one field sanitization would otherwise destroy with no way back.\n let written: Awaited<ReturnType<AtomicAttachmentWriter['write']>>\n try {\n written = await options.attachmentWriter.write(options.scopeId, path, resolved.bytes, {\n mediaType,\n name: filename,\n originalName: options.raw.filename ?? filename,\n size: resolved.bytes.byteLength,\n ownership,\n })\n } catch (err) {\n let abortError: unknown\n try {\n await options.attachmentWriter.abort(options.scopeId, ownership)\n } catch (error) {\n abortError = error\n }\n logAttachmentStorageError(logger, '[promote-file-part] write failed', {\n path,\n ownershipId: ownership.id,\n error: redactErrorMessage(err),\n ...(abortError === undefined ? {} : { abortError: redactErrorMessage(abortError) }),\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n const result = inspectAtomicAttachmentWriteResult(written, ownership)\n if (!result) {\n let abortError: unknown\n try {\n await options.attachmentWriter.abort(options.scopeId, ownership)\n } catch (error) {\n abortError = error\n }\n logAttachmentStorageError(logger, '[promote-file-part] writer returned a mismatched ownership receipt', {\n path,\n ownershipId: ownership.id,\n ...(abortError === undefined ? {} : { abortError: redactErrorMessage(abortError) }),\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n if (!result.ok) {\n const compensation = await compensatePromotionWrite(\n options.attachmentWriter,\n options.scopeId,\n ownership,\n result.receipt,\n )\n logAttachmentStorageError(logger, '[promote-file-part] write rejected', {\n path,\n ownershipId: ownership.id,\n error: redactErrorMessage(result.reason),\n ...(compensation.rollbackError === undefined\n ? {}\n : { rollbackError: redactErrorMessage(compensation.rollbackError) }),\n ...(compensation.abortError === undefined\n ? {}\n : { abortError: redactErrorMessage(compensation.abortError) }),\n })\n return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE }\n }\n\n return {\n succeeded: true,\n part: {\n type: kind,\n path,\n name: filename,\n size: resolved.bytes.byteLength,\n mediaType,\n },\n }\n}\n","/**\n * `createAttachmentUploadRoute` — the fleet-primitive durable-store upload\n * route: a two-phase batch (every file is validated before any file is written),\n * with a stable legacy lane and an ownership-safe receipt lane for new callers,\n * a content-sniffed type gate\n * (`checkAttachmentType` over `sniffBinary`'s magic-byte read, not the\n * extension or the browser-reported MIME), binary/text caps with optional\n * per-sniffed-mime overrides, an aggregate byte cap, and sanitized filenames.\n * Storage is fully seamed through the injected\n * `WriteAttachmentFn` or `AtomicAttachmentWriter` (`./attachment-store`) — no\n * default store, the product owns where bytes actually live (vault, object\n * store, …), and auth/rate limiting is entirely the injected `authorize`\n * seam's job: this factory\n * never invents a 401 or 429 response, it only returns `auth.response`\n * verbatim on failure.\n *\n * Two body shapes: a `multipart/form-data` batch, parsed whole, and one raw\n * file body named by the `filename` query parameter. A raw body larger than\n * the sniff head streams to `writeAttachmentStream` when the product supplies\n * one: the Worker never holds the file whole, which is what lets a product\n * admit data files of tens of MB inside a 128 MB isolate.\n *\n * Lifted from gtm-agent's `src/routes/api.vault.upload.ts` (the hardening\n * lineage other lifted modules in this vertical cite: gtm#584 binary\n * corruption, gtm#592 sniff gate/caps, gtm#593 batch-atomic writes) and\n * generalized the way `resolve-attachments.ts` generalized gtm's read path —\n * the vault-specific pieces (KV vault paths, frontmatter, per-user rate\n * limiting) are all injected seams here, while the validate-then-write phase\n * split and the type/size gate ordering survive byte-for-byte.\n *\n * @remarks Sibling to, NOT an extension of, `./upload.ts`'s\n * `createUploadRoute` — a different persistence model (durable product store\n * vs. inline-`data:`-or-ephemeral-sandbox-workspace). See that module's doc\n * comment for the up-to-date framing between the two.\n */\n\nimport { formatBytes, type ChatAttachmentInput, type ChatAttachmentKind } from './wire'\nimport { attachmentKindForMime } from '../chat-store/parts'\nimport { redactErrorMessage } from '../redact'\nimport {\n ATTACHMENT_ROLLBACK_FAILURE_CODE,\n ATTACHMENT_ROLLBACK_FAILURE_MESSAGE,\n ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n type AtomicAttachmentWriter,\n immutableAttachmentPath,\n type AttachmentWriteOwnership,\n type AttachmentWriteReceipt,\n type WriteAttachmentFn,\n type WriteAttachmentStreamFn,\n} from './attachment-store'\nimport {\n logAttachmentStorageError,\n inspectAtomicAttachmentWriteResult,\n inspectLegacyAttachmentWriteResult,\n} from './attachment-write-safety'\nimport {\n ALLOWED_ATTACHMENT_SNIFFED_MIMES,\n ATTACHMENT_MAX_COUNT,\n MAX_ATTACHMENT_TOTAL_BYTES,\n MAX_BINARY_ATTACHMENT_BYTES,\n MAX_TEXT_ATTACHMENT_BYTES,\n attachmentSizeErrorMessage,\n attachmentTotalSizeErrorMessage,\n checkAttachmentType,\n defaultValidateAttachmentPath,\n sanitizeAttachmentFileName,\n sniffedMimeImpliedByName,\n type AttachmentPathCheck,\n} from './attachment-validation'\nimport { createStreamingSniffer, sniffBinary, STREAM_SNIFF_HEAD_BYTES, type SniffResult } from './binary-sniff'\nimport { sniffMimeFromName } from './promote-file-part'\n\n/** Stable authorization result for the original writer contract. */\nexport type AttachmentUploadAuthorization =\n | {\n ok: true\n scopeId: string\n writeAttachment?: WriteAttachmentFn\n writeAttachmentStream?: WriteAttachmentStreamFn\n }\n | { ok: false; response: Response }\n\n/** Authorization result for an ownership-safe attachment writer. */\nexport type AtomicAttachmentUploadAuthorization =\n | {\n ok: true\n scopeId: string\n attachmentWriter?: AtomicAttachmentWriter\n }\n | { ok: false; response: Response }\n\n/** The logger receives only sanitized backend details. The client receives the\n * opaque message below, regardless of the store's failure text. */\nexport type AttachmentUploadLogger = Pick<Console, 'error'>\n\n\n\ninterface AttachmentUploadRouteCommonOptions {\n /** Overridable caps. Defaults come from `./attachment-validation`. */\n limits?: {\n /** Most files one request may carry. Default {@link ATTACHMENT_MAX_COUNT}. */\n maxCount?: number\n /** Ceiling on a binary file's raw size. Default {@link MAX_BINARY_ATTACHMENT_BYTES}. */\n maxBinaryBytes?: number\n /** Optional binary-file ceilings keyed by the content-sniffed mime. */\n maxBytesBySniffedMime?: ReadonlyMap<string, number>\n /** Ceiling on a text file's raw size. Default {@link MAX_TEXT_ATTACHMENT_BYTES}. */\n maxTextBytes?: number\n /** Aggregate raw-byte ceiling. Default {@link MAX_ATTACHMENT_TOTAL_BYTES}. */\n maxTotalBytes?: number\n /** Largest `multipart/form-data` body this route parses. A form body is\n * held whole while it parses, at about three copies at peak, so a\n * product that admits files too large for that sets this and takes them\n * as raw bodies (see {@link createAttachmentUploadRoute}). Default: no\n * limit beyond the per-file and aggregate caps. */\n maxFormBytes?: number\n }\n /** Attachment kinds this route accepts. Default `['image', 'file']`. */\n allowedKinds?: ChatAttachmentKind[]\n /** Sniffed-mime allowlist fed to `checkAttachmentType`. */\n allowedSniffedMimes?: ReadonlySet<string>\n /** Sanitized-name → logical store path. */\n pathFor?: (name: string) => string\n /** Store-path validator. Default {@link defaultValidateAttachmentPath}. */\n validatePath?: (path: string) => AttachmentPathCheck\n /** Last-resort media-type hook for text content the sniffer cannot type. */\n sniffMime?: (name: string) => string\n /** Unique id source for atomic ownership keys. */\n createWriteId?: () => string\n /** Server-side error sink. Backend text is sanitized before it is logged. */\n logger?: AttachmentUploadLogger\n}\n\n/** Stable route options for products using the original writer contract. */\nexport interface CreateLegacyAttachmentUploadRouteOptions extends AttachmentUploadRouteCommonOptions {\n /** Authenticate the caller, rate-limit, and resolve the store scope\n * (workspace/tenant id) — never a query param. */\n authorize(args: { request: Request }): Promise<AttachmentUploadAuthorization>\n /** Stable writer. `authorize` may override it per-request. */\n writeAttachment: WriteAttachmentFn\n /** Writer for a raw-body upload larger than {@link STREAM_SNIFF_HEAD_BYTES}:\n * the route checks the file while it streams to this writer, so the file\n * is never held whole. Without it, a raw body is read whole and goes\n * through `writeAttachment` under the same caps. */\n writeAttachmentStream?: WriteAttachmentStreamFn\n}\n\n/**\n * The original public route-options interface remains available for consumers\n * that extend it. Ownership-safe callers use the atomic interface below.\n */\nexport interface CreateAttachmentUploadRouteOptions extends CreateLegacyAttachmentUploadRouteOptions {}\n\n/** Ownership-safe route options for new products. */\nexport interface CreateAtomicAttachmentUploadRouteOptions extends AttachmentUploadRouteCommonOptions {\n /** Authenticate the caller, rate-limit, and resolve the store scope. */\n authorize(args: { request: Request }): Promise<AtomicAttachmentUploadAuthorization>\n /** Complete writer + ambiguous-write cleanup adapter. */\n attachmentWriter: AtomicAttachmentWriter\n}\n\nfunction attachmentUploadError(status: number, code: string, message: string, path?: string): Response {\n return Response.json(\n { error: path === undefined ? { code, message } : { code, message, path } },\n { status },\n )\n}\n\nfunction atomicAttachmentFailure(path: string, cleanupFailures = 0): Response {\n return attachmentUploadError(\n 503,\n cleanupFailures > 0 ? ATTACHMENT_ROLLBACK_FAILURE_CODE : 'attachment_store_unavailable',\n cleanupFailures > 0 ? ATTACHMENT_ROLLBACK_FAILURE_MESSAGE : ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n path,\n )\n}\n\n/** Longest raw-upload `filename` accepted. */\nconst MAX_RAW_FILENAME_LENGTH = 255\n\ntype RawUploadTarget =\n | { succeeded: true; filename: string; declaredBytes: number }\n | { succeeded: false; response: Response }\n\n/**\n * A raw upload is one file as the request body, named by the `filename`\n * query parameter, with its size in `Content-Length` or `X-Upload-Length`\n * (the browser's `File.size`), as in `/object-store`'s upload route. Knowing\n * the size up front is what lets a store receive a fixed-length stream.\n */\nfunction rawUploadTarget(request: Request): RawUploadTarget {\n const filename = new URL(request.url).searchParams.get('filename')\n if (!filename || filename.length > MAX_RAW_FILENAME_LENGTH) {\n return {\n succeeded: false,\n response: attachmentUploadError(\n 400,\n 'invalid_upload',\n 'Expected a multipart/form-data body with file fields, or one raw file body named by the filename query parameter',\n ),\n }\n }\n const uploadLength = request.headers.get('X-Upload-Length')\n const transportLength = request.headers.get('Content-Length')\n if (uploadLength !== null && transportLength !== null && uploadLength !== transportLength) {\n return { succeeded: false, response: attachmentUploadError(400, 'invalid_length', 'Conflicting upload lengths') }\n }\n const declared = uploadLength ?? transportLength\n if (declared === null) {\n return {\n succeeded: false,\n response: attachmentUploadError(411, 'length_required', 'A raw upload declares its size in Content-Length or X-Upload-Length'),\n }\n }\n const declaredBytes = Number(declared)\n if (!/^(0|[1-9]\\d*)$/.test(declared) || !Number.isSafeInteger(declaredBytes)) {\n return { succeeded: false, response: attachmentUploadError(400, 'invalid_length', 'Invalid upload length') }\n }\n return { succeeded: true, filename, declaredBytes }\n}\n\nconst LENGTH_MISMATCH_MESSAGE = 'Upload length does not match the file body'\n\n/** Read a small raw body whole, refusing one longer or shorter than declared. */\nasync function readRawBody(\n request: Request,\n declaredBytes: number,\n): Promise<{ succeeded: true; value: Uint8Array<ArrayBuffer> } | { succeeded: false; response: Response }> {\n const mismatch = { succeeded: false as const, response: attachmentUploadError(400, 'invalid_length', LENGTH_MISMATCH_MESSAGE) }\n const bytes = new Uint8Array(declaredBytes)\n if (!request.body) return declaredBytes === 0 ? { succeeded: true, value: bytes } : mismatch\n const reader = request.body.getReader()\n let offset = 0\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (offset + value.length > declaredBytes) {\n await reader.cancel().catch(() => undefined)\n return mismatch\n }\n bytes.set(value, offset)\n offset += value.length\n }\n } catch {\n return { succeeded: false, response: attachmentUploadError(400, 'invalid_upload', 'The upload body ended early') }\n }\n return offset === declaredBytes ? { succeeded: true, value: bytes } : mismatch\n}\n\n/** Read a body of at most `maxBytes`, refusing a longer one as soon as it\n * passes the cap. A declared `Content-Length` over the cap is refused before\n * any byte is read. */\nasync function readBodyUpTo(\n request: Request,\n maxBytes: number,\n): Promise<{ succeeded: true; value: Uint8Array<ArrayBuffer> } | { succeeded: false; tooLarge: boolean }> {\n const declared = Number(request.headers.get('Content-Length') ?? Number.NaN)\n if (Number.isFinite(declared) && declared > maxBytes) return { succeeded: false, tooLarge: true }\n if (!request.body) return { succeeded: true, value: new Uint8Array(0) }\n const reader = request.body.getReader()\n const chunks: Uint8Array[] = []\n let length = 0\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n length += value.length\n if (length > maxBytes) {\n await reader.cancel().catch(() => undefined)\n return { succeeded: false, tooLarge: true }\n }\n chunks.push(value)\n }\n } catch {\n return { succeeded: false, tooLarge: false }\n }\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.length\n }\n return { succeeded: true, value: bytes }\n}\n\n/** The media type a streamed write records before the whole file is read.\n * The head decides every family except a zip container, whose Office\n * subtype lives in the central directory at the end; for that, the\n * extension's implied type stands in, and the route's response carries the\n * final one. */\nfunction provisionalMediaType(name: string, head: SniffResult, sniffMime: (name: string) => string): string {\n if (!head.binary) return sniffMime(name)\n if (head.mime === 'application/zip') return sniffedMimeImpliedByName(name) ?? head.mime\n return head.mime ?? 'application/octet-stream'\n}\n\ninterface SuccessfulAttachmentWrite {\n path: string\n ownership: AttachmentWriteOwnership\n receipt: AttachmentWriteReceipt\n}\n\n/** Run every available compensation, from the newest write to the oldest. The\n * receipt owns the compare-and-delete operation; this route never deletes a\n * logical path itself. */\nasync function rollbackSuccessfulWrites(\n writes: readonly SuccessfulAttachmentWrite[],\n scopeId: string,\n writer: AtomicAttachmentWriter,\n logger: AttachmentUploadLogger,\n): Promise<number> {\n let failures = 0\n for (let index = writes.length - 1;index >= 0;index -= 1) {\n const write = writes[index]!\n try {\n await write.receipt.rollback()\n } catch (error) {\n failures += 1\n logAttachmentStorageError(logger, '[attachment-upload] cleanup failed', {\n path: write.path,\n ownershipId: write.ownership.id,\n error: redactErrorMessage(error),\n })\n failures += await abortOwnership(writer, scopeId, write.ownership, logger)\n }\n }\n return failures\n}\n\nasync function abortOwnership(\n writer: AtomicAttachmentWriter,\n scopeId: string,\n ownership: AttachmentWriteOwnership,\n logger: AttachmentUploadLogger,\n): Promise<number> {\n try {\n await writer.abort(scopeId, ownership)\n return 0\n } catch (error) {\n logAttachmentStorageError(logger, '[attachment-upload] ambiguous write cleanup failed', {\n path: ownership.path,\n ownershipId: ownership.id,\n error: redactErrorMessage(error),\n })\n return 1\n }\n}\n\nfunction isAtomicRouteOptions(\n options: CreateAttachmentUploadRouteOptions | CreateAtomicAttachmentUploadRouteOptions,\n): options is CreateAtomicAttachmentUploadRouteOptions {\n return 'attachmentWriter' in options\n}\n\n/** Resolve an attachment upload route handler with customizable limits and validation options. */\nexport function createAttachmentUploadRoute(\n options: CreateAttachmentUploadRouteOptions | CreateAtomicAttachmentUploadRouteOptions,\n): (request: Request) => Promise<Response> {\n const atomic = isAtomicRouteOptions(options)\n const maxCount = options.limits?.maxCount ?? ATTACHMENT_MAX_COUNT\n const maxBinaryBytes = options.limits?.maxBinaryBytes ?? MAX_BINARY_ATTACHMENT_BYTES\n const maxBytesBySniffedMime = options.limits?.maxBytesBySniffedMime\n const maxTextBytes = options.limits?.maxTextBytes ?? MAX_TEXT_ATTACHMENT_BYTES\n const maxTotalBytes = options.limits?.maxTotalBytes ?? MAX_ATTACHMENT_TOTAL_BYTES\n const allowedKinds: ChatAttachmentKind[] = options.allowedKinds ?? ['image', 'file']\n const allowedSniffedMimes = options.allowedSniffedMimes ?? ALLOWED_ATTACHMENT_SNIFFED_MIMES\n const pathFor = options.pathFor ?? ((name: string) => name)\n const validatePath = options.validatePath ?? defaultValidateAttachmentPath\n const sniffMime = options.sniffMime ?? sniffMimeFromName\n const createWriteId = atomic\n ? options.createWriteId ?? (() => {\n if (typeof crypto === 'undefined' || typeof crypto.randomUUID !== 'function') {\n throw new Error('attachment upload requires crypto.randomUUID')\n }\n return crypto.randomUUID()\n })\n : undefined\n const logger = options.logger ?? console\n const maxFormBytes = options.limits?.maxFormBytes\n const streamWriter = atomic ? undefined : options.writeAttachmentStream\n const limitFor = (sniff: SniffResult): number => {\n if (!sniff.binary) return maxTextBytes\n return sniff.mime === null ? maxBinaryBytes : maxBytesBySniffedMime?.get(sniff.mime) ?? maxBinaryBytes\n }\n // The most any admitted type may weigh, checked against a raw upload's\n // declared size before a byte is read; the type's own cap is checked once\n // the content is known.\n const largestFileBytes = Math.max(maxTextBytes, maxBinaryBytes, ...(maxBytesBySniffedMime?.values() ?? []))\n\n /**\n * The streamed lane: one raw body larger than the sniff head, written as it\n * arrives. The sniffer keeps only the head and tail, and the last chunk is\n * withheld until the whole file passes the type, kind and size gates, so a\n * refused file never reaches the store in full and its write fails.\n */\n const { streamRawUpload } = createRawUploadStream(sniffMime, allowedSniffedMimes, allowedKinds, limitFor, logger)\n\n return async function attachmentUpload(request: Request): Promise<Response> {\n const auth = await options.authorize({ request })\n if (!auth.ok) return auth.response\n const atomicWriter = atomic\n ? (auth as Extract<AtomicAttachmentUploadAuthorization, { ok: true }>).attachmentWriter ?? options.attachmentWriter\n : undefined\n const legacyWriter = atomic\n ? undefined\n : (auth as Extract<AttachmentUploadAuthorization, { ok: true }>).writeAttachment ?? options.writeAttachment\n if (atomic && !atomicWriter) {\n return attachmentUploadError(503, 'attachment_store_unavailable', ATTACHMENT_STORAGE_FAILURE_MESSAGE)\n }\n\n const files: File[] = []\n const contentType = request.headers.get('Content-Type')?.toLowerCase() ?? ''\n if (!contentType.startsWith('multipart/form-data')) {\n const target = rawUploadTarget(request)\n if (!target.succeeded) return target.response\n const { filename, declaredBytes } = target\n const name = sanitizeAttachmentFileName(filename)\n if (declaredBytes > largestFileBytes) {\n return attachmentUploadError(413, 'attachment_too_large', attachmentSizeErrorMessage(name, declaredBytes, largestFileBytes))\n }\n if (declaredBytes > maxTotalBytes) {\n return attachmentUploadError(413, 'attachments_total_too_large', attachmentTotalSizeErrorMessage(declaredBytes, maxTotalBytes))\n }\n if (streamWriter && declaredBytes > STREAM_SNIFF_HEAD_BYTES) {\n const path = pathFor(name)\n const pathCheck = validatePath(path)\n if (!pathCheck.succeeded) return attachmentUploadError(400, 'invalid_attachment_path', pathCheck.error, path)\n const writer = (auth as Extract<AttachmentUploadAuthorization, { ok: true }>).writeAttachmentStream ?? streamWriter\n return streamRawUpload({ request, scopeId: auth.scopeId, writer, filename, name, path, declaredBytes })\n }\n // A small raw body takes the batch path below as a one-file batch.\n const body = await readRawBody(request, declaredBytes)\n if (!body.succeeded) return body.response\n files.push(new File([body.value], filename))\n } else {\n let formSource: Request | Response = request\n if (maxFormBytes !== undefined) {\n // Read at most the cap before parsing, whether or not the client sent\n // a Content-Length, so an oversized form is refused while small.\n const bounded = await readBodyUpTo(request, maxFormBytes)\n if (!bounded.succeeded && !bounded.tooLarge) {\n return attachmentUploadError(400, 'invalid_upload', 'The upload body ended early')\n }\n if (!bounded.succeeded) {\n return attachmentUploadError(\n 413,\n 'form_upload_too_large',\n `Form uploads are limited to ${formatBytes(maxFormBytes)}; send a larger file as a raw request body named by the filename query parameter`,\n )\n }\n formSource = new Response(bounded.value, { headers: { 'Content-Type': request.headers.get('Content-Type') ?? '' } })\n }\n let form: FormData\n try {\n form = await formSource.formData()\n } catch {\n return attachmentUploadError(400, 'invalid_upload', 'Expected a multipart/form-data body with file fields')\n }\n // Collect every File value regardless of field name — the client may\n // send one field per file or a single repeated field.\n form.forEach((value) => {\n if (value instanceof File) files.push(value)\n })\n }\n if (files.length === 0) {\n return attachmentUploadError(400, 'invalid_upload', 'No files in the upload body')\n }\n\n if (files.length > maxCount) {\n return attachmentUploadError(\n 400,\n 'attachment_count_exceeded',\n `Too many files — the ${maxCount}-file limit was exceeded`,\n )\n }\n\n // Advisory only: client-controlled `file.size`, so a dishonest caller can\n // slip past it — but an honest oversized batch should fail before a\n // single byte is read. The authoritative aggregate check (against the\n // sniffed/decoded byte length) runs per-file in phase 1, below.\n const advisoryTotal = files.reduce((sum, file) => sum + file.size, 0)\n if (advisoryTotal > maxTotalBytes) {\n return attachmentUploadError(\n 413,\n 'attachments_total_too_large',\n attachmentTotalSizeErrorMessage(advisoryTotal, maxTotalBytes),\n )\n }\n\n const preparedBatch = await prepareUploadBatch(files, allowedSniffedMimes, allowedKinds, limitFor, pathFor, atomic, createWriteId, logger, validatePath, maxTotalBytes, sniffMime)\n if (preparedBatch instanceof Response) return preparedBatch\n const { prepared } = preparedBatch\n\n return await commitUploadBatch(prepared, legacyWriter, auth, atomicWriter, atomic, logger)\n }\n}\n\ninterface PreparedWrite {\n path: string\n ownershipId?: string\n name: string\n bytes: Uint8Array\n originalName: string\n size: number\n mediaType: string\n kind: ChatAttachmentKind\n}\n\n\nfunction createRawUploadStream(\n sniffMime: (name: string) => string,\n allowedSniffedMimes: ReadonlySet<string>,\n allowedKinds: ChatAttachmentKind[],\n limitFor: (sniff: SniffResult) => number,\n logger: AttachmentUploadLogger,\n) {\n async function streamRawUpload(input: {\n request: Request\n scopeId: string\n writer: WriteAttachmentStreamFn\n filename: string\n name: string\n path: string\n declaredBytes: number\n }): Promise<Response> {\n const { request, declaredBytes, name, path } = input\n if (!request.body) return attachmentUploadError(400, 'invalid_length', LENGTH_MISMATCH_MESSAGE)\n const reader = request.body.getReader()\n const sniffer = createStreamingSniffer()\n const head: Uint8Array[] = []\n let refusal: Response | undefined\n const tooLong = () => attachmentUploadError(400, 'invalid_length', LENGTH_MISMATCH_MESSAGE)\n\n try {\n while (sniffer.size < STREAM_SNIFF_HEAD_BYTES) {\n const { done, value } = await reader.read()\n if (done) break\n if (sniffer.size + value.length > declaredBytes) {\n await reader.cancel().catch(() => undefined)\n return tooLong()\n }\n sniffer.push(value)\n head.push(value)\n }\n } catch {\n return attachmentUploadError(400, 'invalid_upload', 'The upload body ended early')\n }\n const mediaTypeBeforeEnd = provisionalMediaType(name, sniffBinary(sniffer.head()), sniffMime)\n\n let held = head.pop()\n let finalSniff: SniffResult | undefined\n const refuse = (controller: ReadableStreamDefaultController<Uint8Array>, response: Response) => {\n refusal = response\n controller.error(new Error('attachment upload refused'))\n }\n const content = new ReadableStream<Uint8Array>({\n start(controller) {\n for (const chunk of head) controller.enqueue(chunk)\n },\n async pull(controller) {\n let next: ReadableStreamReadResult<Uint8Array>\n try {\n next = await reader.read()\n } catch {\n refuse(controller, attachmentUploadError(400, 'invalid_upload', 'The upload body ended early'))\n return\n }\n if (!next.done) {\n if (sniffer.size + next.value.length > declaredBytes) {\n await reader.cancel().catch(() => undefined)\n refuse(controller, tooLong())\n return\n }\n sniffer.push(next.value)\n if (held) controller.enqueue(held)\n held = next.value\n return\n }\n if (sniffer.size !== declaredBytes) {\n refuse(controller, tooLong())\n return\n }\n const sniff = sniffer.finish()\n const typeCheck = checkAttachmentType(name, sniff, allowedSniffedMimes)\n if (!typeCheck.succeeded) {\n refuse(controller, attachmentUploadError(\n typeCheck.code === 'attachment_type_mismatch' ? 400 : 415,\n typeCheck.code,\n typeCheck.message,\n ))\n return\n }\n const kind = attachmentKindForMime(sniff.mime ?? '')\n if (!allowedKinds.includes(kind)) {\n refuse(controller, attachmentUploadError(\n 415,\n 'attachment_kind_not_allowed',\n `${name} is a \"${kind}\" attachment, which this upload route does not accept`,\n ))\n return\n }\n const limit = limitFor(sniff)\n if (declaredBytes > limit) {\n refuse(controller, attachmentUploadError(413, 'attachment_too_large', attachmentSizeErrorMessage(name, declaredBytes, limit)))\n return\n }\n finalSniff = sniff\n if (held) controller.enqueue(held)\n held = undefined\n controller.close()\n },\n cancel(reason) {\n return reader.cancel(reason).catch(() => undefined)\n },\n }, { highWaterMark: 0 })\n\n let written: unknown\n try {\n written = await input.writer(input.scopeId, path, content, {\n mediaType: mediaTypeBeforeEnd,\n name,\n originalName: input.filename,\n size: declaredBytes,\n })\n } catch (error) {\n if (!finalSniff) await reader.cancel().catch(() => undefined)\n if (refusal) return refusal\n logAttachmentStorageError(logger, '[attachment-upload] stream writer failed', { path, error: redactErrorMessage(error) })\n return attachmentUploadError(503, 'attachment_store_unavailable', ATTACHMENT_STORAGE_FAILURE_MESSAGE, path)\n }\n if (!finalSniff) await reader.cancel().catch(() => undefined)\n if (refusal) return refusal\n const result = inspectLegacyAttachmentWriteResult(written)\n if (!result || (result.ok && !finalSniff)) {\n // A writer that reports success without reading the file to its end\n // stored something the route never checked.\n logAttachmentStorageError(logger, '[attachment-upload] stream writer returned without a checked file', { path })\n return attachmentUploadError(503, 'attachment_store_unavailable', ATTACHMENT_STORAGE_FAILURE_MESSAGE, path)\n }\n if (!result.ok) {\n const reason = redactErrorMessage(result.reason)\n logAttachmentStorageError(logger, '[attachment-upload] stream write rejected', { path, error: reason })\n return attachmentUploadError(413, 'attachment_write_failed', reason, path)\n }\n const sniff = finalSniff!\n const uploaded: ChatAttachmentInput = {\n path,\n name,\n size: declaredBytes,\n mediaType: sniff.mime ?? sniffMime(name),\n kind: attachmentKindForMime(sniff.mime ?? ''),\n }\n return Response.json({ files: [uploaded] })\n }\n return { streamRawUpload }\n}\n\nasync function prepareUploadBatch(\n files: File[],\n allowedSniffedMimes: ReadonlySet<string>,\n allowedKinds: ChatAttachmentKind[],\n limitFor: (sniff: SniffResult) => number,\n pathFor: (name: string) => string,\n atomic: boolean,\n createWriteId: (() => string) | undefined,\n logger: AttachmentUploadLogger,\n validatePath: (path: string) => AttachmentPathCheck,\n maxTotalBytes: number,\n sniffMime: (name: string) => string,\n) {\n // Phase 1: validate every file and prepare its write input WITHOUT\n // writing anything. A batch fails atomically — any file's validation\n // error must reject the whole request before an earlier file in the\n // same batch is persisted.\n const prepared: PreparedWrite[] = []\n const seenLogicalPaths = new Set<string>()\n let totalBytes = 0\n\n for (const file of files) {\n const bytes = new Uint8Array(await file.arrayBuffer())\n const sniff = sniffBinary(bytes)\n // Attachment paths double as store keys, so the stored name must fit\n // the store charset; the as-uploaded name survives as `originalName`.\n const name = sanitizeAttachmentFileName(file.name)\n\n const typeCheck = checkAttachmentType(name, sniff, allowedSniffedMimes)\n if (!typeCheck.succeeded) {\n return attachmentUploadError(\n typeCheck.code === 'attachment_type_mismatch' ? 400 : 415,\n typeCheck.code,\n typeCheck.message,\n )\n }\n\n const kind = attachmentKindForMime(sniff.mime ?? '')\n if (!allowedKinds.includes(kind)) {\n return attachmentUploadError(\n 415,\n 'attachment_kind_not_allowed',\n `${name} is a \"${kind}\" attachment, which this upload route does not accept`,\n )\n }\n\n const limit = limitFor(sniff)\n if (bytes.length > limit) {\n return attachmentUploadError(\n 413,\n 'attachment_too_large',\n attachmentSizeErrorMessage(name, bytes.length, limit),\n )\n }\n\n const logicalPath = pathFor(name)\n let ownershipId: string | undefined\n let path = logicalPath\n if (atomic) {\n try {\n ownershipId = createWriteId!()\n path = immutableAttachmentPath(logicalPath, ownershipId)\n } catch (error) {\n logAttachmentStorageError(logger, '[attachment-upload] could not allocate ownership key', {\n path: logicalPath,\n error: redactErrorMessage(error),\n })\n return attachmentUploadError(\n 503,\n 'attachment_store_unavailable',\n ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n logicalPath,\n )\n }\n }\n const pathCheck = validatePath(path)\n if (!pathCheck.succeeded) {\n return attachmentUploadError(400, 'invalid_attachment_path', pathCheck.error, path)\n }\n // Small hardening over gtm: a batch whose sanitized names collide onto\n // the same store path (e.g. two variously-cased \"Report.PDF\" uploads)\n // would otherwise silently overwrite one with the other in phase 2.\n const duplicatePath = atomic ? logicalPath : path\n if (seenLogicalPaths.has(duplicatePath)) {\n return attachmentUploadError(\n 400,\n 'attachment_duplicate_path',\n `attachments must not repeat a path within one upload: ${duplicatePath}`,\n path,\n )\n }\n seenLogicalPaths.add(duplicatePath)\n\n // Authoritative aggregate check, against the actual decoded byte\n // length rather than the client-reported `file.size` checked above.\n totalBytes += bytes.length\n if (totalBytes > maxTotalBytes) {\n return attachmentUploadError(\n 413,\n 'attachments_total_too_large',\n attachmentTotalSizeErrorMessage(totalBytes, maxTotalBytes),\n )\n }\n\n const mediaType = sniff.mime ?? sniffMime(name)\n prepared.push({ path, ownershipId, name, bytes, originalName: file.name, size: bytes.length, mediaType, kind })\n }\n return { prepared }\n}\n\nasync function commitUploadBatch(\n prepared: PreparedWrite[],\n legacyWriter: WriteAttachmentFn | undefined,\n auth: { ok: true; scopeId: string; writeAttachment?: WriteAttachmentFn; writeAttachmentStream?: WriteAttachmentStreamFn } | { ok: true; scopeId: string; attachmentWriter?: AtomicAttachmentWriter },\n atomicWriter: AtomicAttachmentWriter | undefined,\n atomic: boolean,\n logger: AttachmentUploadLogger,\n) {\n // Phase 2: every file in the batch passed validation — write them all.\n const uploaded: ChatAttachmentInput[] = []\n const successfulWrites: SuccessfulAttachmentWrite[] = []\n for (const input of prepared) {\n if (!atomic) {\n let written: unknown\n try {\n written = await legacyWriter!(auth.scopeId, input.path, input.bytes, {\n mediaType: input.mediaType,\n name: input.name,\n originalName: input.originalName,\n size: input.size,\n })\n } catch (error) {\n logAttachmentStorageError(logger, '[attachment-upload] legacy writer failed', {\n path: input.path,\n error: redactErrorMessage(error),\n })\n return attachmentUploadError(\n 503,\n 'attachment_store_unavailable',\n ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n input.path,\n )\n }\n const result = inspectLegacyAttachmentWriteResult(written)\n if (!result) {\n logAttachmentStorageError(logger, '[attachment-upload] legacy writer returned an invalid result', {\n path: input.path,\n })\n return attachmentUploadError(\n 503,\n 'attachment_store_unavailable',\n ATTACHMENT_STORAGE_FAILURE_MESSAGE,\n input.path,\n )\n }\n if (!result.ok) {\n const reason = redactErrorMessage(result.reason)\n logAttachmentStorageError(logger, '[attachment-upload] legacy write rejected', {\n path: input.path,\n error: reason,\n })\n return attachmentUploadError(413, 'attachment_write_failed', reason, input.path)\n }\n uploaded.push({\n path: input.path,\n name: input.name,\n size: input.size,\n mediaType: input.mediaType,\n kind: input.kind,\n })\n continue\n }\n\n const ownershipId = input.ownershipId\n if (!ownershipId) {\n return attachmentUploadError(503, 'attachment_store_unavailable', ATTACHMENT_STORAGE_FAILURE_MESSAGE, input.path)\n }\n const ownership: AttachmentWriteOwnership = Object.freeze({ id: ownershipId, path: input.path })\n let written: Awaited<ReturnType<AtomicAttachmentWriter['write']>>\n try {\n written = await atomicWriter!.write(auth.scopeId, input.path, input.bytes, {\n mediaType: input.mediaType,\n name: input.name,\n originalName: input.originalName,\n size: input.size,\n ownership,\n })\n } catch (error) {\n const cleanupFailures = (await abortOwnership(atomicWriter!, auth.scopeId, ownership, logger)) +\n await rollbackSuccessfulWrites(successfulWrites, auth.scopeId, atomicWriter!, logger)\n logAttachmentStorageError(logger, '[attachment-upload] write failed', {\n path: input.path,\n ownershipId: ownership.id,\n cleanupFailures,\n error: redactErrorMessage(error),\n })\n return atomicAttachmentFailure(input.path, cleanupFailures)\n }\n const result = inspectAtomicAttachmentWriteResult(written, ownership)\n if (!result) {\n const cleanupFailures = (await abortOwnership(atomicWriter!, auth.scopeId, ownership, logger)) +\n await rollbackSuccessfulWrites(successfulWrites, auth.scopeId, atomicWriter!, logger)\n logAttachmentStorageError(logger, '[attachment-upload] writer returned a mismatched ownership receipt', {\n path: input.path,\n ownershipId: ownership.id,\n cleanupFailures,\n })\n return atomicAttachmentFailure(input.path, cleanupFailures)\n }\n if (!result.ok) {\n const cleanupFailures = (await rollbackSuccessfulWrites([\n { path: input.path, ownership, receipt: result.receipt },\n ], auth.scopeId, atomicWriter!, logger)) + await rollbackSuccessfulWrites(\n successfulWrites,\n auth.scopeId,\n atomicWriter!,\n logger,\n )\n logAttachmentStorageError(logger, '[attachment-upload] write rejected', {\n path: input.path,\n ownershipId: ownership.id,\n cleanupFailures,\n error: redactErrorMessage(result.reason),\n })\n return atomicAttachmentFailure(input.path, cleanupFailures)\n }\n successfulWrites.push({ path: input.path, ownership, receipt: result.receipt })\n uploaded.push({\n path: input.path,\n name: input.name,\n size: input.size,\n mediaType: input.mediaType,\n kind: input.kind,\n })\n }\n\n return Response.json({ files: uploaded })\n}\n","import type { IntelligenceClient } from '@tangle-network/agent-runtime/intelligence'\nimport type { ChatTurnRouteProducer } from './turn-routes'\nimport { withProducerStream } from './producer-stream'\n\n/** Host-resolved metadata only. Neither input nor output content is exported. */\nexport interface ChatTurnIntelligenceOptions {\n client: () => Pick<IntelligenceClient, 'traceRun'>\n sessionId: string\n userId?: string\n workspaceId?: string\n /** Exact execution identity, when retained by the execution owner. */\n runId?: string\n traceId?: string\n /** Requested model. This is not a receipt for the model that served. */\n model?: string\n /** Existing transport cancellation evidence; grants no new abort authority. */\n signal?: AbortSignal\n /** Receives no exception text, which may contain private customer material. */\n onObservationError?: () => void\n}\n\n/**\n * Observe the source iterator without an execution loop, relay, queue or eager\n * pull. The source still owns cancellation and serializes its own operations.\n * Stream termination is not task correctness, reviewer acceptance or delivery.\n */\nexport function observeChatTurnStream<TEvent>(\n source: AsyncGenerator<TEvent, void, unknown>,\n options: ChatTurnIntelligenceOptions,\n): AsyncGenerator<TEvent, void, unknown> {\n const { client, sessionId, userId, workspaceId, runId, traceId, model, signal, onObservationError } = options\n let state: 'idle' | 'running' | 'terminal' = 'idle'\n let startedAt = 0\n let interrupted = false\n let observation: Promise<void> | undefined\n\n const finish = (termination: 'exhausted' | 'interrupted' | 'failed'): Promise<void> => {\n if (state !== 'running') return observation ?? Promise.resolve()\n state = 'terminal'\n const completedAt = Date.now()\n const observedTermination = signal?.aborted ? 'interrupted' : termination\n observation = Promise.resolve().then(async () => {\n await client().traceRun({\n ...(runId !== undefined ? { runId } : {}),\n ...(traceId !== undefined ? { traceId } : {}),\n ...(model !== undefined ? { model } : {}),\n labels: {\n 'tangle.sessionId': sessionId,\n ...(userId !== undefined ? { 'tangle.userId': userId } : {}),\n ...(workspaceId !== undefined ? { 'tangle.workspaceId': workspaceId } : {}),\n 'tangle.observation.kind': 'stream-lifecycle',\n 'tangle.stream.termination': observedTermination,\n 'tangle.started_at_ms': startedAt,\n 'tangle.completed_at_ms': completedAt,\n 'tangle.duration_ms': Math.max(0, completedAt - startedAt),\n },\n }, async () => undefined)\n }).catch(() => {\n // Even a diagnostic callback must not replace an execution error.\n try { onObservationError?.() } catch { /* Best-effort telemetry only. */ }\n })\n return observation\n }\n\n const invoke = async (\n method: 'next' | 'return' | 'throw',\n operation: () => ReturnType<typeof source.next>,\n ): Promise<Awaited<ReturnType<typeof source.next>>> => {\n if (state === 'idle') {\n // A pre-start close still reaches the source to release factory-owned\n // resources, but does not manufacture an executed-turn observation.\n if (method === 'next') {\n state = 'running'\n startedAt = Date.now()\n } else {\n state = 'terminal'\n }\n }\n try {\n const result = await operation()\n // Apply return intent in source settlement order. A queued return must\n // not relabel an earlier naturally completed next() as cancellation.\n if (method === 'return' && state === 'running') interrupted = true\n if (result.done) await finish(interrupted ? 'interrupted' : 'exhausted')\n return result\n } catch (error) {\n await finish('failed')\n throw error\n }\n }\n\n return {\n [Symbol.asyncIterator]() { return this },\n next(...args) { return invoke('next', () => source.next(...args)) },\n return(value) { return invoke('return', () => source.return(value)) },\n throw(error) { return invoke('throw', () => source.throw(error)) },\n async [Symbol.asyncDispose]() { await this.return(undefined) },\n }\n}\n\n/**\n * Adapter for product producer factories. It preserves every declared\n * ChatTurnRouteProducer projection, lazily bound to the original receiver,\n * including class-backed or frozen producers. No output is read.\n */\nexport async function produceChatTurnWithIntelligence(\n options: ChatTurnIntelligenceOptions & {\n produce: () => ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>\n },\n): Promise<ChatTurnRouteProducer> {\n // Freeze scalar metadata before an asynchronous producer can change context.\n const snapshot: ChatTurnIntelligenceOptions = { ...options }\n const producer = await options.produce()\n const stream = observeChatTurnStream(producer.stream, snapshot)\n return withProducerStream(producer, stream)\n}\n","import { assertSafeKeySegment, type ObjectBody, type ObjectStore } from '../object-store'\nimport type { ReadAttachmentFn, WriteAttachmentFn } from './attachment-store'\nimport { defaultValidateAttachmentPath } from './attachment-validation'\n\n/** A product supplies its private object store after its request bindings are ready. */\nexport interface StoredChatAttachmentsOptions {\n store: ObjectStore | (() => ObjectStore)\n}\n\n/** Scoped stored bytes behind the existing chat attachment reader and writer ports.\n * Authorization remains in the product's routes; these functions validate storage keys.\n * The writer preserves the stable non-atomic port and does not promise batch rollback.\n */\nexport interface StoredChatAttachments {\n readAttachment: ReadAttachmentFn\n writeAttachment: WriteAttachmentFn\n getAttachmentObject(scopeId: string, path: string): Promise<ObjectBody | null>\n attachmentObjectKey(scopeId: string, path: string): string\n}\n\nfunction decodeAttachmentBase64(value: string): Uint8Array {\n const binary = atob(value)\n return Uint8Array.from(binary, (character) => character.charCodeAt(0))\n}\n\n/** Bind durable object storage without capturing an uninitialized request binding. */\nexport function createStoredChatAttachments(options: StoredChatAttachmentsOptions): StoredChatAttachments {\n const store = (): ObjectStore => typeof options.store === 'function' ? options.store() : options.store\n const attachmentObjectKey = (scopeId: string, path: string): string => {\n const scope = assertSafeKeySegment(scopeId)\n const checked = defaultValidateAttachmentPath(path)\n if (!checked.succeeded) throw new Error(checked.error)\n return `${scope}/${path}`\n }\n const getAttachmentObject = async (scopeId: string, path: string): Promise<ObjectBody | null> =>\n store().get(attachmentObjectKey(scopeId, path))\n\n const writeAttachment: WriteAttachmentFn = async (scopeId, path, content, opts) => {\n let bytes: Uint8Array\n let key: string\n try {\n bytes = typeof content === 'string' ? decodeAttachmentBase64(content) : content\n if (opts.size !== undefined && opts.size !== bytes.byteLength) {\n return { ok: false, reason: `Attachment size mismatch for ${path}: expected ${opts.size}, received ${bytes.byteLength}` }\n }\n key = attachmentObjectKey(scopeId, path)\n } catch (error) {\n return { ok: false, reason: `Attachment write failed for ${path}: ${error instanceof Error ? error.message : String(error)}` }\n }\n // Validation refusals use the legacy result; storage outages must reach\n // the route's opaque, retryable 503 response rather than its 413 refusal.\n await store().put(key, bytes, {\n ...(opts.mediaType ? { contentType: opts.mediaType } : {}),\n contentLength: bytes.byteLength,\n })\n return { ok: true }\n }\n\n const readAttachment: ReadAttachmentFn = async (scopeId, path) => {\n try {\n const object = await getAttachmentObject(scopeId, path)\n if (!object) return { ok: false, reason: `Attachment not found: ${path}` }\n const bytes = new Uint8Array(await new Response(object.stream()).arrayBuffer())\n if (bytes.byteLength !== object.size) {\n return { ok: false, reason: `Attachment size mismatch for ${path}: metadata ${object.size}, body ${bytes.byteLength}` }\n }\n return {\n ok: true,\n size: bytes.byteLength,\n bytes,\n ...(object.contentType ? { mediaType: object.contentType } : {}),\n }\n } catch (error) {\n return { ok: false, reason: `Attachment read failed for ${path}: ${error instanceof Error ? error.message : String(error)}` }\n }\n }\n return { readAttachment, writeAttachment, getAttachmentObject, attachmentObjectKey }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAM,sBAA2C,oBAAI,IAAI;AAAA,EACvD;AAAA,EAAQ;AAAA,EAAe;AAAA,EAAW;AAAA,EAAQ;AAAA,EAAY;AAAA,EAAW;AAAA,EACjE;AAAA,EAAgB;AAAA,EAChB;AAAA,EAAgB;AAAA,EAAiB;AAAA,EAAwB;AAAA,EACzD;AAAA,EAA6B;AAC/B,CAAC;AAED,SAAS,sBAAsB,SAAuB,WACpD,4BACoF;AACpF,MAAI,QAAQ,WAAW,QAAQ,YAAY,WAAY,OAAM,IAAI,MAAM,sDAAsD,QAAQ,OAAO,EAAE;AAC9I,MAAI,QAAQ,UAAW,OAAM,IAAI,MAAM,oFAAoF;AAC3H,MAAI,QAAQ,OAAO,YAAY,OAAO,KAAK,QAAQ,MAAM,QAAQ,EAAE,SAAS,GAAG;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