Open History to see the last commit
1/**
2 * The convenience that turns core's *injected* takeover seams into this
3 * package's real ones.
4 *
5 * `@tanstack/ai`'s `RunDriverOptions` deliberately takes `claim` and `pipe` as
6 * functions instead of importing them: {@link withRunClaim} and
7 * {@link pipeToRunLog} live here, and core must not depend on this package to
8 * serve a plain chat run. {@link sandboxRunDriver} fills both in so an
9 * application writes four fields instead of six, and — more importantly — so
10 * the *fencing* is wired correctly by construction rather than by every caller
11 * remembering to.
12 *
13 * WHAT IS EASY TO GET WRONG HERE, and therefore what this module exists to
14 * make impossible:
15 *
16 * 1. **Carrying the real epoch into `pipe`.** Core's `pipe` receives only
17 * `{ runId, threadId, signal }` — no epoch — because core has no concept of
18 * one. But {@link fenceDurability} needs the epoch this driver actually
19 * acquired: a hardcoded epoch (say `0`) is not a weaker fence, it is a
20 * permanently *tripped* one, since `withRunClaim` bumps `driverEpoch` to at
21 * least `1` before `fn` ever runs, so `observed > claim.epoch` holds on the
22 * very first append and EVERY takeover fails. The claim is therefore
23 * captured in a closure by the `claim` wrapper and read back by `pipe`.
24 * 2. **Fencing `close()`.** {@link fenceDurability} wraps only `append` for the
25 * reason spelled out in `claim.ts`: `close()` runs on every teardown path,
26 * including the teardown caused by losing the claim, and a fenced `close`
27 * would wedge the record at `'running'` with every live tailer parked
28 * forever. This module must not add a second fence around it.
29 * 2b. **Fencing only ONE of the two authoritative seams.** A run's facts live in
30 * its log *and* in its record, and `pipeToRunLog` reacts to a refused append
31 * by writing a terminal record — so wrapping the log alone just moves the harm
32 * from "a dead host poisons the successor's stream" to "a dead host marks the
33 * successor's live run failed". {@link fenceRunStore} must be wired here too,
34 * over the SAME claim, which is what makes the two fences share one latch.
35 * 3. **Skipping quiescence.** The successor's first append must come after the
36 * stored log has stopped growing, so a predecessor still writing is observed
37 * rather than raced. The gate belongs inside `pipe`, before `pipeToRunLog`
38 * takes its first `snapshot`.
39 */
40import { pipeToRunLog } from './run'
41import {
42 DEFAULT_FENCE_QUIET_MS,
43 awaitLogQuiescence,
44 fenceDurability,
45 fenceRunStore,
46 withRunClaim,
47} from './claim'
48import type { RunClaim } from './claim'
49import type { InternalLogger } from '@tanstack/ai/adapter-internals'
50import type { LockStore } from '@tanstack/ai/locks'
51import type {
52 RunDriverOptions,
53 RunStore,
54 StreamChunk,
55 StreamDurability,
56} from '@tanstack/ai'
57
58export interface SandboxRunDriverOptions<TOffset extends string = string> {
59 /** The attach request; core reads its run id with `resolveResumeRunId`. */
60 request: Request
61 runs: RunStore
62 locks: LockStore
63 /**
64 * Per-run event log factory, the same shape `RunDeps.durability` takes — a
65 * `StreamDurability` is bound to one run, so the log is resolved FROM the
66 * `runId` rather than handed in pre-bound.
67 *
68 * Generic in the offset type, defaulted to `string` so an existing call site
69 * needs no change. Hardcoding the default made a branded-cursor backend
70 * unusable here: `durableStream` returns
71 * `StreamDurability<DurableStreamOffset>`, which is not assignable to
72 * `StreamDurability<string>` because `read` is contravariant in its offset.
73 */
74 durability: (runId: string) => StreamDurability<TOffset>
75 /** Produce the run's remaining events. Called only once the claim is held. */
76 drive: (input: {
77 runId: string
78 threadId: string
79 signal: AbortSignal
80 }) => AsyncIterable<StreamChunk>
81 /** Quiescence window; defaults to {@link DEFAULT_FENCE_QUIET_MS}. */
82 fenceQuietMs?: number
83 /** Platform keep-alive (e.g. `ctx.waitUntil`) for the background drive. */
84 waitUntil?: (promise: Promise<unknown>) => void
85 logger?: InternalLogger
86}
87
88/**
89 * `pipe` ran without a held claim. Not a recoverable condition: it means the
90 * returned options object was taken apart and `pipe` called outside `claim`, so
91 * there is no epoch to fence with and no lease guaranteeing exclusivity. Any
92 * append made in that state is exactly the duplicate-write bug the claim exists
93 * to prevent, so this fails loudly rather than appending unfenced.
94 */
95export class RunDriverPipeOutsideClaimError extends Error {
96 constructor(readonly runId: string) {
97 super(
98 `run ${runId}: sandboxRunDriver.pipe was called outside its claim, so the driver epoch is unknown; call it from within the claim callback`,
99 )
100 this.name = 'RunDriverPipeOutsideClaimError'
101 }
102}
103
104/**
105 * Fill in a core `driver` block with this package's claim and run log.
106 *
107 * `drive` receives an `AbortSignal` — the driver owns the abort, so it hands
108 * out a signal rather than a controller — but `chat()` takes an
109 * `AbortController`. Mirror one onto the other, exactly as
110 * {@link https://tanstack.com/ai/latest/docs/sandbox/takeover | Takeover & Detached Runs}'s
111 * `controllerFor` does, so a lost claim actually stops the drive.
112 *
113 * @example
114 * ```typescript
115 * function controllerFor(signal: AbortSignal): AbortController {
116 * const controller = new AbortController()
117 * const abort = (): void => controller.abort(signal.reason)
118 * if (signal.aborted) abort()
119 * else signal.addEventListener('abort', abort, { once: true })
120 * return controller
121 * }
122 *
123 * export async function GET(request: Request) {
124 * return resumeServerSentEventsResponse({
125 * adapter: memoryStream(request),
126 * driver: sandboxRunDriver({
127 * request,
128 * runs,
129 * locks,
130 * durability: (runId) => logFor(runId),
131 * drive: ({ runId, threadId, signal }) =>
132 * chat({
133 * ...config,
134 * runId,
135 * threadId,
136 * abortController: controllerFor(signal),
137 * }),
138 * }),
139 * })
140 * }
141 * ```
142 */
143export function sandboxRunDriver<TOffset extends string = string>(
144 input: SandboxRunDriverOptions<TOffset>,
145): RunDriverOptions {
146 const fenceQuietMs = input.fenceQuietMs ?? DEFAULT_FENCE_QUIET_MS
147 // The seam between core's `claim` and core's `pipe`. One options object serves
148 // one attach request and therefore one run, so a single slot is enough; it is
149 // cleared on the way out so a `pipe` after the claim released cannot reuse a
150 // stale epoch.
151 let current: RunClaim | undefined
152
153 return {
154 request: input.request,
155 runs: input.runs,
156 locks: input.locks,
157 drive: input.drive,
158 claim: (claimInput, fn) =>
159 withRunClaim(
160 {
161 ...claimInput,
162 fenceQuietMs,
163 ...(input.logger === undefined ? {} : { logger: input.logger }),
164 },
165 async (claim) => {
166 const previous = current
167 current = claim
168 try {
169 return await fn(claim)
170 } finally {
171 current = previous
172 }
173 },
174 ),
175 pipe: async (stream, i) => {
176 const claim = current
177 if (claim === undefined) {
178 throw new RunDriverPipeOutsideClaimError(i.runId)
179 }
180 // Before the first append, never after: `pipeToRunLog` snapshots to align
181 // and a predecessor still writing must be observed, not raced.
182 await awaitLogQuiescence(input.durability(i.runId), fenceQuietMs)
183 return pipeToRunLog(stream, {
184 // BOTH authoritative seams are fenced at the epoch this driver actually
185 // acquired, and they must be: `pipeToRunLog` answers a refused append by
186 // recording a terminal record, so fencing only the log leaves a
187 // superseded host marking a live run `'failed'` (see `fenceRunStore`).
188 // Neither fence covers `close()` — that stays unfenced on purpose.
189 runs: fenceRunStore(input.runs, claim, {
190 ...(input.logger === undefined ? {} : { logger: input.logger }),
191 }),
192 durability: (runId) =>
193 fenceDurability(input.durability(runId), claim, {
194 runs: input.runs,
195 }),
196 runId: i.runId,
197 threadId: i.threadId,
198 signal: i.signal,
199 ...(input.logger === undefined ? {} : { logger: input.logger }),
200 })
201 },
202 ...(input.waitUntil === undefined ? {} : { waitUntil: input.waitUntil }),
203 ...(input.logger === undefined ? {} : { logger: input.logger }),
204 }
205}