import { C as ChatMessagePart, N as ChatTurnRequestPayload, O as ChatTurnPartInput, P as ChatTurnFilePartInput, b as ChatAttachmentPart, a as ChatAttachmentKind, g as ChatMentionPart } from '../parts-DIKcC1p6.js';
export { Q as ChatAttachmentInput, f as ChatMentionKind, R as ChatTurnInputError, T as ChatTurnTextPartInput, U as DISPATCH_MAX_MEDIA_PARTS, V as DISPATCH_MAX_PARTS, W as DISPATCH_REQUEST_MAX_BYTES, X as DISPATCH_STRUCTURAL_RESERVE_BYTES, M as FileMention, Y as FileMentionsToPartsOptions, Z as INLINE_PARTS_MAX_BYTES, _ as MENTION_MAX_COUNT, $ as ProducerErrorEvent, a0 as ProducerNoticeEvent, a1 as ProducerPassthroughEvent, a2 as ProducerPassthroughEventType, a3 as ProducerReasoningEvent, a4 as ProducerTextEvent, a5 as ProducerToolCallEvent, a6 as ProducerToolResultEvent, a7 as ProducerUsageEvent, a8 as ProducerWireEvent, a9 as SandboxMentionPathCheck, aa as assertPromptPartsWithinCap, ab as base64WireLen, ac as buildMentionPromptBlock, ad as chatTurnRequestInit, ae as fileMentionsToParts, af as formatBytes, ag as mediaTypeForMentionPath, ah as mentionKindForPath, ai as parseChatTurnParts, aj as parseFileMentions, ak as promptPartsByteSize, al as validateSandboxMentionPath } from '../parts-DIKcC1p6.js';
export { A as ALLOWED_ATTACHMENT_SNIFFED_MIMES, a as ATTACHMENT_ACCEPT, b as ATTACHMENT_MAX_COUNT, c as AttachmentTypeCheckResult, C as CreateSandboxFileIndexRouteOptions, F as FileIndexAuthorization, d as FileIndexCache, e as FileIndexReadyResponse, f as FileIndexResponse, g as FileIndexWarmingResponse, M as MAX_ATTACHMENT_TOTAL_BYTES, h as MAX_BINARY_ATTACHMENT_BYTES, i as MAX_TEXT_ATTACHMENT_BYTES, S as SandboxFileTreeSource, j as SandboxTreeFile, k as SandboxTreeResult, l as SniffResult, m as attachmentSizeErrorMessage, n as attachmentTotalSizeErrorMessage, o as checkAttachmentType, p as createSandboxFileIndexRoute, s as sanitizeAttachmentFileName, q as sniffBinary } from '../attachment-validation-yJ6Id4pR.js';
import { ChatTurnIdentity, ChatTurnProducer } from '@tangle-network/agent-runtime';
import { InteractionAnswerRoute, InteractionAnswerRouteOptions } from '../interactions/index.js';
import { PersistedChatMessageForTurn } from '../stream/index.js';
import { T as TurnEventStore } from '../turn-buffer-BcPfhr1_.js';
import { M as ModelFailoverAttempt } from '../failover-D-3UXXTb.js';
export { D as DEFAULT_STALE_TURN_LOCK_GRACE_MS, a as DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS, R as ReconcileStaleTurnLockOptions, b as ReconcileStaleTurnLockResult, S as StaleTurnLockSandboxProbeResult, c as StaleTurnLockSessionProbeResult, r as reconcileStaleTurnLock } from '../stale-turn-lock-DucQzvXu.js';
import { J as JsonRecord } from '../stream-normalizer-DnuqkZvw.js';
import { SandboxExecChannel, PromptInputPart } from '../sandbox/index.js';
import '@tangle-network/agent-interface';
import '../contract-CEewO6DI.js';
import '../types-DeEOhQbv.js';
import '../plans/index.js';
import '@tangle-network/sandbox';
import '../auth-anc7mv2W.js';
import '../types-BCxK0wyS.js';
import '../harness/index.js';
import '../model-CdCDfBA9.js';
import '../budget-BOucfcb_.js';

/**
 * Incremental ("draft") persistence of the assistant row WHILE a turn streams.
 *
 * Why this exists — the scale argument, not a convenience:
 *
 * A live turn is readable from two places. The hot path is the session
 * gateway's in-memory/Redis event buffer, which exists so a viewer survives a
 * network blip: it is keyed one sorted set per session, refreshed on every
 * push, and expires on a TTL. Its memory cost is `arrival_rate x TTL x
 * bytes_per_session` — strictly LINEAR in the TTL. Stretching that TTL to
 * cover "a viewer who opens the tab later" is a category error: it buys memory
 * proportional to the increase and still serves nothing to a viewer who
 * arrives past the new horizon.
 *
 * So the hot buffer must stay SHORT (live delivery + reconnect only), and
 * durable storage must serve history. That only works if durable storage
 * actually HAS the in-flight turn — which, before this module, it did not: the
 * assistant row was written once, after the stream drained. A viewer arriving
 * mid-turn past the hot window read an empty transcript.
 *
 * This module closes that gap: the assistant row is inserted early and patched
 * on a coalesced cadence, so the durable transcript is at most one interval
 * (default 2 s) behind the live stream and the hot buffer never has to be the
 * history tier.
 *
 * Mechanism only. It owns no vocabulary: the caller supplies the snapshot
 * function, the store, and the deterministic row id.
 *
 * Four properties the cadence guarantees:
 * - **Time-floored.** At most one write per `intervalMs`, never one per token.
 * - **Dirty-gated.** Only content-bearing events arm a write; heartbeats,
 *   status pings, and lifecycle envelopes never do.
 * - **Single-flight.** A write already in flight suppresses the next trigger
 *   instead of queueing; the final write is authoritative regardless of how
 *   many drafts landed.
 * - **Best-effort.** A store failure is logged and swallowed — a durability
 *   optimization must never kill a healthy stream (the same rule
 *   `withDurableChatProjection` already states).
 */

/** Message row shape the writer reads back when re-entering a turn. */
interface DraftStoredMessage {
    id: string;
    role: 'user' | 'assistant' | 'system' | 'tool';
    content: string;
    parts?: ChatMessagePart[] | null;
}
/** Values written to the assistant row — the intersection of the append and
 *  patch shapes, so one snapshot serves both. */
interface AssistantRowValues {
    content: string;
    parts?: ChatMessagePart[];
    model?: string | null;
    inputTokens?: number | null;
    outputTokens?: number | null;
    reasoningTokens?: number | null;
    cacheReadTokens?: number | null;
    cacheWriteTokens?: number | null;
    costUsd?: number | null;
}
/** The store capability incremental persistence needs on top of
 *  `appendMessage`. A store without `updateMessage` cannot patch a row, so it
 *  cannot draft at all — the caller keeps today's single-write behavior. */
interface AssistantDraftStore {
    listMessages(threadId: string): Promise<DraftStoredMessage[]>;
    appendMessage(input: AssistantRowValues & {
        id?: string;
        threadId: string;
        role: 'user' | 'assistant';
    }): Promise<unknown>;
    updateMessage?(id: string, patch: AssistantRowValues): Promise<unknown>;
    deleteMessage?(id: string): Promise<unknown>;
}
/** Live snapshot of the assistant body, taken from the producer's own
 *  accumulators. `parts` is the DRAFT projection (`draftParts()`), never the
 *  finalized one — see `draftAssistantParts`. */
interface AssistantDraftSnapshot {
    content: string;
    parts?: Array<Record<string, unknown>>;
    usage?: ChatTurnUsage;
    model?: string;
}
/** Product-tunable cadence. Defaults are stated on each field; a product with
 *  a chattier or heavier workload moves them without forking the writer. */
interface DraftPersistenceTuning {
    /** Minimum wall-clock gap between draft writes, in ms. Default 2000.
     *
     *  Justification for 2 s, from a measured tool-heavy production run (517
     *  stream events over ~90 s wall = ~5.7 events/s): a 2 s floor with the
     *  dirty gate turns 517 candidate writes into <= 45, while leaving the
     *  durable row at most 2 s stale — an order of magnitude below the time it
     *  takes a viewer to open a tab and render, so a late viewer never perceives
     *  the lag. Fleet arithmetic at 10k concurrent 60 s runs: <= 30 updates per
     *  run x 167 run-starts/s = ~334 row-updates/s spread over per-tenant
     *  shards. Lower it and write amplification grows with no perceptible
     *  freshness gain; raise it past ~5 s and a late viewer starts seeing a
     *  visibly truncated answer. */
    intervalMs?: number;
    /** Serialized-parts size (bytes) past which the interval backs off, so a
     *  turn accumulating a megabyte-scale `parts` blob does not rewrite it every
     *  interval. Default 262144 (256 KiB) -> interval x 2.5; ten times that ->
     *  interval x 5. The final write is never throttled. */
    backoffBytes?: number;
    /** Per-tool-part output cap applied to DRAFTS ONLY (bytes). A tool returning
     *  a large blob would otherwise be rewritten in full on every draft. The
     *  final write always carries the untruncated value. Default 32768 (32 KiB);
     *  0 disables truncation. */
    maxDraftToolOutputBytes?: number;
}
/** Define the inputs required to construct an assistant draft writer */
interface AssistantDraftWriterOptions extends DraftPersistenceTuning {
    store: AssistantDraftStore;
    threadId: string;
    /** DETERMINISTIC row id for this turn's assistant message — the whole
     *  idempotency mechanism. Derived from the turn's existing identity
     *  (`deriveExecutionId` in the interactive lane, the turn id in the detached
     *  lane), so a re-entered turn addresses the SAME row: the writer looks the
     *  id up before its first insert and patches what it finds. */
    messageId: string;
    /** Read the producer's live accumulators. Returns null before the producer
     *  is resolved (the assembly defers box resolution into the first pull). */
    snapshot(): AssistantDraftSnapshot | null;
    /** Pre-persist text transform (`/redact`'s `redactPII`). Applied to the
     *  draft's scalar content AND every draft text part — parity with the final
     *  write, or incremental persistence would re-open the at-rest PII leak that
     *  transform closed, just seconds earlier and on every turn. */
    transformText?(text: string): string | Promise<string>;
    log?: (message: string, meta?: Record<string, unknown>) => void;
}
/** Coalescing writer that keeps one durable assistant row in step with a
 *  streaming turn. Created per turn; not reusable. */
interface AssistantDraftWriter {
    /** Arm/trigger a draft write from one engine event. Synchronous by design —
     *  the write itself is fire-and-forget so the stream is never blocked on
     *  store latency. */
    notify(event: {
        type?: unknown;
    }): void;
    /** Stop drafting and settle any in-flight write. Called before the final
     *  write so a late draft can never clobber the authoritative row. */
    close(): Promise<void>;
    /** Write the AUTHORITATIVE completion values onto this turn's row —
     *  insert-or-patch under the same deterministic id, un-throttled and
     *  un-truncated. Errors propagate: the final write is the one that must not
     *  fail silently. Implies {@link close}. */
    finalize(values: AssistantRowValues): Promise<void>;
    /** The durable row this turn is writing, once one exists. */
    rowId(): string | undefined;
    /** Retract the row for a turn that produced nothing (mirrors the final
     *  write's empty-turn skip, which leaves no row at all today). Also retracts
     *  a row a PREVIOUS attempt left behind, so a re-entered turn that ends
     *  empty converges on "no row" rather than a stale partial. */
    discard(): Promise<void>;
    /** Diagnostics: how many draft writes actually reached the store. */
    writeCount(): number;
}
/** True when this event should arm a draft write. */
declare function isDraftContentEvent(event: {
    type?: unknown;
}): boolean;
/** Build the coalescing draft writer for one turn. */
declare function createAssistantDraftWriter(options: AssistantDraftWriterOptions): AssistantDraftWriter;
/** True when a store can support incremental persistence at all. Without
 *  `updateMessage` a draft row could never be patched, so the caller keeps
 *  today's exact single-write behavior. */
declare function storeSupportsDraftPersistence(store: AssistantDraftStore): boolean;
/** The row id an `appendMessage` actually returned, or `null` when the store
 *  returned nothing usable. `ChatTurnMessageStore.appendMessage` is typed
 *  `Promise<unknown>` so a product adapter is free to resolve `void`; every
 *  caller that wants to NAME the row it just wrote has to read defensively.
 *
 *  Deliberately no fallback to a caller-assigned id — see `writeOnce`, which
 *  adds its own. A caller that let the store mint the id has nothing to fall
 *  back TO, and guessing one would report a row that may not exist. */
declare function rowIdOf(inserted: unknown): string | null;
/** The default deterministic assistant-row id for a turn. Readable on purpose
 *  (an operator grepping a transcript row id finds the run), and stable across
 *  re-entries because every input already is. */
declare function assistantRowIdForTurn(turnKey: string): string;

/**
 * `createChatTurnRoutes` — the assembled server chat vertical (issue #188
 * Phase 1). One factory composing the pieces every product re-wired by hand:
 *
 *   body parse/validate      → `/web` `parseJsonObjectBody` + `./wire`
 *   turn identity            → `/stream` `resolveChatTurn` + agent-runtime
 *                              `deriveExecutionId`
 *   producer                 → injected seam (sandbox lane via
 *                              `createSandboxChatProducer`; router lane is the
 *                              product's own `ChatTurnProducer`)
 *   turn engine              → agent-runtime `handleChatTurn` (verbatim)
 *   durability               → `/stream` turn-buffer tap, wired BY DEFAULT
 *                              (tee + drain keeps the turn running after a
 *                              client drop; replay serves the buffered tail)
 *   persistence              → injected `/chat-store`-shaped store
 *                              (user row on send, assistant row on completion)
 *   interactions answer      → `/interactions` `createInteractionAnswerRoute`
 *
 * Handlers are web-standard `Request → Response` (Workers, Node 18+, Deno) —
 * no router import. Auth/access is one injected `authorize` seam, composable
 * with `/app-auth` guards but not coupled to them.
 *
 * Optional product seams let a complex turn-orchestrator compose the vertical
 * instead of hand-rolling a generator — each omittable to the exact behavior
 * above: `turnLock` (single-flight acquire/release around the turn),
 * `contextGate` (pre-producer domain-readiness short-circuit), `beforeTurn`
 * (observe + augment the producer input), `lifecycle` (deterministic
 * start/complete/error telemetry), `heartbeat` (keepalive during silent
 * producer waits), and `onRawEvent` (the raw producer events, for telemetry) —
 * plus the `authorize` result's `insertUserMessage` flag (suppress the user row
 * for a product-dispatched turn). `handleChatTurn` stays the engine — the seams
 * only wrap its input, its producer stream, and its settle.
 *
 * Seam stability: all of the above are STABLE and safe to depend on. They
 * graduated in #227 against the bar this package holds itself to — a seam is
 * provisional until two INDEPENDENT consumers exercise it, because one
 * consumer's shape is indistinguishable from that consumer's assumptions.
 * `turnLock` cleared it with `/turn-stream`'s shared DO adapter (#221);
 * `contextGate`, `beforeTurn`, `onRawEvent` and `insertUserMessage` each
 * cleared it with two product verticals reading them differently — and the
 * review found no leaked assumptions to fix, only `ChatRouteEvent` to export.
 *
 * They stay FLAT top-level options (not grouped under a `hooks` object): that
 * grouping would break every shipped consumer's call for no mechanism gain, and
 * this package's exports are additive-only. For the same reason `onRawEvent`
 * keeps its two-argument `(event, context)` signature rather than being
 * normalized to the single-args shape the other seams take.
 */

/** Usage receipt persisted onto the assistant message (the flattened
 *  `step-finish` shape `/chat-store`'s columns mirror). */
interface ChatTurnUsage {
    inputTokens?: number;
    outputTokens?: number;
    reasoningTokens?: number;
    cacheReadTokens?: number;
    cacheWriteTokens?: number;
    costUsd?: number;
}
/** What the route persists — a structural subset of `/chat-store`'s
 *  `ChatStore`, so `createChatStore(db, tables)` satisfies it directly and a
 *  product with its own persistence adapts without importing drizzle. */
interface ChatTurnMessageStore {
    listMessages(threadId: string): Promise<Array<{
        id: string;
        role: 'user' | 'assistant' | 'system' | 'tool';
        content: string;
        parts?: ChatMessagePart[] | null;
    }>>;
    appendMessage(input: {
        /** Caller-assigned row id. Honored by `/chat-store`'s `createChatStore`;
         *  a product store free to ignore it (the writer then adopts whatever id
         *  the insert returns). Set only by incremental persistence. */
        id?: string;
        threadId: string;
        role: 'user' | 'assistant';
        content: string;
        parts?: ChatMessagePart[];
        model?: string | null;
        inputTokens?: number | null;
        outputTokens?: number | null;
        reasoningTokens?: number | null;
        cacheReadTokens?: number | null;
        cacheWriteTokens?: number | null;
        costUsd?: number | null;
    }): Promise<unknown>;
    /** Patch an existing row. Its PRESENCE is what enables incremental assistant
     *  persistence — a store without it keeps today's exact single-write-on-
     *  completion behavior, which is what makes this additive. */
    updateMessage?(id: string, patch: {
        content?: string;
        parts?: ChatMessagePart[];
        model?: string | null;
        inputTokens?: number | null;
        outputTokens?: number | null;
        reasoningTokens?: number | null;
        cacheReadTokens?: number | null;
        cacheWriteTokens?: number | null;
        costUsd?: number | null;
    }): Promise<unknown>;
    /** Remove a row. Used to retract a draft assistant row for a turn that ended
     *  producing nothing, so the empty-turn case still leaves no row at all. */
    deleteMessage?(id: string): Promise<unknown>;
}
/** `ChatTurnProducer` plus the persisted projection the assembly reads after
 *  drain. `createSandboxChatProducer` returns this; a router-lane producer
 *  may omit the optional members (finalText persists as a single text part). */
interface ChatTurnRouteProducer extends ChatTurnProducer {
    assistantParts?(): Array<Record<string, unknown>>;
    /** MID-STREAM snapshot of the same projection, safe to call while the turn
     *  is running: no dangling-tool terminalization, no pending-ask settlement
     *  (see `/stream`'s `draftAssistantParts`). Read by incremental persistence.
     *  A producer that omits it still drafts — the scalar text — but persists no
     *  parts until the turn completes. */
    draftParts?(): Array<Record<string, unknown>>;
    usage?(): ChatTurnUsage;
    /** The model that SERVED the turn. With failover wired this is the model that
     *  actually answered, which is not necessarily the one the caller preferred —
     *  read it after the stream drains, never before. */
    model?: string;
    /** Model-failover attribution, when the producer supports it. Reported onto
     *  the usage/billing receipt so a downgrade is never silent. */
    modelFailover?(): ChatTurnModelFailover;
}
/** Which model served, and what it took to get there. */
interface ChatTurnModelFailover {
    /** The model that served the turn. */
    model?: string;
    /** Every model tried, in order, with the reason each was abandoned. */
    attempts: ModelFailoverAttempt[];
    /** True when the preferred model did not serve. */
    usedFallback: boolean;
}
/** Resolve authorization status and context for a chat turn including tenant and user identification */
type ChatTurnAuthorization<TContext> = {
    ok: true;
    tenantId: string;
    userId: string;
    context: TContext;
    /** When `false`, skip the `role:'user'` message insert for this turn — for
     *  a product-dispatched / synthetic turn (e.g. a follow-up the product
     *  raised itself) that must not surface a new user row. Composes with —
     *  never overrides — the engine's retry-dedup: `authorize` runs before
     *  turn identity is resolved, so it cannot tell a retry from a fresh turn;
     *  a turn already deduped stays deduped. Omit / `true` → today's behavior.
     *
     *  Settled shape (#227). The validated case in both consumers is the same:
     *  a durable plan-approval follow-up re-entering an execution the decision
     *  route already enqueued — a decision, not a typed message, so it must
     *  not surface a user bubble. Suppressing the insert also propagates:
     *  `ChatTurnProduceArgs.userMessageId` is `null` for the rest of the turn
     *  when there is no row to reuse, so a seam anchoring to the user row must
     *  handle that arm rather than assume a string. */
    insertUserMessage?: boolean;
} | {
    ok: false;
    response: Response;
};
/** Define arguments required to authorize a chat turn based on intent and request details */
interface ChatTurnAuthorizeArgs {
    request: Request;
    intent: 'turn' | 'replay' | 'running';
    /** Parsed, validated POST body (turn intent only). */
    body?: ChatTurnRequestPayload;
    /** The buffered turn id being replayed (replay intent only). */
    turnId?: string;
    /** The thread whose running turns are being discovered (running intent only). */
    threadId?: string;
}
/** Define the arguments required to produce a chat turn with context and messaging details */
interface ChatTurnProduceArgs<TContext> {
    request: Request;
    body: ChatTurnRequestPayload;
    identity: ChatTurnIdentity;
    context: TContext;
    /** The message to send: plain text, or parts when the client attached
     *  files (a text part is prepended from `content` when present). */
    prompt: string | ChatTurnPartInput[];
    /** Stable id for cross-process reconnect (`deriveExecutionId`). */
    executionId: string;
    /** The turn-buffer id announced to the client for replay. */
    turnStreamId: string;
    priorMessages: PersistedChatMessageForTurn[];
    /** The durable `role:'user'` row this turn is anchored to — the row the
     *  factory just inserted, or the one retry-dedup REUSED. Products anchor
     *  optimistic-bubble swaps, retry targeting, and stop-polling to it, and it
     *  is the only way to name a REUSED row (which `priorMessages` excludes).
     *
     *  Three states, all meaningful:
     *  - `undefined` — not resolved yet. `turnLock.acquire` is the one seam that
     *    sees this: it runs before any side effect by contract, so the row does
     *    not exist when it reads the args.
     *  - `null` — resolved, no row: `authorize` returned `insertUserMessage:
     *    false` on a turn with nothing to reuse, or the store's `appendMessage`
     *    resolved without a usable id.
     *  - a string — the row id, for `contextGate`, `beforeTurn`, and `produce`. */
    userMessageId?: string | null;
}
/** One event as it crosses the route: the producer's own vocabulary, or an
 *  injected keepalive. Same shape the engine forwards verbatim.
 *
 *  Public because it IS the vocabulary of two seams — `onRawEvent`'s parameter
 *  and `heartbeat.event`'s return. Exported so a product can declare a
 *  standalone handler (`function onRawEvent(e: ChatRouteEvent, ctx: T)`) rather
 *  than depending on contextual typing from an inline object literal. */
type ChatRouteEvent = {
    type: string;
    data?: Record<string, unknown>;
};
/** Keepalive emitted while the producer is quiet (long tool calls, first-token
 *  wait) so client watchdogs stay re-armed. One is emitted each time
 *  `intervalMs` elapses with no producer event; the window resets on every real
 *  event, so a chatty producer never triggers one. The product owns the event
 *  shape (`type` + `data`). Omit → no keepalives (today's behavior). */
interface ChatTurnHeartbeat {
    intervalMs: number;
    event(info: {
        elapsedMs: number;
        tick: number;
    }): ChatRouteEvent;
}
/** Patch a `beforeTurn` hook returns to augment the producer's input. Omitted
 *  fields keep the route-assembled value; the product's `produce` still owns
 *  the system prompt. */
interface ChatTurnInputPatch {
    prompt?: string | ChatTurnPartInput[];
    priorMessages?: PersistedChatMessageForTurn[];
}
/** Pre-turn readiness verdict — proceed, or short-circuit with the product's
 *  own `Response` (e.g. a canned assistant reply asking for missing context).
 *  Distinct from `authorize`: this gates domain readiness, not access. */
type ChatTurnGateResult = {
    proceed: true;
} | {
    proceed: false;
    response: Response;
};
/** Single-flight lock verdict — acquired (with an opaque handle passed back to
 *  `release`), or already held (short-circuit with the product's 409-style
 *  `Response`). */
type ChatTurnLockResult = {
    acquired: true;
    handle?: unknown;
} | {
    acquired: false;
    response: Response;
};
/** Async acquire/release wrapped around the turn. `acquire` runs before any
 *  side effect; `release` runs once when the turn settles — including on a
 *  short-circuit or a throw. */
interface ChatTurnLock<TContext> {
    acquire(args: ChatTurnProduceArgs<TContext>): ChatTurnLockResult | Promise<ChatTurnLockResult>;
    release(handle: unknown): void | Promise<void>;
}
interface ChatTurnLifecycleBase<TContext> {
    identity: ChatTurnIdentity;
    executionId: string;
    turnStreamId: string;
    context: TContext;
}
/** Define lifecycle start event with context and timestamp for a chat turn */
interface ChatTurnLifecycleStart<TContext> extends ChatTurnLifecycleBase<TContext> {
    startedAt: number;
}
/** Define the structure representing the completion state of a chat turn lifecycle with usage data */
interface ChatTurnLifecycleComplete<TContext> extends ChatTurnLifecycleBase<TContext> {
    finalText: string;
    usage: ChatTurnUsage;
    durationMs: number;
    /** The model that SERVED the turn — the fallback's id when failover moved it.
     *  `usage` is that model's, so telemetry that splits cost or quality by model
     *  must key on this and not on the requested one. */
    model?: string;
    /** Attribution for a downgrade: which models were tried and why each failed.
     *  `undefined` when the producer reports no failover support. */
    modelFailover?: ChatTurnModelFailover;
    /** The durable `role:'assistant'` row this turn wrote, or `null` when it
     *  wrote none (an empty turn leaves no row — a draft started mid-stream is
     *  retracted). The detached lane surfaces the same id as
     *  `DetachedTurnResult.messageId`; one contract, two lanes. */
    assistantMessageId: string | null;
}
/** Represent an error occurring during a chat turn lifecycle with context and duration information */
interface ChatTurnLifecycleError<TContext> extends ChatTurnLifecycleBase<TContext> {
    error: unknown;
    durationMs: number;
}
/** Deterministic run telemetry: `onTurnStart` fires before the producer runs;
 *  exactly one of `onTurnComplete` / `onTurnError` fires after the turn
 *  settles, always after `onTurnStart`. Failure is derived from the turn's own
 *  `error` / `session.run.failed` events (or a drain throw), not the engine's
 *  lifecycle envelope. Hook errors are swallowed — telemetry never fails a
 *  turn. */
interface ChatTurnLifecycle<TContext> {
    onTurnStart?(info: ChatTurnLifecycleStart<TContext>): void | Promise<void>;
    onTurnComplete?(info: ChatTurnLifecycleComplete<TContext>): void | Promise<void>;
    onTurnError?(info: ChatTurnLifecycleError<TContext>): void | Promise<void>;
}
/** What a settled turn reports to `onTurnComplete` — the product's
 *  post-processing seam (billing, titles, audit). */
interface ChatTurnCompleteInput<TContext> {
    identity: ChatTurnIdentity;
    finalText: string;
    context: TContext;
    failed: boolean;
    failureReason?: string;
    /** The model that SERVED this turn. With failover wired it may differ from
     *  the requested one, so a product that bills or scores per model MUST read
     *  it here rather than assuming the model it asked for. */
    model?: string;
    /** Present when the producer supports failover: the full attempt trail, and
     *  `usedFallback` — the flag that makes a silent downgrade impossible. */
    modelFailover?: ChatTurnModelFailover;
    /** The durable `role:'assistant'` row this turn wrote, or `null` when it
     *  wrote none (an empty turn leaves no row).
     *
     *  Populated even when `failed` is true — a terminal error event still
     *  persists whatever partial answer arrived, and that pairing is exactly
     *  what lets a product render an error row against a REAL message instead of
     *  hunting for the newest row in the thread. The detached lane surfaces the
     *  same id as `DetachedTurnResult.messageId`. */
    assistantMessageId: string | null;
}
/** Define options to configure chat turn routes including authorization, storage, and event buffering */
interface CreateChatTurnRoutesOptions<TContext = void> {
    /** Names the product in `deriveExecutionId` so retries land on the same
     *  substrate execution. */
    projectId: string;
    /** Authenticate + authorize the caller for a turn or a replay. The only
     *  product-supplied access step: session auth, thread/workspace access,
     *  seat/balance gates, rate limits all live here. */
    authorize(args: ChatTurnAuthorizeArgs): Promise<ChatTurnAuthorization<TContext>>;
    /** Thread/message persistence (`/chat-store`'s store or a product adapter). */
    store: ChatTurnMessageStore;
    /** Turn-event buffer (`createD1TurnEventStore(env.DB)` or `/turn-stream`'s
     *  `createDurableObjectTurnEventStore(env.TURN_STREAM_DO)` in production,
     *  `createMemoryTurnEventStore()` in tests). Wired by default — every turn
     *  is buffered and replayable. */
    turnStore: TurnEventStore;
    /** Build the turn's event stream. Sandbox lane: `streamSandboxPrompt(...)`
     *  wrapped in `createSandboxChatProducer`. Router/openai-compat lane: the
     *  product's own producer. May be async (box resolution). */
    produce(args: ChatTurnProduceArgs<TContext>): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>;
    /** Single-flight lock acquired before any side effect and released once when
     *  the turn settles (including short-circuit/throw). `/turn-stream`'s
     *  `createDurableTurnLock` is the shared DO-backed implementation. Omit →
     *  no lock. */
    turnLock?: ChatTurnLock<TContext>;
    /** Pre-turn readiness gate that can short-circuit with a product `Response`
     *  before the producer runs (the user row is already persisted). Runs after
     *  `turnLock.acquire`, before `beforeTurn`. Omit → always proceed.
     *
     *  Settled shape (#227). What a consumer may depend on:
     *  - `args.userMessageId` is RESOLVED here — a string, or `null` when the
     *    insert was suppressed with nothing to reuse. (`turnLock.acquire` is the
     *    only seam that sees it `undefined`.)
     *  - `{proceed:false}` releases the lock and returns the product's `Response`
     *    verbatim: `beforeTurn` and `produce` never run, no assistant row is
     *    written, and the user row already inserted is KEPT — a real user turn
     *    whose assistant side is the gate's own response.
     *  - Always returning `{proceed:true}` is supported, not a misuse: the seam
     *    doubles as the one place that runs after the user row exists and before
     *    the producer, which is where per-turn analytics and readiness
     *    precomputation belong. A gate that never gates is a valid consumer. */
    contextGate?(args: ChatTurnProduceArgs<TContext>): ChatTurnGateResult | Promise<ChatTurnGateResult>;
    /** Observe the assembled producer input and optionally augment it (rewrite
     *  the prompt / prior messages) before the producer runs. Omit → no change.
     *
     *  Settled shape (#227). BOTH return arms are contract:
     *  - a `ChatTurnInputPatch` shallow-merges over the route-assembled args, so
     *    an omitted field keeps the route's value;
     *  - `void` means "no patch" — and mutating `args.context` in place is the
     *    supported way to thread request-scoped state forward to `produce` /
     *    `lifecycle` / `onTurnComplete`, which all receive the same object.
     *
     *  A throw propagates (the turn fails with the lock released). It runs BEFORE
     *  `lifecycle.onTurnStart`, so a throw here fires no terminal lifecycle hook —
     *  the span never opened. Telemetry for a failure in this seam belongs in the
     *  seam, not in `lifecycle`. */
    beforeTurn?(args: ChatTurnProduceArgs<TContext>): ChatTurnInputPatch | void | Promise<ChatTurnInputPatch | void>;
    /** Deterministic run telemetry (start / complete / error) with identity and
     *  timing. Omit → no telemetry. */
    lifecycle?: ChatTurnLifecycle<TContext>;
    /** Keepalive injected while the producer is quiet. Omit → no keepalives. */
    heartbeat?: ChatTurnHeartbeat;
    /** Observe each event the producer emits, before the engine frames it and
     *  before any heartbeat injection (the raw sidecar-producer events, for
     *  telemetry). Never alters the stream; errors are swallowed. Distinct from
     *  `onEvent`, which sees the engine-framed stream incl. lifecycle envelopes.
     *
     *  Settled shape (#227). What a consumer may depend on:
     *  - it sees EXACTLY the producer's own events — no engine lifecycle
     *    envelopes, and no injected keepalives (`heartbeat` wraps the stream
     *    downstream of this tap, so a synthetic event never reaches a trace);
     *  - a throw is caught and logged, never surfaced: a broken telemetry sink
     *    cannot fail a turn or truncate the client's stream;
     *  - it is an OBSERVER — the return value is ignored, and the event object
     *    continues downstream. Mutating it mutates the stream; don't.
     *
     *  Takes `(event, context)` rather than one args object, matching both
     *  shipped consumers; see the module header on why it stays that way. */
    onRawEvent?(event: ChatRouteEvent, context: TContext): void | Promise<void>;
    /** Pre-persist transform of the final text (e.g. `/redact`'s `redactPII`).
     *  Live stream is never altered. */
    transformFinalText?(text: string): string | Promise<string>;
    /** Incremental persistence of the assistant row WHILE the turn streams
     *  (`./draft-persistence`), so a viewer arriving mid-run is served from
     *  durable storage instead of the streaming gateway's hot event buffer.
     *
     *  This is what lets the gateway keep that hot buffer SHORT at scale: its
     *  Redis footprint is one sorted set per session refreshed on every push, so
     *  memory grows LINEARLY with `ttl x concurrent sessions`. Stretching the
     *  TTL to cover late viewers buys memory proportional to the increase and
     *  still serves nothing past the new horizon. The buffer stays a reconnect
     *  window; durable storage — kept at most one cadence interval stale by this
     *  option — is the history tier.
     *
     *  Enabled by DEFAULT whenever `store.updateMessage` exists (every
     *  `/chat-store` consumer); a store without it keeps today's exact
     *  single-write behavior. Pass `false` to opt out, or an object to tune the
     *  cadence. Wiring it against a store that cannot patch rows throws at route
     *  construction rather than silently no-op'ing. */
    incrementalPersistence?: false | DraftPersistenceTuning;
    /** Deterministic durable row id for this turn's assistant message. Default
     *  `assistant:<executionId>` — already stable across retries because
     *  `deriveExecutionId` is. Override only if the product's message ids have a
     *  format constraint; it MUST stay deterministic per turn or a re-entered
     *  turn will duplicate its row instead of converging. */
    draftMessageId?(args: {
        identity: ChatTurnIdentity;
        executionId: string;
        threadId: string;
    }): string;
    /** Post-processing after a turn settles (billing, titles, audit). Fires with
     *  `failed:true` + `failureReason` when the turn carried a terminal error
     *  event (model 402 / rate-limit / server error) instead of a clean
     *  completion, so products skip the deduct and render an error row rather
     *  than billing an empty turn and marking it done. A turn that THROWS never
     *  reaches this hook (the engine skips it on a producer throw). Errors are
     *  swallowed by the engine — they never fail a streamed turn. */
    onTurnComplete?(input: ChatTurnCompleteInput<TContext>): Promise<void>;
    /** Per-event side channel (product broadcast). The turn-buffer tap is
     *  already wired; this runs in addition. */
    onEvent?(event: {
        type: string;
        data?: Record<string, unknown>;
    }, context: TContext): void | Promise<void>;
    /** Trace flush handed to `waitUntil` (OTLP export). */
    traceFlush?(context: TContext): Promise<void>;
    /** Compose the interaction-answer endpoints (`/interactions`). Omit when the
     *  product has no sidecar ask channel. */
    interactions?: InteractionAnswerRouteOptions;
    /** Byte budget for inline prompt parts. Default `INLINE_PARTS_MAX_BYTES`. */
    maxInlinePartBytes?: number;
    /** Per-flush coalescer for the turn buffer. Default `coalesceDeltas` (this
     *  assembly streams the client vocabulary's `{type:'text'|'reasoning',
     *  text}` lines, which it merges). A producer streaming raw
     *  `message.part.updated` events passes `coalesceChatStreamEvents`. */
    coalesceTurnEvents?: (events: unknown[]) => unknown[];
    replay?: {
        pollMs?: number;
        timeoutMs?: number;
    };
    log?: (message: string, meta?: Record<string, unknown>) => void;
}
/** Define routes to run, replay, and list running chat turns with streaming and reconnect support */
interface ChatTurnRoutes {
    /** POST — run one turn, streaming NDJSON. First line is
     *  `{type:'turn', turnId}` (the replay handle); the rest is the engine's
     *  event protocol. Pass the platform's `waitUntil` so the turn keeps
     *  running (and buffering) after a client disconnect. */
    turn(request: Request, ctx?: {
        waitUntil?(p: Promise<unknown>): void;
    }): Promise<Response>;
    /** GET — replay a buffered turn from `?fromSeq=` (0 = everything), then
     *  follow it live until it completes. */
    replay(request: Request, params: {
        turnId: string;
    }): Promise<Response>;
    /** GET `?threadId=` — the reconnect-discovery endpoint: the turn ids still
     *  running on a thread, so a client that reloaded mid-turn can re-attach to
     *  the live stream via {@link replay} instead of losing it. Returns `[]` when
     *  the turn store cannot enumerate running turns (`listRunning` unimplemented). */
    running(request: Request): Promise<Response>;
    /** list/answer endpoints from `/interactions`; null when not configured. */
    interactions: InteractionAnswerRoute | null;
}
/** Build chat turn routes to handle and validate incoming chat requests with optional logging */
declare function createChatTurnRoutes<TContext = void>(options: CreateChatTurnRoutesOptions<TContext>): ChatTurnRoutes;

/**
 * Model failover for a STREAMING turn.
 *
 * `/model-resolution`'s `runWithModelFailover` already owns the policy: walk a
 * chain, classify a resolved-or-thrown signal, re-throw a non-outage failure
 * immediately, and carry the attempt trail. This module does NOT re-implement
 * any of that — it composes it. What it adds is the one thing a whole-call
 * primitive cannot express, because a stream fails PARTWAY:
 *
 *   **A turn may only fail over before its first client-visible byte.**
 *
 * Once a text delta, tool call, or ask has reached the browser (and the
 * persisted transcript), restarting on another model would duplicate the
 * answer. So each attempt is probed: open the stream, pull events into a small
 * buffer, and decide at the first meaningful event whether this model is
 * serving. Committing replays the buffer and hands the live iterator through;
 * abandoning discards the buffer (those events describe the dead model's
 * session — including its `step-finish` usage, which must never be billed) and
 * lets `runWithModelFailover` walk to the next model.
 *
 * The classification itself is `isUpstreamUnavailable` verbatim, so this path
 * inherits the measured facts from the 2026-07-25 outage — above all that an
 * outage is NOT always a thrown error: the sandbox RESOLVES a terminal `error`
 * event carrying `{ errorCode: 'provider_inference_unavailable' }`, which a
 * classifier inspecting only `catch` misses entirely. That resolved shape is
 * the whole reason the breakage went unnoticed, so it is classified here first.
 *
 * Conservative by construction:
 * - A terminal failure that is NOT an outage (400, bad schema, content filter)
 *   COMMITS rather than failing over — it surfaces to the user exactly as it
 *   does today. Those fail identically on every model; walking the chain would
 *   only multiply latency and spend to reach the same error.
 * - A clean stream that produced nothing NEVER walks the chain. An empty answer
 *   is not evidence of a dead upstream, and a silent re-roll on another model is
 *   precisely the unattributable downgrade this work exists to prevent. Opt-in
 *   `emptyTurnRetries` re-runs the SAME model instead, which leaves attribution
 *   untouched — measured on production 2026-07-27, an empty turn is a transient
 *   platform flake that a same-model re-run recovers (8 hard cases: 7/8
 *   delivered on the first pass, 8/8 with one re-run, at a cost of 1 extra turn
 *   in 9). Default `0`, so the behavior is unchanged unless a product asks.
 * - A chain of length 1 costs nothing: one attempt, no extra call, no added
 *   latency, byte-identical to no failover at all.
 */

/**
 * True when `event` puts content in front of the user (or in the persisted
 * transcript), making a restart on another model unsafe.
 *
 * Deliberately an allow-list of KNOWN-INERT types rather than a deny-list: an
 * unrecognized event commits. Getting this wrong in the safe direction costs a
 * missed failover; getting it wrong the other way duplicates a user's answer.
 */
declare function isCommittingSandboxEvent(event: unknown): boolean;
/** A terminal failure event, classified. `outage` decides failover vs surface. */
interface TerminalFailure {
    outage: boolean;
    reason: string;
    code?: string;
}
/**
 * Classify a terminal failure event. Returns `null` for any non-terminal event.
 *
 * The RESOLVED shape is checked first and deliberately: the sandbox reports an
 * upstream outage by resolving `{ success: false, errorCode:
 * 'provider_inference_unavailable' }` inside a terminal `error` event's `data`,
 * never by throwing. Both `data` and the whole record are offered to
 * `isUpstreamUnavailable` so a payload nested either way is caught.
 */
declare function classifyTerminalFailure(event: unknown): TerminalFailure | null;
/** Open the raw turn stream for one specific model. */
type OpenModelStream = (args: {
    model: string;
    /** 1 for the preferred model, 2 for the first fallback, and so on. */
    attempt: number;
}) => AsyncIterable<unknown> | Promise<AsyncIterable<unknown>>;
/** Fired when a model is abandoned and the next one is about to be tried. */
interface ModelFallbackInfo {
    from: string;
    to: string;
    reason: string;
}
/** Define inputs for streaming a turn across a model failover chain */
interface ModelFailoverStreamOptions {
    /** Preferred model first, then fallbacks in descending preference. */
    models: readonly string[];
    open: OpenModelStream;
    /** Override the commit-point rule. Default {@link isCommittingSandboxEvent}. */
    isCommitting?: (event: unknown) => boolean;
    onFallback?: (info: ModelFallbackInfo) => void;
    /**
     * How many times to RE-RUN THE SAME MODEL when a turn completes having
     * produced no assistant text at all. Default `0` — byte-identical to no
     * retry.
     *
     * This is deliberately not a chain walk. Falling over to a different model
     * on an empty answer is the unattributable downgrade this module refuses to
     * do; re-running the SAME model changes nothing about attribution, because
     * the model that serves is the model that was asked for.
     *
     * Bounded by the same commit rule as failover: only a turn whose ONLY
     * committing event is a terminal receipt with no text is retried, so nothing
     * that reached the user can ever be produced twice.
     */
    emptyTurnRetries?: number;
    /** Fired when an empty turn is discarded and the same model re-run. */
    onEmptyTurnRetry?: (info: EmptyTurnRetryInfo) => void;
    log?: (message: string, meta?: Record<string, unknown>) => void;
}
/** One same-model re-run of a turn that completed with no assistant text. */
interface EmptyTurnRetryInfo {
    model: string;
    /** 1 for the first re-run. */
    retry: number;
    /** How many re-runs remain after this one. */
    remaining: number;
}
/** The failover-wrapped stream plus the attribution every consumer needs. */
interface ModelFailoverStreamHandle {
    events: AsyncGenerator<unknown, void, unknown>;
    /** The model that actually served. `undefined` until the first pull resolves it. */
    servingModel(): string | undefined;
    /** Every model tried, in order, with the reason each was abandoned. */
    attempts(): ModelFailoverAttempt[];
    /** True when the preferred model did not serve — the attributability signal. */
    usedFallback(): boolean;
}
/**
 * Hard ceiling on same-model re-runs. A turn that comes back blank three times
 * running is not a flake this can retry away, and each pass costs a full
 * sandbox turn — so the budget is capped rather than trusted.
 */
declare const MAX_EMPTY_TURN_RETRIES = 3;
/**
 * Coerce the caller's budget to a finite, bounded, non-negative integer.
 *
 * `Math.trunc(NaN)` is `NaN` and `retry >= NaN` is false for every `retry`, so
 * a naive clamp turns a bad config value into a loop that opens sandbox streams
 * until the worker dies. `Infinity` has the same shape. Both resolve to `0` —
 * an unusable budget disables the retry rather than running unbounded.
 */
declare function resolveEmptyTurnRetries(value: number | undefined): number;
/**
 * Wrap `open` in reactive model failover, streaming from the first model in
 * `models` that reaches its commit point.
 *
 * Zero added latency on the happy path: the preferred model is opened first and,
 * the moment it emits anything meaningful, its events flow straight through.
 *
 * @throws ModelFailoverExhaustedError when every model's upstream is down, and
 *         re-throws a non-outage error from the FIRST model without walking the
 *         chain (both behaviors inherited from `runWithModelFailover`).
 */
declare function streamWithModelFailover(options: ModelFailoverStreamOptions): ModelFailoverStreamHandle;

/**
 * Sandbox lane: bridge a raw sandbox event stream (`streamSandboxPrompt`) into
 * the `ChatTurnProducer` shape agent-runtime's `handleChatTurn` consumes AND
 * the client vocabulary `/web-react`'s `dispatchChatStreamLine` already parses
 * (`text` / `reasoning` / `tool_call` / `tool_result` / `usage` /
 * `notice` / structured `error` / `interaction`). Legal and tax each hand-rolled
 * this mapping differently;
 * this is that middle, composed from `/stream`'s normalizers — no new loop
 * logic, no SDK import (the event source is an injected `AsyncIterable`).
 *
 * Alongside the live mapping it accumulates the PERSISTED projection — the
 * `message.parts` rows `/chat-store` stores — via `normalizePersistedPart` /
 * `mergePersistedPart` / `finalizeAssistantParts`, plus the usage receipt from
 * `step-finish` parts. `createChatTurnRoutes` reads both after drain.
 */

/** Outcome of a `promoteFilePart` attempt. `key`, when given, becomes the
 *  persisted part's row key (e.g. `attachment:<path>`) so repeat promotions
 *  of the same underlying file fold into one segment instead of appending;
 *  omitted, the default `getPartKey` keying applies.
 *
 *  On failure, `part` is an OPTIONAL substitute part to persist in place of
 *  the raw url-bearing one — this is how a product swaps in a transcript
 *  notice (gtm persists a `warning` notice part, never the transient url) for
 *  a failed promotion instead of baking a `data:`/sandbox-path url into the
 *  durable row. When `part` is present it is persisted (via the same
 *  `recordPersistedPart` path as a success, honoring the optional `key`);
 *  when absent, the existing raw-part fallback applies unchanged — so a
 *  caller that only returns `{ succeeded: false, reason }` keeps today's
 *  behavior verbatim. */
type FilePartPromotionOutcome = {
    succeeded: true;
    part: Record<string, unknown>;
    key?: string;
} | {
    succeeded: false;
    reason: string;
    part?: Record<string, unknown>;
    key?: string;
};
/** Define options for producing sandbox chat events with rendering and interaction controls */
interface SandboxChatProducerOptions {
    /** The raw sandbox event stream (e.g. `streamSandboxPrompt(...)`).
     *
     *  An ALREADY-OPEN stream is bound to one model and cannot be reopened, so
     *  this form can never fail over. Prefer {@link openEvents}; exactly one of
     *  the two is required. */
    events?: AsyncIterable<unknown>;
    /** Open the raw sandbox stream FOR A GIVEN MODEL — the failover-capable form
     *  of {@link events}. The callback receives the model to run and returns the
     *  same `AsyncIterable` `events` would have been (typically
     *  `streamSandboxPrompt(shell, box, prompt, { ...opts, model })`).
     *
     *  Wiring this turns failover ON with no further flag: whenever the resolved
     *  chain (`model` + {@link fallbackModels}) holds more than one entry, a model
     *  whose upstream is dead is abandoned BEFORE its first client-visible byte
     *  and the next one is tried. A one-entry chain opens exactly once — no extra
     *  call, no added latency, byte-identical to today.
     *
     *  Requires {@link model}: failover has to know which model it is running. */
    openEvents?: OpenModelStream;
    /** Recorded on the persisted assistant message. When failover moves the turn
     *  to another model, the producer's `model` reports the model that ACTUALLY
     *  served, not this preferred one — see {@link modelFailover}. */
    model?: string;
    /** Models to try, in order, when `model`'s upstream is dead. Product config,
     *  never a shell default: agent-app cannot know which ids are live, and a
     *  baked list would rot into exactly the stale-liveness bug this guards
     *  against. Empty/omitted → one attempt, today's behavior.
     *
     *  Pick these deliberately. A same-family fallback is NOT automatically safe:
     *  `gemini-2.5-flash` produced zero persisted deliverables in 2 of 3 measured
     *  runs on a med-legal filing flow where `gemini-2.5-pro` succeeded. That is
     *  why every fallback is surfaced (persisted `model`, a transcript notice, and
     *  `modelFailover()`) instead of being applied silently. */
    fallbackModels?: readonly string[];
    /** Opt out of failover while still using {@link openEvents}. `false` collapses
     *  the chain to `model` alone. */
    modelFailover?: false;
    /** Fired when a model is abandoned mid-chain (telemetry/alerting). The user
     *  already sees a transcript notice; this is for the operator. */
    onModelFallback?: (info: ModelFallbackInfo) => void;
    /** Re-run the SAME model this many times when a turn completes with no
     *  assistant text at all. Default `0` (unchanged behavior). Requires
     *  {@link openEvents} — there is nothing to re-open on a fixed stream.
     *
     *  Distinct from {@link fallbackModels} on purpose: this never changes which
     *  model answers, so it carries none of the attribution risk a downgrade
     *  does. Measured on production 2026-07-27 through gtm-agent's profile, a
     *  completed-but-blank turn is a transient platform flake — 8 hard cases went
     *  7/8 delivered to 8/8 with one re-run, costing 1 extra turn in 9. */
    emptyTurnRetries?: number;
    /** Fired when a blank turn is discarded and the same model re-run. */
    onEmptyTurnRetry?: (info: EmptyTurnRetryInfo) => void;
    /** Which ask kinds the product renders a card for. Anything else is
     *  auto-declined (see `declineInteraction`) so the run never hangs in the
     *  broker waiting on a card no client will show. Default: question/plan.
     *  Products with per-turn plan mode can close over it without another option:
     *  `(kind) => kind === 'question' || (kind === 'plan' && planEnabled)`. */
    isRenderableInteraction?: (kind: string) => boolean;
    /** Resolve a non-renderable ask (wire `respondToSessionInteraction` with the
     *  session's sidecar connection). Without it, a failure notice is emitted and
     *  the run stays blocked until the broker times out. */
    declineInteraction?: (id: string) => Promise<void>;
    /** Opt-in eager promotion of harness-emitted `file` parts. Unset, a `file`
     *  part persists exactly as the harness sent it — a transient `url` (a
     *  `data:` URI or in-sandbox path) baked into the transcript, which is
     *  today's behavior and stays byte-identical if this is never wired. Set,
     *  EVERY `file` part (never `image`, never any other kind) is routed
     *  through this callback instead of `recordPersistedPart`'s default
     *  fallback — including a part with NEITHER `id` NOR `url` (gtm always
     *  attempts promotion; such a part simply fails "carries no url" and
     *  resolves through the same failure path as any other rejection, rather
     *  than being persisted raw and unpromoted) — so the product can durably
     *  write the bytes and swap in a path-bearing part before the raw url ever
     *  reaches the persisted transcript. Keyed per source-prefixed `id:<id>` /
     *  `url:<url>` (an `id` and a `url` sharing the same text must never collide
     *  onto one memo entry) and memoized by PROMISE (not result), so re-emitted
     *  snapshot events for the same part —
     *  the harness resends the whole part on every update, not just deltas —
     *  fold onto the one in-flight or settled attempt rather than promoting
     *  twice or racing two concurrent writes; a raw part with neither `id` nor
     *  `url` cannot be keyed, so it is invoked UN-memoized (once per event) —
     *  each occurrence is its own attempt. A rejecting promise is caught,
     *  logged via `log`, and treated as `succeeded: false`. On `succeeded:
     *  false` the outcome's optional `part` (a substitute — e.g. a warning
     *  notice — see {@link FilePartPromotionOutcome}) persists in its place when
     *  given; otherwise the raw part persists exactly as it does today — this
     *  seam only decides whether to call the promoter and what to do with its
     *  outcomes; the promotion mechanics (vault write, key derivation, notice
     *  construction) live in the caller's callback, not here. */
    promoteFilePart?: (raw: JsonRecord) => Promise<FilePartPromotionOutcome>;
    log?: (message: string, meta?: Record<string, unknown>) => void;
}
/** Create a sandbox chat producer that manages chat turn routing with logging and interaction rendering options */
declare function createSandboxChatProducer(options: SandboxChatProducerOptions): ChatTurnRouteProducer;

/**
 * Detached (autonomous) turn → live buffer bridge.
 *
 * The interactive lane (`createChatTurnRoutes`) already streams a user-typed
 * turn to the browser while it runs. An AUTONOMOUS turn — a mission step, a
 * queue job, an inbound-email review — runs detached (`dispatchPrompt`/
 * `streamPrompt` server-side so it survives no one watching) and, historically,
 * only persisted its FINAL message. A browser opening the session mid-run saw a
 * dead screen: the live tokens existed server-side but were never written to
 * the turn-event buffer the client re-attach path (`listRunning` + `/replay`)
 * reads.
 *
 * `runDetachedTurn` is that missing bridge, packaged. It taps the same buffer
 * the interactive lane uses (`createBufferedTurnTap`) with the same producer
 * mapping (`createSandboxChatProducer`), so an autonomous run is watchable
 * token-by-token exactly like an interactive one — while staying durable
 * (a durable driver re-invokes it after a crash; a turn that finished
 * server-side short-circuits instead of re-streaming). Products supply only the
 * domain seams: the raw sandbox event stream, the turn store, and the ids.
 *
 * This is app-shell mechanism (turn durability + live projection), not engine:
 * it owns no loop logic and imports no SDK — the event source is an injected
 * `AsyncIterable`.
 */

/** The normalized structured message body (tool-call / file / plan / interaction
 *  parts) that `/chat-store` persists as the durable assistant row — the same
 *  shape `createSandboxChatProducer().assistantParts()` returns. */
type DetachedTurnParts = Array<Record<string, unknown>>;
/** Authoritative final receipt for a turn that finished server-side, or whose
 *  live stream carried no usage (some harness paths only expose tokens via the
 *  completed-turn record, e.g. `box.findCompletedTurn(turnId)`). */
interface DetachedTurnFinal {
    text?: string;
    usage?: ChatTurnUsage;
    /** The structured parts to persist when this receipt IS the result (the
     *  cached / finished-server-side path). Omitted when the record only carries
     *  a usage receipt. */
    parts?: DetachedTurnParts;
}
/** Define options for managing and projecting a detached turn event stream in a session */
interface DetachedTurnOptions {
    store: TurnEventStore;
    turnId: string;
    /** Thread/session id — recorded as the buffer scope so a browser opening the
     *  session mid-run rediscovers this turn via `listRunning(scopeId)` after it
     *  has lost the turnId. */
    scopeId: string;
    /** The raw sandbox event stream for this turn (e.g. `streamSandboxPrompt`).
     *  Ownership of the box, prompt, tooling, and attachments stays with the
     *  caller — this only projects the stream.
     *
     *  An already-open stream is bound to one model and cannot fail over. Prefer
     *  {@link openEvents}; exactly one of the two is required. */
    events?: AsyncIterable<unknown>;
    /** Open the raw sandbox stream FOR A GIVEN MODEL — the failover-capable form
     *  of {@link events}. Wiring it turns failover on with no further flag
     *  whenever {@link fallbackModels} is non-empty. Requires {@link model}.
     *
     *  An autonomous run is the case that most needs this: nobody is watching to
     *  notice a dead upstream and retry by hand, so without failover the mission
     *  step or queue job simply fails. Forwarded to the producer. */
    openEvents?: SandboxChatProducerOptions['openEvents'];
    /** Models to try, in order, when `model`'s upstream is dead. Product config —
     *  see the producer's note on why a same-family fallback is not automatically
     *  safe and why every fallback is surfaced. */
    fallbackModels?: SandboxChatProducerOptions['fallbackModels'];
    /** Opt out of failover while still using {@link openEvents}. */
    modelFailover?: false;
    /** Fired when a model is abandoned mid-chain (telemetry/alerting). */
    onModelFallback?: SandboxChatProducerOptions['onModelFallback'];
    /** The PREFERRED model. Recorded on the persisted assistant message + usage
     *  receipt — unless failover moved the turn, in which case the model that
     *  actually served is recorded instead and surfaced on the result. */
    model?: string;
    /** Per-flush buffer coalescer. Default `coalesceDeltas`. */
    coalesce?: (events: unknown[]) => unknown[];
    /** Which ask kinds the product renders a card for; anything else is
     *  auto-declined via {@link declineInteraction}. Forwarded to the producer. */
    isRenderableInteraction?: SandboxChatProducerOptions['isRenderableInteraction'];
    /** Resolve a non-renderable ask so the run never hangs in the broker. An
     *  autonomous turn has NO human watching to answer an ask, so a caller that
     *  omits this risks the run blocking until the broker times out — wire it for
     *  any unattended run. Forwarded to the producer. */
    declineInteraction?: SandboxChatProducerOptions['declineInteraction'];
    /** Opt-in eager promotion of harness-emitted `file` parts. Forwarded to the
     *  producer (see its docs). */
    promoteFilePart?: SandboxChatProducerOptions['promoteFilePart'];
    /** Authoritative final receipt, consulted whenever a re-invoke finds a prior
     *  buffer: (a) an already-`complete` turn returns it as the cached result,
     *  (b) a `running` turn (crash mid-run) uses it to detect a run that finished
     *  server-side, and (c) a clean run whose stream carried no usage/text falls
     *  back to it. Typically `() => box.findCompletedTurn(turnId)`. */
    completedResult?: () => Promise<DetachedTurnFinal | null | undefined>;
    /** Clear the prior partial buffer for `turnId` before a genuine re-stream.
     *  A crash mid-run leaves buffered rows at seqs 1..N with status `running`;
     *  re-streaming restarts the tap's seq at 0 and would duplicate/interleave
     *  rows. Wire this (delete `turnId`'s buffered events) so a retry is clean.
     *  Unset, a re-stream over a `running` buffer is still attempted but logged
     *  as a possible-duplication hazard. */
    resetBuffer?: (turnId: string) => Promise<void>;
    /** Own the durable assistant row for this turn instead of returning the body
     *  for the caller to insert — and keep it in step with the stream.
     *
     *  An autonomous run is exactly the case a late viewer hits: nobody is
     *  watching when it starts, so by the time a browser opens the session the
     *  streaming gateway's hot event buffer may already have expired it. Keeping
     *  that buffer short is what makes it affordable at scale (its Redis
     *  footprint is linear in `ttl x concurrent sessions`), so the durable row —
     *  written incrementally here — is what serves the late viewer.
     *
     *  WIRING THIS TRANSFERS ROW OWNERSHIP: the returned {@link
     *  DetachedTurnResult.messageId} names the row this call wrote (draft rows
     *  during the stream, authoritative values at the end, retraction when the
     *  turn produced nothing). The caller must NOT insert its own assistant row
     *  for the turn. Omit the seam and nothing changes — the result is returned
     *  and the caller persists it exactly as today.
     *
     *  Idempotency reuses the turn's own identity: the row id defaults to
     *  `assistant:<turnId>`, so a durable driver re-invoking after a crash
     *  patches the same row instead of duplicating parts. */
    persist?: DraftPersistenceTuning & {
        store: AssistantDraftStore;
        threadId: string;
        /** Deterministic row id. Default `assistant:<turnId>`. */
        messageId?: string;
        /** Pre-persist text transform (`/redact`), applied to drafts AND the final
         *  write — parity with the interactive lane's `transformFinalText`. */
        transformText?: (text: string) => string | Promise<string>;
    };
    log?: (message: string, meta?: Record<string, unknown>) => void;
}
/** Describe the result of a detached turn including state, text, parts, usage, and optional error or cache flag */
interface DetachedTurnResult {
    /** `completed` — clean drain: persist + bill. `failed` — a terminal error
     *  event, including the producer's structured `sandbox.stream_failed` event
     *  when the raw sandbox stream throws: skip billing, render an error row. */
    state: 'completed' | 'failed';
    text: string;
    /** The structured assistant body to persist (tool calls, file/plan/interaction
     *  parts). Empty array when the run produced none. */
    parts: DetachedTurnParts;
    usage: ChatTurnUsage;
    /** Present when `state === 'failed'`. */
    error?: string;
    /** True when a prior buffer meant this call returned a cached/finished result
     *  WITHOUT re-streaming (durable-driver retry after a crash). */
    cached: boolean;
    /** The durable assistant row this call wrote, when `persist` was wired.
     *  `null` when the turn produced nothing and the row was retracted. Absent
     *  when the caller owns persistence (today's behavior). */
    messageId?: string | null;
    /** The model that SERVED the turn — the fallback's id when failover moved it.
     *  A caller that bills or scores per model must read this, not the model it
     *  requested. */
    model?: string;
    /** True when the preferred model did not serve. Makes an autonomous
     *  downgrade — which no human watched happen — attributable after the fact. */
    usedModelFallback?: boolean;
    /** Every model tried, in order, with the reason each was abandoned. */
    modelAttempts?: ModelFailoverAttempt[];
}
/**
 * Stream a detached turn into the live turn-event buffer, durably.
 *
 * - Idempotent: an already-`complete` turn returns the cached result without
 *   re-streaming (a second event sequence would collide with the buffered one).
 * - Crash-safe: a `running` turn (a prior attempt crashed mid-tap) consults
 *   `completedResult` to detect a run that finished server-side; only a run that
 *   genuinely did not complete is re-streamed, and then over a `resetBuffer`-
 *   cleared buffer so seqs don't corrupt.
 * - Marks the turn `running` under `scopeId` so a mid-run browser finds it.
 * - Settles `complete`/`error` so the client stops tailing and billing/render
 *   can branch on `state`.
 */
declare function runDetachedTurn(opts: DetachedTurnOptions): Promise<DetachedTurnResult>;

/** Resolve chat route events and materialize their durable state records */
interface ChatRouteDurableProjection {
    observe(event: unknown): void | Promise<void>;
    materialize(): Array<Record<string, unknown>> | Promise<Array<Record<string, unknown>>>;
}
/** Log chat route projection messages with optional metadata for durable processing */
type ChatRouteDurableProjectionLogger = (message: string, meta?: Record<string, unknown>) => void;
/** Adds durable lifecycle projection to any producer lane without moving its
 * transport into agent-app. Purely STRUCTURAL: agent-app ships no implementer
 * of {@link ChatRouteDurableProjection} and deliberately does not — the one it
 * used to ship (`/durable-chat`) was removed in 0.44.0 with zero fleet imports.
 * Pass any `{ observe, materialize }` object backed by your own store. The projection is observed inline and its
 * materialized parts replace same-key pending snapshots after the stream
 * drains. Projection persistence is best-effort for the live lane: a store
 * outage must not terminate an otherwise healthy sandbox stream. Failures are
 * reported through the optional logger so products can retain diagnostics. */
declare function withDurableChatProjection(producer: ChatTurnRouteProducer, projection: ChatRouteDurableProjection, log?: ChatRouteDurableProjectionLogger): ChatTurnRouteProducer;

/**
 * `createUploadRoute` — the multimodal middle. Accepts multipart file uploads
 * and returns `PromptInputPart`-shaped descriptors the client echoes back on
 * send (`ChatTurnRequestPayload.parts`):
 *
 *   ≤ inlineMaxBytes (700 KiB default) → inline `data:` URI part — rides the
 *     turn body directly, no sandbox round trip.
 *   > inlineMaxBytes → written into the sandbox workspace (base64 through the
 *     structural `write` seam — `box.fs` satisfies it) and referenced by
 *     `path`. Mandatory two-step: the gateway caps request bodies at ~1 MiB,
 *     so a large file can never ride the prompt POST.
 *
 * The sink is structural (no sandbox-SDK import); products pass `box.fs`.
 *
 * @remarks Sole consumer today is the `--chat` scaffold (`create-agent-app
 * --chat` → `template-chat/src/chat.ts`), the reference multimodal path — its
 * inline-`data:`-or-ephemeral-sandbox-workspace split stays the scaffold's
 * proven upload pattern, not a fleet primitive; keep that distinction in mind
 * before widening its surface. Fleet apps with a durable store of their own
 * (KV, or AES-GCM-encrypted R2) no longer need to hand-roll a vault upload
 * route: `createAttachmentUploadRoute` (`./attachment-upload`, agent-app#234)
 * is the shared hardened path for that persistence model — a content-sniffed
 * type gate, two-phase atomic batch writes, and per-kind/aggregate size caps,
 * all seamed through an injected `WriteAttachmentFn`. Point readers there
 * instead of widening this route to cover both models.
 */

/** 700 KiB: base64 inflates ~4/3, so an inline part stays comfortably under
 *  the ~1 MiB gateway body cap alongside the JSON envelope. */
declare const UPLOAD_INLINE_MAX_BYTES: number;
/** 8 MiB default ceiling per file — one base64 `write` call handles it. Raise
 *  it only with a sink that can take the bigger single write. */
declare const UPLOAD_MAX_FILE_BYTES: number;
/** Structural match of the sandbox SDK's `box.fs` write surface (v0.10.5+:
 *  `encoding: 'base64'` is the worker-safe binary path). */
interface SandboxUploadSink {
    write(path: string, content: string, options?: {
        encoding?: 'utf8' | 'base64';
    }): Promise<unknown>;
}
/** Resolve upload authorization status and provide upload destination or error response */
type UploadAuthorization = {
    ok: true;
    /** Where large files land. Absent/null: only inline uploads are
     *  accepted and an over-inline-cap file is rejected with 413. */
    sink?: SandboxUploadSink | null;
    /** Per-request override of the workspace directory large files go to. */
    uploadDir?: string;
} | {
    ok: false;
    response: Response;
};
/** Define options to authorize uploads and configure file size limits and upload directory */
interface CreateUploadRouteOptions {
    /** Authenticate the caller and resolve the sandbox file sink (usually
     *  `ensureWorkspaceSandbox(...)` → `box.fs`). */
    authorize(args: {
        request: Request;
    }): Promise<UploadAuthorization>;
    /** Inline-vs-sandbox threshold. Default {@link UPLOAD_INLINE_MAX_BYTES}. */
    inlineMaxBytes?: number;
    /** Hard per-file cap. Default {@link UPLOAD_MAX_FILE_BYTES}. */
    maxFileBytes?: number;
    /** Workspace directory for path-ref files. Default `'uploads'`. */
    uploadDir?: string;
}
/** One uploaded file, ready for the composer chip and the turn body. */
interface UploadedChatFile {
    id: string;
    name: string;
    size: number;
    mediaType: string;
    /** True when the part carries the bytes inline (`data:` URI). */
    inline: boolean;
    /** Echo this back verbatim in `ChatTurnRequestPayload.parts`. */
    part: ChatTurnFilePartInput;
}
/** Path-safe file name: basename only, conservative charset, length-capped. */
declare function sanitizeUploadFilename(name: string): string;
/** Convert a Uint8Array of bytes into a base64-encoded string */
declare function bytesToBase64(bytes: Uint8Array): string;
/** Create an upload route handler that authorizes requests and processes file uploads with size limits */
declare function createUploadRoute(options: CreateUploadRouteOptions): (request: Request) => Promise<Response>;

/**
 * Storage seams for the chat-attachment vertical (`resolveChatAttachments`,
 * `buildDispatchParts`, `promoteAgentFilePart`). Structural function ports in
 * the same style as `upload.ts`'s `SandboxUploadSink`: REQUIRED injection, no
 * default implementation — agent-app owns the size/budget/idempotency
 * mechanism, the product owns where the bytes actually live.
 *
 * One reader, two callers: `resolveChatAttachments` reads only the
 * authoritative `size` (never trusting the client-reported size), while
 * `buildDispatchParts` reads the inline `content` (base64 or raw bytes) to
 * build a `data:` URI. Both fit behind ONE `ReadAttachmentFn` so a product
 * wires a single vault/object-store adapter, not two. gtm's KV vault (stores
 * base64 bodies) and `/object-store`'s `ObjectStore` (hands back raw bytes)
 * both satisfy this shape.
 */
/**
 * The result of reading one stored attachment. `ok:true` MUST carry the
 * authoritative decoded byte `size` (the cap is meaningless against a
 * client-controlled number) and, when the caller needs to inline the file,
 * its content as `base64` and/or raw `bytes`. `mediaType` is the stored
 * content type when the store knows it (used as the fallback when the wire
 * part carried none). `ok:false` carries a human `reason` that SHOULD name the
 * offending path — it is surfaced verbatim in the caller's typed outcome.
 */
type AttachmentReadResult = {
    ok: true;
    /** Authoritative decoded byte length of the stored content. */
    size: number;
    /** Inline content as base64 — reused verbatim for a `data:` URI, so a
     *  store holding already-base64 bodies never decodes-and-re-encodes. */
    base64?: string;
    /** Inline content as raw bytes — base64-encoded by the caller when a
     *  `data:` URI is needed. Ignored when `base64` is present. */
    bytes?: Uint8Array;
    /** Stored content type, when the store tracks one. */
    mediaType?: string;
} | {
    ok: false;
    reason: string;
};
/**
 * Read one stored attachment for `scopeId` (the product's workspace/tenant
 * key) at its store-relative `path`. Missing, deleted, or unreadable content
 * MUST resolve to `{ ok: false, reason }`, never throw — a store failure is a
 * per-attachment outcome the caller folds into its own typed result, not a
 * turn-level exception.
 */
type ReadAttachmentFn = (scopeId: string, path: string) => Promise<AttachmentReadResult>;
/** Outcome of persisting one attachment. Mirrors `AttachmentReadResult`'s
 *  `ok`/`reason` shape and `upload.ts`'s `{ ok }` convention. */
type AttachmentWriteResult = {
    ok: true;
} | {
    ok: false;
    reason: string;
};
/**
 * Persist `content` for `scopeId` at `path`. `content` is either raw `bytes`
 * or a base64 `string` — a string argument is ALWAYS base64 (never utf8), so
 * a store that speaks base64 (gtm's vault) writes it verbatim and one that
 * speaks bytes decodes once. Like the reader, failures resolve to
 * `{ ok: false, reason }` rather than throwing.
 *
 * `opts` mirrors the vault frontmatter gtm's `writeAttachmentVaultFile`
 * persists alongside the body (promote-file-parts.ts:181-190), so a product
 * reimplementing that vault writer through this seam can reproduce it
 * exactly:
 * - `mediaType` — the resolved MIME type; gtm's frontmatter key `mime`.
 * - `name` — the sanitized (store-path-safe) display filename; gtm passes
 *   this only to shape its oversize message, not into frontmatter.
 * - `originalName` — the filename as the harness/browser reported it, BEFORE
 *   sanitization (`raw.filename ?? filename` — falls back to the sanitized
 *   name when the source carried none); gtm's frontmatter key `originalName`.
 *   This is the one field with no other recovery path once sanitization has
 *   run, so it must ride the write, not be re-derived after the fact.
 * - `size` — the authoritative decoded byte length being written; gtm's
 *   frontmatter key `size`.
 */
type WriteAttachmentFn = (scopeId: string, path: string, content: Uint8Array | string, opts: {
    mediaType?: string;
    name?: string;
    originalName?: string;
    size?: number;
}) => Promise<AttachmentWriteResult>;

/**
 * `resolveChatAttachments` — validate a turn body's `attachments` field into
 * persistable {@link ChatAttachmentPart}s. Every path is re-validated (a path
 * off the wire is never trusted to stay inside the store root) and every size
 * is re-derived from the STORED body via the injected {@link ReadAttachmentFn},
 * never the client-reported `size` — the upload path lets a caller rewrite its
 * own frontmatter, so a stored size cannot bound anything and the wire size can
 * be anything. Both the aggregate cap and the size carried on the returned part
 * come from the authoritative read.
 *
 * Storage-parameterized: the frontmatter parsing / base64 sizing that derives
 * the authoritative size lives BEHIND `readAttachment` (a product's vault or
 * object-store adapter), so this module is a pure validator + budget gate with
 * no store knowledge. Lifted from gtm-agent's `resolve-attachments.ts`
 * (workspaceId → scopeId, the vault read → the injected reader) and kept
 * behavior-identical for gtm-agent#618 adoption.
 */

/** Resolve the result of chat attachment processing with success status and corresponding data or error */
type ResolveChatAttachmentsResult = {
    succeeded: true;
    value: ChatAttachmentPart[];
} | {
    succeeded: false;
    error: string;
};
/** Verdict of a path check: OK, or a rejection naming why. Mirrors
 *  `SandboxMentionPathCheck` in `./wire`. */
type AttachmentPathCheck = {
    succeeded: true;
} | {
    succeeded: false;
    error: string;
};
/**
 * Default path validator when a caller supplies none. Rejects the ways a path
 * picked in a client can escape the store root — traversal (`..` segment),
 * absolute (leading `/`), backslashes, null bytes, control characters (see
 * {@link CONTROL_CHARS} — a path also feeds {@link buildAttachmentPromptBlock}'s
 * `(vault: ${path})` pointer, so it is exposed to the same injection surface as
 * `name`) — plus a dotfile/hidden segment (a leading `.` on any segment).
 * Generalized from gtm's `validateVaultFilePath`, in the spirit of
 * `validateSandboxMentionPath` (`/chat-routes`'s wire mention-path validator) —
 * but the dotfile rejection here is INTENTIONALLY stricter than that sibling:
 * an uploaded attachment path is sanitized store-relative storage the product
 * itself assigned, whereas a mention path points at a file that already exists
 * in the sandbox and may legitimately live under a dotfile segment. A caller
 * that needs gtm's exact (looser) rule can supply `validatePath` to override
 * this default entirely.
 */
declare function defaultValidateAttachmentPath(path: string): AttachmentPathCheck;
/** Define options to resolve and validate chat attachments with size, count, and path constraints */
interface ResolveChatAttachmentsOptions {
    /** The product's workspace/tenant key, passed to `readAttachment`. */
    scopeId: string;
    /** Authoritative size + content reader — see {@link ReadAttachmentFn}. */
    readAttachment: ReadAttachmentFn;
    /** Most attachments one request may carry. Default {@link ATTACHMENT_MAX_COUNT}. */
    maxCount?: number;
    /** Aggregate raw-byte ceiling. Default {@link MAX_ATTACHMENT_TOTAL_BYTES}. */
    maxTotalBytes?: number;
    /** Path validator override. Default {@link defaultValidateAttachmentPath}. */
    validatePath?: (path: string) => AttachmentPathCheck;
}
/**
 * Validate and resolve a turn body's `attachments` field into persistable
 * parts. Every path is confirmed present (and not deleted) in the caller's own
 * store by `readAttachment` before it is trusted, and size is derived from the
 * authoritative read for both the aggregate cap and the returned part's size.
 */
declare function resolveChatAttachments(value: unknown, options: ResolveChatAttachmentsOptions): Promise<ResolveChatAttachmentsResult>;

/**
 * `createAttachmentUploadRoute` — the fleet-primitive durable-store upload
 * route: a two-phase atomic batch (every file is validated before any file is
 * written — a batch never partially lands), a content-sniffed type gate
 * (`checkAttachmentType` over `sniffBinary`'s magic-byte read, not the
 * extension or the browser-reported MIME), per-kind + aggregate byte caps,
 * and sanitized filenames. Storage is fully seamed through the injected
 * `WriteAttachmentFn` (`./attachment-store`) — no default store, the product
 * owns where bytes actually live (vault, object store, …) — and auth/rate
 * limiting is entirely the injected `authorize` seam's job: this factory
 * never invents a 401 or 429 response, it only returns `auth.response`
 * verbatim on failure.
 *
 * Lifted from gtm-agent's `src/routes/api.vault.upload.ts` (the hardening
 * lineage other lifted modules in this vertical cite: gtm#584 binary
 * corruption, gtm#592 sniff gate/caps, gtm#593 batch-atomic writes) and
 * generalized the way `resolve-attachments.ts` generalized gtm's read path —
 * the vault-specific pieces (KV vault paths, frontmatter, per-user rate
 * limiting) are all injected seams here, while the validate-then-write phase
 * split and the type/size gate ordering survive byte-for-byte.
 *
 * @remarks Sibling to, NOT an extension of, `./upload.ts`'s
 * `createUploadRoute` — a different persistence model (durable product store
 * vs. inline-`data:`-or-ephemeral-sandbox-workspace). See that module's doc
 * comment for the up-to-date framing between the two.
 */

/** Outcome of the injected `authorize` seam: auth + rate limiting +
 *  scope resolution, all in one place so a 429 rides `{ok:false, response}`
 *  exactly like a 401 does — this factory has no rate-limit opinion of its
 *  own. `writeAttachment` lets a single request override the option-level
 *  store (e.g. routing per-tenant), defaulting to `options.writeAttachment`
 *  when absent. */
type AttachmentUploadAuthorization = {
    ok: true;
    scopeId: string;
    writeAttachment?: WriteAttachmentFn;
} | {
    ok: false;
    response: Response;
};
/** Define options to authorize, write, and limit attachment uploads in a route */
interface CreateAttachmentUploadRouteOptions {
    /** Authenticate the caller, rate-limit, and resolve the store scope
     *  (workspace/tenant id) — never a query param. */
    authorize(args: {
        request: Request;
    }): Promise<AttachmentUploadAuthorization>;
    /** Default store writer. `authorize` may override it per-request. */
    writeAttachment: WriteAttachmentFn;
    /** Overridable caps. Defaults come from `./attachment-validation`. */
    limits?: {
        /** Most files one request may carry. Default {@link ATTACHMENT_MAX_COUNT}. */
        maxCount?: number;
        /** Ceiling on a binary file's raw size. Default {@link MAX_BINARY_ATTACHMENT_BYTES}. */
        maxBinaryBytes?: number;
        /** Ceiling on a text file's raw size. Default {@link MAX_TEXT_ATTACHMENT_BYTES}. */
        maxTextBytes?: number;
        /** Aggregate raw-byte ceiling across the batch. Default {@link MAX_ATTACHMENT_TOTAL_BYTES}. */
        maxTotalBytes?: number;
    };
    /** Attachment kinds this route accepts. Default `['image', 'file']`. */
    allowedKinds?: ChatAttachmentKind[];
    /** Sniffed-mime allowlist fed to `checkAttachmentType`. Default
     *  {@link ALLOWED_ATTACHMENT_SNIFFED_MIMES}. */
    allowedSniffedMimes?: ReadonlySet<string>;
    /** Sanitized-name → store path. Default identity (the sanitized name IS
     *  the path); gtm passes `vaultFolderForFileName`, a tenant product a
     *  scope prefix. */
    pathFor?: (name: string) => string;
    /** Store-path validator. Default {@link defaultValidateAttachmentPath}. */
    validatePath?: (path: string) => AttachmentPathCheck;
    /** Last-resort media-type hook for text content the sniffer can't type.
     *  Default {@link sniffMimeFromName}. */
    sniffMime?: (name: string) => string;
}
/** Resolve an attachment upload route handler with customizable limits and validation options */
declare function createAttachmentUploadRoute(options: CreateAttachmentUploadRouteOptions): (request: Request) => Promise<Response>;

/**
 * `buildDispatchParts` — assemble the `PromptInputPart[]` a turn carrying
 * attachments and/or `@`-mentions dispatches to the sandbox. `parts[0]` is
 * always the full prompt text (typed text plus the attachment + mention pointer
 * blocks); each attachment or mention becomes one media part. An attachment
 * (read from the product store via the injected reader) draws the inline byte
 * budget first; a mention (read from the LIVE box) takes what is left. A file
 * inlines as a `data:` URI when it fits the remaining budget, otherwise demotes
 * to an in-box path part so the whole request stays under the proxy cap. Every
 * media part is deduped by its resolved absolute path. This module only
 * produces the parts array; the caller decides when a turn dispatches parts
 * instead of a plain string.
 *
 * Storage-parameterized port of gtm-agent's `dispatch-parts.ts`: the vault
 * default reader is dropped (`readAttachment` is REQUIRED — the product supplies
 * its store adapter), the `GTM_SANDBOX_VAULT_DIR` prefixing becomes the required
 * `resolveAttachmentPath` seam, the `GTM_MULTIMODAL_FORCE_PATH` env fallback
 * becomes an explicit `forcePath` flag, and every budget cap reads an overridable
 * `./wire` constant. Kept behavior-identical for gtm-agent#618 adoption (the
 * demotion math and emitted part shapes reproduce its dispatched prompt bytes).
 */

/** Resolve the outcome of dispatching parts with success status and corresponding value or error message */
type DispatchPartsOutcome = {
    succeeded: true;
    value: PromptInputPart[];
} | {
    succeeded: false;
    error: string;
};
/** One mention file's size (always) and inline bytes (only when the caller
 *  asked for them — a path-only mention never reads its bytes). */
type SandboxMentionReadOutcome = {
    succeeded: true;
    value: {
        size: number;
        base64?: string;
    };
} | {
    succeeded: false;
    error: string;
};
/** Resolve sandbox mention details by reading from a specified path with optional byte reading */
type ReadSandboxMentionFn = (box: SandboxExecChannel, absolutePath: string, options: {
    readBytes: boolean;
}) => Promise<SandboxMentionReadOutcome>;
/** Build input parameters for dispatching chat message parts including text, attachments, mentions, and history */
interface BuildDispatchPartsInput {
    text: string;
    attachments: ChatAttachmentPart[];
    mentions?: ChatMentionPart[];
    history: Array<{
        role: 'user' | 'assistant';
        content: string;
    }>;
    systemPrompt: string;
    /** Serialized size of the backend profile the SDK inlines into the same
     *  prompt request body — a large, non-negotiable rider that must come out of
     *  the inline budget or near-cap attachments 413 at the proxy instead of
     *  demoting to path parts. */
    profileWireBytes: number;
    /** The product's workspace/tenant key, passed to `readAttachment`. */
    scopeId: string;
    /** Maps an attachment's store-relative path to the in-box absolute path a
     *  path-based part references (same seam style as `fileMentionsToParts`'s
     *  `resolvePath`). */
    resolveAttachmentPath: (path: string) => string;
    /** Maps a mention's workspace-relative path to its in-box absolute path.
     *  Default: {@link BuildDispatchPartsInput.resolveAttachmentPath} — in gtm the
     *  vault mount roots both; a product that mounts them apart overrides this. */
    resolveMentionPath?: (path: string) => string;
    /** The turn's already-ensured box — required when `mentions` is non-empty
     *  (mention bytes are read from the live box, not the store). */
    box?: SandboxExecChannel;
    /** Force every media part to a path reference, skipping all inlining. */
    forcePath?: boolean;
    /** REQUIRED store reader for attachment content — no default (the product
     *  owns its store; see {@link ReadAttachmentFn}). */
    readAttachment: ReadAttachmentFn;
    readSandboxMention?: ReadSandboxMentionFn;
    /** Whole-request proxy cap. Default {@link DISPATCH_REQUEST_MAX_BYTES}. */
    requestMaxBytes?: number;
    /** JSON-envelope reserve off the top of the request cap. Default
     *  {@link DISPATCH_STRUCTURAL_RESERVE_BYTES}. */
    structuralReserveBytes?: number;
    /** Sidecar per-request parts-array cap. Default {@link DISPATCH_MAX_PARTS}. */
    maxParts?: number;
}
/** Build dispatch parts from input by resolving mentions, paths, and applying size constraints asynchronously */
declare function buildDispatchParts(input: BuildDispatchPartsInput): Promise<DispatchPartsOutcome>;

/**
 * `promoteAgentFilePart` — turn a harness-emitted `type:"file"` stream part
 * into a store-backed {@link ChatAttachmentPart}. The harness hands back a URL
 * pointing at bytes it produced (a `data:` URI, or a path inside the sandbox);
 * nothing durable survives past the turn unless it is written into the
 * product's store, the same way a user upload is. Typed outcomes throughout:
 * every failure mode (unsupported scheme, no sandbox, oversize, store-write
 * failure, malformed part) resolves to `{ succeeded: false, filename, reason }`
 * rather than throwing past this boundary, so the caller folds a visible notice
 * instead of losing the file silently.
 *
 * Storage-parameterized port of gtm-agent's `promote-file-parts.ts` with the
 * refactor gtm never made: persistence goes through the injected
 * {@link WriteAttachmentFn} (gtm hard-wired its vault writer), the path strategy
 * is the injected `buildAttachmentPath` (neutral `uploads/agent/<date>/` default,
 * no domain bucket taxonomy baked), the MIME map is an injectable hook, and the
 * date segment reads an injectable clock. The idempotent `hash8(id ?? url ??
 * filename)` naming is preserved so re-promoting the same source part resolves
 * to the same path.
 */

/** Default ceiling on a promoted file's raw (pre-encoding) byte size. */
declare const PROMOTE_MAX_FILE_BYTES: number;
/** Define the structure for a raw file part with optional metadata and media type information */
interface RawAgentFilePart {
    type: 'file';
    id?: string;
    filename?: string;
    /** AI-SDK-shaped parts carry the MIME type here… */
    mediaType?: string;
    /** …but OpenCode's native FilePart calls the same field `mime`. */
    mime?: string;
    url?: string;
}
/** Resolve the result of promoting a file part with success status and relevant data or error details */
type PromoteFilePartResult = {
    succeeded: true;
    part: ChatAttachmentPart;
} | {
    succeeded: false;
    filename: string;
    reason: string;
};
/** Arguments handed to a {@link PromoteAgentFilePartOptions.buildAttachmentPath}
 *  override — everything needed to place the file deterministically. */
interface AttachmentPathArgs {
    /** Sanitized display filename (basename, safe charset). */
    filename: string;
    /** First 8 hex chars of the SHA-256 idempotency digest. */
    hash8: string;
    /** `YYYY-MM-DD` from the injected clock. */
    date: string;
    /** Resolved media type. */
    mediaType: string;
    /** `image`/`file` split of the media type. */
    kind: ChatAttachmentKind;
}
/** Default MIME hook: extension → mime, or `text/plain` for the unknown. */
declare function sniffMimeFromName(filename: string): string;
/** Define options for promoting a part of an agent file within a specific session and scope */
interface PromoteAgentFilePartOptions {
    raw: RawAgentFilePart;
    /** The turn's box — required only to promote a sandbox-path part; a `data:`
     *  URI needs none. */
    box?: SandboxExecChannel;
    /** The product's workspace/tenant key, passed to `writeAttachment`. */
    scopeId: string;
    /** The turn's session id, used for the sandbox stat/read exec calls. */
    sessionId: string;
    /** REQUIRED store writer — no default (the product owns its store). */
    writeAttachment: WriteAttachmentFn;
    /** Store-path strategy. Default {@link defaultBuildAttachmentPath}. */
    buildAttachmentPath?: (args: AttachmentPathArgs) => string;
    /** Raw-byte ceiling. Default {@link PROMOTE_MAX_FILE_BYTES}. */
    maxBytes?: number;
    /** Last-resort media-type hook. Default {@link sniffMimeFromName}. */
    sniffMime?: (filename: string) => string;
    /** Clock for the date path segment. Default `() => new Date()`. */
    now?: () => Date;
}
/** Promote a part of an agent file with optional byte limits and MIME type detection */
declare function promoteAgentFilePart(options: PromoteAgentFilePartOptions): Promise<PromoteFilePartResult>;

export { type AssistantDraftSnapshot, type AssistantDraftStore, type AssistantDraftWriter, type AssistantDraftWriterOptions, type AssistantRowValues, type AttachmentPathArgs, type AttachmentPathCheck, type AttachmentReadResult, type AttachmentUploadAuthorization, type AttachmentWriteResult, type BuildDispatchPartsInput, ChatAttachmentKind, type ChatRouteDurableProjection, type ChatRouteDurableProjectionLogger, type ChatRouteEvent, type ChatTurnAuthorization, type ChatTurnAuthorizeArgs, type ChatTurnCompleteInput, ChatTurnFilePartInput, type ChatTurnGateResult, type ChatTurnHeartbeat, type ChatTurnInputPatch, type ChatTurnLifecycle, type ChatTurnLifecycleComplete, type ChatTurnLifecycleError, type ChatTurnLifecycleStart, type ChatTurnLock, type ChatTurnLockResult, type ChatTurnMessageStore, type ChatTurnModelFailover, ChatTurnPartInput, type ChatTurnProduceArgs, ChatTurnRequestPayload, type ChatTurnRouteProducer, type ChatTurnRoutes, type ChatTurnUsage, type CreateAttachmentUploadRouteOptions, type CreateChatTurnRoutesOptions, type CreateUploadRouteOptions, type DetachedTurnFinal, type DetachedTurnOptions, type DetachedTurnParts, type DetachedTurnResult, type DispatchPartsOutcome, type DraftPersistenceTuning, type DraftStoredMessage, type EmptyTurnRetryInfo, type FilePartPromotionOutcome, MAX_EMPTY_TURN_RETRIES, type ModelFailoverStreamHandle, type ModelFailoverStreamOptions, type ModelFallbackInfo, type OpenModelStream, PROMOTE_MAX_FILE_BYTES, type PromoteAgentFilePartOptions, type PromoteFilePartResult, PromptInputPart, type RawAgentFilePart, type ReadAttachmentFn, type ReadSandboxMentionFn, type ResolveChatAttachmentsOptions, type ResolveChatAttachmentsResult, type SandboxChatProducerOptions, type SandboxUploadSink, UPLOAD_INLINE_MAX_BYTES, UPLOAD_MAX_FILE_BYTES, type UploadAuthorization, type UploadedChatFile, type WriteAttachmentFn, assistantRowIdForTurn, buildDispatchParts, bytesToBase64, classifyTerminalFailure, createAssistantDraftWriter, createAttachmentUploadRoute, createChatTurnRoutes, createSandboxChatProducer, createUploadRoute, defaultValidateAttachmentPath, isCommittingSandboxEvent, isDraftContentEvent, promoteAgentFilePart, resolveChatAttachments, resolveEmptyTurnRetries, rowIdOf, runDetachedTurn, sanitizeUploadFilename, sniffMimeFromName, storeSupportsDraftPersistence, streamWithModelFailover, withDurableChatProjection };
