import { defineChatMiddleware, fromSpecTokenUsage, getDetachableRun, InterruptResumeValidationError, LoadChildCapability, MetadataCapability, modelMessagesToUIMessages, provideLoadChild, provideMetadata, readInterruptBinding, validateInterruptResumeBatch, wasCancelRequested, } from '@tanstack/ai' import { createInterruptBinding, getGenericInterruptDefinitionRegistry, isActivityChunk, mergeActivityRecords, providePendingTurn, rehydrateInterruptRequest, toRunErrorPayload, } from '@tanstack/ai/adapter-internals' import type { GenericInterruptRequest, InterruptDefinition, } from '@tanstack/ai/adapter-internals' import { base64ToUint8Array } from '@tanstack/ai-utils' import { mergeMetadata, withTanstackMetadata } from '@tanstack/ai/client' import { InterruptsCapability, PersistenceCapability, PersistenceCompletionCapability, provideInterrupts, providePersistence, providePersistenceCompletion, } from './capabilities' import { hasReservedInterruptBinding, isChatOwnedPendingInterrupt, isPersistedInterruptDescriptor, warnIfUnboundToolInterrupt, } from './interrupt-ownership' import { mergeStoredMessages, storedCutoff } from './merge-stored' import { createSubagentRunRecorder } from './subagent-runs' import { validateChatPersistenceStores, validateGenerationPersistenceStores, } from './types' import type { AbortInfo, ActivityRecord, ChatMiddleware, ChatMiddlewareConfig, ChatMiddlewareContext, ChatResumeToolState, ErrorInfo, FinishInfo, GenerationAbortInfo, GenerationErrorInfo, GenerationFinishInfo, GenerationMiddleware, GenerationMiddlewareContext, ModelMessage, PendingInterruptResumeRecord, PersistedArtifactActivity, PersistedArtifactRef, PersistedArtifactRole, RunAgentResumeItem, StreamChunk, Tool, BilledUsage, TokenUsage, } from '@tanstack/ai' import type { AIPersistence, AIPersistenceStores, ArtifactRecord, BlobBody, ChatTranscriptStores, InterruptCommitEntry, InterruptRecord, InterruptStore, MessagePage, RunStore, } from './types' /** The durable resume check that chat() runs after its onConfig chain. */ const DURABLE_RESUME = Symbol.for('tanstack.ai.durableResume') /** * How generated media is turned into durable artifacts: which pieces of a * result become artifacts, what they are named, where their bytes land, and how * the bytes are fetched when the provider returns a URL rather than inline data. * * Consumed by {@link withGenerationPersistence} through * {@link WithGenerationPersistenceOptions}. Chat persistence has no artifacts — * its options are {@link WithPersistenceOptions}. */ export interface ArtifactPersistenceOptions { extractArtifacts?: ( input: GenerationArtifactExtractionInput, ) => | Array | Promise> nameArtifact?: (input: GenerationArtifactNameInput) => string /** * Map a freshly-persisted artifact ref to the durable app-origin URL that * serves its bytes (your `GET` route around `retrieveArtifact` / * `retrieveBlob`). The returned URL is stamped onto `ref.url` and written into * the result's media field, so both the live and the restored result render * durable media from your own origin instead of the provider's expiring link. * Return `undefined` to leave a ref without a durable URL. */ artifactUrl?: (ref: PersistedArtifactRef) => string | undefined /** * Choose the blob-store key each artifact's bytes are written under, so * generated media can land in your own folder structure rather than the * default `artifacts//`. * * ```ts * storageKey: ({ runId, artifactId, mimeType }) => * `video/${videoId}/frames/${runId}-${artifactId}.png` * ``` * * Server-side only, and deliberately so: a key supplied by the browser would * be a path-traversal and cross-tenant-write vector. * * The resolved key is recorded on `ArtifactRecord.blobKey`, because once the * path is arbitrary a reader can no longer recompute it. Returning a * non-unique key overwrites — include `artifactId` (or something equally * unique) unless you intend that. */ storageKey?: (input: { artifactId: string runId: string threadId: string role: PersistedArtifactRole activity: PersistedArtifactActivity path: string mimeType: string name: string }) => string /** * Opt in to fetching prompt media referenced by URL (`role: 'input'`). * * Off by default, and deliberately expressed as a predicate rather than a * boolean: input URLs come from the caller, so fetching them server-side * turns your server into a proxy for whatever the caller names — cloud * metadata endpoints, `localhost` admin services, anything your network can * reach. The bytes are also redundant in the common case, since the client * already had the media it referenced. * * Enable this only when you genuinely need a durable copy of caller-supplied * media (a "paste an image URL" input box, say), and validate the target: * * ```ts * allowInputUrl: ({ url }) => url.hostname.endsWith('.cdn.example.com') * ``` * * Requests are additionally forced through the same baseline checks every * artifact fetch gets (http/https only, timeout, size cap), plus — because * the target is untrusted — a loopback/private/link-local host block and * `redirect: 'manual'` so a 302 cannot hop to an internal address. Those are * a backstop, not a substitute for a narrow predicate: a hostname that * resolves to a private address still passes a literal-IP check. */ allowInputUrl?: (input: { url: URL descriptor: GenerationArtifactDescriptor }) => boolean | Promise /** Abort an artifact fetch after this many ms. Default 30_000. */ artifactFetchTimeoutMs?: number /** * Refuse an artifact body larger than this many bytes. Default 1 GiB. * * This is a bound on TRANSFER, not on memory: the URL path streams into the * blob store and never buffers, so a 1 GiB artifact costs a streaming store * (R2, S3, filesystem) flat memory. What the cap buys is a ceiling on what a * broken or hostile origin can make you pull and store — `content-length` is * advisory, so without it an artifact fetch is an unbounded transfer billed * to you. * * Pass `false` to remove the ceiling entirely. That also removes the * cap-enforcing `TransformStream` wrapper, so the fetched body reaches your * store exactly as `fetch` produced it — on workerd that means it keeps its * native declared length and `R2Bucket.put` can single-shot it with no hint, * no multipart, and nothing buffered. Do that when you trust the origins you * fetch from (your provider's CDN); keep the cap when `allowInputUrl` lets * callers name the URL. */ maxArtifactBytes?: number | false /** * `fetch` used to download artifact bytes. Defaults to the global. Inject to * route downloads through a proxy or an egress-restricted agent — the most * robust SSRF control available here, since it can resolve and check the * address actually connected to. */ artifactFetch?: typeof globalThis.fetch } /** * Options for {@link withGenerationPersistence}: everything in * {@link ArtifactPersistenceOptions}, plus an optional scope override. */ export interface WithGenerationPersistenceOptions extends ArtifactPersistenceOptions { /** * Override the scope runs are filed under. Defaults to the `threadId` you * passed the activity, which is normally what you want, so leave this unset * unless the record belongs somewhere other than the activity's own scope. */ threadId?: string } /** * The slot this generation's runs are filed under: `ctx.threadId` (the * `threadId` the caller passed the activity), or the option when it overrides. * * Throws when neither supplies one. A run filed under no scope can never be * hydrated by one, so `persistence: true` would restore nothing, forever. That * is worth failing loudly for, since the alternative is a silent hole a reader * cannot diagnose from behavior. */ function generationScope( ctx: GenerationMiddlewareContext, opts: WithGenerationPersistenceOptions, ): string { const threadId = opts.threadId ?? ctx.threadId if (threadId === undefined || threadId.length === 0) { throw new Error( 'Generation persistence requires a `threadId`, the stable scope successive ' + 'runs are filed under. Pass it to the activity, e.g. ' + '`generateImage({ threadId, middleware: [withGenerationPersistence(p)] })`, ' + 'or override it with `withGenerationPersistence(p, { threadId })`.', ) } return threadId } const DEFAULT_ARTIFACT_FETCH_TIMEOUT_MS = 30_000 // 1 GiB, because generated video clips routinely run to a few hundred MB and // the old 100 MiB default silently failed them. The cap is a drain-time // counter, not a buffer: the URL path streams into the store, so raising it // costs a streaming store nothing in memory. It still earns its keep as the // only ceiling on what a runaway or hostile origin can make you transfer and // store (`content-length` is advisory, and on a compressed reply it measures // the compressed body). `maxArtifactBytes: false` removes it — and the wrapper // with it, which is the zero-copy path onto workerd + R2. const DEFAULT_MAX_ARTIFACT_BYTES = 1024 * 1024 * 1024 export interface GenerationArtifactDescriptor { role: PersistedArtifactRole path: string mediaType?: PersistedArtifactRef['source']['mediaType'] mimeType?: string bytes?: BlobBody url?: string json?: unknown name?: string jobId?: string expiresAt?: string | Date } export interface GenerationArtifactExtractionInput { activity: PersistedArtifactActivity provider: string model: string threadId: string runId: string inputs: unknown result: unknown } export interface GenerationArtifactNameInput { descriptor: GenerationArtifactDescriptor activity: PersistedArtifactActivity provider: string model: string threadId: string runId: string index: number } interface RunStateEntry { merged: boolean interrupted: boolean /** * Ids of the new rows that this run saved before `onStart`. Their `index` * is not a stored place, so the reload cuts leave them out of the count. */ earlyActivityIds: Set /** * Activity ids that arrived on the request. Append placement is only for * rows emitted in `setup`, so these keep their inbound index. */ inboundActivityIds: Set /** * Resumes accepted in `onConfig` but not yet committed to the interrupt * store. They are applied (resolve/cancel) only once the run reaches a * successful boundary — see {@link commitPendingResumes}. Left uncommitted * (still pending in the store) if the run fails or aborts first. */ pendingResumes?: { pending: Array resumeByInterruptId: Map /** Non-subagent toolCallIds answered by this resume batch. */ resumedToolCallIds: Set } /** Interrupt ids claimed in-process for this run to stop concurrent double-resume. */ claimedInterruptIds?: Array /** Usage accumulated across every model call in this chat invocation. */ usage?: TokenUsage /** Accumulated terminal-turn text, for throttled streaming snapshots (B). */ streamingText?: string /** Epoch ms of the last streaming snapshot, to throttle writes (B). */ lastSnapshotAt?: number /** * The current assistant turn's stream messageId, captured from * `TEXT_MESSAGE_START`. Persisted onto the assistant message so its identity * survives the persist → hydrate round-trip and a reload can resume the same * bubble in place. */ streamingMessageId?: string streamingMessageCreatedAt?: Date /** Metadata of the current model call (source, response id), for snapshots. */ streamingMetadata?: Record /** Ids of the snapshot rows of the current model call. */ streamingMessageIds?: Set /** * Length of `ctx.messages` when this run started. Messages from this index * on are the ones this run added, so they get its run id on save (#1061). */ firstRunMessage?: number completion?: { promise: Promise resolve: () => void reject: (error: unknown) => void } } const runState = new WeakMap() const claimedByStore = new WeakMap>() function claimPendingInterrupts( store: InterruptStore, interruptIds: ReadonlyArray, ctx: Pick, interruptedRunId: string, ): void { if (interruptIds.length === 0) return let claimed = claimedByStore.get(store) if (!claimed) { claimed = new Set() claimedByStore.set(store, claimed) } const keys = interruptIds.map((id) => claimKey(ctx.threadId, id)) const conflicts = keys.filter((key) => claimed.has(key)) if (conflicts.length > 0) { throw new InterruptResumeValidationError([ { scope: 'batch', threadId: ctx.threadId, interruptedRunId, generation: 0, interruptIds: [...interruptIds], code: 'conflict', message: 'A resume for these pending interrupts is already in flight.', source: 'server', retryable: true, }, ]) } for (const key of keys) claimed.add(key) } /** Interrupt ids are unique per thread only, so a claim names both. */ function claimKey(threadId: string, interruptId: string): string { return JSON.stringify([threadId, interruptId]) } function releasePendingClaims( store: InterruptStore | undefined, threadId: string, interruptIds: ReadonlyArray | undefined, ): void { if (!store || !interruptIds?.length) return const claimed = claimedByStore.get(store) if (!claimed) return for (const id of interruptIds) claimed.delete(claimKey(threadId, id)) } function toolCallIdOfPendingRecord( interrupt: InterruptRecord, ): string | undefined { if (stringField(interrupt.payload, 'subagentRunId') !== undefined) { return undefined } if (isPersistedInterruptDescriptor(interrupt.payload)) { const binding = readInterruptBinding(interrupt.payload) if (binding && 'toolCallId' in binding) return binding.toolCallId } const topLevel = stringField(interrupt.payload, 'toolCallId') if (topLevel !== undefined) return topLevel const metadata = objectValue(interrupt.payload.metadata) const inner = objectValue(metadata?.['tanstack:interruptPayload']) return inner ? stringField(inner, 'toolCallId') : undefined } function isPendingExecutionToolMessage(message: ModelMessage): boolean { if ( message.role !== 'tool' || message.error !== undefined || typeof message.content !== 'string' ) { return false } try { const parsed: unknown = JSON.parse(message.content) return ( typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) && (parsed as Record).pendingExecution === true ) } catch { return false } } function stripStalePendingToolRows( messages: ReadonlyArray, pendingApprovalToolCallIds: ReadonlySet, pendingOwnedToolCallIds: ReadonlySet, ): Array { if ( pendingApprovalToolCallIds.size === 0 && pendingOwnedToolCallIds.size === 0 ) { return [...messages] } return messages.filter((message) => { if (message.role !== 'tool' || message.toolCallId === undefined) { return true } if (pendingApprovalToolCallIds.has(message.toolCallId)) return false if ( pendingOwnedToolCallIds.has(message.toolCallId) && isPendingExecutionToolMessage(message) ) { return false } return true }) } /** * Stored activity rows that sit before the reload cutoff. A reload drops the * old assistant turn, so its activity rows go too. The `early` rows of this * run have no stored place, so the count leaves them out and they stay. */ function keptActivities( records: Array, stored: Array, cutoff: number, early: ReadonlySet = new Set(), ): Array { if (cutoff >= stored.length) return records const keptUi = modelMessagesToUIMessages(stored.slice(0, cutoff)).length const isEarly = (record: ActivityRecord) => early.has(record.id) // `index` counts the earlier activity rows too, so subtract them. // ponytail: assumes one row per index, which is what chat() writes. return [ ...records .filter((record) => !isEarly(record)) .sort((a, b) => a.index - b.index) .filter((record, earlier) => record.index - earlier < keptUi), ...records.filter(isEarly), ] } /** * How many stored messages the incoming history still has, for the activity * rows. It starts at `storedCutoff`. A stored message after that still counts * when the incoming history has its tool call or its tool result: the client * and the store can give that message different ids, or none. Without this, * a turn that ends with a tool call looks like a reload, and its rows go. */ function activityCutoff( stored: ReadonlyArray, incoming: ReadonlyArray, ): number { const callIds = new Set( incoming.flatMap((message) => [ ...(message.toolCalls ?? []).map((call) => call.id), ...(message.role === 'tool' && message.toolCallId !== undefined ? [message.toolCallId] : []), ]), ) const hasCall = (message: ModelMessage) => (message.role === 'tool' && message.toolCallId !== undefined && callIds.has(message.toolCallId)) || (message.toolCalls ?? []).some((call) => callIds.has(call.id)) let cutoff = storedCutoff(stored, incoming) for (const message of stored.slice(cutoff)) { if (!hasCall(message)) break cutoff++ } return cutoff } /** * Give the early rows of this run their place after the stored thread. A * client sends no activity rows, and `chat()` places a row that comes before * `onConfig` from the request only. So the `index` of an early row is too * small. Each early row goes after the messages and the other rows, in the * order of its own `index`. */ function placeEarlyActivities( records: Array, messages: Array, isEarly: (record: ActivityRecord) => boolean, ): Array { const early = records.filter(isEarly).sort((a, b) => a.index - b.index) let index = modelMessagesToUIMessages(messages).length + records.length - early.length const places = new Map(early.map((record) => [record.id, index++])) return records.map((record) => { const place = places.get(record.id) return place === undefined ? record : { ...record, index: place } }) } /** * Shift a new inbound row by the stored messages and activity rows that sit * before the incoming transcript. Setup rows (`isEarly`) keep the append * placement from {@link placeEarlyActivities}. */ function rebaseInboundActivities( records: Array, storedIds: ReadonlySet, isEarly: (record: ActivityRecord) => boolean, extraIndex: number, ): Array { if (extraIndex === 0) return records return records.map((record) => storedIds.has(record.id) || isEarly(record) ? record : { ...record, index: record.index + extraIndex }, ) } /** Stored UI messages and activity rows that precede the incoming transcript. */ function inboundActivityOffset( mergedMessages: Array, incomingMessages: ReadonlyArray, storedActivities: ReadonlyArray, incomingActivities: ReadonlyArray, ): number { const extraUi = modelMessagesToUIMessages([...mergedMessages]).length - modelMessagesToUIMessages([...incomingMessages]).length const incomingIds = new Set(incomingActivities.map((record) => record.id)) const extraActivities = storedActivities.filter( (record) => !incomingIds.has(record.id), ).length return extraUi + extraActivities } /** `metadata.tanstack.run.id` of a stored message, when set. */ function runTagOf(message: ModelMessage): string | undefined { const tanstack: unknown = message.metadata?.tanstack if (typeof tanstack !== 'object' || tanstack === null) return const run: unknown = (tanstack as { run?: unknown }).run if (typeof run !== 'object' || run === null) return const id: unknown = (run as { id?: unknown }).id return typeof id === 'string' && id !== '' ? id : undefined } function withRunTag(message: ModelMessage, runId: string): ModelMessage { const metadata = message.metadata ?? {} const tanstack: unknown = metadata.tanstack return { ...message, metadata: { ...metadata, tanstack: { ...(typeof tanstack === 'object' && tanstack !== null ? tanstack : {}), run: { id: runId }, }, }, } } /** * The thread to save, with this run's id on the assistant messages it added * (`metadata.tanstack.run.id`). `reconstructChat` uses it to match each * message to its run. Messages from earlier runs are left as they are. */ function runMessages( ctx: ChatMiddlewareContext, state: RunStateEntry | undefined, ): Array { const from = state?.firstRunMessage if (from === undefined) return [...ctx.messages] return ctx.messages.map((message, index) => index >= from && message.role === 'assistant' && runTagOf(message) === undefined ? withRunTag(message, ctx.runId) : message, ) } const validResumeStatuses = new Set(['resolved', 'cancelled']) function rejectMixedRunPending( pending: Array, ctx: Pick, ): void { const runIds = new Set(pending.map((interrupt) => interrupt.runId)) if (runIds.size <= 1) return throw new InterruptResumeValidationError([ { scope: 'batch', threadId: ctx.threadId, interruptedRunId: ctx.runId, generation: 0, interruptIds: pending.map((interrupt) => interrupt.interruptId), code: 'stale', message: 'Thread has pending interrupts from more than one run.', source: 'server', retryable: false, }, ]) } /** * The pending records this run answers itself. A record that a child raised * names that child in `subagentRunId`. The engine splits the resume with the * subagent cards that the client sent (`ctx.childResumeIds`). That split must * match the stored records, or a forged card could move an interrupt between * the parent and a child. */ function rejectForgedChildSplit( pending: Array, ctx: Pick, ): Array { const childIds = pending .filter((interrupt) => stringField(interrupt.payload, 'subagentRunId')) .map((interrupt) => interrupt.interruptId) const claimed = ctx.childResumeIds ?? new Set() if ( claimed.size !== childIds.length || childIds.some((id) => !claimed.has(id)) ) { throw new InterruptResumeValidationError([ { scope: 'batch', threadId: ctx.threadId, interruptedRunId: pending[0]?.runId ?? ctx.runId, generation: 0, interruptIds: pending.map((interrupt) => interrupt.interruptId), code: 'conflict', message: 'The subagent cards in the messages do not match the stored subagent interrupts.', source: 'client', retryable: false, }, ]) } return pending.filter((interrupt) => !claimed.has(interrupt.interruptId)) } function validatePendingResumes( pending: Array, resume: Array | undefined, ctx: Pick, ): Map { const interruptedRunId = pending[0]?.runId ?? ctx.runId const failure = ( interruptId: string, code: 'conflict' | 'unknown-interrupt', message: string, ): never => { throw new InterruptResumeValidationError([ { scope: 'item', threadId: ctx.threadId, interruptedRunId, generation: 0, interruptId, code, message, source: 'client', retryable: false, }, { scope: 'batch', threadId: ctx.threadId, interruptedRunId, generation: 0, interruptIds: pending.map((interrupt) => interrupt.interruptId), code: code === 'conflict' ? 'conflict' : 'incomplete-batch', message: 'Resume entries must resolve or cancel the complete interrupt batch.', source: 'client', retryable: false, }, ]) } const pendingInterruptIds = new Set( pending.map((interrupt) => interrupt.interruptId), ) const resumeByInterruptId = new Map() for (const entry of resume ?? []) { if (resumeByInterruptId.has(entry.interruptId)) { return failure( entry.interruptId, 'conflict', `Interrupt ${entry.interruptId} has duplicate resume entries.`, ) } resumeByInterruptId.set(entry.interruptId, entry) } if (pending.length === 0) { const staleEntry = resume?.[0] if (staleEntry) { return failure( staleEntry.interruptId, 'unknown-interrupt', `Resume entry references non-pending interrupt ${staleEntry.interruptId}.`, ) } return resumeByInterruptId } const firstPending = pending[0] if (firstPending === undefined) return resumeByInterruptId if (!resume || resume.length === 0) { return failure( firstPending.interruptId, 'unknown-interrupt', `Thread has pending interrupts; resume is required before accepting new input.`, ) } const bindingKindOf = (interrupt: InterruptRecord) => isPersistedInterruptDescriptor(interrupt.payload) ? readInterruptBinding(interrupt.payload)?.kind : undefined const hasPendingGeneric = pending.some( (interrupt) => bindingKindOf(interrupt) === 'generic', ) const allPendingGenericAnswered = hasPendingGeneric && pending.every((interrupt) => { if (bindingKindOf(interrupt) !== 'generic') return true const entry = resumeByInterruptId.get(interrupt.interruptId) return entry !== undefined && validResumeStatuses.has(entry.status) }) for (const interrupt of pending) { const entry = resumeByInterruptId.get(interrupt.interruptId) if (!entry) { // Match core's validateInterruptResumeBatch: when generic interrupts are // all answered, client-tool-execution interrupts in the same batch may be // omitted and either re-emitted or cancelled after generic resolution. if ( allPendingGenericAnswered && bindingKindOf(interrupt) === 'client-tool-execution' ) { continue } return failure( interrupt.interruptId, 'unknown-interrupt', `Missing resume entry for pending interrupt ${interrupt.interruptId}.`, ) } if (!validResumeStatuses.has(entry.status)) { return failure( interrupt.interruptId, 'unknown-interrupt', `Invalid resume status for pending interrupt ${interrupt.interruptId}: ${entry.status}.`, ) } } for (const entry of resume) { if (!pendingInterruptIds.has(entry.interruptId)) { return failure( entry.interruptId, 'unknown-interrupt', `Resume entry references non-pending interrupt ${entry.interruptId}.`, ) } } return resumeByInterruptId } async function applyPendingResumes( pending: Array, resumeByInterruptId: Map, interrupts: NonNullable, keepPendingIds?: ReadonlySet, ): Promise> { const entries: Array = [] for (const interrupt of pending) { if (keepPendingIds?.has(interrupt.interruptId)) continue const entry = resumeByInterruptId.get(interrupt.interruptId) if (entry?.status === 'resolved') { entries.push({ interruptId: interrupt.interruptId, status: 'resolved', response: entry.payload, }) } else { entries.push({ interruptId: interrupt.interruptId, status: 'cancelled', }) } } if (entries.length === 0) return [] const committedIds = entries.map((entry) => entry.interruptId) if (interrupts.commitBatch) { await interrupts.commitBatch(entries) return committedIds } const ids = new Set() for (const entry of entries) { if (ids.has(entry.interruptId)) { throw new Error( `Interrupt batch contains duplicate id: ${entry.interruptId}.`, ) } ids.add(entry.interruptId) const existing = await interrupts.get(entry.interruptId) if (!existing) { throw new Error( `Interrupt batch references missing id: ${entry.interruptId}.`, ) } if (existing.status !== 'pending') { throw new Error( `Interrupt batch references non-pending id: ${entry.interruptId}.`, ) } } for (const entry of entries) { if (entry.status === 'resolved') { await interrupts.resolve(entry.interruptId, entry.response) } else { await interrupts.cancel(entry.interruptId) } } return committedIds } /** * Commit the resumes stashed in `onConfig`, marking each resumed interrupt * resolved/cancelled. Called only from success boundaries (`beforeModel` after * tools finish, `onFinish`, and the `onChunk` interrupt boundary) so a provider * failure or abort before tools run leaves interrupts pending for retry. */ async function commitPendingResumes( state: RunStateEntry | undefined, interrupts: AIPersistence['stores']['interrupts'], keepPendingIds?: ReadonlySet, ): Promise> { if (!state?.pendingResumes || !interrupts) return [] const { pending, resumeByInterruptId } = state.pendingResumes // Apply first; only clear the in-memory stash after every resolve/cancel // succeeds so a mid-loop store failure can still re-drive remaining ids // if the hook is retried (or a later boundary re-enters commit). const committedIds = await applyPendingResumes( pending, resumeByInterruptId, interrupts, keepPendingIds, ) const threadId = pending[0]?.threadId if (threadId !== undefined) { releasePendingClaims(interrupts, threadId, committedIds) } if (state.claimedInterruptIds) { const committedSet = new Set(committedIds) state.claimedInterruptIds = state.claimedInterruptIds.filter( (id) => !committedSet.has(id), ) } state.pendingResumes = undefined return committedIds } function objectValue(value: unknown): Record | null { return value && typeof value === 'object' ? (value as Record) : null } function stringField( value: Record, key: string, ): string | undefined { return typeof value[key] === 'string' ? value[key] : undefined } function durableGenericFailure( ctx: Pick, persisted: InterruptRecord, message: string, ): InterruptResumeValidationError { return new InterruptResumeValidationError([ { scope: 'item', threadId: ctx.threadId, interruptedRunId: persisted.runId || ctx.runId, generation: 0, interruptId: persisted.interruptId, code: 'stale', message, source: 'server', retryable: false, }, { scope: 'batch', threadId: ctx.threadId, interruptedRunId: persisted.runId || ctx.runId, generation: 0, interruptIds: [persisted.interruptId], code: 'item-validation-failed', message: 'One or more persisted interrupt records are invalid.', source: 'server', retryable: false, }, ]) } const APPROVAL_CONTEXT = 'tanstack:approvalContext' type ApprovalContext = { v: 1 approvalInterruptId: string approvalRunId: string generation: number toolCallId: string toolName: string inputSchemaHash: string approvalSchemaHash: string responseSchemaHash: string } function readApprovalContext(value: unknown): ApprovalContext | undefined { const record = objectValue(value) const fields = [ 'v', 'approvalInterruptId', 'approvalRunId', 'generation', 'toolCallId', 'toolName', 'inputSchemaHash', 'approvalSchemaHash', 'responseSchemaHash', ] if ( !record || Array.isArray(value) || Object.keys(record).length !== fields.length || fields.some((key) => !Object.hasOwn(record, key)) ) return undefined const { v, approvalInterruptId, approvalRunId, generation, toolCallId, toolName, inputSchemaHash, approvalSchemaHash, responseSchemaHash, } = record if ( v !== 1 || typeof generation !== 'number' || !Number.isSafeInteger(generation) || generation < 0 || typeof approvalInterruptId !== 'string' || !approvalInterruptId || typeof approvalRunId !== 'string' || !approvalRunId || typeof toolCallId !== 'string' || !toolCallId || typeof toolName !== 'string' || !toolName || typeof inputSchemaHash !== 'string' || !inputSchemaHash || typeof approvalSchemaHash !== 'string' || !approvalSchemaHash || typeof responseSchemaHash !== 'string' || !responseSchemaHash ) return undefined return { v, approvalInterruptId, approvalRunId, generation, toolCallId, toolName, inputSchemaHash, approvalSchemaHash, responseSchemaHash, } } function clientInterruptPayload( interrupt: unknown, state: RunStateEntry | undefined, ): Record { const payload = interruptPayload(interrupt) if (!isPersistedInterruptDescriptor(payload)) return payload const client = readInterruptBinding(payload) if (client?.kind !== 'client-tool-execution') return payload const metadata = { ...objectValue(payload.metadata) } delete metadata[APPROVAL_CONTEXT] for (const previous of state?.pendingResumes?.pending ?? []) { if (!isPersistedInterruptDescriptor(previous.payload)) continue const binding = readInterruptBinding(previous.payload) const resume = state?.pendingResumes?.resumeByInterruptId.get( previous.interruptId, ) const decision = objectValue(resume?.payload) if ( binding?.kind !== 'tool-approval' || binding.toolCallId !== client.toolCallId || binding.toolName !== client.toolName || binding.generation !== client.generation || resume?.status !== 'resolved' || (resume.payload !== true && decision?.approved !== true) ) continue const context: ApprovalContext = { v: 1, approvalInterruptId: previous.interruptId, approvalRunId: previous.runId, generation: binding.generation, toolCallId: binding.toolCallId, toolName: binding.toolName, inputSchemaHash: binding.inputSchemaHash, approvalSchemaHash: binding.approvalSchemaHash, responseSchemaHash: binding.responseSchemaHash, } metadata[APPROVAL_CONTEXT] = context break } return { ...payload, metadata } } async function durableGenericResumeState( ctx: ChatMiddlewareContext, pending: Array, resume: ReadonlyArray, tools: Array, interrupts: InterruptStore, ): Promise { const registry = getGenericInterruptDefinitionRegistry(ctx, { optional: true, }) const records: Array = [] for (const persisted of pending) { if (!isPersistedInterruptDescriptor(persisted.payload)) { if (hasReservedInterruptBinding(persisted.payload)) { throw durableGenericFailure( ctx, persisted, `Persisted interrupt ${persisted.interruptId} has an invalid binding descriptor.`, ) } continue } const descriptor = persisted.payload const binding = readInterruptBinding(descriptor) if (!binding) { if (hasReservedInterruptBinding(descriptor)) { throw durableGenericFailure( ctx, persisted, `Persisted interrupt ${persisted.interruptId} has an invalid or incomplete binding.`, ) } continue } if ( descriptor.id !== persisted.interruptId || binding.interruptId !== persisted.interruptId || binding.interruptedRunId !== persisted.runId || binding.generation !== 0 ) { throw durableGenericFailure( ctx, persisted, `Persisted interrupt ${persisted.interruptId} has stale correlation metadata.`, ) } if (binding.kind !== 'generic') { records.push({ interruptId: persisted.interruptId, payload: descriptor, binding, }) continue } if ( !binding.definitionId || !binding.key || binding.batchIndex === undefined ) { records.push({ interruptId: persisted.interruptId, payload: descriptor, binding, }) continue } if (!registry) { throw durableGenericFailure( ctx, persisted, `Persisted generic interrupt ${persisted.interruptId} cannot be restored because no interrupt registry is available.`, ) } const definition = registry.definitions.get(binding.definitionId) if (!definition) { throw durableGenericFailure( ctx, persisted, `Persisted generic interrupt definition ${binding.definitionId} is unavailable.`, ) } const metadata = objectValue(descriptor.metadata) const payload = metadata?.['tanstack:interruptPayload'] let request: GenericInterruptRequest< InterruptDefinition > try { request = rehydrateInterruptRequest(definition, { key: binding.key, reason: descriptor.reason, message: descriptor.message, ...(descriptor.expiresAt !== undefined ? { expiresAt: descriptor.expiresAt } : {}), ...(payload !== undefined ? { payload } : {}), }) } catch (error) { throw durableGenericFailure( ctx, persisted, `Persisted generic interrupt ${persisted.interruptId} is invalid: ${error instanceof Error ? error.message : String(error)}`, ) } const emitted = createInterruptBinding(request, { batchIndex: binding.batchIndex, }) if ( emitted.descriptor.responseSchemaHash !== binding.responseSchemaHash || emitted.descriptor.payloadSchemaHash !== binding.payloadSchemaHash || binding.interruptId !== persisted.interruptId ) { throw durableGenericFailure( ctx, persisted, `Persisted generic interrupt ${persisted.interruptId} is stale.`, ) } records.push({ interruptId: persisted.interruptId, payload: descriptor, binding, genericRequest: request, }) } const firstRecord = records[0] if (firstRecord === undefined) return undefined const interruptedRunId = firstRecord.binding.interruptedRunId const generation = firstRecord.binding.generation const validated = await validateInterruptResumeBatch({ threadId: ctx.threadId, interruptedRunId, generation, pending: records, resume: resume.filter((entry) => records.some((record) => record.interruptId === entry.interruptId), ), tools, }) if (validated.errors.length > 0 || !validated.resumeToolState) { throw new InterruptResumeValidationError(validated.errors) } const approvals = new Map(validated.resumeToolState.approvals) for (const record of records) { if (record.binding.kind !== 'client-tool-execution') continue const entry = resume.find((item) => item.interruptId === record.interruptId) // Skip prior-approval checks when this client tool is cancelled or omitted // from a mixed generic batch so cancellation works after approval expiry. if (!entry || entry.status === 'cancelled') continue const toolName = record.binding.toolName const tool = tools.find((candidate) => candidate.name === toolName) if (!tool?.needsApproval) continue const metadata = objectValue(objectValue(record.payload)?.metadata) const hasContext = !!metadata && Object.hasOwn(metadata, APPROVAL_CONTEXT) const context = hasContext ? readApprovalContext(metadata?.[APPROVAL_CONTEXT]) : undefined const previous = await interrupts.get( context?.approvalInterruptId ?? `approval_${record.binding.toolCallId}`, ) const isMatch = !!previous && previous.status === 'resolved' && previous.threadId === ctx.threadId && (hasContext ? !!context && context.approvalRunId === previous.runId : previous.runId === record.binding.interruptedRunId) && isPersistedInterruptDescriptor(previous.payload) // A record with no approval context (written before this binding, or by // a path that does not add it) resumes as it did before. if (!hasContext && !isMatch) continue if ( !previous || !isMatch || !isPersistedInterruptDescriptor(previous.payload) ) { const persisted = pending.find( (entry) => entry.interruptId === record.interruptId, ) if (!persisted) throw new Error( `Missing persisted client interrupt ${record.interruptId}`, ) throw durableGenericFailure( ctx, persisted, `Client tool ${record.binding.toolName} has no matching resolved approval.`, ) } const binding = readInterruptBinding(previous.payload) if ( !binding || binding.kind !== 'tool-approval' || binding.toolCallId !== record.binding.toolCallId || binding.toolName !== record.binding.toolName || previous.payload.id !== previous.interruptId || binding.interruptedRunId !== previous.runId || binding.generation !== record.binding.generation || binding.interruptId !== previous.interruptId || (hasContext && (!context || context.approvalInterruptId !== previous.interruptId || context.toolCallId !== binding.toolCallId || context.toolName !== binding.toolName || context.generation !== binding.generation || context.inputSchemaHash !== binding.inputSchemaHash || context.approvalSchemaHash !== binding.approvalSchemaHash || context.responseSchemaHash !== binding.responseSchemaHash)) ) { throw durableGenericFailure( ctx, previous, `Client tool ${record.binding.toolName} has a stale resolved approval.`, ) } const restored = await validateInterruptResumeBatch({ threadId: ctx.threadId, interruptedRunId: binding.interruptedRunId, generation: binding.generation, pending: [ { interruptId: previous.interruptId, payload: previous.payload, binding, }, ], resume: [ { interruptId: previous.interruptId, status: 'resolved', payload: previous.response, }, ], tools, ...(previous.resolvedAt !== undefined ? { now: previous.resolvedAt } : {}), }) if (restored.errors.length > 0 || !restored.resumeToolState) throw new InterruptResumeValidationError(restored.errors) const decision = restored.resumeToolState.approvals?.get(binding.toolCallId) if ( decision !== true && (typeof decision !== 'object' || !decision.approved) ) throw durableGenericFailure( ctx, previous, `Client tool ${record.binding.toolName} was not approved.`, ) approvals.set(binding.toolCallId, decision) } type GenericRecord = PendingInterruptResumeRecord & { binding: Extract< PendingInterruptResumeRecord['binding'], { kind: 'generic' } > genericRequest: GenericInterruptRequest< InterruptDefinition > } const isGenericRecord = ( record: PendingInterruptResumeRecord, ): record is GenericRecord => record.binding.kind === 'generic' && record.genericRequest !== undefined const genericRecords: Array<{ record: GenericRecord; batchIndex: number }> = [] const batchIndexes = new Set() for (const record of records) { if (!isGenericRecord(record)) continue const batchIndex = record.binding.batchIndex if (batchIndex === undefined || batchIndexes.has(batchIndex)) { throw new InterruptResumeValidationError([ { scope: 'batch', threadId: ctx.threadId, interruptedRunId, generation, interruptIds: records.map((item) => item.interruptId), code: 'stale', message: 'Persisted generic interrupts have duplicate or invalid batch indexes.', source: 'server', retryable: false, }, ]) } batchIndexes.add(batchIndex) genericRecords.push({ record, batchIndex }) } genericRecords.sort((left, right) => left.batchIndex - right.batchIndex) return { ...validated.resumeToolState, approvals, genericInterruptRequests: new Map( genericRecords.flatMap(({ record }) => record.genericRequest ? [[record.interruptId, record.genericRequest] as const] : [], ), ), } } function interruptPayload(interrupt: unknown): Record { return interrupt && typeof interrupt === 'object' ? { ...(interrupt as Record) } : { value: interrupt } } // --------------------------------------------------------------------------- // Generation artifact extraction / persistence // --------------------------------------------------------------------------- function isArtifactRef(value: unknown): value is PersistedArtifactRef { const record = objectValue(value) return !!record && typeof record.artifactId === 'string' } function mediaActivity( activity: GenerationMiddlewareContext['activity'], ): PersistedArtifactActivity | undefined { return activity === 'image' || activity === 'audio' || activity === 'tts' || activity === 'video' || activity === 'transcription' ? activity : undefined } function parseDataUrl( value: string, ): { mimeType: string; bytes: Uint8Array } | undefined { const match = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(value) if (!match) return undefined const mimeType = match[1] || 'application/octet-stream' const raw = match[3] ?? '' // A plain (non-base64) data URL may carry a bare `%` (`data:text/plain,100%`), // which makes `decodeURIComponent` throw. Fall back to the literal payload so // a malformed escape doesn't fail the whole generation. let payload: string try { payload = decodeURIComponent(raw) } catch { payload = raw } return { mimeType, bytes: match[2] ? base64ToUint8Array(payload) : new TextEncoder().encode(payload), } } function extensionForMime(mimeType: string | undefined): string { if (mimeType === undefined) return 'bin' switch (mimeType) { case 'image/png': return 'png' case 'image/jpeg': return 'jpg' case 'audio/wav': return 'wav' case 'audio/mpeg': return 'mp3' case 'audio/mp3': return 'mp3' case 'video/mp4': return 'mp4' case 'application/json': return 'json' default: return 'bin' } } /** * The DEFAULT blob-store key a generation artifact's bytes are stored under, * used when `withGenerationPersistence` is given no `storageKey` mapper. * * Reads use the record's `blobKey` instead: a record written with a custom * `storageKey` carries its real key there, and recomputing the default would * look in the wrong place. */ function artifactBlobKey( ref: Pick, ): string { return `artifacts/${ref.runId}/${ref.artifactId}` } function defaultArtifactName( descriptor: GenerationArtifactDescriptor, activity: PersistedArtifactActivity, index: number, ): string { const ext = extensionForMime(descriptor.mimeType) return `${activity}-${descriptor.role}-${descriptor.mediaType ?? 'artifact'}-${index}.${ext}` } function sourcePartDescriptors( part: unknown, role: PersistedArtifactRole, path: string, ): Array { const record = objectValue(part) const type = stringField(record ?? {}, 'type') const source = objectValue(record?.source) if ( !record || !source || (type !== 'image' && type !== 'audio' && type !== 'video') ) { return [] } const sourceType = stringField(source, 'type') const mimeType = stringField(source, 'mimeType') ?? `${type}/mpeg` if (sourceType === 'data') { const value = stringField(source, 'value') if (!value) return [] return [ { role, path, mediaType: type, mimeType, bytes: base64ToUint8Array(value), }, ] } if (sourceType === 'url') { const value = stringField(source, 'value') if (!value) return [] return [{ role, path, mediaType: type, mimeType, url: value }] } return [] } function promptInputDescriptors( inputs: unknown, ): Array { const prompt = objectValue(inputs)?.prompt if (!Array.isArray(prompt)) return [] const counts: Record = { image: 0, audio: 0, video: 0 } const descriptors: Array = [] for (const part of prompt) { const type = stringField(objectValue(part) ?? {}, 'type') if (type !== 'image' && type !== 'audio' && type !== 'video') continue const index = counts[type] ?? 0 counts[type] = index + 1 descriptors.push( ...sourcePartDescriptors(part, 'input', `prompt.${type}s.${index}`), ) } return descriptors } function generatedMediaDescriptor(args: { role: PersistedArtifactRole path: string mediaType: 'image' | 'audio' | 'video' mimeType: string media: unknown jobId?: string expiresAt?: string | Date }): GenerationArtifactDescriptor | undefined { const media = objectValue(args.media) if (!media) return undefined const b64Json = stringField(media, 'b64Json') if (b64Json) { return { role: args.role, path: args.path, mediaType: args.mediaType, mimeType: stringField(media, 'contentType') ?? args.mimeType, bytes: base64ToUint8Array(b64Json), jobId: args.jobId, expiresAt: args.expiresAt, } } const url = stringField(media, 'url') if (url) { return { role: args.role, path: args.path, mediaType: args.mediaType, mimeType: stringField(media, 'contentType') ?? args.mimeType, url, jobId: args.jobId, expiresAt: args.expiresAt, } } return undefined } function builtInArtifactDescriptors( activity: PersistedArtifactActivity, inputs: unknown, result: unknown, ): Array { const descriptors = promptInputDescriptors(inputs) const output = objectValue(result) if (!output) return descriptors if (activity === 'image' && Array.isArray(output.images)) { output.images.forEach((image, index) => { const descriptor = generatedMediaDescriptor({ role: 'output', path: `images.${index}`, mediaType: 'image', mimeType: 'image/png', media: image, }) if (descriptor) descriptors.push(descriptor) }) } if (activity === 'audio') { const descriptor = generatedMediaDescriptor({ role: 'output', path: 'audio', mediaType: 'audio', mimeType: 'audio/mpeg', media: output.audio, }) if (descriptor) descriptors.push(descriptor) } if (activity === 'tts') { const audio = stringField(output, 'audio') if (audio) { const format = stringField(output, 'format') descriptors.push({ role: 'output', path: 'audio', mediaType: 'audio', mimeType: stringField(output, 'contentType') ?? (format ? `audio/${format}` : 'audio/mpeg'), bytes: base64ToUint8Array(audio), }) } } if (activity === 'video' && output.body instanceof ReadableStream) { // Provider bytes with no URL: stream them straight into the blob store. descriptors.push({ role: 'output', path: 'video', mediaType: 'video', mimeType: stringField(output, 'contentType') ?? 'video/mp4', bytes: output.body, jobId: stringField(output, 'jobId'), }) } else if (activity === 'video' && typeof output.url === 'string') { descriptors.push({ role: 'output', path: 'video', mediaType: 'video', mimeType: 'video/mp4', url: output.url, jobId: stringField(output, 'jobId'), expiresAt: output.expiresAt instanceof Date ? output.expiresAt : undefined, }) } if (activity === 'transcription') { const audio = objectValue(inputs)?.audio if (typeof audio === 'string') { const data = parseDataUrl(audio) descriptors.push({ role: 'input', path: 'audio', mediaType: 'audio', mimeType: data?.mimeType ?? 'audio/mpeg', bytes: data?.bytes ?? base64ToUint8Array(audio), }) } else if (audio instanceof ArrayBuffer) { descriptors.push({ role: 'input', path: 'audio', mediaType: 'audio', mimeType: 'audio/mpeg', bytes: audio.slice(0), }) } else if (typeof Blob !== 'undefined' && audio instanceof Blob) { descriptors.push({ role: 'input', path: 'audio', mediaType: 'audio', mimeType: audio.type || 'audio/mpeg', bytes: audio, }) } if (Array.isArray(output.segments) || Array.isArray(output.words)) { descriptors.push({ role: 'output', path: 'transcription', mediaType: 'json', mimeType: 'application/json', json: output, }) } } return descriptors } /** * Reject hosts that only make sense as an SSRF target: loopback, link-local * (including the cloud metadata address), private, and unique-local ranges. * * Applied to caller-supplied input URLs only. Provider result URLs skip it on * purpose — a self-hosted or local provider legitimately returns a `localhost` * URL, and those live inside the same trust boundary as the adapter itself. * * This checks IP *literals*. A hostname that resolves to a private address * passes, which is why `allowInputUrl` is required rather than optional. */ function isBlockedInputHost(hostname: string): boolean { const host = hostname.toLowerCase().replace(/^\[|\]$/g, '') if (host === 'localhost' || host.endsWith('.localhost')) return true const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host) if (ipv4) { const [a, b] = [Number(ipv4[1]), Number(ipv4[2])] if (a === 127 || a === 0 || a === 10) return true if (a === 169 && b === 254) return true // link-local + cloud metadata if (a === 172 && b >= 16 && b <= 31) return true if (a === 192 && b === 168) return true return false } if (host === '::' || host === '::1') return true if (host.startsWith('fe80:')) return true // link-local if (/^f[cd][0-9a-f]{2}:/.test(host)) return true // unique-local // IPv4-mapped IPv6 — re-check the embedded address. `new URL()` normalizes // `::ffff:127.0.0.1` to the hex form `::ffff:7f00:1`, so accept both. const mappedDotted = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec( host, ) if (mappedDotted?.[1]) return isBlockedInputHost(mappedDotted[1]) const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host) if (mappedHex?.[1] && mappedHex[2]) { const high = Number.parseInt(mappedHex[1], 16) const low = Number.parseInt(mappedHex[2], 16) return isBlockedInputHost( `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`, ) } return false } /** * Fail the stream once more than `maxBytes` have passed through, so an * unexpectedly huge artifact can't fill the blob store. * * Only used when the response does NOT already bound itself — a chunked reply, * or a content-encoded one whose declared length describes the compressed * bytes. When `content-length` describes the body the store will drain, HTTP * framing is the bound and wrapping would only cost the caller the declared * length: a `TransformStream`'s readable side carries none, which is what * pushes a length-strict runtime (workerd + R2) onto a multipart upload. */ function capBodySize( body: ReadableStream, maxBytes: number, url: string, ): ReadableStream { let seen = 0 return body.pipeThrough( new TransformStream({ transform(chunk, controller) { seen += chunk.byteLength if (seen > maxBytes) { controller.error( new Error( `Artifact at ${url} exceeds maxArtifactBytes (${maxBytes}).`, ), ) return } controller.enqueue(chunk) }, }), ) } /** * Resolve a descriptor to the bytes to store. Returns `undefined` when the * descriptor is deliberately not persisted — today that means a caller-supplied * input URL without an `allowInputUrl` opt-in. */ async function descriptorBody( descriptor: GenerationArtifactDescriptor, opts: ArtifactPersistenceOptions | undefined, ): Promise< | { body: BlobBody size: number /** * Exact byte length of a streamed body, when the origin declared one * that survives decoding — forwarded to `BlobStore.put` as * `BlobPutOptions.expectedLength`. Undefined when unknown. */ expectedLength?: number mimeType: string sourceUrl?: string } | undefined > { if (descriptor.json !== undefined) { const body = JSON.stringify(descriptor.json) return { body, size: new TextEncoder().encode(body).byteLength, mimeType: descriptor.mimeType ?? 'application/json', } } if (descriptor.bytes !== undefined) { const body = descriptor.bytes let size: number if (typeof body === 'string') { size = new TextEncoder().encode(body).byteLength } else if (body instanceof ArrayBuffer) { size = body.byteLength } else if (ArrayBuffer.isView(body)) { size = body.byteLength } else if (typeof Blob !== 'undefined' && body instanceof Blob) { size = body.size } else { size = 0 } return { body, size, mimeType: descriptor.mimeType ?? 'application/octet-stream', } } if (descriptor.url) { const data = parseDataUrl(descriptor.url) if (data) { return { body: data.bytes, size: data.bytes.byteLength, mimeType: descriptor.mimeType ?? data.mimeType, } } // A caller-controlled input URL is never fetched unless the app opted in // with a validating predicate. Skipped, not thrown: not mirroring someone // else's URL is the intended default, and the run itself is fine. const isCallerSupplied = descriptor.role === 'input' const allowInputUrl = opts?.allowInputUrl if (isCallerSupplied && !allowInputUrl) return undefined let target: URL try { target = new URL(descriptor.url) } catch { throw new Error( `Failed to persist artifact: ${descriptor.url} is not a valid URL.`, ) } if (target.protocol !== 'https:' && target.protocol !== 'http:') { throw new Error( `Refusing to fetch artifact over ${target.protocol} (${descriptor.path}).`, ) } if (allowInputUrl && isCallerSupplied) { if (isBlockedInputHost(target.hostname)) { throw new Error( `Refusing to fetch input artifact from internal host ${target.hostname}.`, ) } if (!(await allowInputUrl({ url: target, descriptor }))) { throw new Error( `Refusing to fetch input artifact from ${target.hostname}: rejected by allowInputUrl.`, ) } } const maxBytes = opts?.maxArtifactBytes ?? DEFAULT_MAX_ARTIFACT_BYTES const fetchArtifact = opts?.artifactFetch ?? globalThis.fetch const response = await fetchArtifact(target, { // Provider CDNs redirect routinely, so output fetches follow. An input // fetch must not: a 302 would land on a host neither check ever saw. redirect: isCallerSupplied ? 'manual' : 'follow', signal: AbortSignal.timeout( opts?.artifactFetchTimeoutMs ?? DEFAULT_ARTIFACT_FETCH_TIMEOUT_MS, ), }) if (isCallerSupplied && response.status >= 300 && response.status < 400) { throw new Error( `Refusing to follow a redirect for input artifact ${descriptor.path}.`, ) } if (!response.ok) { throw new Error( `Failed to persist artifact from ${descriptor.url}: HTTP ${response.status}`, ) } // `headers.get` returns null when the header is absent, and // `Number(null) === 0` — parse only a present header, or a chunked reply // would read as a declared length of 0 (harmless, but the early-reject // below would silently never be reachable for it). const contentLength = response.headers.get('content-length') const declaredLength = contentLength === null ? undefined : Number(contentLength) if ( maxBytes !== false && declaredLength !== undefined && Number.isFinite(declaredLength) && declaredLength > maxBytes ) { throw new Error( `Artifact at ${descriptor.url} exceeds maxArtifactBytes (${maxBytes}).`, ) } const mimeType = descriptor.mimeType ?? response.headers.get('content-type') ?? 'application/octet-stream' // A declared length is the DECODED body's length only when the response is // not content-encoded: fetch transparently decompresses, so on a gzipped // reply `content-length` measures the compressed bytes and the decoded // stream can be arbitrarily longer. Only trust it when it provably // describes what the store will drain. const encoding = response.headers.get('content-encoding') const decodedLengthIsKnown = declaredLength !== undefined && Number.isFinite(declaredLength) && (encoding === null || encoding === 'identity') const expectedLength = decodedLengthIsKnown ? declaredLength : undefined // Stream the body straight into the blob store instead of buffering the // whole artifact in memory. `size` is left 0 (unknown up front); the store // records the actual byte length as it drains the stream. Fall back to // buffering only when the response has no body to stream. if (response.body) { return { // Wrap ONLY when the response does not already bound itself. A // trustworthy `content-length` was checked against the cap above, and // HTTP framing holds the origin to it — a body cannot exceed a length // it declared — so the counter would add nothing and cost everything: // it is a TransformStream, whose readable side has no declared length, // and that missing length is precisely what breaks `R2Bucket.put`. // Unwrapped, the runtime's own length rides along and R2 single-shots // the stream. What still needs the counter: a chunked reply (no // declared length at all) and a content-encoded one (declared length // measures the compressed bytes, so the decoded stream is a // decompression bomb waiting to happen). body: maxBytes === false || decodedLengthIsKnown ? response.body : capBodySize(response.body, maxBytes, descriptor.url), size: 0, expectedLength, mimeType, sourceUrl: descriptor.url, } } const body = await response.arrayBuffer() if (maxBytes !== false && body.byteLength > maxBytes) { throw new Error( `Artifact at ${descriptor.url} exceeds maxArtifactBytes (${maxBytes}).`, ) } return { body, size: body.byteLength, mimeType, sourceUrl: descriptor.url, } } throw new Error( `Artifact descriptor ${descriptor.path} has no bytes, url, or json.`, ) } async function persistGenerationArtifacts( persistence: AIPersistence, opts: WithGenerationPersistenceOptions, ctx: GenerationMiddlewareContext, result: unknown, ): Promise> { const activity = mediaActivity(ctx.activity) if (!activity) return [] // Resolved the same way the run record is, so an artifact always lands in the // same slot as the run that produced it. const threadId = generationScope(ctx, opts) const runId = ctx.runId ?? ctx.requestId const extractionInput: GenerationArtifactExtractionInput = { activity, provider: ctx.provider, model: ctx.model, threadId, runId, inputs: ctx.artifactInputs, result, } const extracted = opts?.extractArtifacts !== undefined ? await opts.extractArtifacts(extractionInput) : builtInArtifactDescriptors(activity, ctx.artifactInputs, result) if (extracted.length === 0) return [] const existingRefs = extracted.filter(isArtifactRef) const descriptors = extracted.filter( (item): item is GenerationArtifactDescriptor => !isArtifactRef(item), ) if (descriptors.length === 0) return existingRefs if (!persistence.stores.artifacts || !persistence.stores.blobs) { throw new Error( 'Generation artifact persistence requires stores.artifacts and stores.blobs.', ) } const refs: Array = [...existingRefs] for (const [index, descriptor] of descriptors.entries()) { const artifactId = ctx.createId('artifact') const resolved = await descriptorBody(descriptor, opts) // Deliberately not persisted (an input URL with no `allowInputUrl` opt-in): // no blob, no record, no ref — the rest of the run is unaffected. if (!resolved) continue const { body, size, expectedLength, mimeType, sourceUrl } = resolved // Resolved before the blob write so `storageKey` can build a path from the // final filename (extensions, slugs) rather than guessing at one. const name = opts?.nameArtifact?.({ descriptor: { ...descriptor, mimeType }, activity, provider: ctx.provider, model: ctx.model, threadId, runId, index, }) ?? descriptor.name ?? defaultArtifactName({ ...descriptor, mimeType }, activity, index) const key = opts?.storageKey?.({ artifactId, runId, threadId, role: descriptor.role, activity, path: descriptor.path, mimeType, name, }) ?? artifactBlobKey({ runId, artifactId }) const stored = await persistence.stores.blobs.put(key, body, { contentType: mimeType, // Exact decoded length when the origin declared one — lets a store // single-shot the stream (e.g. R2 via FixedLengthStream) instead of // buffering or going multipart. Absent when unknown. ...(expectedLength !== undefined ? { expectedLength } : {}), customMetadata: { runId, threadId, role: descriptor.role, activity, path: descriptor.path, }, }) // For streamed downloads the descriptor size is unknown (0); the store // reports the real byte length once it has drained the stream. const resolvedSize = size || stored.size || 0 const createdAtMs = Date.now() const record: ArtifactRecord = { artifactId, runId, threadId, // Always recorded: with a custom `storageKey` the path is no longer // derivable from the record, so the reader has to be told where it went. blobKey: key, name, mimeType, size: resolvedSize, sourceUrl, createdAt: createdAtMs, } await persistence.stores.artifacts.save(record) refs.push({ role: descriptor.role, artifactId, threadId, runId, name, mimeType, size: resolvedSize, createdAt: new Date(createdAtMs).toISOString(), ...(sourceUrl ? { sourceUrl } : {}), source: { activity, path: descriptor.path, provider: ctx.provider, model: ctx.model, mediaType: descriptor.mediaType, jobId: descriptor.jobId, expiresAt: descriptor.expiresAt instanceof Date ? descriptor.expiresAt.toISOString() : descriptor.expiresAt, }, }) } // Stamp the durable app-origin serve URL onto every ref that lacks one, so // clients render + restore media from your own origin, not the provider link. if (opts?.artifactUrl) { for (let i = 0; i < refs.length; i++) { const ref = refs[i] if (ref && !ref.url) { const url = opts.artifactUrl(ref) if (url) refs[i] = { ...ref, url } } } } return refs } /** * Rewrite the live result's media fields to each output ref's durable serve URL * (`ref.url`), so the live result matches what a reload restores. Keyed off the * ref's `source.path`: `images.` → `result.images[i].url`, `video` → * `result.url`, `audio` (object) → `result.audio.url`. tts (a base64 string) and * transcription (json) have no media-URL field, so they are left as-is; their * durable bytes are reachable via `result.artifacts`. A no-op when no ref has a * `url`. */ function applyDurableMediaUrls( result: Record, refs: Array, ): Record { let next = result for (const ref of refs) { if (ref.role !== 'output' || !ref.url) continue const path = ref.source.path if (path.startsWith('images.')) { const index = Number(path.slice('images.'.length)) const images = next.images if (Array.isArray(images) && objectValue(images[index])) { const cloned = [...images] cloned[index] = { ...objectValue(images[index]), url: ref.url } next = { ...next, images: cloned } } } else if (path === 'video') { // The stream is now in the blob store; only the durable URL goes on. const { body: _body, contentType: _contentType, ...rest } = next next = { ...rest, url: ref.url } } else if (path === 'audio' && objectValue(next.audio)) { next = { ...next, audio: { ...objectValue(next.audio), url: ref.url } } } } return next } // --------------------------------------------------------------------------- // Shared store / feature plan // --------------------------------------------------------------------------- interface PersistencePlan { wantsInterrupts: boolean wantsArtifactPersistence: boolean runs: AIPersistence['stores']['runs'] sessions: AIPersistence['stores']['sessions'] } function resolvePersistencePlan(persistence: AIPersistence): PersistencePlan { return { wantsInterrupts: persistence.stores.interrupts !== undefined, wantsArtifactPersistence: persistence.stores.artifacts !== undefined && persistence.stores.blobs !== undefined, runs: persistence.stores.runs, sessions: persistence.stores.sessions, } } type StoreIsDefinitelyPresent< TStores extends AIPersistenceStores, TKey extends keyof AIPersistenceStores, > = TKey extends keyof TStores ? object extends Pick ? false : [Exclude] extends [never] ? false : true : false type StoreIsDefinitelyAbsent< TStores extends AIPersistenceStores, TKey extends keyof AIPersistenceStores, > = TKey extends keyof TStores ? [Exclude] extends [never] ? true : false : true /** * Chat entrypoint invalid when: * - `messages` is known-absent, or * - `interrupts` is known-present without `runs`. * * Fully optional bags (`AIPersistence` with all `?` keys) stay assignable and * are checked at runtime by {@link validateChatPersistenceStores}. */ type InvalidChatPersistence = StoreIsDefinitelyAbsent extends true ? true : StoreIsDefinitelyPresent extends true ? StoreIsDefinitelyAbsent : false /** * Generation entrypoint invalid when `generationRuns` is known-absent, or when * exactly one of `artifacts` / `blobs` is present (artifact persistence needs * both). */ type InvalidGenerationPersistence = StoreIsDefinitelyAbsent extends true ? true : StoreIsDefinitelyPresent extends true ? StoreIsDefinitelyAbsent : StoreIsDefinitelyPresent extends true ? StoreIsDefinitelyAbsent : false type ValidChatPersistence = InvalidChatPersistence extends true ? never : unknown type ValidGenerationPersistence = InvalidGenerationPersistence extends true ? never : unknown async function createOrResumeRun( runs: RunStore | undefined, runId: string, threadId: string, ): Promise { const run = await runs?.createOrResume({ runId, threadId, startedAt: Date.now(), }) // Reset an interrupted or failed continuation back to running so readers // and findActiveRun observe the live resumed run. Leave completed and // aborted records terminal. if (run && (run.status === 'interrupted' || run.status === 'failed')) { await runs?.update(runId, { status: 'running' }) } return run?.usage } function sumOptionalNumber( current: number | undefined, next: number | undefined, ): number | undefined { if (current === undefined) return next if (next === undefined) return current return current + next } function sumNumberFields( current: T | undefined, next: T | undefined, ): T | undefined { if (!current) return next if (!next) return current const result = { ...current } for (const key of Object.keys(next) as Array) { const currentValue = current[key] const nextValue = next[key] if (typeof nextValue === 'number') { result[key] = ((typeof currentValue === 'number' ? currentValue : 0) + nextValue) as T[keyof T] } } return result } function tokenUsageFromChunk(chunk: StreamChunk): TokenUsage | undefined { if (chunk.type !== 'RUN_FINISHED' && chunk.type !== 'RUN_ERROR') { return undefined } const usage = chunk.usage if ( usage != null && typeof usage === 'object' && !Array.isArray(usage) && 'promptTokens' in usage ) { return usage } const metadata = chunk.metadata const tanstack = metadata != null && typeof metadata === 'object' && 'tanstack' in metadata ? metadata.tanstack : undefined const leftover = tanstack != null && typeof tanstack === 'object' && !Array.isArray(tanstack) ? (tanstack as { usage?: TokenUsage }).usage : undefined return fromSpecTokenUsage(Array.isArray(usage) ? usage : undefined, leftover) } function accumulateTokenUsage( current: TokenUsage | undefined, next: TokenUsage, ): TokenUsage { if (!current) return { ...next } const promptTokensDetails = sumNumberFields( current.promptTokensDetails, next.promptTokensDetails, ) const completionTokensDetails = sumNumberFields( current.completionTokensDetails, next.completionTokensDetails, ) const costDetails = sumNumberFields(current.costDetails, next.costDetails) // Provider-specific details are opaque, so retain the latest reported bag. const providerUsageDetails = next.providerUsageDetails ?? current.providerUsageDetails const billed = accumulateBilled(current.billed, next.billed) const cost = sumOptionalNumber(current.cost, next.cost) return { ...current, ...next, promptTokens: current.promptTokens + next.promptTokens, completionTokens: current.completionTokens + next.completionTokens, totalTokens: current.totalTokens + next.totalTokens, ...(promptTokensDetails ? { promptTokensDetails } : {}), ...(completionTokensDetails ? { completionTokensDetails } : {}), ...(billed !== undefined ? { billed } : {}), ...(cost !== undefined ? { cost } : {}), ...(costDetails ? { costDetails } : {}), ...(providerUsageDetails ? { providerUsageDetails } : {}), } } /** * Sum billed quantities when both reports use the same unit. Different units * cannot be added, so the later report wins. */ function accumulateBilled( current: BilledUsage | undefined, next: BilledUsage | undefined, ): BilledUsage | undefined { if (!current) return next if (!next) return current if (current.unit !== next.unit) return next return { quantity: current.quantity + next.quantity, unit: current.unit } } async function completeRun( runs: RunStore | undefined, runId: string, usage?: TokenUsage, ): Promise { // A late detach stamp from a superseded host can land after takeover // claimed the run. A terminal run is not detached. await runs?.update(runId, { status: 'completed', finishedAt: Date.now(), detachedSince: undefined, ...(usage ? { usage } : {}), }) } async function failRun( runs: RunStore | undefined, runId: string, error: unknown, usage?: TokenUsage, ): Promise { const runError = toRunErrorPayload(error) await runs?.update(runId, { status: 'failed', finishedAt: Date.now(), detachedSince: undefined, error: { message: runError.message, ...(runError.code !== undefined ? { code: runError.code } : {}), }, ...(usage ? { usage } : {}), }) } /** * Record a human-in-the-loop PAUSE. * * Deliberately writes NO `finishedAt`: `'interrupted'` is not a terminal status * (`isTerminalRunStatus('interrupted')` is `false`), and stamping a terminal * timestamp on it told every reader the run was over while it was in fact * waiting for a human. Only `abortRun`/`completeRun`/`failRun` finish a run. */ export async function interruptRun( runs: RunStore | undefined, runId: string, usage?: TokenUsage, ): Promise { await runs?.update(runId, { status: 'interrupted', ...(usage ? { usage } : {}), }) } /** * Record that the run has ended for good — an explicit cancel, or a disconnect * on a run that has nothing to reattach to. Terminal, so it carries * `finishedAt`. */ export async function abortRun( runs: RunStore | undefined, runId: string, usage?: TokenUsage, ): Promise { await runs?.update(runId, { status: 'aborted', finishedAt: Date.now(), detachedSince: undefined, ...(usage ? { usage } : {}), }) } /** * Whether some middleware has declared this run detachable — i.e. it has a * durable event log and a run store, so a disconnect can be survived and the * run picked back up rather than destroyed. * * The capability is read from CORE, never from `@tanstack/ai-sandbox`: sandbox * provides it, persistence consumes it, and a persistence → sandbox import * would invert the layering. */ function detachableRun(ctx: ChatMiddlewareContext): boolean { return getDetachableRun(ctx, { optional: true }) === true } // --------------------------------------------------------------------------- // Chat middleware // --------------------------------------------------------------------------- function threadMessages( loaded: Array | MessagePage, ): Array { return Array.isArray(loaded) ? loaded : loaded.messages } export interface WithPersistenceOptions { /** * Also persist a throttled snapshot of the in-progress assistant reply while * it streams. Off by default — the transcript is otherwise persisted at the * pending turn (`onStart`), interrupt boundaries, and completion (`onFinish`). * Enable it to recover partial output if the process dies mid-generation, at * the cost of extra writes. Snapshots are throttled to at most one per * {@link WithPersistenceOptions.snapshotIntervalMs}. */ snapshotStreaming?: boolean /** * Minimum milliseconds between streaming snapshots when `snapshotStreaming` * is on. Defaults to 1000. A streaming subagent child always uses the same * interval for its transcript writes, with or without `snapshotStreaming`. */ snapshotIntervalMs?: number /** * The tenant of the thread, for `stores.sessions`. The middleware reads the * parent entry of a subagent child from this tenant and writes the child * entry in it. Without it, the default tenant. */ tenantId?: string } /** * Chat-only **state** persistence middleware. Provides durable transcript, * run records, and interrupts for `chat()`. Does **not** provide locks — * use `withLocks` from `@tanstack/ai` for multi-instance coordination. * * This middleware never mutates the chunk stream; delivery durability * (replaying a disconnected/reloaded stream) is a separate transport-layer * concern (see the resumable-streams docs). * * Requires `stores.messages`. When `stores.interrupts` is present, * `stores.runs` is also required. * * Incoming `messages` merge into the stored thread by id. An empty list loads * the stored thread. The last incoming id that already exists in stored is a * cutoff; stored messages after it are dropped (reload). If no incoming id is * in stored, every stored message stays. Same id: incoming wins. New ids and * messages with no id are appended. `saveThread` still replaces the thread * with that merged list. * * @param persistence - Must satisfy {@link ChatTranscriptStores} (messages * required). Known-absent `messages` or `interrupts` without `runs` fail at * compile time; fully dynamic bags are checked at runtime. */ export function withPersistence( persistence: AIPersistence & ValidChatPersistence, options: WithPersistenceOptions = {}, ): ChatMiddleware { // Runtime validation covers dynamic bags that bypass the generic constraint. validateChatPersistenceStores(persistence) const snapshotStreaming = options.snapshotStreaming ?? false const snapshotIntervalMs = options.snapshotIntervalMs ?? 1000 const plan = resolvePersistencePlan(persistence) const { wantsInterrupts, runs, sessions } = plan const messageStore = persistence.stores.messages if (!messageStore) { // validateChatPersistenceStores already throws; this narrows for TypeScript. throw new Error('Chat persistence requires stores.messages.') } const activityStore = persistence.stores.activities // Best-effort: the activity store is an optional sidecar, so a failed save // must never fail the run or block the message, run, and interrupt writes. async function persistActivities(ctx: ChatMiddlewareContext): Promise { // A hand-built context can have no `activities`. `saveActivities` replaces // the thread's rows, so saving `[]` for it would wipe the store. if (!activityStore || ctx.activities === undefined) return // `onStart` sets `firstRunMessage`. Before that, `ctx.activities` can miss // the stored rows, so merge them in first. A row from `setup` is then // saved at once, also when the run fails or stops before it starts. // ponytail: one extra store read for each activity chunk before the run // starts. Keep the loaded rows in the run state if a store is slow. const state = runState.get(ctx) const isBeforeStart = state?.firstRunMessage === undefined // With no rows, the merge gives back the stored rows. Skip that save. if (isBeforeStart && ctx.activities.length === 0) return try { // A failed load skips the save, because the save would delete the // stored rows. let list = [...ctx.activities] if (isBeforeStart) { const stored = await activityStore.loadActivities(ctx.threadId) const storedIds = new Set(stored.map((record) => record.id)) const isEarly = (record: ActivityRecord) => state?.earlyActivityIds.has(record.id) === true for (const { id } of ctx.activities) { if ( !storedIds.has(id) && state?.inboundActivityIds.has(id) !== true ) { state?.earlyActivityIds.add(id) } } // ponytail: one more read, of the stored messages, for each of these // saves. A boot that fails before onConfig keeps this place. const messages = mergeStoredMessages( threadMessages(await messageStore.loadThread(ctx.threadId)), ctx.messages, ) list = placeEarlyActivities( rebaseInboundActivities( mergeActivityRecords(stored, ctx.activities), storedIds, isEarly, inboundActivityOffset( messages, ctx.messages, stored, ctx.activities, ), ), messages, isEarly, ) } await activityStore.saveActivities(ctx.threadId, list) } catch (error) { console.warn( `[ai-persistence] saveActivities failed for thread '${ctx.threadId}'`, error, ) } } const provides = [ PersistenceCapability, PersistenceCompletionCapability, LoadChildCapability, ...(persistence.stores.metadata ? [MetadataCapability] : []), ...(wantsInterrupts ? [InterruptsCapability] : []), ] const subagentRuns = createSubagentRunRecorder({ messages: messageStore, runs, addUsage: accumulateTokenUsage, intervalMs: snapshotIntervalMs, ...(wantsInterrupts && persistence.stores.interrupts ? { interrupts: persistence.stores.interrupts } : {}), ...(sessions ? { sessions } : {}), ...(options.tenantId !== undefined ? { tenantId: options.tenantId } : {}), }) function resetStreaming(state: RunStateEntry) { state.streamingMetadata = undefined state.streamingMessageIds = new Set() state.streamingMessageId = undefined state.streamingMessageCreatedAt = undefined state.streamingText = '' state.lastSnapshotAt = undefined } /** * Write the call metadata, and the stop reason of a failed call, onto the * snapshot rows of the current model call. Replay drops a failed call. */ async function updateStreamingRows( ctx: ChatMiddlewareContext, stopReason?: 'error' | 'aborted', ) { const state = runState.get(ctx) const ids = state?.streamingMessageIds if (!state || !ids?.size) return const loaded = threadMessages(await messageStore.loadThread(ctx.threadId)) let changed = false const messages = loaded.map((message) => { if ( message.role !== 'assistant' || message.id === undefined || !ids.has(message.id) ) return message changed = true const metadata = mergeMetadata(message.metadata, state.streamingMetadata) const next = { ...message, ...(metadata !== undefined ? { metadata } : {}), } return stopReason === undefined ? next : withTanstackMetadata(next, { stopReason }) }) if (changed) await messageStore.saveThread(ctx.threadId, messages) } return defineChatMiddleware({ name: 'chat-persistence', routedSubagentPersistence: subagentRuns, provides, setup(ctx: ChatMiddlewareContext) { providePersistence(ctx, persistence) if (persistence.stores.metadata) { provideMetadata(ctx, persistence.stores.metadata) } // The agent tools read stored children through this, to continue // one by `sessionId`. Only the children of this chat can load. // With a parent, the caller is that child. `loadChild` then proves // that the nested child belongs to it. provideLoadChild(ctx, (subagentRunId, nested) => { const caller = nested?.parentSubagentRunId ?? ctx.subagentRunId return subagentRuns.loadChild(subagentRunId, { threadId: ctx.threadId, ...(caller !== undefined && { subagentRunId: caller }), }) }) let resolveCompletion: () => void = () => undefined let rejectCompletion: (error: unknown) => void = () => undefined const completion = new Promise((resolve, reject) => { resolveCompletion = resolve rejectCompletion = reject }) // Consumers may not need this capability. Mark the rejection handled while // preserving the original promise for callers that do await it. void completion.catch(() => undefined) runState.set(ctx, { merged: false, interrupted: false, earlyActivityIds: new Set(), inboundActivityIds: new Set( (ctx.activities ?? []).map((record) => record.id), ), completion: { promise: completion, resolve: resolveCompletion, reject: rejectCompletion, }, }) providePersistenceCompletion(ctx, { waitForRunCompletion: () => completion, }) if (wantsInterrupts && persistence.stores.interrupts) { provideInterrupts(ctx, persistence.stores.interrupts) } // Offer the pending-turn seam so a middleware that is about to be SLOW can // have the user's turn stored before it starts. Only `onStart` stores the // turn otherwise, and `onStart` runs after every middleware `setup` — which // is milliseconds for a normal run and MINUTES for one that builds a sandbox. // For that whole window the thread reads as empty, so a reload or a second // device shows no sign of the message the user just sent. // // Offering it changes nothing on its own: a run whose middleware never calls // it behaves exactly as before. See `PendingTurnCapability`. providePendingTurn(ctx, { snapshot: async () => { const stored = threadMessages( await messageStore.loadThread(ctx.threadId), ) // Same merge as onConfig. saveThread replaces the thread, so a short // incoming list must not drop stored extras. const list = mergeStoredMessages(stored, ctx.messages) await messageStore.saveThread(ctx.threadId, list) // This save can cut a reloaded turn before onConfig sees it, so cut // that turn's activity rows here too. const cutoff = activityCutoff(stored, ctx.messages) if (activityStore && cutoff < stored.length) { await activityStore.saveActivities( ctx.threadId, keptActivities( await activityStore.loadActivities(ctx.threadId), stored, cutoff, runState.get(ctx)?.earlyActivityIds, ), ) } }, }) }, async onConfig(ctx: ChatMiddlewareContext, config: ChatMiddlewareConfig) { if (ctx.phase === 'beforeModel') { const current = runState.get(ctx) if (snapshotStreaming && current) { // A new model call starts its own snapshot rows. resetStreaming(current) } // Commit tool-bound resumes before the follow-up model call once every // answered tool call has a real tool result in ctx.messages. That stops // a later LLM failure from resurrecting already-executed tool approvals. if ( wantsInterrupts && persistence.stores.interrupts && current?.pendingResumes && current.pendingResumes.resumedToolCallIds.size > 0 ) { const allToolResultsReady = [ ...current.pendingResumes.resumedToolCallIds, ].every((toolCallId) => ctx.messages.some( (message) => message.role === 'tool' && message.toolCallId === toolCallId && !isPendingExecutionToolMessage(message), ), ) if (allToolResultsReady) { const prevMessages = threadMessages( await messageStore.loadThread(ctx.threadId), ) await messageStore.saveThread( ctx.threadId, runMessages(ctx, current), ) let committedIds: ReadonlyArray try { committedIds = await commitPendingResumes( current, persistence.stores.interrupts, ) } catch (error) { await messageStore .saveThread(ctx.threadId, prevMessages) .catch(() => undefined) throw error } // The model call below can still fail. This tells the client // that the answers are used, so it does not show them again. if (committedIds.length > 0) { ctx.emitCustomEvent('interrupts:committed', { interruptIds: [...committedIds], }) } } } return } if (ctx.phase !== 'init') return const patch: Partial = {} const state = runState.get(ctx) const pendingApprovalToolCallIds = new Set() const pendingOwnedToolCallIds = new Set() let claimedIds: Array | undefined try { if (wantsInterrupts && persistence.stores.interrupts) { const pending = await persistence.stores.interrupts.listPending( ctx.threadId, ) // Gate only records that this chat owns. A foreign AG-UI interrupt can // share the durable thread, but its owner resolves it outside this // resume protocol. Including it would deadlock this chat resume. const ownedPending = pending.filter((record) => { if (isChatOwnedPendingInterrupt(record)) return true warnIfUnboundToolInterrupt(record) return false }) rejectMixedRunPending(ownedPending, ctx) const resumeByInterruptId = validatePendingResumes( ownedPending, config.resume, ctx, ) if (ownedPending.length > 0 && config.resume?.length) { const idsToClaim = ownedPending.map((record) => record.interruptId) claimPendingInterrupts( persistence.stores.interrupts, idsToClaim, ctx, ownedPending[0]?.runId ?? ctx.runId, ) claimedIds = idsToClaim if (state) state.claimedInterruptIds = [...idsToClaim] } for (const record of ownedPending) { const toolCallId = toolCallIdOfPendingRecord(record) if (toolCallId !== undefined) { pendingOwnedToolCallIds.add(toolCallId) if ( isPersistedInterruptDescriptor(record.payload) && readInterruptBinding(record.payload)?.kind === 'tool-approval' ) { pendingApprovalToolCallIds.add(toolCallId) } } } // Persistence is the server-authoritative resume path: translate the // persisted interrupts into the engine's resume tool state and CLEAR // `config.resume`, so the engine skips its ephemeral reconstruction // (which needs a parentRunId and the client message history the // persistence flow deliberately omits). if (config.resume?.length) { // A subagent tool call answers its own interrupts against its own // tools. They are still committed below with the rest of the batch. const runPending = rejectForgedChildSplit(ownedPending, ctx) const resume = config.resume const interrupts = persistence.stores.interrupts patch.resume = [] // chat() runs this after the whole onConfig chain, so a tool that a // later middleware adds can be resumed too. Object.assign(patch, { [DURABLE_RESUME]: (tools: ChatMiddlewareConfig['tools']) => durableGenericResumeState( ctx, runPending, resume, tools, interrupts, ), }) } // Defer marking these interrupts resolved/cancelled until the run // completes the tool phase or finishes (see commitPendingResumes). if (state && ownedPending.length > 0) { const resumedToolCallIds = new Set() for (const record of ownedPending) { if (!resumeByInterruptId.has(record.interruptId)) continue const toolCallId = toolCallIdOfPendingRecord(record) if (toolCallId !== undefined) resumedToolCallIds.add(toolCallId) } state.pendingResumes = { pending: ownedPending, resumeByInterruptId, resumedToolCallIds, } } } const storedUsage = await createOrResumeRun( runs, ctx.runId, ctx.threadId, ) // A continuation has a fresh middleware context but resumes the same run. if (state && storedUsage) state.usage = storedUsage if (!state?.merged) { if (state) state.merged = true const stored = stripStalePendingToolRows( threadMessages(await messageStore.loadThread(ctx.threadId)), pendingApprovalToolCallIds, pendingOwnedToolCallIds, ) const incoming = stripStalePendingToolRows( config.messages, pendingApprovalToolCallIds, pendingOwnedToolCallIds, ) patch.messages = mergeStoredMessages(stored, incoming) if (activityStore) { // Not best-effort like the save: a failed load followed by a save // would wipe the stored rows, so a load error fails the run. const storedRows = await activityStore.loadActivities(ctx.threadId) const storedIds = new Set(storedRows.map((record) => record.id)) const current = ctx.activities ?? [] const isEarly = (record: ActivityRecord) => state?.earlyActivityIds.has(record.id) === true patch.activities = placeEarlyActivities( rebaseInboundActivities( mergeActivityRecords( keptActivities( storedRows, stored, activityCutoff(stored, incoming), state?.earlyActivityIds, ), current, ), storedIds, isEarly, inboundActivityOffset( patch.messages, incoming, storedRows, current, ), ), patch.messages, isEarly, ) } } return Object.keys(patch).length > 0 ? patch : undefined } catch (error) { releasePendingClaims( persistence.stores.interrupts, ctx.threadId, claimedIds, ) if (state) state.claimedInterruptIds = undefined throw error } }, async onStart(ctx: ChatMiddlewareContext) { // (A) Persist the pending turn (the just-submitted user message plus any // prior history) as soon as the run starts, so a reload mid-run rehydrates // it before the assistant reply exists. Best-effort: a failed eager // snapshot must not abort the run — the authoritative save is `onFinish`. const state = runState.get(ctx) if (state) state.firstRunMessage = ctx.messages.length try { await messageStore.saveThread(ctx.threadId, [...ctx.messages]) await persistActivities(ctx) } catch { // Eager pre-save is best-effort; the run continues and onFinish saves. } }, async onChunk(ctx: ChatMiddlewareContext, chunk: StreamChunk) { await subagentRuns.chunk({ threadId: ctx.threadId, runId: ctx.runId, ...(ctx.subagentRunId !== undefined && { subagentRunId: ctx.subagentRunId, }), chunk, }) const current = runState.get(ctx) const isParentChunk = !('subagentRunId' in chunk) || chunk.subagentRunId === undefined // Save the rows on each activity chunk of this run, so a reload during // the run shows them. The engine adds the row to `ctx.activities` // before `onChunk`. This includes a row that `setup` sends. // ponytail: one write per activity chunk. Throttle it if a store // cannot keep up with a fast stream of deltas. if (isParentChunk && isActivityChunk(chunk)) await persistActivities(ctx) if (snapshotStreaming && isParentChunk && current) { if (chunk.type === 'RUN_STARTED') resetStreaming(current) // The same call metadata that a finished assistant message gets. current.streamingMetadata = { tanstack: { ...ctx.callMetadata } } if (chunk.type === 'RUN_FINISHED') await updateStreamingRows(ctx) } // Capture the current assistant turn's identity for optional in-progress // snapshots. Completed messages already live in `ctx.messages`. if (snapshotStreaming && ctx.phase === 'modelStream') { const s = runState.get(ctx) if (s && chunk.type === 'TEXT_MESSAGE_START') { // An empty/malformed messageId means "no identity" (matching the // engine's convention), leaving room for the TOOL_CALL_START // parentMessageId fallback below — but the per-turn accumulator // still resets so snapshots never mix text across turns. s.streamingMessageId = typeof chunk.messageId === 'string' && chunk.messageId !== '' ? chunk.messageId : undefined s.streamingMessageCreatedAt = new Date() s.streamingText = '' } else if ( s && chunk.type === 'TOOL_CALL_START' && typeof chunk.parentMessageId === 'string' && chunk.parentMessageId !== '' && s.streamingMessageId === undefined ) { s.streamingMessageId = chunk.parentMessageId s.streamingMessageCreatedAt ??= new Date() } } // (B) Optional throttled snapshot of the in-progress assistant reply, so // partial output survives a crash/reload before onFinish. Off unless // `snapshotStreaming` is set. The completed turn enters `ctx.messages` // only after streaming ends, so accumulate its text here and persist // `ctx.messages` + that partial assistant message (tagged with its id). if ( snapshotStreaming && chunk.type === 'TEXT_MESSAGE_CONTENT' && typeof chunk.delta === 'string' ) { const snapshotState = runState.get(ctx) if (snapshotState) { snapshotState.streamingText = (snapshotState.streamingText ?? '') + chunk.delta const now = Date.now() if (now - (snapshotState.lastSnapshotAt ?? 0) >= snapshotIntervalMs) { snapshotState.lastSnapshotAt = now try { await messageStore.saveThread(ctx.threadId, [ ...ctx.messages, { role: 'assistant', content: snapshotState.streamingText, ...(snapshotState.streamingMetadata !== undefined ? { metadata: snapshotState.streamingMetadata } : {}), ...(snapshotState.streamingMessageId ? { id: snapshotState.streamingMessageId } : {}), ...(snapshotState.streamingMessageCreatedAt ? { createdAt: snapshotState.streamingMessageCreatedAt } : {}), }, ]) if (snapshotState.streamingMessageId !== undefined) { snapshotState.streamingMessageIds ??= new Set() snapshotState.streamingMessageIds.add( snapshotState.streamingMessageId, ) } await persistActivities(ctx) } catch { // Streaming snapshots are best-effort; onFinish persists final. } } } } // State-only: react to the interrupt boundary (create interrupt records, // mark the run interrupted, snapshot thread messages). The chunk stream is // never mutated — delivery durability is a transport-layer concern. if ( chunk.type !== 'RUN_FINISHED' || chunk.outcome?.type !== 'interrupt' ) { return } const state = runState.get(ctx) if (!state) return const keepPendingIds = new Set( chunk.outcome.interrupts.map((interrupt) => interrupt.id), ) const payloads = wantsInterrupts && persistence.stores.interrupts ? chunk.outcome.interrupts.map((interrupt) => ({ interrupt, payload: clientInterruptPayload(interrupt, state), })) : [] // Save the transcript, then commit answered resumes, then create fresh // interrupts and pause the run. A reload never sees pending interrupts // without their assistant tool calls, and a failed save consumes no // approval. A failed commit rolls the transcript back, as onFinish does. if (wantsInterrupts && persistence.stores.interrupts) { const prevMessages = state.pendingResumes ? threadMessages(await messageStore.loadThread(ctx.threadId)) : undefined await messageStore.saveThread(ctx.threadId, runMessages(ctx, state)) try { await commitPendingResumes( state, persistence.stores.interrupts, keepPendingIds, ) } catch (error) { if (prevMessages !== undefined) { await messageStore .saveThread(ctx.threadId, prevMessages) .catch(() => undefined) } throw error } } else { await messageStore.saveThread(ctx.threadId, runMessages(ctx, state)) } if (wantsInterrupts && persistence.stores.interrupts) { for (const { interrupt, payload } of payloads) { await persistence.stores.interrupts.create({ interruptId: interrupt.id, runId: ctx.runId, threadId: ctx.threadId, requestedAt: Date.now(), payload, }) } } // Adapter terminals arrive before `onUsage`; synthesized tool boundaries // arrive after it with the same usage already in state. const chunkUsage = tokenUsageFromChunk(chunk) const usage = ctx.phase === 'modelStream' && chunkUsage ? accumulateTokenUsage(state.usage, chunkUsage) : (state.usage ?? chunkUsage) state.usage = usage await interruptRun(runs, ctx.runId, usage) state.interrupted = true await persistActivities(ctx) releasePendingClaims( persistence.stores.interrupts, ctx.threadId, state.claimedInterruptIds, ) state.claimedInterruptIds = undefined state.completion?.resolve() }, onUsage(ctx: ChatMiddlewareContext, usage: TokenUsage) { const state = runState.get(ctx) if (!state || state.interrupted) return state.usage = accumulateTokenUsage(state.usage, usage) }, async onFinish(ctx: ChatMiddlewareContext, info: FinishInfo) { const state = runState.get(ctx) if (state?.interrupted) { releasePendingClaims( persistence.stores.interrupts, ctx.threadId, state.claimedInterruptIds, ) state.claimedInterruptIds = undefined return } // Transcript first: if saveThread fails the run stays non-completed and // resumes stay pending so a retry can re-apply them. Roll back the saved // transcript when committing pending resumes throws so retries do not // duplicate the assistant turn. let prevMessages: Array | undefined try { // Inside the try, so a failed read still fails the run and releases // its claims. if (state?.pendingResumes) { prevMessages = threadMessages( await messageStore.loadThread(ctx.threadId), ) } await messageStore.saveThread(ctx.threadId, runMessages(ctx, state)) await commitPendingResumes(state, persistence.stores.interrupts) await completeRun(runs, ctx.runId, state?.usage ?? info.usage) await persistActivities(ctx) state?.completion?.resolve() } catch (error) { if (prevMessages !== undefined && state?.pendingResumes) { await messageStore .saveThread(ctx.threadId, prevMessages) .catch(() => undefined) } // Core has already selected its terminal hook. Persist the failed run // here, so a failed transcript save or batch write does not leave an // interrupted or completed run whose pending records need retrying. try { await failRun(runs, ctx.runId, error, state?.usage) } finally { state?.completion?.reject(error) } throw error } finally { releasePendingClaims( persistence.stores.interrupts, ctx.threadId, state?.claimedInterruptIds, ) if (state) state.claimedInterruptIds = undefined } }, async onError(ctx: ChatMiddlewareContext, info: ErrorInfo) { const state = runState.get(ctx) try { try { await updateStreamingRows(ctx, 'error') } finally { await failRun(runs, ctx.runId, info.error, state?.usage) } } finally { releasePendingClaims( persistence.stores.interrupts, ctx.threadId, state?.claimedInterruptIds, ) if (state) state.claimedInterruptIds = undefined state?.completion?.reject(info.error) // After the completion settles, so a slow save cannot hold it up. await persistActivities(ctx) } }, async onAbort(ctx: ChatMiddlewareContext, info: AbortInfo) { const state = runState.get(ctx) let terminal = false try { // The durable cancel read is best-effort. It must not bypass the // terminal persistence path or prevent the completion promise from // settling when the run store is unavailable. const cancelled = info.cancelRequested === true || (runs !== undefined && (await wasCancelRequested(runs, ctx.runId))) terminal = cancelled || (!detachableRun(ctx) && state?.interrupted !== true) if (terminal) { if (cancelled && wantsInterrupts && persistence.stores.interrupts) { // Explicit cancel ends the run for good: cancel any pending // interrupts owned by this run so later messages are not blocked. const pending = persistence.stores.interrupts.listPendingByRun ? await persistence.stores.interrupts.listPendingByRun(ctx.runId) : ( await persistence.stores.interrupts.listPending(ctx.threadId) ).filter((record) => record.runId === ctx.runId) for (const record of pending) { await persistence.stores.interrupts.cancel(record.interruptId) } } try { await updateStreamingRows(ctx, 'aborted') } finally { await abortRun(runs, ctx.runId, state?.usage) } } } finally { releasePendingClaims( persistence.stores.interrupts, ctx.threadId, state?.claimedInterruptIds, ) if (state) state.claimedInterruptIds = undefined if (terminal) { state?.completion?.reject(info.reason) await persistActivities(ctx) } else if (state?.interrupted === true) { state.completion?.resolve() } } }, }) } // --------------------------------------------------------------------------- // Generation middleware // --------------------------------------------------------------------------- /** * Generation-only persistence middleware. Tracks generation run status (run * records keyed by `runId`) and, when `stores.artifacts` + `stores.blobs` are * both provided, persists the generated media for image, audio, TTS, video, and * transcription activities. * * Requires `stores.generationRuns`. A generation activity has no conversation, * so the run is keyed on its own `runId` (`ctx.runId ?? ctx.requestId`), which * is never faked from anything else. * * A `threadId` is REQUIRED alongside it — not as a link to a chat, but as the * stable app-chosen slot successive runs of the same thing fill * (`product-123-hero`, `video-9-start-frame`). It is what * `stores.generationRuns.findLatestForThread` keys on, and therefore the only * way a run is ever hydrated again. It comes from the `threadId` passed to the * activity, or from {@link WithGenerationPersistenceOptions.threadId} when that * overrides it; supplying neither throws at `onStart` rather than filing a run * nothing can find. * * On success the terminal result metadata (ids, urls — never media bytes) and, * when artifact persistence is on, the persisted artifact refs are captured onto * the run record so a server-authoritative client can hydrate the last * generation for a thread via {@link reconstructGeneration}. */ export function withGenerationPersistence( persistence: AIPersistence & ValidGenerationPersistence, opts?: WithGenerationPersistenceOptions, ): GenerationMiddleware export function withGenerationPersistence( persistence: AIPersistence, opts: WithGenerationPersistenceOptions = {}, ): GenerationMiddleware { validateGenerationPersistenceStores(persistence) const { wantsArtifactPersistence } = resolvePersistencePlan(persistence) const generationRuns = persistence.stores.generationRuns if (!generationRuns) { // validateGenerationPersistenceStores already throws; this narrows for TypeScript. throw new Error('Generation persistence requires stores.generationRuns.') } const runIdOf = (ctx: GenerationMiddlewareContext): string => ctx.runId ?? ctx.requestId return { name: 'generation-persistence', async onStart(ctx: GenerationMiddlewareContext) { const runId = runIdOf(ctx) await generationRuns.createOrResume({ runId, activity: ctx.activity, provider: ctx.provider, model: ctx.model, startedAt: Date.now(), threadId: generationScope(ctx, opts), }) // Extract + persist artifact bytes (media → blobs, metadata → artifacts) // and merge the resulting refs onto the result. Gated on artifact stores. if (wantsArtifactPersistence) { ctx.resultTransforms?.push(async (result) => { const refs = await persistGenerationArtifacts( persistence, opts, ctx, result, ) if (refs.length === 0) return undefined const base = objectValue(result) ?? {} const existing = base.artifacts const withArtifacts = { ...base, artifacts: [...(Array.isArray(existing) ? existing : []), ...refs], } // Point the live result's media at the durable serve URL (when // `artifactUrl` stamped one), so live and restored results match. return applyDurableMediaUrls(withArtifacts, refs) }) } // Always capture the terminal result metadata + any artifact refs onto the // run record. Registered AFTER the artifact transform so it observes the // fully-merged result (with the artifact refs attached). `result` is // metadata/urls only — the media bytes already live in the blob store. ctx.resultTransforms?.push(async (result) => { const rawArtifacts = objectValue(result)?.artifacts const artifacts = Array.isArray(rawArtifacts) ? rawArtifacts.filter(isArtifactRef) : [] await generationRuns.update(runId, { result, ...(artifacts.length > 0 ? { artifacts } : {}), }) return undefined }) }, async onFinish( ctx: GenerationMiddlewareContext, info: GenerationFinishInfo, ) { await generationRuns.update(runIdOf(ctx), { status: 'completed', finishedAt: Date.now(), ...(info.usage ? { usage: info.usage } : {}), }) }, async onError(ctx: GenerationMiddlewareContext, info: GenerationErrorInfo) { await generationRuns.update(runIdOf(ctx), { status: 'failed', finishedAt: Date.now(), error: { message: info.error instanceof Error ? info.error.message : String(info.error), }, }) }, async onAbort( ctx: GenerationMiddlewareContext, _info: GenerationAbortInfo, ) { // Unconditional, unlike chat's: a generation job has no journal and no // agent loop, so there is nothing to reattach to. An aborted generation is // over, full stop — hence `'aborted'` (terminal) rather than // `'interrupted'`, which now means "parked, waiting for a human" and is // deliberately NOT terminal-shaped, so pairing it with `finishedAt` would // leave the run looking permanently active. await generationRuns.update(runIdOf(ctx), { status: 'aborted', finishedAt: Date.now(), }) }, } }