@tangle-network/agent-app 0.43.50 → 0.43.52

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/chat-routes/turn-routes.ts","../../src/chat-routes/sandbox-producer.ts","../../src/chat-routes/durable-projection.ts","../../src/chat-routes/upload.ts","../../src/chat-routes/resolve-attachments.ts","../../src/chat-routes/dispatch-parts.ts","../../src/chat-routes/promote-file-part.ts"],"sourcesContent":["/**\n * `createChatTurnRoutes` — the assembled server chat vertical (issue #188\n * Phase 1). One factory composing the pieces every product re-wired by hand:\n *\n * body parse/validate → `/web` `parseJsonObjectBody` + `./wire`\n * turn identity → `/stream` `resolveChatTurn` + agent-runtime\n * `deriveExecutionId`\n * producer → injected seam (sandbox lane via\n * `createSandboxChatProducer`; router lane is the\n * product's own `ChatTurnProducer`)\n * turn engine → agent-runtime `handleChatTurn` (verbatim)\n * durability → `/stream` turn-buffer tap, wired BY DEFAULT\n * (tee + drain keeps the turn running after a\n * client drop; replay serves the buffered tail)\n * persistence → injected `/chat-store`-shaped store\n * (user row on send, assistant row on completion)\n * interactions answer → `/interactions` `createInteractionAnswerRoute`\n *\n * Handlers are web-standard `Request → Response` (Workers, Node 18+, Deno) —\n * no router import. Auth/access is one injected `authorize` seam, composable\n * with `/app-auth` guards but not coupled to them.\n *\n * Six optional product seams let a complex turn-orchestrator compose the\n * vertical instead of hand-rolling a generator — each omittable to the exact\n * behavior above: `turnLock` (single-flight acquire/release around the turn),\n * `contextGate` (pre-producer domain-readiness short-circuit), `beforeTurn`\n * (observe + augment the producer input), `lifecycle` (deterministic\n * start/complete/error telemetry), `heartbeat` (keepalive during silent\n * producer waits), plus `onRawEvent` (the raw producer events, for telemetry).\n * `handleChatTurn` stays the engine — the seams only wrap its input, its\n * producer stream, and its settle.\n *\n * Seam stability: `lifecycle`, `heartbeat`, and `turnLock` are generic and\n * stable (`turnLock` graduated with `/turn-stream`'s shared DO adapter, #221).\n * `contextGate`, `beforeTurn`, and `onRawEvent` are `@experimental` — proven\n * by a single consumer (gtm's chat vertical, #200) and may change once a\n * second consumer exercises them. They stay FLAT top-level options (not\n * grouped under a `hooks` object): that grouping would break the shipped\n * consumer's call for no mechanism gain, and this package's exports are\n * additive-only.\n */\n\nimport { deriveExecutionId, handleChatTurn } from '@tangle-network/agent-runtime'\nimport type { ChatTurnIdentity, ChatTurnProducer } from '@tangle-network/agent-runtime'\nimport { mentionInputToPart, toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport {\n createInteractionAnswerRoute,\n type InteractionAnswerRoute,\n type InteractionAnswerRouteOptions,\n} from '../interactions/route'\nimport {\n coalesceDeltas,\n createBufferedTurnTap,\n normalizeClientTurnId,\n replayTurnEvents,\n resolveChatTurn,\n type PersistedChatMessageForTurn,\n type TurnEventStore,\n} from '../stream/index'\nimport { parseJsonObjectBody } from '../web/index'\nimport {\n assertPromptPartsWithinCap,\n ChatTurnInputError,\n parseChatTurnParts,\n parseFileMentions,\n type ChatTurnFilePartInput,\n type ChatTurnPartInput,\n type ChatTurnRequestPayload,\n type FileMention,\n} from './wire'\n\n// ── seams ───────────────────────────────────────────────────────────────────\n\n/** Usage receipt persisted onto the assistant message (the flattened\n * `step-finish` shape `/chat-store`'s columns mirror). */\nexport interface ChatTurnUsage {\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n costUsd?: number\n}\n\n/** What the route persists — a structural subset of `/chat-store`'s\n * `ChatStore`, so `createChatStore(db, tables)` satisfies it directly and a\n * product with its own persistence adapts without importing drizzle. */\nexport interface ChatTurnMessageStore {\n listMessages(threadId: string): Promise<Array<{\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n }>>\n appendMessage(input: {\n threadId: string\n role: 'user' | 'assistant'\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n }): Promise<unknown>\n}\n\n/** `ChatTurnProducer` plus the persisted projection the assembly reads after\n * drain. `createSandboxChatProducer` returns this; a router-lane producer\n * may omit the optional members (finalText persists as a single text part). */\nexport interface ChatTurnRouteProducer extends ChatTurnProducer {\n assistantParts?(): Array<Record<string, unknown>>\n usage?(): ChatTurnUsage\n model?: string\n}\n\nexport type ChatTurnAuthorization<TContext> =\n | {\n ok: true\n tenantId: string\n userId: string\n context: TContext\n /** When `false`, skip the `role:'user'` message insert for this turn — for\n * a product-dispatched / synthetic turn (e.g. a follow-up the product\n * raised itself) that must not surface a new user row. Composes with —\n * never overrides — the engine's retry-dedup: `authorize` runs before\n * turn identity is resolved, so it cannot tell a retry from a fresh turn;\n * a turn already deduped stays deduped. Omit / `true` → today's behavior.\n * @experimental Single-consumer; shape may change. */\n insertUserMessage?: boolean\n }\n | { ok: false; response: Response }\n\nexport interface ChatTurnAuthorizeArgs {\n request: Request\n intent: 'turn' | 'replay' | 'running'\n /** Parsed, validated POST body (turn intent only). */\n body?: ChatTurnRequestPayload\n /** The buffered turn id being replayed (replay intent only). */\n turnId?: string\n /** The thread whose running turns are being discovered (running intent only). */\n threadId?: string\n}\n\nexport interface ChatTurnProduceArgs<TContext> {\n request: Request\n body: ChatTurnRequestPayload\n identity: ChatTurnIdentity\n context: TContext\n /** The message to send: plain text, or parts when the client attached\n * files (a text part is prepended from `content` when present). */\n prompt: string | ChatTurnPartInput[]\n /** Stable id for cross-process reconnect (`deriveExecutionId`). */\n executionId: string\n /** The turn-buffer id announced to the client for replay. */\n turnStreamId: string\n priorMessages: PersistedChatMessageForTurn[]\n}\n\n/** One event as it crosses the route: the producer's own vocabulary, or an\n * injected keepalive. Same shape the engine forwards verbatim. */\ntype ChatRouteEvent = { type: string; data?: Record<string, unknown> }\n\n/** Best-effort human-readable cause from a terminal `error` /\n * `session.run.failed` event's `data`. */\nfunction failureReasonOf(data: Record<string, unknown> | undefined): string | undefined {\n if (!data) return undefined\n const message = data.message ?? data.error ?? data.reason\n if (typeof message === 'string' && message.length > 0) return message\n return undefined\n}\n\n/** Keepalive emitted while the producer is quiet (long tool calls, first-token\n * wait) so client watchdogs stay re-armed. One is emitted each time\n * `intervalMs` elapses with no producer event; the window resets on every real\n * event, so a chatty producer never triggers one. The product owns the event\n * shape (`type` + `data`). Omit → no keepalives (today's behavior). */\nexport interface ChatTurnHeartbeat {\n intervalMs: number\n event(info: { elapsedMs: number; tick: number }): ChatRouteEvent\n}\n\n/** Patch a `beforeTurn` hook returns to augment the producer's input. Omitted\n * fields keep the route-assembled value; the product's `produce` still owns\n * the system prompt. */\nexport interface ChatTurnInputPatch {\n prompt?: string | ChatTurnPartInput[]\n priorMessages?: PersistedChatMessageForTurn[]\n}\n\n/** Pre-turn readiness verdict — proceed, or short-circuit with the product's\n * own `Response` (e.g. a canned assistant reply asking for missing context).\n * Distinct from `authorize`: this gates domain readiness, not access. */\nexport type ChatTurnGateResult =\n | { proceed: true }\n | { proceed: false; response: Response }\n\n/** Single-flight lock verdict — acquired (with an opaque handle passed back to\n * `release`), or already held (short-circuit with the product's 409-style\n * `Response`). */\nexport type ChatTurnLockResult =\n | { acquired: true; handle?: unknown }\n | { acquired: false; response: Response }\n\n/** Async acquire/release wrapped around the turn. `acquire` runs before any\n * side effect; `release` runs once when the turn settles — including on a\n * short-circuit or a throw. */\nexport interface ChatTurnLock<TContext> {\n acquire(args: ChatTurnProduceArgs<TContext>): ChatTurnLockResult | Promise<ChatTurnLockResult>\n release(handle: unknown): void | Promise<void>\n}\n\ninterface ChatTurnLifecycleBase<TContext> {\n identity: ChatTurnIdentity\n executionId: string\n turnStreamId: string\n context: TContext\n}\nexport interface ChatTurnLifecycleStart<TContext> extends ChatTurnLifecycleBase<TContext> {\n startedAt: number\n}\nexport interface ChatTurnLifecycleComplete<TContext> extends ChatTurnLifecycleBase<TContext> {\n finalText: string\n usage: ChatTurnUsage\n durationMs: number\n}\nexport interface ChatTurnLifecycleError<TContext> extends ChatTurnLifecycleBase<TContext> {\n error: unknown\n durationMs: number\n}\n\n/** Deterministic run telemetry: `onTurnStart` fires before the producer runs;\n * exactly one of `onTurnComplete` / `onTurnError` fires after the turn\n * settles, always after `onTurnStart`. Failure is derived from the turn's own\n * `error` / `session.run.failed` events (or a drain throw), not the engine's\n * lifecycle envelope. Hook errors are swallowed — telemetry never fails a\n * turn. */\nexport interface ChatTurnLifecycle<TContext> {\n onTurnStart?(info: ChatTurnLifecycleStart<TContext>): void | Promise<void>\n onTurnComplete?(info: ChatTurnLifecycleComplete<TContext>): void | Promise<void>\n onTurnError?(info: ChatTurnLifecycleError<TContext>): void | Promise<void>\n}\n\nexport interface CreateChatTurnRoutesOptions<TContext = void> {\n /** Names the product in `deriveExecutionId` so retries land on the same\n * substrate execution. */\n projectId: string\n /** Authenticate + authorize the caller for a turn or a replay. The only\n * product-supplied access step: session auth, thread/workspace access,\n * seat/balance gates, rate limits all live here. */\n authorize(args: ChatTurnAuthorizeArgs): Promise<ChatTurnAuthorization<TContext>>\n /** Thread/message persistence (`/chat-store`'s store or a product adapter). */\n store: ChatTurnMessageStore\n /** Turn-event buffer (`createD1TurnEventStore(env.DB)` or `/turn-stream`'s\n * `createDurableObjectTurnEventStore(env.TURN_STREAM_DO)` in production,\n * `createMemoryTurnEventStore()` in tests). Wired by default — every turn\n * is buffered and replayable. */\n turnStore: TurnEventStore\n /** Build the turn's event stream. Sandbox lane: `streamSandboxPrompt(...)`\n * wrapped in `createSandboxChatProducer`. Router/openai-compat lane: the\n * product's own producer. May be async (box resolution). */\n produce(args: ChatTurnProduceArgs<TContext>): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>\n /** Single-flight lock acquired before any side effect and released once when\n * the turn settles (including short-circuit/throw). `/turn-stream`'s\n * `createDurableTurnLock` is the shared DO-backed implementation. Omit →\n * no lock. */\n turnLock?: ChatTurnLock<TContext>\n /** Pre-turn readiness gate that can short-circuit with a product `Response`\n * before the producer runs (the user row is already persisted). Runs after\n * `turnLock.acquire`, before `beforeTurn`. Omit → always proceed.\n * @experimental Single-consumer (gtm, #200); shape may change. */\n contextGate?(args: ChatTurnProduceArgs<TContext>): ChatTurnGateResult | Promise<ChatTurnGateResult>\n /** Observe the assembled producer input and optionally augment it (rewrite\n * the prompt / prior messages) before the producer runs. Omit → no change.\n * @experimental Single-consumer (gtm, #200); shape may change. */\n beforeTurn?(args: ChatTurnProduceArgs<TContext>): ChatTurnInputPatch | void | Promise<ChatTurnInputPatch | void>\n /** Deterministic run telemetry (start / complete / error) with identity and\n * timing. Omit → no telemetry. */\n lifecycle?: ChatTurnLifecycle<TContext>\n /** Keepalive injected while the producer is quiet. Omit → no keepalives. */\n heartbeat?: ChatTurnHeartbeat\n /** Observe each event the producer emits, before the engine frames it and\n * before any heartbeat injection (the raw sidecar-producer events, for\n * telemetry). Never alters the stream; errors are swallowed. Distinct from\n * `onEvent`, which sees the engine-framed stream incl. lifecycle envelopes.\n * @experimental Single-consumer (gtm, #200); shape may change. */\n onRawEvent?(event: ChatRouteEvent, context: TContext): void | Promise<void>\n /** Pre-persist transform of the final text (e.g. `/redact`'s `redactPII`).\n * Live stream is never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Post-processing after a turn settles (billing, titles, audit). Fires with\n * `failed:true` + `failureReason` when the turn carried a terminal error\n * event (model 402 / rate-limit / server error) instead of a clean\n * completion, so products skip the deduct and render an error row rather\n * than billing an empty turn and marking it done. A turn that THROWS never\n * reaches this hook (the engine skips it on a producer throw). Errors are\n * swallowed by the engine — they never fail a streamed turn. */\n onTurnComplete?(input: {\n identity: ChatTurnIdentity\n finalText: string\n context: TContext\n failed: boolean\n failureReason?: string\n }): Promise<void>\n /** Per-event side channel (product broadcast). The turn-buffer tap is\n * already wired; this runs in addition. */\n onEvent?(event: { type: string; data?: Record<string, unknown> }, context: TContext): void | Promise<void>\n /** Trace flush handed to `waitUntil` (OTLP export). */\n traceFlush?(context: TContext): Promise<void>\n /** Compose the interaction-answer endpoints (`/interactions`). Omit when the\n * product has no sidecar ask channel. */\n interactions?: InteractionAnswerRouteOptions\n /** Byte budget for inline prompt parts. Default `INLINE_PARTS_MAX_BYTES`. */\n maxInlinePartBytes?: number\n /** Per-flush coalescer for the turn buffer. Default `coalesceDeltas` (this\n * assembly streams the client vocabulary's `{type:'text'|'reasoning',\n * text}` lines, which it merges). A producer streaming raw\n * `message.part.updated` events passes `coalesceChatStreamEvents`. */\n coalesceTurnEvents?: (events: unknown[]) => unknown[]\n replay?: { pollMs?: number; timeoutMs?: number }\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\nexport interface ChatTurnRoutes {\n /** POST — run one turn, streaming NDJSON. First line is\n * `{type:'turn', turnId}` (the replay handle); the rest is the engine's\n * event protocol. Pass the platform's `waitUntil` so the turn keeps\n * running (and buffering) after a client disconnect. */\n turn(request: Request, ctx?: { waitUntil?(p: Promise<unknown>): void }): Promise<Response>\n /** GET — replay a buffered turn from `?fromSeq=` (0 = everything), then\n * follow it live until it completes. */\n replay(request: Request, params: { turnId: string }): Promise<Response>\n /** GET `?threadId=` — the reconnect-discovery endpoint: the turn ids still\n * running on a thread, so a client that reloaded mid-turn can re-attach to\n * the live stream via {@link replay} instead of losing it. Returns `[]` when\n * the turn store cannot enumerate running turns (`listRunning` unimplemented). */\n running(request: Request): Promise<Response>\n /** list/answer endpoints from `/interactions`; null when not configured. */\n interactions: InteractionAnswerRoute | null\n}\n\n// ── body validation ────────────────────────────────────────────────────────\n\nfunction errorResponse(err: ChatTurnInputError): Response {\n return Response.json({ code: err.code, error: err.message }, { status: err.status })\n}\n\ninterface ParsedTurnBody {\n payload: ChatTurnRequestPayload\n content: string\n fileParts: ChatTurnFilePartInput[]\n mentions: FileMention[]\n turnId: string | undefined\n}\n\nfunction validateTurnBody(body: Record<string, unknown>, maxInlinePartBytes: number | undefined): ParsedTurnBody {\n const threadId = typeof body.threadId === 'string' ? body.threadId.trim() : ''\n if (!threadId) throw new ChatTurnInputError('Missing threadId')\n const rawContent = body.content ?? body.message ?? ''\n if (typeof rawContent !== 'string') throw new ChatTurnInputError('content must be a string')\n const content = rawContent.trim()\n const fileParts = parseChatTurnParts(body.parts)\n // Path references, not bytes — validated for traversal/charset/count, never\n // counted against the inline-parts byte budget below.\n const mentions = parseFileMentions(body.mentions)\n // A mention is a turn's whole payload often enough to count: \"@chart.png\"\n // with no prose is a real ask, and the pointer block the mentions produce is\n // prompt content the model reads.\n if (!content && fileParts.length === 0 && mentions.length === 0) {\n throw new ChatTurnInputError('Missing content (send text, parts, mentions, or any combination)')\n }\n assertPromptPartsWithinCap(fileParts, maxInlinePartBytes)\n let turnId: string | undefined\n try {\n turnId = normalizeClientTurnId(body.turnId)\n } catch (err) {\n throw new ChatTurnInputError(err instanceof Error ? err.message : 'Invalid turnId')\n }\n return {\n // The VALIDATED, deduped mention list replaces the raw one on the payload,\n // so every downstream seam (`authorize`, `contextGate`, `beforeTurn`,\n // `produce`) reads checked paths and never the request's own.\n payload: { ...body, threadId, content, mentions } as ChatTurnRequestPayload,\n content,\n fileParts,\n mentions,\n turnId,\n }\n}\n\n/** File parts persist onto the user message verbatim — the wire shape is the\n * persisted `ChatFilePart`/`ChatImagePart` vocabulary already. Mentions get\n * the one mapping step their own vocabulary needs. The typed projection is\n * `/chat-store`'s (same boundary as the assistant hop).\n *\n * Mentions persist as parts rather than being folded into the prompt because\n * the prompt is not readable back: a retry rebuilds the turn from the stored\n * row, and a transcript draws its pills from it. Turning them INTO prompt\n * text stays the product's job — only the product knows how to resolve a\n * workspace-relative path to an in-box one (`fileMentionsToParts`'\n * `resolvePath` seam), so the route never dispatches them itself. */\nfunction userPartsWithFiles(\n userParts: Array<Record<string, unknown>>,\n fileParts: ChatTurnFilePartInput[],\n mentions: FileMention[],\n): ChatMessagePart[] {\n return toChatMessageParts([\n ...userParts,\n ...fileParts.map((part) => ({ ...part })),\n ...mentions.map((mention) => ({ ...mentionInputToPart(mention) })),\n ])\n}\n\n// ── producer-stream wrappers (heartbeat + raw tap) ───────────────────────────\n\n/** Fire `onRawEvent` for each producer event, before the engine frames it.\n * Best-effort — a telemetry throw is logged, never propagated. */\nasync function* tapRawEvents(\n source: AsyncIterable<ChatRouteEvent>,\n onRawEvent: (event: ChatRouteEvent) => void | Promise<void>,\n log: (message: string, meta?: Record<string, unknown>) => void,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n for await (const event of source) {\n try {\n await onRawEvent(event)\n } catch (err) {\n log('[chat-routes] onRawEvent failed', { error: err instanceof Error ? err.message : String(err) })\n }\n yield event\n }\n}\n\n/** Inject a keepalive whenever `intervalMs` elapses with no source event. The\n * silent window (elapsed + tick) resets on every real event, so a producer\n * that keeps emitting never triggers a heartbeat. Closes the source on early\n * return, matching a `for await` over it. */\nasync function* withStreamHeartbeat(\n source: AsyncIterable<ChatRouteEvent>,\n intervalMs: number,\n makeEvent: (info: { elapsedMs: number; tick: number }) => ChatRouteEvent,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n let pending = iterator.next()\n let windowStart = Date.now()\n let tick = 0\n for (;;) {\n let timer: ReturnType<typeof setTimeout> | undefined\n let winner: 'event' | 'heartbeat'\n try {\n const heartbeat = new Promise<'heartbeat'>((resolve) => {\n timer = setTimeout(() => resolve('heartbeat'), intervalMs)\n })\n winner = await Promise.race([pending.then(() => 'event' as const), heartbeat])\n } finally {\n // Clear the pending timer on EVERY exit — including a `pending`\n // rejection — so a rejected source never orphans a setTimeout that\n // keeps the runtime alive for up to `intervalMs`.\n if (timer !== undefined) clearTimeout(timer)\n }\n if (winner === 'heartbeat') {\n tick += 1\n yield makeEvent({ elapsedMs: Date.now() - windowStart, tick })\n continue\n }\n const result = await pending\n if (result.done) return\n yield result.value\n pending = iterator.next()\n windowStart = Date.now()\n tick = 0\n }\n } finally {\n await iterator.return?.()\n }\n}\n\n// ── the factory ────────────────────────────────────────────────────────────\n\nexport function createChatTurnRoutes<TContext = void>(\n options: CreateChatTurnRoutesOptions<TContext>,\n): ChatTurnRoutes {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n\n async function turn(request: Request, ctx?: { waitUntil?(p: Promise<unknown>): void }): Promise<Response> {\n const [rawBody, badBody] = await parseJsonObjectBody(request)\n if (badBody) return badBody\n\n let parsed: ParsedTurnBody\n try {\n parsed = validateTurnBody(rawBody, options.maxInlinePartBytes)\n } catch (err) {\n if (err instanceof ChatTurnInputError) return errorResponse(err)\n throw err\n }\n const { payload, content, fileParts, mentions, turnId } = parsed\n\n const auth = await options.authorize({ request, intent: 'turn', body: payload })\n if (!auth.ok) return auth.response\n const { tenantId, userId, context } = auth\n\n // Turn identity: reuse the just-persisted user row on a retry (same\n // turnId or identical trailing content) instead of double-inserting.\n const existingMessages = (await options.store.listMessages(payload.threadId)).map((m) => ({\n id: m.id,\n role: m.role,\n content: m.content,\n parts: (m.parts ?? null) as PersistedChatMessageForTurn['parts'],\n }))\n const chatTurn = resolveChatTurn({ existingMessages, userContent: content, turnId })\n\n const identity: ChatTurnIdentity = {\n tenantId,\n sessionId: payload.threadId,\n userId,\n turnIndex: chatTurn.turnIndex,\n }\n const executionId = deriveExecutionId({\n projectId: options.projectId,\n sessionId: payload.threadId,\n turnIndex: chatTurn.turnIndex,\n })\n const turnStreamId = crypto.randomUUID()\n\n const prompt: string | ChatTurnPartInput[] =\n fileParts.length === 0\n ? content\n : content\n ? [{ type: 'text', text: content }, ...fileParts]\n : [...fileParts]\n\n // The producer input every pre-turn seam reads (and `beforeTurn` may\n // rewrite). Mutated in place before the producer's deferred first pull.\n let produceArgs: ChatTurnProduceArgs<TContext> = {\n request,\n body: payload,\n identity,\n context,\n prompt,\n executionId,\n turnStreamId,\n priorMessages: chatTurn.priorMessages,\n }\n\n // Single-flight lock: acquire before any side effect. `release` runs\n // exactly once — in the drain's `finally` on a normal turn, or right here\n // on a short-circuit / throw.\n let lockAcquired = false\n let lockHandle: unknown\n let lockReleased = false\n const releaseLock = async (): Promise<void> => {\n if (!lockAcquired || lockReleased) return\n lockReleased = true\n try {\n await options.turnLock!.release(lockHandle)\n } catch (err) {\n log('[chat-routes] turnLock.release failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n if (options.turnLock) {\n const acquired = await options.turnLock.acquire(produceArgs)\n if (!acquired.acquired) return acquired.response\n lockAcquired = true\n lockHandle = acquired.handle\n }\n\n // Turn state, hoisted so the pre-stream `catch` can settle the lifecycle\n // (fire `onTurnError`, close the span) even when a seam throws\n // synchronously before the drain — the drain would otherwise be the only\n // path that runs the terminal hook.\n let producer: ChatTurnRouteProducer | undefined\n let runFailed = false\n // Data of the event that marked the run failed — handed to `onTurnError`\n // when no drain throw supplies a richer cause.\n let lastFailureData: Record<string, unknown> | undefined\n let turnStartedAtMs = 0\n let turnStarted = false\n let lifecycleSettled = false\n\n // Exactly one terminal lifecycle hook, after the turn settles (idempotent).\n // Failure is this route's own verdict (`runFailed` from error/failed\n // events, or a drain/sync throw), not the engine's envelope.\n const fireTerminalLifecycle = async (failed: boolean, terminalError: unknown): Promise<void> => {\n if (lifecycleSettled) return\n lifecycleSettled = true\n const lifecycle = options.lifecycle\n if (!lifecycle) return\n const durationMs = Date.now() - turnStartedAtMs\n try {\n if (failed) {\n await lifecycle.onTurnError?.({\n identity, executionId, turnStreamId, context, durationMs,\n error: terminalError ?? lastFailureData ?? new Error('chat turn failed'),\n })\n } else {\n await lifecycle.onTurnComplete?.({\n identity, executionId, turnStreamId, context, durationMs,\n finalText: producer?.finalText() ?? '',\n usage: producer?.usage?.() ?? {},\n })\n }\n } catch (err) {\n log('[chat-routes] lifecycle terminal hook failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n try {\n // The product (via `authorize`) may suppress the user-row insert for a\n // dispatched/synthetic turn. AND-composition: it can only subtract, never\n // resurrect a turn the engine already deduped as a retry.\n const insertUserMessage = chatTurn.shouldInsertUserMessage && (auth.insertUserMessage ?? true)\n if (insertUserMessage) {\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'user',\n content,\n parts: userPartsWithFiles(chatTurn.userParts, fileParts, mentions),\n })\n }\n\n // Domain-readiness gate: may short-circuit with the product's own\n // response before the producer runs. The user row above is kept (a real\n // user turn); the gate's response is the assistant side of it.\n if (options.contextGate) {\n const gate = await options.contextGate(produceArgs)\n if (!gate.proceed) {\n await releaseLock()\n return gate.response\n }\n }\n\n // Observe + optionally augment the assembled producer input.\n if (options.beforeTurn) {\n const patch = await options.beforeTurn(produceArgs)\n if (patch) produceArgs = { ...produceArgs, ...patch }\n }\n\n // Durability tap: every engine event buffers (coalesced) so a dropped\n // client replays the tail. Live delivery rides the Response body, not the\n // tap, so `write` is intentionally absent.\n const tap = createBufferedTurnTap({\n store: options.turnStore,\n turnId: turnStreamId,\n scopeId: payload.threadId,\n coalesce: options.coalesceTurnEvents ?? coalesceDeltas,\n })\n const turnMarker = { type: 'turn', turnId: turnStreamId }\n await tap.onEvent(turnMarker)\n\n turnStartedAtMs = Date.now()\n turnStarted = true\n if (options.lifecycle?.onTurnStart) {\n try {\n await options.lifecycle.onTurnStart({\n identity, executionId, turnStreamId, context, startedAt: turnStartedAtMs,\n })\n } catch (err) {\n log('[chat-routes] lifecycle.onTurnStart failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n const result = handleChatTurn({\n identity,\n waitUntil: ctx?.waitUntil,\n log,\n hooks: {\n // The engine wants a synchronous producer; box resolution is async —\n // defer it into the generator's first pull.\n produce: () => ({\n stream: (async function* () {\n producer = await options.produce(produceArgs)\n let source: AsyncIterable<ChatRouteEvent> = producer.stream\n if (options.onRawEvent) {\n source = tapRawEvents(source, (event) => options.onRawEvent!(event, context), log)\n }\n if (options.heartbeat) {\n source = withStreamHeartbeat(source, options.heartbeat.intervalMs, options.heartbeat.event)\n }\n for await (const event of source) yield event\n })(),\n finalText: () => producer?.finalText() ?? '',\n }),\n onEvent: async (event) => {\n if (event.type === 'session.run.failed' || event.type === 'error') {\n runFailed = true\n lastFailureData = event.data\n }\n await tap.onEvent(event)\n if (options.onEvent) await options.onEvent(event, context)\n },\n ...(options.transformFinalText ? { transformFinalText: options.transformFinalText } : {}),\n persistAssistantMessage: async ({ finalText }) => {\n // The typed boundary: stream-normalizer records → stored vocabulary\n // (validating projection owned by /chat-store — no cast here). The\n // scalar `finalText` arrives already transformed by the engine; the\n // producer's text PARTS are raw, so the same transform must run over\n // each text segment before persistence or a redaction (legal PII)\n // leaks at rest through message.parts.\n const rawParts = producer?.assistantParts ? producer.assistantParts() : undefined\n const projected =\n rawParts && options.transformFinalText\n ? await Promise.all(\n rawParts.map(async (part) =>\n String((part as { type?: unknown }).type ?? '') === 'text'\n ? { ...part, text: await options.transformFinalText!(String((part as { text?: unknown }).text ?? '')) }\n : part,\n ),\n )\n : rawParts\n const parts = projected ? toChatMessageParts(projected) : undefined\n if (!finalText.trim() && (!parts || parts.length === 0)) return\n const usage = producer?.usage?.() ?? {}\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'assistant',\n content: finalText,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(producer?.model ? { model: producer.model } : {}),\n ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),\n ...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cacheWriteTokens !== undefined ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),\n ...(usage.costUsd !== undefined ? { costUsd: usage.costUsd } : {}),\n })\n },\n ...(options.onTurnComplete\n ? {\n // Wired into the engine's completion hook, which fires only when\n // the stream ended without throwing. A terminal error EVENT\n // (not a throw) still lands here — so surface `runFailed` so the\n // product skips billing an errored turn instead of marking it\n // complete with empty text.\n onTurnComplete: ({ identity: turnIdentity, finalText }: { identity: ChatTurnIdentity; finalText: string }) =>\n options.onTurnComplete!({\n identity: turnIdentity,\n finalText,\n context,\n failed: runFailed,\n ...(runFailed ? { failureReason: failureReasonOf(lastFailureData) } : {}),\n }),\n }\n : {}),\n ...(options.traceFlush ? { traceFlush: () => options.traceFlush!(context) } : {}),\n },\n })\n\n // Tee: one branch to the live client, one drained under waitUntil so the\n // turn (and its buffering via onEvent) runs to completion after a client\n // drop — the engine body executes as it is pulled.\n const [clientBody, drainBody] = result.body.tee()\n const drained = (async () => {\n const reader = drainBody.getReader()\n let drainError: unknown\n try {\n for (;;) {\n const { done } = await reader.read()\n if (done) break\n }\n } catch (err) {\n drainError = err\n log('[chat-routes] turn drain failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n const failed = runFailed || drainError !== undefined\n try {\n await tap.done(failed ? 'error' : 'complete')\n } catch (err) {\n log('[chat-routes] turn buffer finalize failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n await fireTerminalLifecycle(failed, drainError)\n await releaseLock()\n })()\n if (ctx?.waitUntil) ctx.waitUntil(drained)\n else void drained.catch(() => {})\n\n // Announce the replay handle before the engine's first event.\n const encoder = new TextEncoder()\n const marker = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(encoder.encode(`${JSON.stringify(turnMarker)}\\n`))\n controller.close()\n },\n })\n const body = concatStreams([marker, clientBody])\n\n return new Response(body, {\n headers: {\n 'Content-Type': result.contentType,\n 'Cache-Control': 'no-cache',\n },\n })\n } catch (err) {\n // A throw before the turn began streaming (user-insert, gate, beforeTurn,\n // lifecycle-start, tap setup, engine construction, tee). If the turn had\n // already started, settle the lifecycle with `onTurnError` (close the\n // span) — the drain never ran to do it. Then release the lock, propagate.\n if (turnStarted) await fireTerminalLifecycle(true, err)\n await releaseLock()\n throw err\n }\n }\n\n async function replay(request: Request, params: { turnId: string }): Promise<Response> {\n const turnId = params.turnId?.trim()\n if (!turnId) return Response.json({ error: 'Missing turnId' }, { status: 400 })\n const auth = await options.authorize({ request, intent: 'replay', turnId })\n if (!auth.ok) return auth.response\n\n const fromSeqRaw = new URL(request.url).searchParams.get('fromSeq')\n const fromSeq = fromSeqRaw ? Math.max(0, Math.trunc(Number(fromSeqRaw)) || 0) : 0\n\n const encoder = new TextEncoder()\n const events = replayTurnEvents({\n store: options.turnStore,\n turnId,\n fromSeq,\n ...(options.replay?.pollMs !== undefined ? { pollMs: options.replay.pollMs } : {}),\n ...(options.replay?.timeoutMs !== undefined ? { timeoutMs: options.replay.timeoutMs } : {}),\n })\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n const { done, value } = await events.next()\n if (done) {\n controller.close()\n return\n }\n controller.enqueue(encoder.encode(`${value.event}\\n`))\n },\n cancel() {\n void events.return(undefined)\n },\n })\n return new Response(body, {\n headers: {\n 'Content-Type': 'application/x-ndjson',\n 'Cache-Control': 'no-cache',\n },\n })\n }\n\n async function running(request: Request): Promise<Response> {\n const threadId = new URL(request.url).searchParams.get('threadId')?.trim()\n if (!threadId) return Response.json({ error: 'Missing threadId' }, { status: 400 })\n const auth = await options.authorize({ request, intent: 'running', threadId })\n if (!auth.ok) return auth.response\n // `listRunning` is optional on the store; a store that cannot enumerate\n // running turns simply reports none — the client falls back to the persisted\n // transcript, never to a hang.\n const ids = (await options.turnStore.listRunning?.(threadId)) ?? []\n return Response.json({ running: ids })\n }\n\n return {\n turn,\n replay,\n running,\n interactions: options.interactions ? createInteractionAnswerRoute(options.interactions) : null,\n }\n}\n\n/** Sequential concat of byte streams (marker line, then the engine body). */\nfunction concatStreams(streams: ReadableStream<Uint8Array>[]): ReadableStream<Uint8Array> {\n let index = 0\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n if (!reader) {\n const next = streams[index++]\n if (!next) {\n controller.close()\n return\n }\n reader = next.getReader()\n }\n const { done, value } = await reader.read()\n if (done) {\n reader = null\n continue\n }\n controller.enqueue(value)\n return\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n for (const stream of streams.slice(index)) await stream.cancel(reason)\n },\n })\n}\n","/**\n * Sandbox lane: bridge a raw sandbox event stream (`streamSandboxPrompt`) into\n * the `ChatTurnProducer` shape agent-runtime's `handleChatTurn` consumes AND\n * the client vocabulary `/web-react`'s `dispatchChatStreamLine` already parses\n * (`text` / `reasoning` / `tool_call` / `tool_result` / `usage` /\n * `interaction`). Legal and tax each hand-rolled this mapping differently;\n * this is that middle, composed from `/stream`'s normalizers — no new loop\n * logic, no SDK import (the event source is an injected `AsyncIterable`).\n *\n * Alongside the live mapping it accumulates the PERSISTED projection — the\n * `message.parts` rows `/chat-store` stores — via `normalizePersistedPart` /\n * `mergePersistedPart` / `finalizeAssistantParts`, plus the usage receipt from\n * `step-finish` parts. `createChatTurnRoutes` reads both after drain.\n */\n\nimport {\n cancelStatusFor,\n interactionPartKey,\n interactionToPersistedPart,\n isRenderableInteractionKind,\n parseInteractionCancel,\n parseInteractionRequest,\n} from '../interactions/contract'\nimport {\n parsePlanSubmittedEvent,\n planToPersistedPart,\n} from '../plans/index'\nimport {\n asRecord,\n asString,\n finalizeAssistantParts,\n getPartKey,\n mergePersistedPart,\n normalizePersistedPart,\n normalizeToolEvent,\n type JsonRecord,\n type StreamEvent,\n} from '../stream/index'\nimport type { ChatTurnRouteProducer, ChatTurnUsage } from './turn-routes'\n\n/** Outcome of a `promoteFilePart` attempt. `key`, when given, becomes the\n * persisted part's row key (e.g. `attachment:<path>`) so repeat promotions\n * of the same underlying file fold into one segment instead of appending;\n * omitted, the default `getPartKey` keying applies.\n *\n * On failure, `part` is an OPTIONAL substitute part to persist in place of\n * the raw url-bearing one — this is how a product swaps in a transcript\n * notice (gtm persists a `warning` notice part, never the transient url) for\n * a failed promotion instead of baking a `data:`/sandbox-path url into the\n * durable row. When `part` is present it is persisted (via the same\n * `recordPersistedPart` path as a success, honoring the optional `key`);\n * when absent, the existing raw-part fallback applies unchanged — so a\n * caller that only returns `{ succeeded: false, reason }` keeps today's\n * behavior verbatim. */\nexport type FilePartPromotionOutcome =\n | { succeeded: true; part: Record<string, unknown>; key?: string }\n | { succeeded: false; reason: string; part?: Record<string, unknown>; key?: string }\n\nexport interface SandboxChatProducerOptions {\n /** The raw sandbox event stream (e.g. `streamSandboxPrompt(...)`). */\n events: AsyncIterable<unknown>\n /** Recorded on the persisted assistant message. */\n model?: string\n /** Which ask kinds the product renders a card for. Anything else is\n * auto-declined (see `declineInteraction`) so the run never hangs in the\n * broker waiting on a card no client will show. Default: question/plan. */\n isRenderableInteraction?: (kind: string) => boolean\n /** Resolve a non-renderable ask (wire `respondToSessionInteraction` with the\n * session's sidecar connection). Without it, non-renderable asks are only\n * logged — the run stays blocked until the broker times out. */\n declineInteraction?: (id: string) => Promise<void>\n /** Opt-in eager promotion of harness-emitted `file` parts. Unset, a `file`\n * part persists exactly as the harness sent it — a transient `url` (a\n * `data:` URI or in-sandbox path) baked into the transcript, which is\n * today's behavior and stays byte-identical if this is never wired. Set,\n * EVERY `file` part (never `image`, never any other kind) is routed\n * through this callback instead of `recordPersistedPart`'s default\n * fallback — including a part with NEITHER `id` NOR `url` (gtm always\n * attempts promotion; such a part simply fails \"carries no url\" and\n * resolves through the same failure path as any other rejection, rather\n * than being persisted raw and unpromoted) — so the product can durably\n * write the bytes and swap in a path-bearing part before the raw url ever\n * reaches the persisted transcript. Keyed per source-prefixed `id:<id>` /\n * `url:<url>` (an `id` and a `url` sharing the same text must never collide\n * onto one memo entry) and memoized by PROMISE (not result), so re-emitted\n * snapshot events for the same part —\n * the harness resends the whole part on every update, not just deltas —\n * fold onto the one in-flight or settled attempt rather than promoting\n * twice or racing two concurrent writes; a raw part with neither `id` nor\n * `url` cannot be keyed, so it is invoked UN-memoized (once per event) —\n * each occurrence is its own attempt. A rejecting promise is caught,\n * logged via `log`, and treated as `succeeded: false`. On `succeeded:\n * false` the outcome's optional `part` (a substitute — e.g. a warning\n * notice — see {@link FilePartPromotionOutcome}) persists in its place when\n * given; otherwise the raw part persists exactly as it does today — this\n * seam only decides whether to call the promoter and what to do with its\n * outcomes; the promotion mechanics (vault write, key derivation, notice\n * construction) live in the caller's callback, not here. */\n promoteFilePart?: (raw: JsonRecord) => Promise<FilePartPromotionOutcome>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\ninterface TextTracker {\n /** Full accumulated text per part key, to derive suffix deltas from\n * snapshot-only harness events. */\n seen: Map<string, string>\n}\n\n/** Delta to emit for one text/reasoning part update: prefer the harness's\n * explicit delta; otherwise diff the snapshot against what was already\n * emitted for that part (snapshot-only harnesses re-send the whole text). */\nfunction textDelta(tracker: TextTracker, key: string, part: JsonRecord, rawDelta: unknown): string {\n const explicit = typeof rawDelta === 'string' ? rawDelta : undefined\n const previous = tracker.seen.get(key) ?? ''\n if (explicit !== undefined) {\n tracker.seen.set(key, previous + explicit)\n return explicit\n }\n const snapshot = asString(part.text) ?? asString(part.content) ?? ''\n if (!snapshot) return ''\n if (snapshot.startsWith(previous)) {\n tracker.seen.set(key, snapshot)\n return snapshot.slice(previous.length)\n }\n // The snapshot replaced the text outright — emit it whole; the persisted\n // projection stays correct because finalText is authoritative at finalize.\n tracker.seen.set(key, snapshot)\n return snapshot\n}\n\nfunction usageFromStepFinish(part: JsonRecord, usage: ChatTurnUsage): void {\n const tokens = asRecord(part.tokens)\n if (tokens) {\n const cache = asRecord(tokens.cache)\n const add = (current: number | undefined, value: unknown): number | undefined => {\n const n = Number(value)\n if (!Number.isFinite(n)) return current\n return (current ?? 0) + n\n }\n usage.inputTokens = add(usage.inputTokens, tokens.input)\n usage.outputTokens = add(usage.outputTokens, tokens.output)\n usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning)\n if (cache) {\n usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read)\n usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write)\n }\n }\n const cost = Number(part.cost)\n if (Number.isFinite(cost)) usage.costUsd = (usage.costUsd ?? 0) + cost\n}\n\nexport function createSandboxChatProducer(options: SandboxChatProducerOptions): ChatTurnRouteProducer {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n const renderable = options.isRenderableInteraction ?? isRenderableInteractionKind\n\n let fullText = ''\n const partOrder: string[] = []\n const partMap = new Map<string, JsonRecord>()\n const tracker: TextTracker = { seen: new Map() }\n const usage: ChatTurnUsage = {}\n /** Tool ids already announced as `tool_call` / settled as `tool_result`. */\n const announcedTools = new Set<string>()\n const settledTools = new Set<string>()\n /** Id-less step boundaries: one occurrence per key, never merged. */\n let stepCounter = 0\n /** `promoteFilePart` memo, keyed by `id ?? url` of the raw part. Holds the\n * PROMISE (never the settled result) so concurrent duplicate events for\n * the same part await the one in-flight attempt instead of each starting\n * their own; the promise never rejects (see below), so a later duplicate\n * reading a settled entry reuses that first outcome — success or\n * failure — rather than retrying. */\n const promotedFileParts = new Map<string, Promise<FilePartPromotionOutcome>>()\n\n function recordPersistedPart(part: JsonRecord, delta: string | undefined, keyOverride?: string): void {\n const persisted = normalizePersistedPart(part)\n if (!persisted) return\n const key = keyOverride ?? getPartKey(persisted)\n if (!partMap.has(key)) partOrder.push(key)\n partMap.set(key, mergePersistedPart(partMap.get(key), persisted, delta))\n }\n\n async function* stream(): AsyncGenerator<StreamEvent, void, unknown> {\n for await (const raw of options.events) {\n const record = asRecord(raw)\n if (!record || typeof record.type !== 'string') continue\n // Fold bare tool_call/tool_result shapes into the canonical part event;\n // everything else keeps its original record (verbatim forwarding must\n // not strip fields outside `data`).\n const normalized = normalizeToolEvent({ type: record.type, data: asRecord(record.data) })\n const event = normalized.type === 'message.part.updated' ? normalized : (record as unknown as StreamEvent)\n\n if (event.type === 'message.part.updated') {\n const part = asRecord(event.data?.part)\n if (!part) continue\n const rawDelta = event.data?.delta\n const partType = String(part.type ?? '')\n\n if (partType === 'text' || partType === 'reasoning') {\n const key = getPartKey(part)\n const delta = textDelta(tracker, key, part, rawDelta)\n recordPersistedPart(part, delta || undefined)\n if (delta) {\n if (partType === 'text') fullText += delta\n yield { type: partType, text: delta } as StreamEvent & { text: string }\n }\n continue\n }\n\n if (partType === 'tool') {\n recordPersistedPart(part, undefined)\n const persisted = partMap.get(getPartKey(part))\n const state = asRecord(persisted?.state)\n const toolId = String(persisted?.id ?? '')\n const toolName = String(persisted?.tool ?? 'tool')\n if (toolId && !announcedTools.has(toolId)) {\n announcedTools.add(toolId)\n yield {\n type: 'tool_call',\n call: { toolCallId: toolId, toolName, args: asRecord(state?.input) ?? {} },\n } as StreamEvent\n }\n const status = String(state?.status ?? '')\n if (toolId && (status === 'completed' || status === 'error') && !settledTools.has(toolId)) {\n settledTools.add(toolId)\n yield {\n type: 'tool_result',\n toolCallId: toolId,\n toolName,\n outcome: {\n ok: status === 'completed',\n ...(state?.output !== undefined ? { result: state.output } : {}),\n ...(asString(state?.error) ? { message: asString(state?.error) } : {}),\n },\n } as StreamEvent\n }\n continue\n }\n\n if (partType === 'step-finish') {\n usageFromStepFinish(part, usage)\n // Persist the per-step receipt too (unique key per occurrence: the\n // parts have no id and two receipts must never merge into one).\n recordPersistedPart(part, undefined, `step-finish:#${stepCounter++}`)\n const promptTokens = usage.inputTokens ?? 0\n const completionTokens = usage.outputTokens ?? 0\n if (promptTokens || completionTokens) {\n yield { type: 'usage', usage: { promptTokens, completionTokens } } as StreamEvent\n }\n continue\n }\n\n if (partType === 'step-start') {\n recordPersistedPart(part, undefined, `step-start:#${stepCounter}`)\n continue\n }\n\n if (partType === 'file' && options.promoteFilePart) {\n const promote = options.promoteFilePart\n // Prefixed by source (`id:`/`url:`) rather than the bare raw string —\n // an `id` and a `url` that happen to share the same text (e.g. both\n // `\"abc\"`) would otherwise collide onto one memo entry and fold two\n // unrelated parts' promotions together. Internal Map key only; never\n // observable outside this module.\n const rawId = asString(part.id)\n const rawUrl = asString(part.url)\n const memoKey = rawId ? `id:${rawId}` : rawUrl ? `url:${rawUrl}` : undefined\n // Always invoke the callback for a `file` part when one is wired —\n // gtm never skips promotion outright, even for a part with neither\n // `id` nor `url` (it simply fails \"carries no url\" and resolves\n // through the ordinary failure path). Memoization by PROMISE only\n // applies when there is something to key it on; keyless parts are\n // invoked un-memoized, once per occurrence.\n //\n // `Promise.resolve().then(...)` (rather than calling `promote(part)`\n // directly) so a SYNC throw from a non-async `promoteFilePart` is\n // captured into the promise chain instead of escaping this function\n // call outright — `.catch` below only ever sees a rejection, never a\n // thrown exception that unwinds past `attempt()`.\n const attempt = (): Promise<FilePartPromotionOutcome> =>\n Promise.resolve()\n .then(() => promote(part))\n .catch((err) => {\n const reason = err instanceof Error ? err.message : String(err)\n log('[chat-routes] file part promotion threw', { key: memoKey ?? '(keyless)', error: reason })\n return { succeeded: false as const, reason }\n })\n\n let pending: Promise<FilePartPromotionOutcome>\n if (memoKey) {\n pending = promotedFileParts.get(memoKey) ?? attempt()\n promotedFileParts.set(memoKey, pending)\n } else {\n pending = attempt()\n }\n\n const outcome = await pending\n if (outcome.succeeded) {\n recordPersistedPart(outcome.part, undefined, outcome.key)\n } else if (outcome.part) {\n // Substitute part (e.g. a warning notice) takes the raw part's\n // place in the transcript — the transient url never lands.\n recordPersistedPart(outcome.part, undefined, outcome.key)\n } else {\n recordPersistedPart(part, undefined)\n }\n continue\n }\n\n // Remaining storable kinds (file/image/subtask) have no live\n // vocabulary line; they persist so the transcript keeps them.\n recordPersistedPart(part, undefined)\n continue\n }\n\n if (event.type === 'interaction') {\n const parsed = parseInteractionRequest(asRecord(record.data))\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed interaction event', { error: parsed.error })\n continue\n }\n if (renderable(parsed.value.kind)) {\n recordPersistedPart(\n interactionToPersistedPart(parsed.value, 'pending'),\n undefined,\n interactionPartKey(parsed.value.id),\n )\n yield event\n continue\n }\n // Non-renderable ask: the run is blocked in the broker until someone\n // answers. Decline it so the turn proceeds instead of hanging.\n if (options.declineInteraction) {\n try {\n await options.declineInteraction(parsed.value.id)\n } catch (err) {\n log('[chat-routes] failed to auto-decline interaction', {\n id: parsed.value.id,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n } else {\n log('[chat-routes] non-renderable interaction with no declineInteraction wired', {\n id: parsed.value.id,\n kind: parsed.value.kind,\n })\n }\n continue\n }\n\n if (event.type === 'interaction.cancel') {\n const parsed = parseInteractionCancel(asRecord(record.data))\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed interaction.cancel event', { error: parsed.error })\n continue\n }\n const key = interactionPartKey(parsed.value.id)\n const existing = partMap.get(key)\n if (existing?.type === 'interaction' && existing.status === 'pending') {\n recordPersistedPart({\n ...existing,\n status: cancelStatusFor(parsed.value.reason),\n ...(parsed.value.reason ? { cancelReason: parsed.value.reason } : {}),\n }, undefined, key)\n }\n yield event\n continue\n }\n\n if (event.type === 'plan.submitted') {\n const parsed = parsePlanSubmittedEvent(record)\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed plan.submitted event', { error: parsed.error })\n continue\n }\n recordPersistedPart(planToPersistedPart(parsed.value), undefined)\n yield event\n continue\n }\n\n if (event.type === 'result') {\n const finalText = asString(event.data?.finalText)\n if (finalText) fullText = finalText\n const resultUsage = asRecord(event.data?.usage)\n if (resultUsage) {\n const input = Number(resultUsage.inputTokens)\n const output = Number(resultUsage.outputTokens)\n if (Number.isFinite(input)) usage.inputTokens = input\n if (Number.isFinite(output)) usage.outputTokens = output\n }\n continue\n }\n\n // Everything else (error, lifecycle) forwards\n // verbatim — the client parser ignores unknown types.\n yield event\n }\n\n }\n\n return {\n stream: stream(),\n finalText: () => fullText,\n assistantParts: () => finalizeAssistantParts(partOrder, partMap, fullText),\n usage: () => usage,\n ...(options.model ? { model: options.model } : {}),\n }\n}\n","import { getPartKey, mergePersistedPart, type StreamEvent } from '../stream/index'\nimport type { ChatTurnRouteProducer } from './turn-routes'\n\nexport interface ChatRouteDurableProjection {\n observe(event: unknown): void | Promise<void>\n materialize(): Array<Record<string, unknown>> | Promise<Array<Record<string, unknown>>>\n}\n\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. 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 * `createUploadRoute` — the multimodal middle. Accepts multipart file uploads\n * and returns `PromptInputPart`-shaped descriptors the client echoes back on\n * send (`ChatTurnRequestPayload.parts`):\n *\n * ≤ inlineMaxBytes (700 KiB default) → inline `data:` URI part — rides the\n * turn body directly, no sandbox round trip.\n * > inlineMaxBytes → written into the sandbox workspace (base64 through the\n * structural `write` seam — `box.fs` satisfies it) and referenced by\n * `path`. Mandatory two-step: the gateway caps request bodies at ~1 MiB,\n * so a large file can never ride the prompt POST.\n *\n * The sink is structural (no sandbox-SDK import); products pass `box.fs`.\n *\n * @remarks Sole consumer today is the `--chat` scaffold (`create-agent-app\n * --chat` → `template-chat/src/chat.ts`), the reference multimodal path. The\n * fleet apps (gtm/tax/legal/insurance) each keep their OWN upload route into a\n * durable vault (KV, or AES-GCM-encrypted R2) — a different persistence model\n * from this route's inline-`data:`-or-ephemeral-sandbox-workspace split, so\n * they don't (and shouldn't) route through it. This stays the scaffold's proven\n * upload pattern, not a fleet primitive; keep that distinction in mind before\n * widening its surface.\n */\n\nimport type { ChatTurnFilePartInput } from './wire'\n\n/** 700 KiB: base64 inflates ~4/3, so an inline part stays comfortably under\n * the ~1 MiB gateway body cap alongside the JSON envelope. */\nexport const UPLOAD_INLINE_MAX_BYTES = 700 * 1024\n\n/** 8 MiB default ceiling per file — one base64 `write` call handles it. Raise\n * it only with a sink that can take the bigger single write. */\nexport const UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024\n\n/** Structural match of the sandbox SDK's `box.fs` write surface (v0.10.5+:\n * `encoding: 'base64'` is the worker-safe binary path). */\nexport interface SandboxUploadSink {\n write(path: string, content: string, options?: { encoding?: 'utf8' | 'base64' }): Promise<unknown>\n}\n\nexport type UploadAuthorization =\n | {\n ok: true\n /** Where large files land. Absent/null: only inline uploads are\n * accepted and an over-inline-cap file is rejected with 413. */\n sink?: SandboxUploadSink | null\n /** Per-request override of the workspace directory large files go to. */\n uploadDir?: string\n }\n | { ok: false; response: Response }\n\nexport interface CreateUploadRouteOptions {\n /** Authenticate the caller and resolve the sandbox file sink (usually\n * `ensureWorkspaceSandbox(...)` → `box.fs`). */\n authorize(args: { request: Request }): Promise<UploadAuthorization>\n /** Inline-vs-sandbox threshold. Default {@link UPLOAD_INLINE_MAX_BYTES}. */\n inlineMaxBytes?: number\n /** Hard per-file cap. Default {@link UPLOAD_MAX_FILE_BYTES}. */\n maxFileBytes?: number\n /** Workspace directory for path-ref files. Default `'uploads'`. */\n uploadDir?: string\n}\n\n/** One uploaded file, ready for the composer chip and the turn body. */\nexport interface UploadedChatFile {\n id: string\n name: string\n size: number\n mediaType: string\n /** True when the part carries the bytes inline (`data:` URI). */\n inline: boolean\n /** Echo this back verbatim in `ChatTurnRequestPayload.parts`. */\n part: ChatTurnFilePartInput\n}\n\n/** Path-safe file name: basename only, conservative charset, length-capped. */\nexport function sanitizeUploadFilename(name: string): string {\n const base = name.split(/[\\\\/]/).pop() ?? 'file'\n const safe = base.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '_')\n return (safe || 'file').slice(0, 120)\n}\n\nconst BASE64_CHUNK = 0x8000\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n let binary = ''\n for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK))\n }\n return btoa(binary)\n}\n\nfunction uploadError(status: number, code: string, error: string): Response {\n return Response.json({ code, error }, { status })\n}\n\nexport function createUploadRoute(options: CreateUploadRouteOptions): (request: Request) => Promise<Response> {\n const inlineMaxBytes = options.inlineMaxBytes ?? UPLOAD_INLINE_MAX_BYTES\n const maxFileBytes = options.maxFileBytes ?? UPLOAD_MAX_FILE_BYTES\n\n return async function upload(request: Request): Promise<Response> {\n const auth = await options.authorize({ request })\n if (!auth.ok) return auth.response\n const sink = auth.sink ?? null\n const uploadDir = (auth.uploadDir ?? options.uploadDir ?? 'uploads').replace(/\\/+$/, '')\n\n let form: FormData\n try {\n form = await request.formData()\n } catch {\n return uploadError(400, 'INVALID_UPLOAD', 'Expected a multipart/form-data body with file fields')\n }\n const files: File[] = []\n form.forEach((value) => {\n if (value instanceof File) files.push(value)\n })\n if (files.length === 0) {\n return uploadError(400, 'INVALID_UPLOAD', 'No files in the upload body')\n }\n\n const uploaded: UploadedChatFile[] = []\n for (const file of files) {\n const name = sanitizeUploadFilename(file.name)\n const mediaType = file.type || 'application/octet-stream'\n const partType: ChatTurnFilePartInput['type'] = mediaType.startsWith('image/') ? 'image' : 'file'\n\n if (file.size > maxFileBytes) {\n return uploadError(\n 413,\n 'FILE_TOO_LARGE',\n `${name} is ${file.size}B, over the ${maxFileBytes}B per-file cap`,\n )\n }\n\n const id = crypto.randomUUID()\n if (file.size <= inlineMaxBytes) {\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: true,\n part: {\n type: partType,\n filename: name,\n mediaType,\n url: `data:${mediaType};base64,${base64}`,\n },\n })\n continue\n }\n\n if (!sink) {\n return uploadError(\n 413,\n 'SANDBOX_REQUIRED',\n `${name} is ${file.size}B, over the ${inlineMaxBytes}B inline cap, and no sandbox is available to hold it`,\n )\n }\n const path = `${uploadDir}/${id}-${name}`\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n await sink.write(path, base64, { encoding: 'base64' })\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: false,\n part: { type: partType, filename: name, mediaType, path },\n })\n }\n\n return Response.json({ files: uploaded })\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 { formatBytes, type ChatAttachmentInput, type ChatAttachmentKind } from './wire'\nimport { attachmentInputToPart, type ChatAttachmentPart } from '../chat-store/parts'\nimport type { ReadAttachmentFn } from './attachment-store'\n\nexport type ResolveChatAttachmentsResult =\n | { succeeded: true; value: ChatAttachmentPart[] }\n | { succeeded: false; error: string }\n\n/** Verdict of a path check: OK, or a rejection naming why. Mirrors\n * `SandboxMentionPathCheck` in `./wire`. */\nexport type AttachmentPathCheck =\n | { succeeded: true }\n | { succeeded: false; error: string }\n\n/** Most files a single request may carry. */\nexport const ATTACHMENT_MAX_COUNT = 10\n\n/** Aggregate raw-byte ceiling across one message's attachments. */\nexport const MAX_ATTACHMENT_TOTAL_BYTES = 25 * 1024 * 1024\n\n/** Longest attachment display name accepted — bounds what gets echoed into the\n * prompt block and rendered as a chip label. */\nconst MAX_ATTACHMENT_NAME_LENGTH = 256\n\n/** Human-readable error for a message whose combined attachments exceed the\n * aggregate raw-byte ceiling. Ported to match gtm's `attachmentTotalSizeErrorMessage`\n * (attachment-limits.ts:93-95) verbatim, via the shared {@link formatBytes} —\n * e.g. \"Attachments total 25MB; each message is limited to 25MB\", not raw\n * byte counts. */\nexport function attachmentTotalSizeErrorMessage(totalBytes: number, limitBytes: number): string {\n return `Attachments total ${formatBytes(totalBytes)}; each message is limited to ${formatBytes(limitBytes)}`\n}\n\nfunction isAttachmentKind(value: unknown): value is ChatAttachmentKind {\n return value === 'image' || value === 'file'\n}\n\n/** C0 control characters (0x00–0x1F) plus DEL (0x7F) — covers `\\n`/`\\r`/`\\t`.\n * A `name` or `path` carrying one of these has no legitimate use here and\n * everything to gain from an attacker: {@link buildAttachmentPromptBlock} in\n * `/chat-store` renders both fields verbatim into the dispatched agent\n * prompt, so an embedded newline fabricates new prompt lines (a\n * prompt-injection vector) rather than naming a file. Rejected at this\n * boundary — not merely neutralized downstream — so the wire never accepts\n * the input in the first place; a legitimate name/path never contains one. */\nconst CONTROL_CHARS = /[\\x00-\\x1F\\x7F]/\n\n/**\n * Default path validator when a caller supplies none. Rejects the ways a path\n * picked in a client can escape the store root — traversal (`..` segment),\n * absolute (leading `/`), backslashes, null bytes, control characters (see\n * {@link CONTROL_CHARS} — a path also feeds {@link buildAttachmentPromptBlock}'s\n * `(vault: ${path})` pointer, so it is exposed to the same injection surface as\n * `name`) — plus a dotfile/hidden segment (a leading `.` on any segment).\n * Generalized from gtm's `validateVaultFilePath`, in the spirit of\n * `validateSandboxMentionPath` (`/chat-routes`'s wire mention-path validator) —\n * but the dotfile rejection here is INTENTIONALLY stricter than that sibling:\n * an uploaded attachment path is sanitized store-relative storage the product\n * itself assigned, whereas a mention path points at a file that already exists\n * in the sandbox and may legitimately live under a dotfile segment. A caller\n * that needs gtm's exact (looser) rule can supply `validatePath` to override\n * this default entirely.\n */\nexport function defaultValidateAttachmentPath(path: string): AttachmentPathCheck {\n if (path.includes('\\0')) return { succeeded: false, error: 'attachment path must not contain null bytes' }\n if (path.includes('\\\\')) return { succeeded: false, error: 'attachment path must not contain backslashes' }\n if (CONTROL_CHARS.test(path)) return { succeeded: false, error: 'attachment path must not contain control characters' }\n if (path.startsWith('/')) return { succeeded: false, error: 'attachment path must be store-relative, not absolute' }\n const segments = path.split('/')\n if (segments.some((segment) => segment === '..')) {\n return { succeeded: false, error: 'attachment path must not contain \"..\" segments' }\n }\n if (segments.some((segment) => segment.startsWith('.'))) {\n return { succeeded: false, error: 'attachment path must not contain a hidden (dotfile) segment' }\n }\n return { succeeded: true }\n}\n\nfunction parseAttachmentInput(\n value: unknown,\n index: number,\n validatePath: (path: string) => AttachmentPathCheck,\n): { succeeded: true; value: ChatAttachmentInput } | { succeeded: false; error: string } {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return { succeeded: false, error: `attachments[${index}] must be an object` }\n }\n const record = value as Record<string, unknown>\n\n const path = record.path\n if (typeof path !== 'string' || !path) {\n return { succeeded: false, error: `attachments[${index}].path must be a non-empty string` }\n }\n const name = record.name\n if (typeof name !== 'string' || !name.trim()) {\n return { succeeded: false, error: `attachments[${index}].name must be a non-empty string` }\n }\n if (name.length > MAX_ATTACHMENT_NAME_LENGTH) {\n return { succeeded: false, error: `attachments[${index}].name must not exceed ${MAX_ATTACHMENT_NAME_LENGTH} characters` }\n }\n if (CONTROL_CHARS.test(name)) {\n return { succeeded: false, error: `attachments[${index}].name must not contain control characters` }\n }\n const size = record.size\n if (typeof size !== 'number' || !Number.isFinite(size)) {\n return { succeeded: false, error: `attachments[${index}].size must be a finite number` }\n }\n if (size < 0) {\n return { succeeded: false, error: `attachments[${index}].size must not be negative` }\n }\n const mediaType = record.mediaType\n if (typeof mediaType !== 'string') {\n return { succeeded: false, error: `attachments[${index}].mediaType must be a string` }\n }\n const kind = record.kind\n if (!isAttachmentKind(kind)) {\n return { succeeded: false, error: `attachments[${index}].kind must be \"image\" or \"file\"` }\n }\n\n const pathCheck = validatePath(path)\n if (!pathCheck.succeeded) return { succeeded: false, error: pathCheck.error }\n\n return { succeeded: true, value: { path, name, size, mediaType, kind } }\n}\n\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 maxCount = options.maxCount ?? ATTACHMENT_MAX_COUNT\n const maxTotalBytes = options.maxTotalBytes ?? MAX_ATTACHMENT_TOTAL_BYTES\n const validatePath = options.validatePath ?? defaultValidateAttachmentPath\n\n if (value === undefined || value === null) return { succeeded: true, value: [] }\n if (!Array.isArray(value)) return { succeeded: false, error: 'attachments must be an array' }\n if (value.length > maxCount) {\n return { succeeded: false, error: `attachments must not exceed ${maxCount} entries` }\n }\n\n const inputs: ChatAttachmentInput[] = []\n const seenPaths = new Set<string>()\n for (let index = 0; index < value.length; index += 1) {\n const parsed = parseAttachmentInput(value[index], index, validatePath)\n if (!parsed.succeeded) return parsed\n if (seenPaths.has(parsed.value.path)) {\n return { succeeded: false, error: `attachments must not repeat a path: ${parsed.value.path}` }\n }\n seenPaths.add(parsed.value.path)\n inputs.push(parsed.value)\n }\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","/**\n * `buildDispatchParts` — assemble the `PromptInputPart[]` a turn carrying\n * attachments and/or `@`-mentions dispatches to the sandbox. `parts[0]` is\n * always the full prompt text (typed text plus the attachment + mention pointer\n * blocks); each attachment or mention becomes one media part. An attachment\n * (read from the product store via the injected reader) draws the inline byte\n * budget first; a mention (read from the LIVE box) takes what is left. A file\n * inlines as a `data:` URI when it fits the remaining budget, otherwise demotes\n * to an in-box path part so the whole request stays under the proxy cap. Every\n * media part is deduped by its resolved absolute path. This module only\n * produces the parts array; the caller decides when a turn dispatches parts\n * instead of a plain string.\n *\n * Storage-parameterized port of gtm-agent's `dispatch-parts.ts`: the vault\n * default reader is dropped (`readAttachment` is REQUIRED — the product supplies\n * its store adapter), the `GTM_SANDBOX_VAULT_DIR` prefixing becomes the required\n * `resolveAttachmentPath` seam, the `GTM_MULTIMODAL_FORCE_PATH` env fallback\n * becomes an explicit `forcePath` flag, and every budget cap reads an overridable\n * `./wire` constant. Kept behavior-identical for gtm-agent#618 adoption (the\n * demotion math and emitted part shapes reproduce its dispatched prompt bytes).\n */\n\nimport { flattenHistory, type PromptInputPart } from '../sandbox'\nimport {\n statSandboxFileSize,\n readSandboxBinaryBytes,\n type SandboxExecChannel,\n} from '../sandbox/binary-read'\nimport {\n mediaTypeForMentionPath,\n base64WireLen,\n DISPATCH_REQUEST_MAX_BYTES,\n DISPATCH_STRUCTURAL_RESERVE_BYTES,\n DISPATCH_MAX_PARTS,\n} from './wire'\nimport type { ChatAttachmentPart, ChatMentionPart } from '../chat-store/parts'\nimport { bytesToBase64 } from './upload'\nimport type { ReadAttachmentFn } from './attachment-store'\n\nexport type { PromptInputPart }\n\nexport type DispatchPartsOutcome =\n | { succeeded: true; value: PromptInputPart[] }\n | { succeeded: false; error: string }\n\n/** One mention file's size (always) and inline bytes (only when the caller\n * asked for them — a path-only mention never reads its bytes). */\ntype SandboxMentionReadOutcome =\n | { succeeded: true; value: { size: number; base64?: string } }\n | { succeeded: false; error: string }\n\nexport type ReadSandboxMentionFn = (\n box: SandboxExecChannel,\n absolutePath: string,\n options: { readBytes: boolean },\n) => Promise<SandboxMentionReadOutcome>\n\nfunction byteLen(value: string): number {\n return new TextEncoder().encode(value).length\n}\n\n/**\n * Default mention reader: stats the in-box file (which also proves it still\n * exists — a since-deleted mention fails loud here), then reads its bytes only\n * when the caller wants to inline it. Both hops cross the sandbox exec channel\n * via the substrate's binary-read helpers.\n */\nasync function readSandboxMention(\n box: SandboxExecChannel,\n absolutePath: string,\n options: { readBytes: boolean },\n): Promise<SandboxMentionReadOutcome> {\n const stat = await statSandboxFileSize(box, absolutePath)\n if (!stat.succeeded) {\n return { succeeded: false, error: `mentioned sandbox file missing or unreadable: ${absolutePath} — ${stat.error}` }\n }\n if (!options.readBytes) return { succeeded: true, value: { size: stat.value } }\n\n const read = await readSandboxBinaryBytes(box, absolutePath, stat.value)\n if (!read.succeeded) {\n return { succeeded: false, error: `mentioned sandbox file read failed: ${absolutePath} — ${read.error}` }\n }\n return { succeeded: true, value: { size: stat.value, base64: bytesToBase64(read.value.bytes) } }\n}\n\n/** HARD INVARIANT: a media part (`image`/`file`) must carry exactly one of a\n * non-empty `data:` URL or a non-empty absolute path — never both, never\n * neither. The OpenCode adapter falls back to `part.url || part.path || \"\"`,\n * so a part violating this silently degrades to an empty target instead of\n * failing loud. */\nfunction violatesUrlPathXor(part: PromptInputPart): boolean {\n if (part.type === 'text') return false\n const hasUrl = typeof part.url === 'string' && part.url.startsWith('data:')\n const hasPath = typeof part.path === 'string' && part.path.startsWith('/')\n return hasUrl === hasPath\n}\n\nexport interface BuildDispatchPartsInput {\n text: string\n attachments: ChatAttachmentPart[]\n mentions?: ChatMentionPart[]\n history: Array<{ role: 'user' | 'assistant'; content: string }>\n systemPrompt: string\n /** Serialized size of the backend profile the SDK inlines into the same\n * prompt request body — a large, non-negotiable rider that must come out of\n * the inline budget or near-cap attachments 413 at the proxy instead of\n * demoting to path parts. */\n profileWireBytes: number\n /** The product's workspace/tenant key, passed to `readAttachment`. */\n scopeId: string\n /** Maps an attachment's store-relative path to the in-box absolute path a\n * path-based part references (same seam style as `fileMentionsToParts`'s\n * `resolvePath`). */\n resolveAttachmentPath: (path: string) => string\n /** Maps a mention's workspace-relative path to its in-box absolute path.\n * Default: {@link BuildDispatchPartsInput.resolveAttachmentPath} — in gtm the\n * vault mount roots both; a product that mounts them apart overrides this. */\n resolveMentionPath?: (path: string) => string\n /** The turn's already-ensured box — required when `mentions` is non-empty\n * (mention bytes are read from the live box, not the store). */\n box?: SandboxExecChannel\n /** Force every media part to a path reference, skipping all inlining. */\n forcePath?: boolean\n /** REQUIRED store reader for attachment content — no default (the product\n * owns its store; see {@link ReadAttachmentFn}). */\n readAttachment: ReadAttachmentFn\n readSandboxMention?: ReadSandboxMentionFn\n /** Whole-request proxy cap. Default {@link DISPATCH_REQUEST_MAX_BYTES}. */\n requestMaxBytes?: number\n /** JSON-envelope reserve off the top of the request cap. Default\n * {@link DISPATCH_STRUCTURAL_RESERVE_BYTES}. */\n structuralReserveBytes?: number\n /** Sidecar per-request parts-array cap. Default {@link DISPATCH_MAX_PARTS}. */\n maxParts?: number\n}\n\n/** Content of one attachment read, normalized to the base64 a `data:` URI\n * needs — `base64` reused verbatim, else `bytes` encoded once. */\nfunction readResultToBase64(read: { base64?: string; bytes?: Uint8Array }): string | undefined {\n if (typeof read.base64 === 'string') return read.base64\n if (read.bytes) return bytesToBase64(read.bytes)\n return undefined\n}\n\nexport async function buildDispatchParts(input: BuildDispatchPartsInput): Promise<DispatchPartsOutcome> {\n const readMention = input.readSandboxMention ?? readSandboxMention\n const resolveMentionPath = input.resolveMentionPath ?? input.resolveAttachmentPath\n const forcePath = input.forcePath ?? false\n const mentions = input.mentions ?? []\n const requestMaxBytes = input.requestMaxBytes ?? DISPATCH_REQUEST_MAX_BYTES\n const structuralReserveBytes = input.structuralReserveBytes ?? DISPATCH_STRUCTURAL_RESERVE_BYTES\n const maxParts = input.maxParts ?? DISPATCH_MAX_PARTS\n\n const parts: PromptInputPart[] = [{ type: 'text', text: input.text }]\n // Absolute in-box paths already emitted — a file both attached and mentioned\n // (or mentioned twice) rides as a single media part.\n const emittedAbsPaths = new Set<string>()\n\n const flattenedForSizing = flattenHistory(input.text, input.history)\n // May go negative when history/systemPrompt alone are large — every\n // attachment then fails the `runningInline + cost <= inlineBudget` check\n // below and demotes to a path part, which is correct behavior (path parts\n // don't draw on this budget), not a failure.\n const inlineBudget =\n requestMaxBytes\n - base64WireLen(byteLen(flattenedForSizing))\n - byteLen(JSON.stringify(input.systemPrompt))\n - input.profileWireBytes\n - structuralReserveBytes\n\n let runningInline = 0\n\n // Stable input order: attachments dispatch in the order the user attached\n // them, and the pointer block in `input.text` already names them in that\n // same order.\n for (const attachment of input.attachments) {\n if (!attachment.path) {\n return { succeeded: false, error: `attachment path must be non-empty: ${attachment.name}` }\n }\n\n // The reader crosses an external boundary (store/coordinator) — a rejection\n // there must land in the typed outcome, not escape as a thrown error the\n // caller would misattribute to stream init.\n let read: Awaited<ReturnType<ReadAttachmentFn>>\n try {\n read = await input.readAttachment(input.scopeId, attachment.path)\n } catch (err) {\n return {\n succeeded: false,\n error: `attachment store read failed: ${attachment.path} — ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n if (!read.ok) return { succeeded: false, error: read.reason }\n\n const base64 = readResultToBase64(read)\n if (base64 === undefined) {\n return { succeeded: false, error: `attachment store read produced no content: ${attachment.path}` }\n }\n\n const mediaType = attachment.mediaType ?? read.mediaType\n if (attachment.type === 'image' && !mediaType) {\n return { succeeded: false, error: `attachment is missing a mediaType required for an image data URI: ${attachment.path}` }\n }\n\n const absPath = input.resolveAttachmentPath(attachment.path)\n emittedAbsPaths.add(absPath)\n\n if (attachment.type === 'image') {\n const inlinePart: PromptInputPart = {\n type: 'image',\n filename: attachment.name,\n mediaType,\n url: `data:${mediaType};base64,${base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n if (!forcePath && runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n } else {\n parts.push({ type: 'image', filename: attachment.name, mediaType, path: absPath })\n }\n continue\n }\n\n // File part. Sidecar's file-part zod union is tried [Legacy: {path\n // required, content?} strips mediaType/filename] then [AISDK: {filename\n // required, url required, mediaType?}] — so an inline file part must carry\n // `filename` + `url` and no `path` key at all, while a path-based file part\n // must carry only `path` (mediaType/filename would be stripped by the\n // Legacy branch anyway).\n const fileMediaType = mediaType ?? 'application/octet-stream'\n const inlinePart: PromptInputPart = {\n type: 'file',\n filename: attachment.name,\n mediaType: fileMediaType,\n url: `data:${fileMediaType};base64,${base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n if (!forcePath && runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n } else {\n parts.push({ type: 'file', path: absPath })\n }\n }\n\n if (mentions.length > 0 && !input.box) {\n return { succeeded: false, error: 'internal error: sandbox mentions require a box to read from' }\n }\n for (const mention of mentions) {\n if (!mention.path) {\n return { succeeded: false, error: `mention path must be non-empty: ${mention.name}` }\n }\n const absPath = resolveMentionPath(mention.path)\n if (emittedAbsPaths.has(absPath)) continue\n emittedAbsPaths.add(absPath)\n\n const isImage = mention.mentionKind === 'image'\n const mediaType = isImage ? mediaTypeForMentionPath(mention.path) : undefined\n\n // Every mention is stat'd first: it proves the file still exists (a deleted\n // mention fails the turn loud) and gives the size for the inline budget\n // decision without pulling bytes across the exec channel.\n let stat: SandboxMentionReadOutcome\n try {\n stat = await readMention(input.box!, absPath, { readBytes: false })\n } catch (err) {\n return { succeeded: false, error: `mention read failed: ${absPath} — ${err instanceof Error ? err.message : String(err)}` }\n }\n if (!stat.succeeded) return { succeeded: false, error: stat.error }\n\n // Only an image that projects within the remaining budget reads its bytes\n // to inline; every other mention (and a budget-exceeding image) ships\n // path-only, so a large file is never base64'd just to be demoted.\n const projectedInlineCost = base64WireLen(stat.value.size)\n + byteLen(JSON.stringify({ type: 'image', filename: mention.name, mediaType: mediaType ?? '', url: '' }))\n if (isImage && mediaType && !forcePath && runningInline + projectedInlineCost <= inlineBudget) {\n let read: SandboxMentionReadOutcome\n try {\n read = await readMention(input.box!, absPath, { readBytes: true })\n } catch (err) {\n return { succeeded: false, error: `mention read failed: ${absPath} — ${err instanceof Error ? err.message : String(err)}` }\n }\n if (!read.succeeded) return { succeeded: false, error: read.error }\n if (!read.value.base64) return { succeeded: false, error: `mentioned image produced no bytes: ${absPath}` }\n const inlinePart: PromptInputPart = {\n type: 'image',\n filename: mention.name,\n mediaType,\n url: `data:${mediaType};base64,${read.value.base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n // Re-check against the actual serialized cost — the projection can\n // undershoot; a real overshoot demotes to a path part rather than 413ing.\n if (runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n continue\n }\n }\n\n // Path-only mention: an image keeps its `mediaType`, everything else is a\n // bare `file` path (the sidecar's Legacy file-part branch strips extra keys).\n parts.push(\n isImage && mediaType\n ? { type: 'image', filename: mention.name, mediaType, path: absPath }\n : { type: 'file', path: absPath },\n )\n }\n\n for (const part of parts) {\n if (violatesUrlPathXor(part)) {\n return { succeeded: false, error: 'internal error: emitted media part violates the url/path exclusivity invariant' }\n }\n }\n\n // Final whole-request check sized against what actually crosses the wire: the\n // history-merged text part (the substrate folds `history` into `parts[0]`\n // before dispatch), the media parts, the system prompt, and the inlined\n // backend profile riding the same body — the same terms `inlineBudget` was\n // derived from.\n const textPartSize = base64WireLen(byteLen(flattenedForSizing))\n const mediaPartsSize = parts.slice(1).reduce((total, part) => total + byteLen(JSON.stringify(part)), 0)\n const systemPromptSize = byteLen(JSON.stringify(input.systemPrompt))\n if (textPartSize + mediaPartsSize + systemPromptSize + input.profileWireBytes + structuralReserveBytes > requestMaxBytes) {\n return { succeeded: false, error: 'dispatch parts exceed the sandbox proxy request cap even after path demotion' }\n }\n\n // The sidecar rejects the whole request past its parts-array cap; the caller\n // selects which media ride natively, so overflow here is a caller bug\n // surfaced loudly rather than a truncation.\n if (parts.length > maxParts) {\n return { succeeded: false, error: `dispatch parts exceed the sidecar per-request cap of ${maxParts}` }\n }\n\n return { succeeded: true, value: parts }\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 the injected\n * {@link WriteAttachmentFn} (gtm hard-wired its vault writer), the path strategy\n * is the injected `buildAttachmentPath` (neutral `uploads/agent/<date>/` default,\n * no domain bucket taxonomy baked), the MIME map is an injectable hook, and the\n * date segment reads an injectable clock. The idempotent `hash8(id ?? url ??\n * filename)` naming is preserved so re-promoting the same source part resolves\n * to the same path.\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 type { WriteAttachmentFn } from './attachment-store'\nimport { formatBytes } from './wire'\n\n/** Default ceiling on a promoted file's raw (pre-encoding) byte size. */\nexport const PROMOTE_MAX_FILE_BYTES = 10 * 1024 * 1024\n\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\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/** Minimal extension→mime map — the last-resort media type when the part\n * carries none. Generic file typing, NOT a product accept-list (which is a\n * domain value the product supplies): an unknown extension falls to\n * `text/plain`, it never rejects. */\nconst EXT_TO_MIME: Record<string, string> = {\n md: 'text/markdown',\n markdown: 'text/markdown',\n txt: 'text/plain',\n log: 'text/plain',\n csv: 'text/csv',\n tsv: 'text/tab-separated-values',\n json: 'application/json',\n yaml: 'text/yaml',\n yml: 'text/yaml',\n xml: 'application/xml',\n html: 'text/html',\n htm: 'text/html',\n pdf: 'application/pdf',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n heic: 'image/heic',\n heif: 'image/heif',\n svg: 'image/svg+xml',\n mp4: 'video/mp4',\n webm: 'video/webm',\n mov: 'video/quicktime',\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n m4a: 'audio/mp4',\n aac: 'audio/aac',\n}\n\n/** Default MIME hook: extension → mime, or `text/plain` for the unknown. */\nexport function sniffMimeFromName(filename: string): string {\n const ext = filename.split('.').pop()?.toLowerCase()\n if (!ext) return 'text/plain'\n return EXT_TO_MIME[ext] ?? 'text/plain'\n}\n\n/**\n * Rewrite a filename into a store-path-safe charset (`A-Za-z0-9._-`). Runs of\n * unsupported characters collapse to one `-`; leading dots/dashes are stripped\n * so the name can't read as a hidden segment. The original name is preserved on\n * the returned part, so sanitization loses nothing.\n */\nfunction sanitizeAttachmentFileName(name: string): string {\n const sanitized = name\n .trim()\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/^[.-]+/, '')\n return sanitized || 'file'\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]*)$/.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:([^;,]+)[;,]/.exec(url)\n return match ? match[1] : undefined\n}\n\nfunction basenameFromUrl(url: string | undefined): string | undefined {\n if (!url || url.startsWith('data:')) 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 = url.startsWith('file://') ? 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: ${err instanceof Error ? err.message : String(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: ${err instanceof Error ? err.message : String(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: ${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: ${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 (url.startsWith('data:')) return resolveDataUrlBytes(url, input.filename, input.maxBytes)\n\n const isSandboxPath = url.startsWith('file://') || url.startsWith('/')\n if (!isSandboxPath) return { succeeded: false, reason: `unsupported file URL scheme: ${url}` }\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\nexport interface PromoteAgentFilePartOptions {\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 /** REQUIRED store writer — no default (the product owns its store). */\n writeAttachment: WriteAttachmentFn\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}\n\nexport async function promoteAgentFilePart(options: PromoteAgentFilePartOptions): Promise<PromoteFilePartResult> {\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\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 const mediaType = options.raw.mediaType ?? options.raw.mime ?? dataUrlMime(options.raw.url) ?? sniffMime(filename)\n const kind = attachmentKindForMime(mediaType)\n const digest = await hash8(options.raw.id ?? options.raw.url ?? filename)\n const date = now().toISOString().split('T')[0] ?? ''\n const path = buildAttachmentPath({ filename, hash8: digest, date, mediaType, kind })\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<WriteAttachmentFn>>\n try {\n written = await options.writeAttachment(options.scopeId, path, resolved.bytes, {\n mediaType,\n name: filename,\n originalName: options.raw.filename ?? filename,\n size: resolved.bytes.byteLength,\n })\n } catch (err) {\n return { succeeded: false, filename, reason: err instanceof Error ? err.message : String(err) }\n }\n if (!written.ok) return { succeeded: false, filename, reason: written.reason }\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAS,mBAAmB,sBAAsB;AA6HlD,SAAS,gBAAgB,MAA+D;AACtF,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,UAAU,KAAK,WAAW,KAAK,SAAS,KAAK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,IAClC,KAAK,QAAQ;AAAA,IACb,KAAK,QAAQ;AAAA,IACb,WAAW,QAAQ;AAAA,IACnB;AAAA,IACA;AAAA,EACF,CAAC;AACD,MAAI,CAAC,SAAS,UAAW,QAAO,EAAE,WAAW,OAAO,UAAU,QAAQ,SAAS,OAAO;AAEtF,QAAM,YAAY,QAAQ,IAAI,aAAa,QAAQ,IAAI,QAAQ,YAAY,QAAQ,IAAI,GAAG,KAAK,UAAU,QAAQ;AACjH,QAAM,OAAO,sBAAsB,SAAS;AAC5C,QAAM,SAAS,MAAM,MAAM,QAAQ,IAAI,MAAM,QAAQ,IAAI,OAAO,QAAQ;AACxE,QAAM,OAAO,IAAI,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE,CAAC,KAAK;AAClD,QAAM,OAAO,oBAAoB,EAAE,UAAU,OAAO,QAAQ,MAAM,WAAW,KAAK,CAAC;AAKnF,MAAI;AACJ,MAAI;AACF,cAAU,MAAM,QAAQ,gBAAgB,QAAQ,SAAS,MAAM,SAAS,OAAO;AAAA,MAC7E;AAAA,MACA,MAAM;AAAA,MACN,cAAc,QAAQ,IAAI,YAAY;AAAA,MACtC,MAAM,SAAS,MAAM;AAAA,IACvB,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,WAAO,EAAE,WAAW,OAAO,UAAU,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE;AAAA,EAChG;AACA,MAAI,CAAC,QAAQ,GAAI,QAAO,EAAE,WAAW,OAAO,UAAU,QAAQ,QAAQ,OAAO;AAE7E,SAAO;AAAA,IACL,WAAW;AAAA,IACX,MAAM;AAAA,MACJ,MAAM;AAAA,MACN;AAAA,MACA,MAAM;AAAA,MACN,MAAM,SAAS,MAAM;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;","names":["base64","inlinePart","cost"]}
1
+ {"version":3,"sources":["../../src/chat-routes/turn-routes.ts","../../src/chat-routes/sandbox-producer.ts","../../src/chat-routes/detached-turn.ts","../../src/chat-routes/durable-projection.ts","../../src/chat-routes/upload.ts","../../src/chat-routes/resolve-attachments.ts","../../src/chat-routes/promote-file-part.ts","../../src/chat-routes/attachment-upload.ts","../../src/chat-routes/dispatch-parts.ts"],"sourcesContent":["/**\n * `createChatTurnRoutes` — the assembled server chat vertical (issue #188\n * Phase 1). One factory composing the pieces every product re-wired by hand:\n *\n * body parse/validate → `/web` `parseJsonObjectBody` + `./wire`\n * turn identity → `/stream` `resolveChatTurn` + agent-runtime\n * `deriveExecutionId`\n * producer → injected seam (sandbox lane via\n * `createSandboxChatProducer`; router lane is the\n * product's own `ChatTurnProducer`)\n * turn engine → agent-runtime `handleChatTurn` (verbatim)\n * durability → `/stream` turn-buffer tap, wired BY DEFAULT\n * (tee + drain keeps the turn running after a\n * client drop; replay serves the buffered tail)\n * persistence → injected `/chat-store`-shaped store\n * (user row on send, assistant row on completion)\n * interactions answer → `/interactions` `createInteractionAnswerRoute`\n *\n * Handlers are web-standard `Request → Response` (Workers, Node 18+, Deno) —\n * no router import. Auth/access is one injected `authorize` seam, composable\n * with `/app-auth` guards but not coupled to them.\n *\n * Six optional product seams let a complex turn-orchestrator compose the\n * vertical instead of hand-rolling a generator — each omittable to the exact\n * behavior above: `turnLock` (single-flight acquire/release around the turn),\n * `contextGate` (pre-producer domain-readiness short-circuit), `beforeTurn`\n * (observe + augment the producer input), `lifecycle` (deterministic\n * start/complete/error telemetry), `heartbeat` (keepalive during silent\n * producer waits), plus `onRawEvent` (the raw producer events, for telemetry).\n * `handleChatTurn` stays the engine — the seams only wrap its input, its\n * producer stream, and its settle.\n *\n * Seam stability: `lifecycle`, `heartbeat`, and `turnLock` are generic and\n * stable (`turnLock` graduated with `/turn-stream`'s shared DO adapter, #221).\n * `contextGate`, `beforeTurn`, and `onRawEvent` are `@experimental` — proven\n * by a single consumer (gtm's chat vertical, #200) and may change once a\n * second consumer exercises them. They stay FLAT top-level options (not\n * grouped under a `hooks` object): that grouping would break the shipped\n * consumer's call for no mechanism gain, and this package's exports are\n * additive-only.\n */\n\nimport { deriveExecutionId, handleChatTurn } from '@tangle-network/agent-runtime'\nimport type { ChatTurnIdentity, ChatTurnProducer } from '@tangle-network/agent-runtime'\nimport { mentionInputToPart, toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport {\n createInteractionAnswerRoute,\n type InteractionAnswerRoute,\n type InteractionAnswerRouteOptions,\n} from '../interactions/route'\nimport {\n coalesceDeltas,\n createBufferedTurnTap,\n normalizeClientTurnId,\n replayTurnEvents,\n resolveChatTurn,\n type PersistedChatMessageForTurn,\n type TurnEventStore,\n} from '../stream/index'\nimport { parseJsonObjectBody } from '../web/index'\nimport {\n assertPromptPartsWithinCap,\n ChatTurnInputError,\n parseChatTurnParts,\n parseFileMentions,\n type ChatTurnFilePartInput,\n type ChatTurnPartInput,\n type ChatTurnRequestPayload,\n type FileMention,\n} from './wire'\n\n// ── seams ───────────────────────────────────────────────────────────────────\n\n/** Usage receipt persisted onto the assistant message (the flattened\n * `step-finish` shape `/chat-store`'s columns mirror). */\nexport interface ChatTurnUsage {\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n costUsd?: number\n}\n\n/** What the route persists — a structural subset of `/chat-store`'s\n * `ChatStore`, so `createChatStore(db, tables)` satisfies it directly and a\n * product with its own persistence adapts without importing drizzle. */\nexport interface ChatTurnMessageStore {\n listMessages(threadId: string): Promise<Array<{\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n }>>\n appendMessage(input: {\n threadId: string\n role: 'user' | 'assistant'\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n }): Promise<unknown>\n}\n\n/** `ChatTurnProducer` plus the persisted projection the assembly reads after\n * drain. `createSandboxChatProducer` returns this; a router-lane producer\n * may omit the optional members (finalText persists as a single text part). */\nexport interface ChatTurnRouteProducer extends ChatTurnProducer {\n assistantParts?(): Array<Record<string, unknown>>\n usage?(): ChatTurnUsage\n model?: string\n}\n\nexport type ChatTurnAuthorization<TContext> =\n | {\n ok: true\n tenantId: string\n userId: string\n context: TContext\n /** When `false`, skip the `role:'user'` message insert for this turn — for\n * a product-dispatched / synthetic turn (e.g. a follow-up the product\n * raised itself) that must not surface a new user row. Composes with —\n * never overrides — the engine's retry-dedup: `authorize` runs before\n * turn identity is resolved, so it cannot tell a retry from a fresh turn;\n * a turn already deduped stays deduped. Omit / `true` → today's behavior.\n * @experimental Single-consumer; shape may change. */\n insertUserMessage?: boolean\n }\n | { ok: false; response: Response }\n\nexport interface ChatTurnAuthorizeArgs {\n request: Request\n intent: 'turn' | 'replay' | 'running'\n /** Parsed, validated POST body (turn intent only). */\n body?: ChatTurnRequestPayload\n /** The buffered turn id being replayed (replay intent only). */\n turnId?: string\n /** The thread whose running turns are being discovered (running intent only). */\n threadId?: string\n}\n\nexport interface ChatTurnProduceArgs<TContext> {\n request: Request\n body: ChatTurnRequestPayload\n identity: ChatTurnIdentity\n context: TContext\n /** The message to send: plain text, or parts when the client attached\n * files (a text part is prepended from `content` when present). */\n prompt: string | ChatTurnPartInput[]\n /** Stable id for cross-process reconnect (`deriveExecutionId`). */\n executionId: string\n /** The turn-buffer id announced to the client for replay. */\n turnStreamId: string\n priorMessages: PersistedChatMessageForTurn[]\n}\n\n/** One event as it crosses the route: the producer's own vocabulary, or an\n * injected keepalive. Same shape the engine forwards verbatim. */\ntype ChatRouteEvent = { type: string; data?: Record<string, unknown> }\n\n/** Best-effort human-readable cause from a terminal `error` /\n * `session.run.failed` event's `data`. */\nfunction failureReasonOf(data: Record<string, unknown> | undefined): string | undefined {\n if (!data) return undefined\n const message = data.message ?? data.error ?? data.reason\n if (typeof message === 'string' && message.length > 0) return message\n return undefined\n}\n\n/** Keepalive emitted while the producer is quiet (long tool calls, first-token\n * wait) so client watchdogs stay re-armed. One is emitted each time\n * `intervalMs` elapses with no producer event; the window resets on every real\n * event, so a chatty producer never triggers one. The product owns the event\n * shape (`type` + `data`). Omit → no keepalives (today's behavior). */\nexport interface ChatTurnHeartbeat {\n intervalMs: number\n event(info: { elapsedMs: number; tick: number }): ChatRouteEvent\n}\n\n/** Patch a `beforeTurn` hook returns to augment the producer's input. Omitted\n * fields keep the route-assembled value; the product's `produce` still owns\n * the system prompt. */\nexport interface ChatTurnInputPatch {\n prompt?: string | ChatTurnPartInput[]\n priorMessages?: PersistedChatMessageForTurn[]\n}\n\n/** Pre-turn readiness verdict — proceed, or short-circuit with the product's\n * own `Response` (e.g. a canned assistant reply asking for missing context).\n * Distinct from `authorize`: this gates domain readiness, not access. */\nexport type ChatTurnGateResult =\n | { proceed: true }\n | { proceed: false; response: Response }\n\n/** Single-flight lock verdict — acquired (with an opaque handle passed back to\n * `release`), or already held (short-circuit with the product's 409-style\n * `Response`). */\nexport type ChatTurnLockResult =\n | { acquired: true; handle?: unknown }\n | { acquired: false; response: Response }\n\n/** Async acquire/release wrapped around the turn. `acquire` runs before any\n * side effect; `release` runs once when the turn settles — including on a\n * short-circuit or a throw. */\nexport interface ChatTurnLock<TContext> {\n acquire(args: ChatTurnProduceArgs<TContext>): ChatTurnLockResult | Promise<ChatTurnLockResult>\n release(handle: unknown): void | Promise<void>\n}\n\ninterface ChatTurnLifecycleBase<TContext> {\n identity: ChatTurnIdentity\n executionId: string\n turnStreamId: string\n context: TContext\n}\nexport interface ChatTurnLifecycleStart<TContext> extends ChatTurnLifecycleBase<TContext> {\n startedAt: number\n}\nexport interface ChatTurnLifecycleComplete<TContext> extends ChatTurnLifecycleBase<TContext> {\n finalText: string\n usage: ChatTurnUsage\n durationMs: number\n}\nexport interface ChatTurnLifecycleError<TContext> extends ChatTurnLifecycleBase<TContext> {\n error: unknown\n durationMs: number\n}\n\n/** Deterministic run telemetry: `onTurnStart` fires before the producer runs;\n * exactly one of `onTurnComplete` / `onTurnError` fires after the turn\n * settles, always after `onTurnStart`. Failure is derived from the turn's own\n * `error` / `session.run.failed` events (or a drain throw), not the engine's\n * lifecycle envelope. Hook errors are swallowed — telemetry never fails a\n * turn. */\nexport interface ChatTurnLifecycle<TContext> {\n onTurnStart?(info: ChatTurnLifecycleStart<TContext>): void | Promise<void>\n onTurnComplete?(info: ChatTurnLifecycleComplete<TContext>): void | Promise<void>\n onTurnError?(info: ChatTurnLifecycleError<TContext>): void | Promise<void>\n}\n\nexport interface CreateChatTurnRoutesOptions<TContext = void> {\n /** Names the product in `deriveExecutionId` so retries land on the same\n * substrate execution. */\n projectId: string\n /** Authenticate + authorize the caller for a turn or a replay. The only\n * product-supplied access step: session auth, thread/workspace access,\n * seat/balance gates, rate limits all live here. */\n authorize(args: ChatTurnAuthorizeArgs): Promise<ChatTurnAuthorization<TContext>>\n /** Thread/message persistence (`/chat-store`'s store or a product adapter). */\n store: ChatTurnMessageStore\n /** Turn-event buffer (`createD1TurnEventStore(env.DB)` or `/turn-stream`'s\n * `createDurableObjectTurnEventStore(env.TURN_STREAM_DO)` in production,\n * `createMemoryTurnEventStore()` in tests). Wired by default — every turn\n * is buffered and replayable. */\n turnStore: TurnEventStore\n /** Build the turn's event stream. Sandbox lane: `streamSandboxPrompt(...)`\n * wrapped in `createSandboxChatProducer`. Router/openai-compat lane: the\n * product's own producer. May be async (box resolution). */\n produce(args: ChatTurnProduceArgs<TContext>): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>\n /** Single-flight lock acquired before any side effect and released once when\n * the turn settles (including short-circuit/throw). `/turn-stream`'s\n * `createDurableTurnLock` is the shared DO-backed implementation. Omit →\n * no lock. */\n turnLock?: ChatTurnLock<TContext>\n /** Pre-turn readiness gate that can short-circuit with a product `Response`\n * before the producer runs (the user row is already persisted). Runs after\n * `turnLock.acquire`, before `beforeTurn`. Omit → always proceed.\n * @experimental Single-consumer (gtm, #200); shape may change. */\n contextGate?(args: ChatTurnProduceArgs<TContext>): ChatTurnGateResult | Promise<ChatTurnGateResult>\n /** Observe the assembled producer input and optionally augment it (rewrite\n * the prompt / prior messages) before the producer runs. Omit → no change.\n * @experimental Single-consumer (gtm, #200); shape may change. */\n beforeTurn?(args: ChatTurnProduceArgs<TContext>): ChatTurnInputPatch | void | Promise<ChatTurnInputPatch | void>\n /** Deterministic run telemetry (start / complete / error) with identity and\n * timing. Omit → no telemetry. */\n lifecycle?: ChatTurnLifecycle<TContext>\n /** Keepalive injected while the producer is quiet. Omit → no keepalives. */\n heartbeat?: ChatTurnHeartbeat\n /** Observe each event the producer emits, before the engine frames it and\n * before any heartbeat injection (the raw sidecar-producer events, for\n * telemetry). Never alters the stream; errors are swallowed. Distinct from\n * `onEvent`, which sees the engine-framed stream incl. lifecycle envelopes.\n * @experimental Single-consumer (gtm, #200); shape may change. */\n onRawEvent?(event: ChatRouteEvent, context: TContext): void | Promise<void>\n /** Pre-persist transform of the final text (e.g. `/redact`'s `redactPII`).\n * Live stream is never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Post-processing after a turn settles (billing, titles, audit). Fires with\n * `failed:true` + `failureReason` when the turn carried a terminal error\n * event (model 402 / rate-limit / server error) instead of a clean\n * completion, so products skip the deduct and render an error row rather\n * than billing an empty turn and marking it done. A turn that THROWS never\n * reaches this hook (the engine skips it on a producer throw). Errors are\n * swallowed by the engine — they never fail a streamed turn. */\n onTurnComplete?(input: {\n identity: ChatTurnIdentity\n finalText: string\n context: TContext\n failed: boolean\n failureReason?: string\n }): Promise<void>\n /** Per-event side channel (product broadcast). The turn-buffer tap is\n * already wired; this runs in addition. */\n onEvent?(event: { type: string; data?: Record<string, unknown> }, context: TContext): void | Promise<void>\n /** Trace flush handed to `waitUntil` (OTLP export). */\n traceFlush?(context: TContext): Promise<void>\n /** Compose the interaction-answer endpoints (`/interactions`). Omit when the\n * product has no sidecar ask channel. */\n interactions?: InteractionAnswerRouteOptions\n /** Byte budget for inline prompt parts. Default `INLINE_PARTS_MAX_BYTES`. */\n maxInlinePartBytes?: number\n /** Per-flush coalescer for the turn buffer. Default `coalesceDeltas` (this\n * assembly streams the client vocabulary's `{type:'text'|'reasoning',\n * text}` lines, which it merges). A producer streaming raw\n * `message.part.updated` events passes `coalesceChatStreamEvents`. */\n coalesceTurnEvents?: (events: unknown[]) => unknown[]\n replay?: { pollMs?: number; timeoutMs?: number }\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\nexport interface ChatTurnRoutes {\n /** POST — run one turn, streaming NDJSON. First line is\n * `{type:'turn', turnId}` (the replay handle); the rest is the engine's\n * event protocol. Pass the platform's `waitUntil` so the turn keeps\n * running (and buffering) after a client disconnect. */\n turn(request: Request, ctx?: { waitUntil?(p: Promise<unknown>): void }): Promise<Response>\n /** GET — replay a buffered turn from `?fromSeq=` (0 = everything), then\n * follow it live until it completes. */\n replay(request: Request, params: { turnId: string }): Promise<Response>\n /** GET `?threadId=` — the reconnect-discovery endpoint: the turn ids still\n * running on a thread, so a client that reloaded mid-turn can re-attach to\n * the live stream via {@link replay} instead of losing it. Returns `[]` when\n * the turn store cannot enumerate running turns (`listRunning` unimplemented). */\n running(request: Request): Promise<Response>\n /** list/answer endpoints from `/interactions`; null when not configured. */\n interactions: InteractionAnswerRoute | null\n}\n\n// ── body validation ────────────────────────────────────────────────────────\n\nfunction errorResponse(err: ChatTurnInputError): Response {\n return Response.json({ code: err.code, error: err.message }, { status: err.status })\n}\n\ninterface ParsedTurnBody {\n payload: ChatTurnRequestPayload\n content: string\n fileParts: ChatTurnFilePartInput[]\n mentions: FileMention[]\n turnId: string | undefined\n}\n\nfunction validateTurnBody(body: Record<string, unknown>, maxInlinePartBytes: number | undefined): ParsedTurnBody {\n const threadId = typeof body.threadId === 'string' ? body.threadId.trim() : ''\n if (!threadId) throw new ChatTurnInputError('Missing threadId')\n const rawContent = body.content ?? body.message ?? ''\n if (typeof rawContent !== 'string') throw new ChatTurnInputError('content must be a string')\n const content = rawContent.trim()\n const fileParts = parseChatTurnParts(body.parts)\n // Path references, not bytes — validated for traversal/charset/count, never\n // counted against the inline-parts byte budget below.\n const mentions = parseFileMentions(body.mentions)\n // A mention is a turn's whole payload often enough to count: \"@chart.png\"\n // with no prose is a real ask, and the pointer block the mentions produce is\n // prompt content the model reads.\n if (!content && fileParts.length === 0 && mentions.length === 0) {\n throw new ChatTurnInputError('Missing content (send text, parts, mentions, or any combination)')\n }\n assertPromptPartsWithinCap(fileParts, maxInlinePartBytes)\n let turnId: string | undefined\n try {\n turnId = normalizeClientTurnId(body.turnId)\n } catch (err) {\n throw new ChatTurnInputError(err instanceof Error ? err.message : 'Invalid turnId')\n }\n return {\n // The VALIDATED, deduped mention list replaces the raw one on the payload,\n // so every downstream seam (`authorize`, `contextGate`, `beforeTurn`,\n // `produce`) reads checked paths and never the request's own.\n payload: { ...body, threadId, content, mentions } as ChatTurnRequestPayload,\n content,\n fileParts,\n mentions,\n turnId,\n }\n}\n\n/** File parts persist onto the user message verbatim — the wire shape is the\n * persisted `ChatFilePart`/`ChatImagePart` vocabulary already. Mentions get\n * the one mapping step their own vocabulary needs. The typed projection is\n * `/chat-store`'s (same boundary as the assistant hop).\n *\n * Mentions persist as parts rather than being folded into the prompt because\n * the prompt is not readable back: a retry rebuilds the turn from the stored\n * row, and a transcript draws its pills from it. Turning them INTO prompt\n * text stays the product's job — only the product knows how to resolve a\n * workspace-relative path to an in-box one (`fileMentionsToParts`'\n * `resolvePath` seam), so the route never dispatches them itself. */\nfunction userPartsWithFiles(\n userParts: Array<Record<string, unknown>>,\n fileParts: ChatTurnFilePartInput[],\n mentions: FileMention[],\n): ChatMessagePart[] {\n return toChatMessageParts([\n ...userParts,\n ...fileParts.map((part) => ({ ...part })),\n ...mentions.map((mention) => ({ ...mentionInputToPart(mention) })),\n ])\n}\n\n// ── producer-stream wrappers (heartbeat + raw tap) ───────────────────────────\n\n/** Fire `onRawEvent` for each producer event, before the engine frames it.\n * Best-effort — a telemetry throw is logged, never propagated. */\nasync function* tapRawEvents(\n source: AsyncIterable<ChatRouteEvent>,\n onRawEvent: (event: ChatRouteEvent) => void | Promise<void>,\n log: (message: string, meta?: Record<string, unknown>) => void,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n for await (const event of source) {\n try {\n await onRawEvent(event)\n } catch (err) {\n log('[chat-routes] onRawEvent failed', { error: err instanceof Error ? err.message : String(err) })\n }\n yield event\n }\n}\n\n/** Inject a keepalive whenever `intervalMs` elapses with no source event. The\n * silent window (elapsed + tick) resets on every real event, so a producer\n * that keeps emitting never triggers a heartbeat. Closes the source on early\n * return, matching a `for await` over it. */\nasync function* withStreamHeartbeat(\n source: AsyncIterable<ChatRouteEvent>,\n intervalMs: number,\n makeEvent: (info: { elapsedMs: number; tick: number }) => ChatRouteEvent,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n let pending = iterator.next()\n let windowStart = Date.now()\n let tick = 0\n for (;;) {\n let timer: ReturnType<typeof setTimeout> | undefined\n let winner: 'event' | 'heartbeat'\n try {\n const heartbeat = new Promise<'heartbeat'>((resolve) => {\n timer = setTimeout(() => resolve('heartbeat'), intervalMs)\n })\n winner = await Promise.race([pending.then(() => 'event' as const), heartbeat])\n } finally {\n // Clear the pending timer on EVERY exit — including a `pending`\n // rejection — so a rejected source never orphans a setTimeout that\n // keeps the runtime alive for up to `intervalMs`.\n if (timer !== undefined) clearTimeout(timer)\n }\n if (winner === 'heartbeat') {\n tick += 1\n yield makeEvent({ elapsedMs: Date.now() - windowStart, tick })\n continue\n }\n const result = await pending\n if (result.done) return\n yield result.value\n pending = iterator.next()\n windowStart = Date.now()\n tick = 0\n }\n } finally {\n await iterator.return?.()\n }\n}\n\n// ── the factory ────────────────────────────────────────────────────────────\n\nexport function createChatTurnRoutes<TContext = void>(\n options: CreateChatTurnRoutesOptions<TContext>,\n): ChatTurnRoutes {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n\n async function turn(request: Request, ctx?: { waitUntil?(p: Promise<unknown>): void }): Promise<Response> {\n const [rawBody, badBody] = await parseJsonObjectBody(request)\n if (badBody) return badBody\n\n let parsed: ParsedTurnBody\n try {\n parsed = validateTurnBody(rawBody, options.maxInlinePartBytes)\n } catch (err) {\n if (err instanceof ChatTurnInputError) return errorResponse(err)\n throw err\n }\n const { payload, content, fileParts, mentions, turnId } = parsed\n\n const auth = await options.authorize({ request, intent: 'turn', body: payload })\n if (!auth.ok) return auth.response\n const { tenantId, userId, context } = auth\n\n // Turn identity: reuse the just-persisted user row on a retry (same\n // turnId or identical trailing content) instead of double-inserting.\n const existingMessages = (await options.store.listMessages(payload.threadId)).map((m) => ({\n id: m.id,\n role: m.role,\n content: m.content,\n parts: (m.parts ?? null) as PersistedChatMessageForTurn['parts'],\n }))\n const chatTurn = resolveChatTurn({ existingMessages, userContent: content, turnId })\n\n const identity: ChatTurnIdentity = {\n tenantId,\n sessionId: payload.threadId,\n userId,\n turnIndex: chatTurn.turnIndex,\n }\n const executionId = deriveExecutionId({\n projectId: options.projectId,\n sessionId: payload.threadId,\n turnIndex: chatTurn.turnIndex,\n })\n const turnStreamId = crypto.randomUUID()\n\n const prompt: string | ChatTurnPartInput[] =\n fileParts.length === 0\n ? content\n : content\n ? [{ type: 'text', text: content }, ...fileParts]\n : [...fileParts]\n\n // The producer input every pre-turn seam reads (and `beforeTurn` may\n // rewrite). Mutated in place before the producer's deferred first pull.\n let produceArgs: ChatTurnProduceArgs<TContext> = {\n request,\n body: payload,\n identity,\n context,\n prompt,\n executionId,\n turnStreamId,\n priorMessages: chatTurn.priorMessages,\n }\n\n // Single-flight lock: acquire before any side effect. `release` runs\n // exactly once — in the drain's `finally` on a normal turn, or right here\n // on a short-circuit / throw.\n let lockAcquired = false\n let lockHandle: unknown\n let lockReleased = false\n const releaseLock = async (): Promise<void> => {\n if (!lockAcquired || lockReleased) return\n lockReleased = true\n try {\n await options.turnLock!.release(lockHandle)\n } catch (err) {\n log('[chat-routes] turnLock.release failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n if (options.turnLock) {\n const acquired = await options.turnLock.acquire(produceArgs)\n if (!acquired.acquired) return acquired.response\n lockAcquired = true\n lockHandle = acquired.handle\n }\n\n // Turn state, hoisted so the pre-stream `catch` can settle the lifecycle\n // (fire `onTurnError`, close the span) even when a seam throws\n // synchronously before the drain — the drain would otherwise be the only\n // path that runs the terminal hook.\n let producer: ChatTurnRouteProducer | undefined\n let runFailed = false\n // Data of the event that marked the run failed — handed to `onTurnError`\n // when no drain throw supplies a richer cause.\n let lastFailureData: Record<string, unknown> | undefined\n let turnStartedAtMs = 0\n let turnStarted = false\n let lifecycleSettled = false\n\n // Exactly one terminal lifecycle hook, after the turn settles (idempotent).\n // Failure is this route's own verdict (`runFailed` from error/failed\n // events, or a drain/sync throw), not the engine's envelope.\n const fireTerminalLifecycle = async (failed: boolean, terminalError: unknown): Promise<void> => {\n if (lifecycleSettled) return\n lifecycleSettled = true\n const lifecycle = options.lifecycle\n if (!lifecycle) return\n const durationMs = Date.now() - turnStartedAtMs\n try {\n if (failed) {\n await lifecycle.onTurnError?.({\n identity, executionId, turnStreamId, context, durationMs,\n error: terminalError ?? lastFailureData ?? new Error('chat turn failed'),\n })\n } else {\n await lifecycle.onTurnComplete?.({\n identity, executionId, turnStreamId, context, durationMs,\n finalText: producer?.finalText() ?? '',\n usage: producer?.usage?.() ?? {},\n })\n }\n } catch (err) {\n log('[chat-routes] lifecycle terminal hook failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n try {\n // The product (via `authorize`) may suppress the user-row insert for a\n // dispatched/synthetic turn. AND-composition: it can only subtract, never\n // resurrect a turn the engine already deduped as a retry.\n const insertUserMessage = chatTurn.shouldInsertUserMessage && (auth.insertUserMessage ?? true)\n if (insertUserMessage) {\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'user',\n content,\n parts: userPartsWithFiles(chatTurn.userParts, fileParts, mentions),\n })\n }\n\n // Domain-readiness gate: may short-circuit with the product's own\n // response before the producer runs. The user row above is kept (a real\n // user turn); the gate's response is the assistant side of it.\n if (options.contextGate) {\n const gate = await options.contextGate(produceArgs)\n if (!gate.proceed) {\n await releaseLock()\n return gate.response\n }\n }\n\n // Observe + optionally augment the assembled producer input.\n if (options.beforeTurn) {\n const patch = await options.beforeTurn(produceArgs)\n if (patch) produceArgs = { ...produceArgs, ...patch }\n }\n\n // Durability tap: every engine event buffers (coalesced) so a dropped\n // client replays the tail. Live delivery rides the Response body, not the\n // tap, so `write` is intentionally absent.\n const tap = createBufferedTurnTap({\n store: options.turnStore,\n turnId: turnStreamId,\n scopeId: payload.threadId,\n coalesce: options.coalesceTurnEvents ?? coalesceDeltas,\n })\n const turnMarker = { type: 'turn', turnId: turnStreamId }\n await tap.onEvent(turnMarker)\n\n turnStartedAtMs = Date.now()\n turnStarted = true\n if (options.lifecycle?.onTurnStart) {\n try {\n await options.lifecycle.onTurnStart({\n identity, executionId, turnStreamId, context, startedAt: turnStartedAtMs,\n })\n } catch (err) {\n log('[chat-routes] lifecycle.onTurnStart failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n const result = handleChatTurn({\n identity,\n waitUntil: ctx?.waitUntil,\n log,\n hooks: {\n // The engine wants a synchronous producer; box resolution is async —\n // defer it into the generator's first pull.\n produce: () => ({\n stream: (async function* () {\n producer = await options.produce(produceArgs)\n let source: AsyncIterable<ChatRouteEvent> = producer.stream\n if (options.onRawEvent) {\n source = tapRawEvents(source, (event) => options.onRawEvent!(event, context), log)\n }\n if (options.heartbeat) {\n source = withStreamHeartbeat(source, options.heartbeat.intervalMs, options.heartbeat.event)\n }\n for await (const event of source) yield event\n })(),\n finalText: () => producer?.finalText() ?? '',\n }),\n onEvent: async (event) => {\n if (event.type === 'session.run.failed' || event.type === 'error') {\n runFailed = true\n lastFailureData = event.data\n }\n await tap.onEvent(event)\n if (options.onEvent) await options.onEvent(event, context)\n },\n ...(options.transformFinalText ? { transformFinalText: options.transformFinalText } : {}),\n persistAssistantMessage: async ({ finalText }) => {\n // The typed boundary: stream-normalizer records → stored vocabulary\n // (validating projection owned by /chat-store — no cast here). The\n // scalar `finalText` arrives already transformed by the engine; the\n // producer's text PARTS are raw, so the same transform must run over\n // each text segment before persistence or a redaction (legal PII)\n // leaks at rest through message.parts.\n const rawParts = producer?.assistantParts ? producer.assistantParts() : undefined\n const projected =\n rawParts && options.transformFinalText\n ? await Promise.all(\n rawParts.map(async (part) =>\n String((part as { type?: unknown }).type ?? '') === 'text'\n ? { ...part, text: await options.transformFinalText!(String((part as { text?: unknown }).text ?? '')) }\n : part,\n ),\n )\n : rawParts\n const parts = projected ? toChatMessageParts(projected) : undefined\n if (!finalText.trim() && (!parts || parts.length === 0)) return\n const usage = producer?.usage?.() ?? {}\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'assistant',\n content: finalText,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(producer?.model ? { model: producer.model } : {}),\n ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),\n ...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cacheWriteTokens !== undefined ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),\n ...(usage.costUsd !== undefined ? { costUsd: usage.costUsd } : {}),\n })\n },\n ...(options.onTurnComplete\n ? {\n // Wired into the engine's completion hook, which fires only when\n // the stream ended without throwing. A terminal error EVENT\n // (not a throw) still lands here — so surface `runFailed` so the\n // product skips billing an errored turn instead of marking it\n // complete with empty text.\n onTurnComplete: ({ identity: turnIdentity, finalText }: { identity: ChatTurnIdentity; finalText: string }) =>\n options.onTurnComplete!({\n identity: turnIdentity,\n finalText,\n context,\n failed: runFailed,\n ...(runFailed ? { failureReason: failureReasonOf(lastFailureData) } : {}),\n }),\n }\n : {}),\n ...(options.traceFlush ? { traceFlush: () => options.traceFlush!(context) } : {}),\n },\n })\n\n // Tee: one branch to the live client, one drained under waitUntil so the\n // turn (and its buffering via onEvent) runs to completion after a client\n // drop — the engine body executes as it is pulled.\n const [clientBody, drainBody] = result.body.tee()\n const drained = (async () => {\n const reader = drainBody.getReader()\n let drainError: unknown\n try {\n for (;;) {\n const { done } = await reader.read()\n if (done) break\n }\n } catch (err) {\n drainError = err\n log('[chat-routes] turn drain failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n const failed = runFailed || drainError !== undefined\n try {\n await tap.done(failed ? 'error' : 'complete')\n } catch (err) {\n log('[chat-routes] turn buffer finalize failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n await fireTerminalLifecycle(failed, drainError)\n await releaseLock()\n })()\n if (ctx?.waitUntil) ctx.waitUntil(drained)\n else void drained.catch(() => {})\n\n // Announce the replay handle before the engine's first event.\n const encoder = new TextEncoder()\n const marker = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(encoder.encode(`${JSON.stringify(turnMarker)}\\n`))\n controller.close()\n },\n })\n const body = concatStreams([marker, clientBody])\n\n return new Response(body, {\n headers: {\n 'Content-Type': result.contentType,\n 'Cache-Control': 'no-cache',\n },\n })\n } catch (err) {\n // A throw before the turn began streaming (user-insert, gate, beforeTurn,\n // lifecycle-start, tap setup, engine construction, tee). If the turn had\n // already started, settle the lifecycle with `onTurnError` (close the\n // span) — the drain never ran to do it. Then release the lock, propagate.\n if (turnStarted) await fireTerminalLifecycle(true, err)\n await releaseLock()\n throw err\n }\n }\n\n async function replay(request: Request, params: { turnId: string }): Promise<Response> {\n const turnId = params.turnId?.trim()\n if (!turnId) return Response.json({ error: 'Missing turnId' }, { status: 400 })\n const auth = await options.authorize({ request, intent: 'replay', turnId })\n if (!auth.ok) return auth.response\n\n const fromSeqRaw = new URL(request.url).searchParams.get('fromSeq')\n const fromSeq = fromSeqRaw ? Math.max(0, Math.trunc(Number(fromSeqRaw)) || 0) : 0\n\n const encoder = new TextEncoder()\n const events = replayTurnEvents({\n store: options.turnStore,\n turnId,\n fromSeq,\n ...(options.replay?.pollMs !== undefined ? { pollMs: options.replay.pollMs } : {}),\n ...(options.replay?.timeoutMs !== undefined ? { timeoutMs: options.replay.timeoutMs } : {}),\n })\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n const { done, value } = await events.next()\n if (done) {\n controller.close()\n return\n }\n controller.enqueue(encoder.encode(`${value.event}\\n`))\n },\n cancel() {\n void events.return(undefined)\n },\n })\n return new Response(body, {\n headers: {\n 'Content-Type': 'application/x-ndjson',\n 'Cache-Control': 'no-cache',\n },\n })\n }\n\n async function running(request: Request): Promise<Response> {\n const threadId = new URL(request.url).searchParams.get('threadId')?.trim()\n if (!threadId) return Response.json({ error: 'Missing threadId' }, { status: 400 })\n const auth = await options.authorize({ request, intent: 'running', threadId })\n if (!auth.ok) return auth.response\n // `listRunning` is optional on the store; a store that cannot enumerate\n // running turns simply reports none — the client falls back to the persisted\n // transcript, never to a hang.\n const ids = (await options.turnStore.listRunning?.(threadId)) ?? []\n return Response.json({ running: ids })\n }\n\n return {\n turn,\n replay,\n running,\n interactions: options.interactions ? createInteractionAnswerRoute(options.interactions) : null,\n }\n}\n\n/** Sequential concat of byte streams (marker line, then the engine body). */\nfunction concatStreams(streams: ReadableStream<Uint8Array>[]): ReadableStream<Uint8Array> {\n let index = 0\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n if (!reader) {\n const next = streams[index++]\n if (!next) {\n controller.close()\n return\n }\n reader = next.getReader()\n }\n const { done, value } = await reader.read()\n if (done) {\n reader = null\n continue\n }\n controller.enqueue(value)\n return\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n for (const stream of streams.slice(index)) await stream.cancel(reason)\n },\n })\n}\n","/**\n * Sandbox lane: bridge a raw sandbox event stream (`streamSandboxPrompt`) into\n * the `ChatTurnProducer` shape agent-runtime's `handleChatTurn` consumes AND\n * the client vocabulary `/web-react`'s `dispatchChatStreamLine` already parses\n * (`text` / `reasoning` / `tool_call` / `tool_result` / `usage` /\n * `interaction`). Legal and tax each hand-rolled this mapping differently;\n * this is that middle, composed from `/stream`'s normalizers — no new loop\n * logic, no SDK import (the event source is an injected `AsyncIterable`).\n *\n * Alongside the live mapping it accumulates the PERSISTED projection — the\n * `message.parts` rows `/chat-store` stores — via `normalizePersistedPart` /\n * `mergePersistedPart` / `finalizeAssistantParts`, plus the usage receipt from\n * `step-finish` parts. `createChatTurnRoutes` reads both after drain.\n */\n\nimport {\n cancelStatusFor,\n interactionPartKey,\n interactionToPersistedPart,\n isRenderableInteractionKind,\n parseInteractionCancel,\n parseInteractionRequest,\n} from '../interactions/contract'\nimport {\n parsePlanSubmittedEvent,\n planToPersistedPart,\n} from '../plans/index'\nimport {\n asRecord,\n asString,\n finalizeAssistantParts,\n getPartKey,\n mergePersistedPart,\n normalizePersistedPart,\n normalizeToolEvent,\n type JsonRecord,\n type StreamEvent,\n} from '../stream/index'\nimport type { ChatTurnRouteProducer, ChatTurnUsage } from './turn-routes'\n\n/** Outcome of a `promoteFilePart` attempt. `key`, when given, becomes the\n * persisted part's row key (e.g. `attachment:<path>`) so repeat promotions\n * of the same underlying file fold into one segment instead of appending;\n * omitted, the default `getPartKey` keying applies.\n *\n * On failure, `part` is an OPTIONAL substitute part to persist in place of\n * the raw url-bearing one — this is how a product swaps in a transcript\n * notice (gtm persists a `warning` notice part, never the transient url) for\n * a failed promotion instead of baking a `data:`/sandbox-path url into the\n * durable row. When `part` is present it is persisted (via the same\n * `recordPersistedPart` path as a success, honoring the optional `key`);\n * when absent, the existing raw-part fallback applies unchanged — so a\n * caller that only returns `{ succeeded: false, reason }` keeps today's\n * behavior verbatim. */\nexport type FilePartPromotionOutcome =\n | { succeeded: true; part: Record<string, unknown>; key?: string }\n | { succeeded: false; reason: string; part?: Record<string, unknown>; key?: string }\n\nexport interface SandboxChatProducerOptions {\n /** The raw sandbox event stream (e.g. `streamSandboxPrompt(...)`). */\n events: AsyncIterable<unknown>\n /** Recorded on the persisted assistant message. */\n model?: string\n /** Which ask kinds the product renders a card for. Anything else is\n * auto-declined (see `declineInteraction`) so the run never hangs in the\n * broker waiting on a card no client will show. Default: question/plan. */\n isRenderableInteraction?: (kind: string) => boolean\n /** Resolve a non-renderable ask (wire `respondToSessionInteraction` with the\n * session's sidecar connection). Without it, non-renderable asks are only\n * logged — the run stays blocked until the broker times out. */\n declineInteraction?: (id: string) => Promise<void>\n /** Opt-in eager promotion of harness-emitted `file` parts. Unset, a `file`\n * part persists exactly as the harness sent it — a transient `url` (a\n * `data:` URI or in-sandbox path) baked into the transcript, which is\n * today's behavior and stays byte-identical if this is never wired. Set,\n * EVERY `file` part (never `image`, never any other kind) is routed\n * through this callback instead of `recordPersistedPart`'s default\n * fallback — including a part with NEITHER `id` NOR `url` (gtm always\n * attempts promotion; such a part simply fails \"carries no url\" and\n * resolves through the same failure path as any other rejection, rather\n * than being persisted raw and unpromoted) — so the product can durably\n * write the bytes and swap in a path-bearing part before the raw url ever\n * reaches the persisted transcript. Keyed per source-prefixed `id:<id>` /\n * `url:<url>` (an `id` and a `url` sharing the same text must never collide\n * onto one memo entry) and memoized by PROMISE (not result), so re-emitted\n * snapshot events for the same part —\n * the harness resends the whole part on every update, not just deltas —\n * fold onto the one in-flight or settled attempt rather than promoting\n * twice or racing two concurrent writes; a raw part with neither `id` nor\n * `url` cannot be keyed, so it is invoked UN-memoized (once per event) —\n * each occurrence is its own attempt. A rejecting promise is caught,\n * logged via `log`, and treated as `succeeded: false`. On `succeeded:\n * false` the outcome's optional `part` (a substitute — e.g. a warning\n * notice — see {@link FilePartPromotionOutcome}) persists in its place when\n * given; otherwise the raw part persists exactly as it does today — this\n * seam only decides whether to call the promoter and what to do with its\n * outcomes; the promotion mechanics (vault write, key derivation, notice\n * construction) live in the caller's callback, not here. */\n promoteFilePart?: (raw: JsonRecord) => Promise<FilePartPromotionOutcome>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\ninterface TextTracker {\n /** Full accumulated text per part key, to derive suffix deltas from\n * snapshot-only harness events. */\n seen: Map<string, string>\n}\n\n/** Delta to emit for one text/reasoning part update: prefer the harness's\n * explicit delta; otherwise diff the snapshot against what was already\n * emitted for that part (snapshot-only harnesses re-send the whole text). */\nfunction textDelta(tracker: TextTracker, key: string, part: JsonRecord, rawDelta: unknown): string {\n const explicit = typeof rawDelta === 'string' ? rawDelta : undefined\n const previous = tracker.seen.get(key) ?? ''\n if (explicit !== undefined) {\n tracker.seen.set(key, previous + explicit)\n return explicit\n }\n const snapshot = asString(part.text) ?? asString(part.content) ?? ''\n if (!snapshot) return ''\n if (snapshot.startsWith(previous)) {\n tracker.seen.set(key, snapshot)\n return snapshot.slice(previous.length)\n }\n // The snapshot replaced the text outright — emit it whole; the persisted\n // projection stays correct because finalText is authoritative at finalize.\n tracker.seen.set(key, snapshot)\n return snapshot\n}\n\nfunction usageFromStepFinish(part: JsonRecord, usage: ChatTurnUsage): void {\n const tokens = asRecord(part.tokens)\n if (tokens) {\n const cache = asRecord(tokens.cache)\n const add = (current: number | undefined, value: unknown): number | undefined => {\n const n = Number(value)\n if (!Number.isFinite(n)) return current\n return (current ?? 0) + n\n }\n usage.inputTokens = add(usage.inputTokens, tokens.input)\n usage.outputTokens = add(usage.outputTokens, tokens.output)\n usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning)\n if (cache) {\n usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read)\n usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write)\n }\n }\n const cost = Number(part.cost)\n if (Number.isFinite(cost)) usage.costUsd = (usage.costUsd ?? 0) + cost\n}\n\nexport function createSandboxChatProducer(options: SandboxChatProducerOptions): ChatTurnRouteProducer {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n const renderable = options.isRenderableInteraction ?? isRenderableInteractionKind\n\n let fullText = ''\n const partOrder: string[] = []\n const partMap = new Map<string, JsonRecord>()\n const tracker: TextTracker = { seen: new Map() }\n const usage: ChatTurnUsage = {}\n /** Tool ids already announced as `tool_call` / settled as `tool_result`. */\n const announcedTools = new Set<string>()\n const settledTools = new Set<string>()\n /** Id-less step boundaries: one occurrence per key, never merged. */\n let stepCounter = 0\n /** `promoteFilePart` memo, keyed by `id ?? url` of the raw part. Holds the\n * PROMISE (never the settled result) so concurrent duplicate events for\n * the same part await the one in-flight attempt instead of each starting\n * their own; the promise never rejects (see below), so a later duplicate\n * reading a settled entry reuses that first outcome — success or\n * failure — rather than retrying. */\n const promotedFileParts = new Map<string, Promise<FilePartPromotionOutcome>>()\n\n function recordPersistedPart(part: JsonRecord, delta: string | undefined, keyOverride?: string): void {\n const persisted = normalizePersistedPart(part)\n if (!persisted) return\n const key = keyOverride ?? getPartKey(persisted)\n if (!partMap.has(key)) partOrder.push(key)\n partMap.set(key, mergePersistedPart(partMap.get(key), persisted, delta))\n }\n\n async function* stream(): AsyncGenerator<StreamEvent, void, unknown> {\n for await (const raw of options.events) {\n const record = asRecord(raw)\n if (!record || typeof record.type !== 'string') continue\n // Fold bare tool_call/tool_result shapes into the canonical part event;\n // everything else keeps its original record (verbatim forwarding must\n // not strip fields outside `data`).\n const normalized = normalizeToolEvent({ type: record.type, data: asRecord(record.data) })\n const event = normalized.type === 'message.part.updated' ? normalized : (record as unknown as StreamEvent)\n\n if (event.type === 'message.part.updated') {\n const part = asRecord(event.data?.part)\n if (!part) continue\n const rawDelta = event.data?.delta\n const partType = String(part.type ?? '')\n\n if (partType === 'text' || partType === 'reasoning') {\n const key = getPartKey(part)\n const delta = textDelta(tracker, key, part, rawDelta)\n recordPersistedPart(part, delta || undefined)\n if (delta) {\n if (partType === 'text') fullText += delta\n yield { type: partType, text: delta } as StreamEvent & { text: string }\n }\n continue\n }\n\n if (partType === 'tool') {\n recordPersistedPart(part, undefined)\n const persisted = partMap.get(getPartKey(part))\n const state = asRecord(persisted?.state)\n const toolId = String(persisted?.id ?? '')\n const toolName = String(persisted?.tool ?? 'tool')\n if (toolId && !announcedTools.has(toolId)) {\n announcedTools.add(toolId)\n yield {\n type: 'tool_call',\n call: { toolCallId: toolId, toolName, args: asRecord(state?.input) ?? {} },\n } as StreamEvent\n }\n const status = String(state?.status ?? '')\n if (toolId && (status === 'completed' || status === 'error') && !settledTools.has(toolId)) {\n settledTools.add(toolId)\n yield {\n type: 'tool_result',\n toolCallId: toolId,\n toolName,\n outcome: {\n ok: status === 'completed',\n ...(state?.output !== undefined ? { result: state.output } : {}),\n ...(asString(state?.error) ? { message: asString(state?.error) } : {}),\n },\n } as StreamEvent\n }\n continue\n }\n\n if (partType === 'step-finish') {\n usageFromStepFinish(part, usage)\n // Persist the per-step receipt too (unique key per occurrence: the\n // parts have no id and two receipts must never merge into one).\n recordPersistedPart(part, undefined, `step-finish:#${stepCounter++}`)\n const promptTokens = usage.inputTokens ?? 0\n const completionTokens = usage.outputTokens ?? 0\n if (promptTokens || completionTokens) {\n yield { type: 'usage', usage: { promptTokens, completionTokens } } as StreamEvent\n }\n continue\n }\n\n if (partType === 'step-start') {\n recordPersistedPart(part, undefined, `step-start:#${stepCounter}`)\n continue\n }\n\n if (partType === 'file' && options.promoteFilePart) {\n const promote = options.promoteFilePart\n // Prefixed by source (`id:`/`url:`) rather than the bare raw string —\n // an `id` and a `url` that happen to share the same text (e.g. both\n // `\"abc\"`) would otherwise collide onto one memo entry and fold two\n // unrelated parts' promotions together. Internal Map key only; never\n // observable outside this module.\n const rawId = asString(part.id)\n const rawUrl = asString(part.url)\n const memoKey = rawId ? `id:${rawId}` : rawUrl ? `url:${rawUrl}` : undefined\n // Always invoke the callback for a `file` part when one is wired —\n // gtm never skips promotion outright, even for a part with neither\n // `id` nor `url` (it simply fails \"carries no url\" and resolves\n // through the ordinary failure path). Memoization by PROMISE only\n // applies when there is something to key it on; keyless parts are\n // invoked un-memoized, once per occurrence.\n //\n // `Promise.resolve().then(...)` (rather than calling `promote(part)`\n // directly) so a SYNC throw from a non-async `promoteFilePart` is\n // captured into the promise chain instead of escaping this function\n // call outright — `.catch` below only ever sees a rejection, never a\n // thrown exception that unwinds past `attempt()`.\n const attempt = (): Promise<FilePartPromotionOutcome> =>\n Promise.resolve()\n .then(() => promote(part))\n .catch((err) => {\n const reason = err instanceof Error ? err.message : String(err)\n log('[chat-routes] file part promotion threw', { key: memoKey ?? '(keyless)', error: reason })\n return { succeeded: false as const, reason }\n })\n\n let pending: Promise<FilePartPromotionOutcome>\n if (memoKey) {\n pending = promotedFileParts.get(memoKey) ?? attempt()\n promotedFileParts.set(memoKey, pending)\n } else {\n pending = attempt()\n }\n\n const outcome = await pending\n if (outcome.succeeded) {\n recordPersistedPart(outcome.part, undefined, outcome.key)\n } else if (outcome.part) {\n // Substitute part (e.g. a warning notice) takes the raw part's\n // place in the transcript — the transient url never lands.\n recordPersistedPart(outcome.part, undefined, outcome.key)\n } else {\n recordPersistedPart(part, undefined)\n }\n continue\n }\n\n // Remaining storable kinds (file/image/subtask) have no live\n // vocabulary line; they persist so the transcript keeps them.\n recordPersistedPart(part, undefined)\n continue\n }\n\n if (event.type === 'interaction') {\n const parsed = parseInteractionRequest(asRecord(record.data))\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed interaction event', { error: parsed.error })\n continue\n }\n if (renderable(parsed.value.kind)) {\n recordPersistedPart(\n interactionToPersistedPart(parsed.value, 'pending'),\n undefined,\n interactionPartKey(parsed.value.id),\n )\n yield event\n continue\n }\n // Non-renderable ask: the run is blocked in the broker until someone\n // answers. Decline it so the turn proceeds instead of hanging.\n if (options.declineInteraction) {\n try {\n await options.declineInteraction(parsed.value.id)\n } catch (err) {\n log('[chat-routes] failed to auto-decline interaction', {\n id: parsed.value.id,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n } else {\n log('[chat-routes] non-renderable interaction with no declineInteraction wired', {\n id: parsed.value.id,\n kind: parsed.value.kind,\n })\n }\n continue\n }\n\n if (event.type === 'interaction.cancel') {\n const parsed = parseInteractionCancel(asRecord(record.data))\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed interaction.cancel event', { error: parsed.error })\n continue\n }\n const key = interactionPartKey(parsed.value.id)\n const existing = partMap.get(key)\n if (existing?.type === 'interaction' && existing.status === 'pending') {\n recordPersistedPart({\n ...existing,\n status: cancelStatusFor(parsed.value.reason),\n ...(parsed.value.reason ? { cancelReason: parsed.value.reason } : {}),\n }, undefined, key)\n }\n yield event\n continue\n }\n\n if (event.type === 'plan.submitted') {\n const parsed = parsePlanSubmittedEvent(record)\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed plan.submitted event', { error: parsed.error })\n continue\n }\n recordPersistedPart(planToPersistedPart(parsed.value), undefined)\n yield event\n continue\n }\n\n if (event.type === 'result') {\n const finalText = asString(event.data?.finalText)\n if (finalText) fullText = finalText\n const resultUsage = asRecord(event.data?.usage)\n if (resultUsage) {\n const input = Number(resultUsage.inputTokens)\n const output = Number(resultUsage.outputTokens)\n if (Number.isFinite(input)) usage.inputTokens = input\n if (Number.isFinite(output)) usage.outputTokens = output\n }\n continue\n }\n\n // Everything else (error, lifecycle) forwards\n // verbatim — the client parser ignores unknown types.\n yield event\n }\n\n }\n\n return {\n stream: stream(),\n finalText: () => fullText,\n assistantParts: () => finalizeAssistantParts(partOrder, partMap, fullText),\n usage: () => usage,\n ...(options.model ? { model: options.model } : {}),\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 completed turn short-circuits\n * instead of re-streaming). Products supply only the domain seams: the raw\n * 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 {\n coalesceDeltas,\n createBufferedTurnTap,\n type TurnEventStore,\n} from '../stream/index'\nimport { createSandboxChatProducer } from './sandbox-producer'\nimport type { ChatTurnUsage } from './turn-routes'\n\n/** Authoritative final receipt for a turn whose live stream carried no usage\n * (some harness paths only expose tokens via the completed-turn record, e.g.\n * `box.findCompletedTurn(turnId)`). */\nexport interface DetachedTurnFinal {\n text?: string\n usage?: ChatTurnUsage\n}\n\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 events: AsyncIterable<unknown>\n /** Recorded on the persisted assistant message + usage receipt. */\n model?: string\n /** Per-flush buffer coalescer. Default `coalesceDeltas`. */\n coalesce?: (events: unknown[]) => unknown[]\n /** Authoritative final receipt, consulted twice: (a) as the cached result\n * when the turn already completed (idempotent re-invoke), and (b) as a\n * fallback when a clean run's stream carried no usage/text. */\n completedResult?: () => Promise<DetachedTurnFinal | null | undefined>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\nexport interface DetachedTurnResult {\n /** `completed` — clean drain: persist + bill. `failed` — a terminal error\n * event or a thrown stream: skip billing, render an error row. */\n state: 'completed' | 'failed'\n text: string\n usage: ChatTurnUsage\n /** Present when `state === 'failed'`. */\n error?: string\n /** True when the turn had already completed and this call returned the cached\n * result WITHOUT re-streaming (durable-driver retry after a crash). */\n cached: boolean\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\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 * - 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 const prior = await store.getStatus(turnId).catch(() => null)\n if (prior === 'complete') {\n const final = opts.completedResult ? await opts.completedResult().catch(() => null) : null\n return { state: 'completed', text: final?.text ?? '', usage: final?.usage ?? {}, cached: true }\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 const producer = createSandboxChatProducer({\n events: opts.events,\n model: opts.model,\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 }\n await tap.done(runError ? 'error' : 'complete')\n } catch (err) {\n await tap.done('error').catch(() => {})\n throw err\n }\n\n const text = producer.finalText?.() ?? ''\n let usage: ChatTurnUsage = producer.usage?.() ?? {}\n\n if (!runError && !hasUsage(usage)) {\n const final = opts.completedResult ? await opts.completedResult().catch(() => null) : null\n if (final?.usage) usage = { ...usage, ...final.usage }\n if (!text && final?.text) return { state: 'completed', text: final.text, usage, cached: false }\n }\n\n if (runError) return { state: 'failed', text, usage, error: runError, cached: false }\n return { state: 'completed', text, usage, cached: false }\n}\n","import { getPartKey, mergePersistedPart, type StreamEvent } from '../stream/index'\nimport type { ChatTurnRouteProducer } from './turn-routes'\n\nexport interface ChatRouteDurableProjection {\n observe(event: unknown): void | Promise<void>\n materialize(): Array<Record<string, unknown>> | Promise<Array<Record<string, unknown>>>\n}\n\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. 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 * `createUploadRoute` — the multimodal middle. Accepts multipart file uploads\n * and returns `PromptInputPart`-shaped descriptors the client echoes back on\n * send (`ChatTurnRequestPayload.parts`):\n *\n * ≤ inlineMaxBytes (700 KiB default) → inline `data:` URI part — rides the\n * turn body directly, no sandbox round trip.\n * > inlineMaxBytes → written into the sandbox workspace (base64 through the\n * structural `write` seam — `box.fs` satisfies it) and referenced by\n * `path`. Mandatory two-step: the gateway caps request bodies at ~1 MiB,\n * so a large file can never ride the prompt POST.\n *\n * The sink is structural (no sandbox-SDK import); products pass `box.fs`.\n *\n * @remarks Sole consumer today is the `--chat` scaffold (`create-agent-app\n * --chat` → `template-chat/src/chat.ts`), the reference multimodal path — its\n * inline-`data:`-or-ephemeral-sandbox-workspace split stays the scaffold's\n * proven upload pattern, not a fleet primitive; keep that distinction in mind\n * before widening its surface. Fleet apps with a durable store of their own\n * (KV, or AES-GCM-encrypted R2) no longer need to hand-roll a vault upload\n * route: `createAttachmentUploadRoute` (`./attachment-upload`, agent-app#234)\n * is the shared hardened path for that persistence model — a content-sniffed\n * type gate, two-phase atomic batch writes, and per-kind/aggregate size caps,\n * all seamed through an injected `WriteAttachmentFn`. Point readers there\n * instead of widening this route to cover both models.\n */\n\nimport type { ChatTurnFilePartInput } from './wire'\n\n/** 700 KiB: base64 inflates ~4/3, so an inline part stays comfortably under\n * the ~1 MiB gateway body cap alongside the JSON envelope. */\nexport const UPLOAD_INLINE_MAX_BYTES = 700 * 1024\n\n/** 8 MiB default ceiling per file — one base64 `write` call handles it. Raise\n * it only with a sink that can take the bigger single write. */\nexport const UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024\n\n/** Structural match of the sandbox SDK's `box.fs` write surface (v0.10.5+:\n * `encoding: 'base64'` is the worker-safe binary path). */\nexport interface SandboxUploadSink {\n write(path: string, content: string, options?: { encoding?: 'utf8' | 'base64' }): Promise<unknown>\n}\n\nexport type UploadAuthorization =\n | {\n ok: true\n /** Where large files land. Absent/null: only inline uploads are\n * accepted and an over-inline-cap file is rejected with 413. */\n sink?: SandboxUploadSink | null\n /** Per-request override of the workspace directory large files go to. */\n uploadDir?: string\n }\n | { ok: false; response: Response }\n\nexport interface CreateUploadRouteOptions {\n /** Authenticate the caller and resolve the sandbox file sink (usually\n * `ensureWorkspaceSandbox(...)` → `box.fs`). */\n authorize(args: { request: Request }): Promise<UploadAuthorization>\n /** Inline-vs-sandbox threshold. Default {@link UPLOAD_INLINE_MAX_BYTES}. */\n inlineMaxBytes?: number\n /** Hard per-file cap. Default {@link UPLOAD_MAX_FILE_BYTES}. */\n maxFileBytes?: number\n /** Workspace directory for path-ref files. Default `'uploads'`. */\n uploadDir?: string\n}\n\n/** One uploaded file, ready for the composer chip and the turn body. */\nexport interface UploadedChatFile {\n id: string\n name: string\n size: number\n mediaType: string\n /** True when the part carries the bytes inline (`data:` URI). */\n inline: boolean\n /** Echo this back verbatim in `ChatTurnRequestPayload.parts`. */\n part: ChatTurnFilePartInput\n}\n\n/** Path-safe file name: basename only, conservative charset, length-capped. */\nexport function sanitizeUploadFilename(name: string): string {\n const base = name.split(/[\\\\/]/).pop() ?? 'file'\n const safe = base.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '_')\n return (safe || 'file').slice(0, 120)\n}\n\nconst BASE64_CHUNK = 0x8000\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n let binary = ''\n for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK))\n }\n return btoa(binary)\n}\n\nfunction uploadError(status: number, code: string, error: string): Response {\n return Response.json({ code, error }, { status })\n}\n\nexport function createUploadRoute(options: CreateUploadRouteOptions): (request: Request) => Promise<Response> {\n const inlineMaxBytes = options.inlineMaxBytes ?? UPLOAD_INLINE_MAX_BYTES\n const maxFileBytes = options.maxFileBytes ?? UPLOAD_MAX_FILE_BYTES\n\n return async function upload(request: Request): Promise<Response> {\n const auth = await options.authorize({ request })\n if (!auth.ok) return auth.response\n const sink = auth.sink ?? null\n const uploadDir = (auth.uploadDir ?? options.uploadDir ?? 'uploads').replace(/\\/+$/, '')\n\n let form: FormData\n try {\n form = await request.formData()\n } catch {\n return uploadError(400, 'INVALID_UPLOAD', 'Expected a multipart/form-data body with file fields')\n }\n const files: File[] = []\n form.forEach((value) => {\n if (value instanceof File) files.push(value)\n })\n if (files.length === 0) {\n return uploadError(400, 'INVALID_UPLOAD', 'No files in the upload body')\n }\n\n const uploaded: UploadedChatFile[] = []\n for (const file of files) {\n const name = sanitizeUploadFilename(file.name)\n const mediaType = file.type || 'application/octet-stream'\n const partType: ChatTurnFilePartInput['type'] = mediaType.startsWith('image/') ? 'image' : 'file'\n\n if (file.size > maxFileBytes) {\n return uploadError(\n 413,\n 'FILE_TOO_LARGE',\n `${name} is ${file.size}B, over the ${maxFileBytes}B per-file cap`,\n )\n }\n\n const id = crypto.randomUUID()\n if (file.size <= inlineMaxBytes) {\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: true,\n part: {\n type: partType,\n filename: name,\n mediaType,\n url: `data:${mediaType};base64,${base64}`,\n },\n })\n continue\n }\n\n if (!sink) {\n return uploadError(\n 413,\n 'SANDBOX_REQUIRED',\n `${name} is ${file.size}B, over the ${inlineMaxBytes}B inline cap, and no sandbox is available to hold it`,\n )\n }\n const path = `${uploadDir}/${id}-${name}`\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n await sink.write(path, base64, { encoding: 'base64' })\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: false,\n part: { type: partType, filename: name, mediaType, path },\n })\n }\n\n return Response.json({ files: uploaded })\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 type { ChatAttachmentInput, ChatAttachmentKind } from './wire'\nimport { attachmentInputToPart, type ChatAttachmentPart } from '../chat-store/parts'\nimport type { ReadAttachmentFn } from './attachment-store'\nimport { ATTACHMENT_MAX_COUNT, MAX_ATTACHMENT_TOTAL_BYTES, attachmentTotalSizeErrorMessage } from './attachment-validation'\n\nexport type ResolveChatAttachmentsResult =\n | { succeeded: true; value: ChatAttachmentPart[] }\n | { succeeded: false; error: string }\n\n/** Verdict of a path check: OK, or a rejection naming why. Mirrors\n * `SandboxMentionPathCheck` in `./wire`. */\nexport type AttachmentPathCheck =\n | { succeeded: true }\n | { succeeded: false; error: string }\n\n/** Longest attachment display name accepted — bounds what gets echoed into the\n * prompt block and rendered as a chip label. */\nconst MAX_ATTACHMENT_NAME_LENGTH = 256\n\nfunction isAttachmentKind(value: unknown): value is ChatAttachmentKind {\n return value === 'image' || value === 'file'\n}\n\n/** C0 control characters (0x00–0x1F) plus DEL (0x7F) — covers `\\n`/`\\r`/`\\t`.\n * A `name` or `path` carrying one of these has no legitimate use here and\n * everything to gain from an attacker: {@link buildAttachmentPromptBlock} in\n * `/chat-store` renders both fields verbatim into the dispatched agent\n * prompt, so an embedded newline fabricates new prompt lines (a\n * prompt-injection vector) rather than naming a file. Rejected at this\n * boundary — not merely neutralized downstream — so the wire never accepts\n * the input in the first place; a legitimate name/path never contains one. */\nconst CONTROL_CHARS = /[\\x00-\\x1F\\x7F]/\n\n/**\n * Default path validator when a caller supplies none. Rejects the ways a path\n * picked in a client can escape the store root — traversal (`..` segment),\n * absolute (leading `/`), backslashes, null bytes, control characters (see\n * {@link CONTROL_CHARS} — a path also feeds {@link buildAttachmentPromptBlock}'s\n * `(vault: ${path})` pointer, so it is exposed to the same injection surface as\n * `name`) — plus a dotfile/hidden segment (a leading `.` on any segment).\n * Generalized from gtm's `validateVaultFilePath`, in the spirit of\n * `validateSandboxMentionPath` (`/chat-routes`'s wire mention-path validator) —\n * but the dotfile rejection here is INTENTIONALLY stricter than that sibling:\n * an uploaded attachment path is sanitized store-relative storage the product\n * itself assigned, whereas a mention path points at a file that already exists\n * in the sandbox and may legitimately live under a dotfile segment. A caller\n * that needs gtm's exact (looser) rule can supply `validatePath` to override\n * this default entirely.\n */\nexport function defaultValidateAttachmentPath(path: string): AttachmentPathCheck {\n if (path.includes('\\0')) return { succeeded: false, error: 'attachment path must not contain null bytes' }\n if (path.includes('\\\\')) return { succeeded: false, error: 'attachment path must not contain backslashes' }\n if (CONTROL_CHARS.test(path)) return { succeeded: false, error: 'attachment path must not contain control characters' }\n if (path.startsWith('/')) return { succeeded: false, error: 'attachment path must be store-relative, not absolute' }\n const segments = path.split('/')\n if (segments.some((segment) => segment === '..')) {\n return { succeeded: false, error: 'attachment path must not contain \"..\" segments' }\n }\n if (segments.some((segment) => segment.startsWith('.'))) {\n return { succeeded: false, error: 'attachment path must not contain a hidden (dotfile) segment' }\n }\n return { succeeded: true }\n}\n\nfunction parseAttachmentInput(\n value: unknown,\n index: number,\n validatePath: (path: string) => AttachmentPathCheck,\n): { succeeded: true; value: ChatAttachmentInput } | { succeeded: false; error: string } {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return { succeeded: false, error: `attachments[${index}] must be an object` }\n }\n const record = value as Record<string, unknown>\n\n const path = record.path\n if (typeof path !== 'string' || !path) {\n return { succeeded: false, error: `attachments[${index}].path must be a non-empty string` }\n }\n const name = record.name\n if (typeof name !== 'string' || !name.trim()) {\n return { succeeded: false, error: `attachments[${index}].name must be a non-empty string` }\n }\n if (name.length > MAX_ATTACHMENT_NAME_LENGTH) {\n return { succeeded: false, error: `attachments[${index}].name must not exceed ${MAX_ATTACHMENT_NAME_LENGTH} characters` }\n }\n if (CONTROL_CHARS.test(name)) {\n return { succeeded: false, error: `attachments[${index}].name must not contain control characters` }\n }\n const size = record.size\n if (typeof size !== 'number' || !Number.isFinite(size)) {\n return { succeeded: false, error: `attachments[${index}].size must be a finite number` }\n }\n if (size < 0) {\n return { succeeded: false, error: `attachments[${index}].size must not be negative` }\n }\n const mediaType = record.mediaType\n if (typeof mediaType !== 'string') {\n return { succeeded: false, error: `attachments[${index}].mediaType must be a string` }\n }\n const kind = record.kind\n if (!isAttachmentKind(kind)) {\n return { succeeded: false, error: `attachments[${index}].kind must be \"image\" or \"file\"` }\n }\n\n const pathCheck = validatePath(path)\n if (!pathCheck.succeeded) return { succeeded: false, error: pathCheck.error }\n\n return { succeeded: true, value: { path, name, size, mediaType, kind } }\n}\n\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 maxCount = options.maxCount ?? ATTACHMENT_MAX_COUNT\n const maxTotalBytes = options.maxTotalBytes ?? MAX_ATTACHMENT_TOTAL_BYTES\n const validatePath = options.validatePath ?? defaultValidateAttachmentPath\n\n if (value === undefined || value === null) return { succeeded: true, value: [] }\n if (!Array.isArray(value)) return { succeeded: false, error: 'attachments must be an array' }\n if (value.length > maxCount) {\n return { succeeded: false, error: `attachments must not exceed ${maxCount} entries` }\n }\n\n const inputs: ChatAttachmentInput[] = []\n const seenPaths = new Set<string>()\n for (let index = 0; index < value.length; index += 1) {\n const parsed = parseAttachmentInput(value[index], index, validatePath)\n if (!parsed.succeeded) return parsed\n if (seenPaths.has(parsed.value.path)) {\n return { succeeded: false, error: `attachments must not repeat a path: ${parsed.value.path}` }\n }\n seenPaths.add(parsed.value.path)\n inputs.push(parsed.value)\n }\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","/**\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 the injected\n * {@link WriteAttachmentFn} (gtm hard-wired its vault writer), the path strategy\n * is the injected `buildAttachmentPath` (neutral `uploads/agent/<date>/` default,\n * no domain bucket taxonomy baked), the MIME map is an injectable hook, and the\n * date segment reads an injectable clock. The idempotent `hash8(id ?? url ??\n * filename)` naming is preserved so re-promoting the same source part resolves\n * to the same path.\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 type { WriteAttachmentFn } from './attachment-store'\nimport { sanitizeAttachmentFileName } from './attachment-validation'\nimport { formatBytes } from './wire'\n\n/** Default ceiling on a promoted file's raw (pre-encoding) byte size. */\nexport const PROMOTE_MAX_FILE_BYTES = 10 * 1024 * 1024\n\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\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/** Minimal extension→mime map — the last-resort media type when the part\n * carries none. Generic file typing, NOT a product accept-list (which is a\n * domain value the product supplies): an unknown extension falls to\n * `text/plain`, it never rejects. */\nconst EXT_TO_MIME: Record<string, string> = {\n md: 'text/markdown',\n markdown: 'text/markdown',\n txt: 'text/plain',\n log: 'text/plain',\n csv: 'text/csv',\n tsv: 'text/tab-separated-values',\n json: 'application/json',\n yaml: 'text/yaml',\n yml: 'text/yaml',\n xml: 'application/xml',\n html: 'text/html',\n htm: 'text/html',\n pdf: 'application/pdf',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n heic: 'image/heic',\n heif: 'image/heif',\n svg: 'image/svg+xml',\n mp4: 'video/mp4',\n webm: 'video/webm',\n mov: 'video/quicktime',\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n m4a: 'audio/mp4',\n aac: 'audio/aac',\n}\n\n/** Default MIME hook: extension → mime, or `text/plain` for the unknown. */\nexport function sniffMimeFromName(filename: string): string {\n const ext = filename.split('.').pop()?.toLowerCase()\n if (!ext) return 'text/plain'\n return EXT_TO_MIME[ext] ?? 'text/plain'\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]*)$/.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:([^;,]+)[;,]/.exec(url)\n return match ? match[1] : undefined\n}\n\nfunction basenameFromUrl(url: string | undefined): string | undefined {\n if (!url || url.startsWith('data:')) 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 = url.startsWith('file://') ? 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: ${err instanceof Error ? err.message : String(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: ${err instanceof Error ? err.message : String(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: ${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: ${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 (url.startsWith('data:')) return resolveDataUrlBytes(url, input.filename, input.maxBytes)\n\n const isSandboxPath = url.startsWith('file://') || url.startsWith('/')\n if (!isSandboxPath) return { succeeded: false, reason: `unsupported file URL scheme: ${url}` }\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\nexport interface PromoteAgentFilePartOptions {\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 /** REQUIRED store writer — no default (the product owns its store). */\n writeAttachment: WriteAttachmentFn\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}\n\nexport async function promoteAgentFilePart(options: PromoteAgentFilePartOptions): Promise<PromoteFilePartResult> {\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\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 const mediaType = options.raw.mediaType ?? options.raw.mime ?? dataUrlMime(options.raw.url) ?? sniffMime(filename)\n const kind = attachmentKindForMime(mediaType)\n const digest = await hash8(options.raw.id ?? options.raw.url ?? filename)\n const date = now().toISOString().split('T')[0] ?? ''\n const path = buildAttachmentPath({ filename, hash8: digest, date, mediaType, kind })\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<WriteAttachmentFn>>\n try {\n written = await options.writeAttachment(options.scopeId, path, resolved.bytes, {\n mediaType,\n name: filename,\n originalName: options.raw.filename ?? filename,\n size: resolved.bytes.byteLength,\n })\n } catch (err) {\n return { succeeded: false, filename, reason: err instanceof Error ? err.message : String(err) }\n }\n if (!written.ok) return { succeeded: false, filename, reason: written.reason }\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 atomic batch (every file is validated before any file is\n * written — a batch never partially lands), a content-sniffed type gate\n * (`checkAttachmentType` over `sniffBinary`'s magic-byte read, not the\n * extension or the browser-reported MIME), per-kind + aggregate byte caps,\n * and sanitized filenames. Storage is fully seamed through the injected\n * `WriteAttachmentFn` (`./attachment-store`) — no default store, the product\n * owns where bytes actually live (vault, object store, …) — and auth/rate\n * limiting is entirely the injected `authorize` seam's job: this factory\n * never invents a 401 or 429 response, it only returns `auth.response`\n * verbatim on failure.\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 type { ChatAttachmentInput, ChatAttachmentKind } from './wire'\nimport { attachmentKindForMime } from '../chat-store/parts'\nimport type { WriteAttachmentFn } from './attachment-store'\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 sanitizeAttachmentFileName,\n} from './attachment-validation'\nimport { sniffBinary } from './binary-sniff'\nimport { defaultValidateAttachmentPath, type AttachmentPathCheck } from './resolve-attachments'\nimport { sniffMimeFromName } from './promote-file-part'\n\n/** Outcome of the injected `authorize` seam: auth + rate limiting +\n * scope resolution, all in one place so a 429 rides `{ok:false, response}`\n * exactly like a 401 does — this factory has no rate-limit opinion of its\n * own. `writeAttachment` lets a single request override the option-level\n * store (e.g. routing per-tenant), defaulting to `options.writeAttachment`\n * when absent. */\nexport type AttachmentUploadAuthorization =\n | { ok: true; scopeId: string; writeAttachment?: WriteAttachmentFn }\n | { ok: false; response: Response }\n\nexport interface CreateAttachmentUploadRouteOptions {\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 /** Default store writer. `authorize` may override it per-request. */\n writeAttachment: WriteAttachmentFn\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 /** Ceiling on a text file's raw size. Default {@link MAX_TEXT_ATTACHMENT_BYTES}. */\n maxTextBytes?: number\n /** Aggregate raw-byte ceiling across the batch. Default {@link MAX_ATTACHMENT_TOTAL_BYTES}. */\n maxTotalBytes?: number\n }\n /** Attachment kinds this route accepts. Default `['image', 'file']`. */\n allowedKinds?: ChatAttachmentKind[]\n /** Sniffed-mime allowlist fed to `checkAttachmentType`. Default\n * {@link ALLOWED_ATTACHMENT_SNIFFED_MIMES}. */\n allowedSniffedMimes?: ReadonlySet<string>\n /** Sanitized-name → store path. Default identity (the sanitized name IS\n * the path); gtm passes `vaultFolderForFileName`, a tenant product a\n * scope prefix. */\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 can't type.\n * Default {@link sniffMimeFromName}. */\n sniffMime?: (name: string) => string\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\nexport function createAttachmentUploadRoute(\n options: CreateAttachmentUploadRouteOptions,\n): (request: Request) => Promise<Response> {\n const maxCount = options.limits?.maxCount ?? ATTACHMENT_MAX_COUNT\n const maxBinaryBytes = options.limits?.maxBinaryBytes ?? MAX_BINARY_ATTACHMENT_BYTES\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\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 write = auth.writeAttachment ?? options.writeAttachment\n\n let form: FormData\n try {\n form = await request.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 const files: File[] = []\n form.forEach((value) => {\n if (value instanceof File) files.push(value)\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 interface PreparedWrite {\n path: string\n name: string\n bytes: Uint8Array\n originalName: string\n size: number\n mediaType: string\n kind: ChatAttachmentKind\n }\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 seenPaths = 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 = sniff.binary ? maxBinaryBytes : maxTextBytes\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 path = pathFor(name)\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 if (seenPaths.has(path)) {\n return attachmentUploadError(\n 400,\n 'attachment_duplicate_path',\n `attachments must not repeat a path within one upload: ${path}`,\n path,\n )\n }\n seenPaths.add(path)\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, name, bytes, originalName: file.name, size: bytes.length, mediaType, kind })\n }\n\n // Phase 2: every file in the batch passed validation — write them all.\n const uploaded: ChatAttachmentInput[] = []\n for (const input of prepared) {\n const written = await write(auth.scopeId, input.path, input.bytes, {\n mediaType: input.mediaType,\n name: input.name,\n originalName: input.originalName,\n size: input.size,\n })\n if (!written.ok) {\n return attachmentUploadError(413, 'attachment_write_failed', written.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 }\n\n return Response.json({ files: uploaded })\n }\n}\n","/**\n * `buildDispatchParts` — assemble the `PromptInputPart[]` a turn carrying\n * attachments and/or `@`-mentions dispatches to the sandbox. `parts[0]` is\n * always the full prompt text (typed text plus the attachment + mention pointer\n * blocks); each attachment or mention becomes one media part. An attachment\n * (read from the product store via the injected reader) draws the inline byte\n * budget first; a mention (read from the LIVE box) takes what is left. A file\n * inlines as a `data:` URI when it fits the remaining budget, otherwise demotes\n * to an in-box path part so the whole request stays under the proxy cap. Every\n * media part is deduped by its resolved absolute path. This module only\n * produces the parts array; the caller decides when a turn dispatches parts\n * instead of a plain string.\n *\n * Storage-parameterized port of gtm-agent's `dispatch-parts.ts`: the vault\n * default reader is dropped (`readAttachment` is REQUIRED — the product supplies\n * its store adapter), the `GTM_SANDBOX_VAULT_DIR` prefixing becomes the required\n * `resolveAttachmentPath` seam, the `GTM_MULTIMODAL_FORCE_PATH` env fallback\n * becomes an explicit `forcePath` flag, and every budget cap reads an overridable\n * `./wire` constant. Kept behavior-identical for gtm-agent#618 adoption (the\n * demotion math and emitted part shapes reproduce its dispatched prompt bytes).\n */\n\nimport { flattenHistory, type PromptInputPart } from '../sandbox'\nimport {\n statSandboxFileSize,\n readSandboxBinaryBytes,\n type SandboxExecChannel,\n} from '../sandbox/binary-read'\nimport {\n mediaTypeForMentionPath,\n base64WireLen,\n DISPATCH_REQUEST_MAX_BYTES,\n DISPATCH_STRUCTURAL_RESERVE_BYTES,\n DISPATCH_MAX_PARTS,\n} from './wire'\nimport type { ChatAttachmentPart, ChatMentionPart } from '../chat-store/parts'\nimport { bytesToBase64 } from './upload'\nimport type { ReadAttachmentFn } from './attachment-store'\n\nexport type { PromptInputPart }\n\nexport type DispatchPartsOutcome =\n | { succeeded: true; value: PromptInputPart[] }\n | { succeeded: false; error: string }\n\n/** One mention file's size (always) and inline bytes (only when the caller\n * asked for them — a path-only mention never reads its bytes). */\ntype SandboxMentionReadOutcome =\n | { succeeded: true; value: { size: number; base64?: string } }\n | { succeeded: false; error: string }\n\nexport type ReadSandboxMentionFn = (\n box: SandboxExecChannel,\n absolutePath: string,\n options: { readBytes: boolean },\n) => Promise<SandboxMentionReadOutcome>\n\nfunction byteLen(value: string): number {\n return new TextEncoder().encode(value).length\n}\n\n/**\n * Default mention reader: stats the in-box file (which also proves it still\n * exists — a since-deleted mention fails loud here), then reads its bytes only\n * when the caller wants to inline it. Both hops cross the sandbox exec channel\n * via the substrate's binary-read helpers.\n */\nasync function readSandboxMention(\n box: SandboxExecChannel,\n absolutePath: string,\n options: { readBytes: boolean },\n): Promise<SandboxMentionReadOutcome> {\n const stat = await statSandboxFileSize(box, absolutePath)\n if (!stat.succeeded) {\n return { succeeded: false, error: `mentioned sandbox file missing or unreadable: ${absolutePath} — ${stat.error}` }\n }\n if (!options.readBytes) return { succeeded: true, value: { size: stat.value } }\n\n const read = await readSandboxBinaryBytes(box, absolutePath, stat.value)\n if (!read.succeeded) {\n return { succeeded: false, error: `mentioned sandbox file read failed: ${absolutePath} — ${read.error}` }\n }\n return { succeeded: true, value: { size: stat.value, base64: bytesToBase64(read.value.bytes) } }\n}\n\n/** HARD INVARIANT: a media part (`image`/`file`) must carry exactly one of a\n * non-empty `data:` URL or a non-empty absolute path — never both, never\n * neither. The OpenCode adapter falls back to `part.url || part.path || \"\"`,\n * so a part violating this silently degrades to an empty target instead of\n * failing loud. */\nfunction violatesUrlPathXor(part: PromptInputPart): boolean {\n if (part.type === 'text') return false\n const hasUrl = typeof part.url === 'string' && part.url.startsWith('data:')\n const hasPath = typeof part.path === 'string' && part.path.startsWith('/')\n return hasUrl === hasPath\n}\n\nexport interface BuildDispatchPartsInput {\n text: string\n attachments: ChatAttachmentPart[]\n mentions?: ChatMentionPart[]\n history: Array<{ role: 'user' | 'assistant'; content: string }>\n systemPrompt: string\n /** Serialized size of the backend profile the SDK inlines into the same\n * prompt request body — a large, non-negotiable rider that must come out of\n * the inline budget or near-cap attachments 413 at the proxy instead of\n * demoting to path parts. */\n profileWireBytes: number\n /** The product's workspace/tenant key, passed to `readAttachment`. */\n scopeId: string\n /** Maps an attachment's store-relative path to the in-box absolute path a\n * path-based part references (same seam style as `fileMentionsToParts`'s\n * `resolvePath`). */\n resolveAttachmentPath: (path: string) => string\n /** Maps a mention's workspace-relative path to its in-box absolute path.\n * Default: {@link BuildDispatchPartsInput.resolveAttachmentPath} — in gtm the\n * vault mount roots both; a product that mounts them apart overrides this. */\n resolveMentionPath?: (path: string) => string\n /** The turn's already-ensured box — required when `mentions` is non-empty\n * (mention bytes are read from the live box, not the store). */\n box?: SandboxExecChannel\n /** Force every media part to a path reference, skipping all inlining. */\n forcePath?: boolean\n /** REQUIRED store reader for attachment content — no default (the product\n * owns its store; see {@link ReadAttachmentFn}). */\n readAttachment: ReadAttachmentFn\n readSandboxMention?: ReadSandboxMentionFn\n /** Whole-request proxy cap. Default {@link DISPATCH_REQUEST_MAX_BYTES}. */\n requestMaxBytes?: number\n /** JSON-envelope reserve off the top of the request cap. Default\n * {@link DISPATCH_STRUCTURAL_RESERVE_BYTES}. */\n structuralReserveBytes?: number\n /** Sidecar per-request parts-array cap. Default {@link DISPATCH_MAX_PARTS}. */\n maxParts?: number\n}\n\n/** Content of one attachment read, normalized to the base64 a `data:` URI\n * needs — `base64` reused verbatim, else `bytes` encoded once. */\nfunction readResultToBase64(read: { base64?: string; bytes?: Uint8Array }): string | undefined {\n if (typeof read.base64 === 'string') return read.base64\n if (read.bytes) return bytesToBase64(read.bytes)\n return undefined\n}\n\nexport async function buildDispatchParts(input: BuildDispatchPartsInput): Promise<DispatchPartsOutcome> {\n const readMention = input.readSandboxMention ?? readSandboxMention\n const resolveMentionPath = input.resolveMentionPath ?? input.resolveAttachmentPath\n const forcePath = input.forcePath ?? false\n const mentions = input.mentions ?? []\n const requestMaxBytes = input.requestMaxBytes ?? DISPATCH_REQUEST_MAX_BYTES\n const structuralReserveBytes = input.structuralReserveBytes ?? DISPATCH_STRUCTURAL_RESERVE_BYTES\n const maxParts = input.maxParts ?? DISPATCH_MAX_PARTS\n\n const parts: PromptInputPart[] = [{ type: 'text', text: input.text }]\n // Absolute in-box paths already emitted — a file both attached and mentioned\n // (or mentioned twice) rides as a single media part.\n const emittedAbsPaths = new Set<string>()\n\n const flattenedForSizing = flattenHistory(input.text, input.history)\n // May go negative when history/systemPrompt alone are large — every\n // attachment then fails the `runningInline + cost <= inlineBudget` check\n // below and demotes to a path part, which is correct behavior (path parts\n // don't draw on this budget), not a failure.\n const inlineBudget =\n requestMaxBytes\n - base64WireLen(byteLen(flattenedForSizing))\n - byteLen(JSON.stringify(input.systemPrompt))\n - input.profileWireBytes\n - structuralReserveBytes\n\n let runningInline = 0\n\n // Stable input order: attachments dispatch in the order the user attached\n // them, and the pointer block in `input.text` already names them in that\n // same order.\n for (const attachment of input.attachments) {\n if (!attachment.path) {\n return { succeeded: false, error: `attachment path must be non-empty: ${attachment.name}` }\n }\n\n // The reader crosses an external boundary (store/coordinator) — a rejection\n // there must land in the typed outcome, not escape as a thrown error the\n // caller would misattribute to stream init.\n let read: Awaited<ReturnType<ReadAttachmentFn>>\n try {\n read = await input.readAttachment(input.scopeId, attachment.path)\n } catch (err) {\n return {\n succeeded: false,\n error: `attachment store read failed: ${attachment.path} — ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n if (!read.ok) return { succeeded: false, error: read.reason }\n\n const base64 = readResultToBase64(read)\n if (base64 === undefined) {\n return { succeeded: false, error: `attachment store read produced no content: ${attachment.path}` }\n }\n\n const mediaType = attachment.mediaType ?? read.mediaType\n if (attachment.type === 'image' && !mediaType) {\n return { succeeded: false, error: `attachment is missing a mediaType required for an image data URI: ${attachment.path}` }\n }\n\n const absPath = input.resolveAttachmentPath(attachment.path)\n emittedAbsPaths.add(absPath)\n\n if (attachment.type === 'image') {\n const inlinePart: PromptInputPart = {\n type: 'image',\n filename: attachment.name,\n mediaType,\n url: `data:${mediaType};base64,${base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n if (!forcePath && runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n } else {\n parts.push({ type: 'image', filename: attachment.name, mediaType, path: absPath })\n }\n continue\n }\n\n // File part. Sidecar's file-part zod union is tried [Legacy: {path\n // required, content?} strips mediaType/filename] then [AISDK: {filename\n // required, url required, mediaType?}] — so an inline file part must carry\n // `filename` + `url` and no `path` key at all, while a path-based file part\n // must carry only `path` (mediaType/filename would be stripped by the\n // Legacy branch anyway).\n const fileMediaType = mediaType ?? 'application/octet-stream'\n const inlinePart: PromptInputPart = {\n type: 'file',\n filename: attachment.name,\n mediaType: fileMediaType,\n url: `data:${fileMediaType};base64,${base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n if (!forcePath && runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n } else {\n parts.push({ type: 'file', path: absPath })\n }\n }\n\n if (mentions.length > 0 && !input.box) {\n return { succeeded: false, error: 'internal error: sandbox mentions require a box to read from' }\n }\n for (const mention of mentions) {\n if (!mention.path) {\n return { succeeded: false, error: `mention path must be non-empty: ${mention.name}` }\n }\n const absPath = resolveMentionPath(mention.path)\n if (emittedAbsPaths.has(absPath)) continue\n emittedAbsPaths.add(absPath)\n\n const isImage = mention.mentionKind === 'image'\n const mediaType = isImage ? mediaTypeForMentionPath(mention.path) : undefined\n\n // Every mention is stat'd first: it proves the file still exists (a deleted\n // mention fails the turn loud) and gives the size for the inline budget\n // decision without pulling bytes across the exec channel.\n let stat: SandboxMentionReadOutcome\n try {\n stat = await readMention(input.box!, absPath, { readBytes: false })\n } catch (err) {\n return { succeeded: false, error: `mention read failed: ${absPath} — ${err instanceof Error ? err.message : String(err)}` }\n }\n if (!stat.succeeded) return { succeeded: false, error: stat.error }\n\n // Only an image that projects within the remaining budget reads its bytes\n // to inline; every other mention (and a budget-exceeding image) ships\n // path-only, so a large file is never base64'd just to be demoted.\n const projectedInlineCost = base64WireLen(stat.value.size)\n + byteLen(JSON.stringify({ type: 'image', filename: mention.name, mediaType: mediaType ?? '', url: '' }))\n if (isImage && mediaType && !forcePath && runningInline + projectedInlineCost <= inlineBudget) {\n let read: SandboxMentionReadOutcome\n try {\n read = await readMention(input.box!, absPath, { readBytes: true })\n } catch (err) {\n return { succeeded: false, error: `mention read failed: ${absPath} — ${err instanceof Error ? err.message : String(err)}` }\n }\n if (!read.succeeded) return { succeeded: false, error: read.error }\n if (!read.value.base64) return { succeeded: false, error: `mentioned image produced no bytes: ${absPath}` }\n const inlinePart: PromptInputPart = {\n type: 'image',\n filename: mention.name,\n mediaType,\n url: `data:${mediaType};base64,${read.value.base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n // Re-check against the actual serialized cost — the projection can\n // undershoot; a real overshoot demotes to a path part rather than 413ing.\n if (runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n continue\n }\n }\n\n // Path-only mention: an image keeps its `mediaType`, everything else is a\n // bare `file` path (the sidecar's Legacy file-part branch strips extra keys).\n parts.push(\n isImage && mediaType\n ? { type: 'image', filename: mention.name, mediaType, path: absPath }\n : { type: 'file', path: absPath },\n )\n }\n\n for (const part of parts) {\n if (violatesUrlPathXor(part)) {\n return { succeeded: false, error: 'internal error: emitted media part violates the url/path exclusivity invariant' }\n }\n }\n\n // Final whole-request check sized against what actually crosses the wire: the\n // history-merged text part (the substrate folds `history` into `parts[0]`\n // before dispatch), the media parts, the system prompt, and the inlined\n // backend profile riding the same body — the same terms `inlineBudget` was\n // derived from.\n const textPartSize = base64WireLen(byteLen(flattenedForSizing))\n const mediaPartsSize = parts.slice(1).reduce((total, part) => total + byteLen(JSON.stringify(part)), 0)\n const systemPromptSize = byteLen(JSON.stringify(input.systemPrompt))\n if (textPartSize + mediaPartsSize + systemPromptSize + input.profileWireBytes + structuralReserveBytes > requestMaxBytes) {\n return { succeeded: false, error: 'dispatch parts exceed the sandbox proxy request cap even after path demotion' }\n }\n\n // The sidecar rejects the whole request past its parts-array cap; the caller\n // selects which media ride natively, so overflow here is a caller bug\n // surfaced loudly rather than a truncation.\n if (parts.length > maxParts) {\n return { succeeded: false, error: `dispatch parts exceed the sidecar per-request cap of ${maxParts}` }\n }\n\n return { succeeded: true, value: parts }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAS,mBAAmB,sBAAsB;AA6HlD,SAAS,gBAAgB,MAA+D;AACtF,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,UAAU,KAAK,WAAW,KAAK,SAAS,KAAK;AACnD,MAAI,OAAO,YAAY,YAAY,QAAQ,SAAS,EAAG,QAAO;AAC9D,SAAO;AACT;AA6KA,SAAS,cAAc,KAAmC;AACxD,SAAO,SAAS,KAAK,EAAE,MAAM,IAAI,MAAM,OAAO,IAAI,QAAQ,GAAG,EAAE,QAAQ,IAAI,OAAO,CAAC;AACrF;AAUA,SAAS,iBAAiB,MAA+B,oBAAwD;AAC/G,QAAM,WAAW,OAAO,KAAK,aAAa,WAAW,KAAK,SAAS,KAAK,IAAI;AAC5E,MAAI,CAAC,SAAU,OAAM,IAAI,mBAAmB,kBAAkB;AAC9D,QAAM,aAAa,KAAK,WAAW,KAAK,WAAW;AACnD,MAAI,OAAO,eAAe,SAAU,OAAM,IAAI,mBAAmB,0BAA0B;AAC3F,QAAM,UAAU,WAAW,KAAK;AAChC,QAAM,YAAY,mBAAmB,KAAK,KAAK;AAG/C,QAAM,WAAW,kBAAkB,KAAK,QAAQ;AAIhD,MAAI,CAAC,WAAW,UAAU,WAAW,KAAK,SAAS,WAAW,GAAG;AAC/D,UAAM,IAAI,mBAAmB,kEAAkE;AAAA,EACjG;AACA,6BAA2B,WAAW,kBAAkB;AACxD,MAAI;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