Open History to see the last commit
1/**
2 * `withSandbox(definition, options?)` — the middleware that PROVIDES the
3 * {@link SandboxCapability} a harness adapter requires.
4 *
5 * - `setup`: resume-or-create the sandbox (via the definition's ensure
6 * algorithm), provide the handle, using the durability seams from
7 * {@link SandboxMiddlewareOptions} (or, failing that, a bus-provided
8 * SandboxInstanceStoreCapability / LocksCapability, then an in-memory
9 * fallback). If `fileEvents` is not false, starts a
10 * watcher that dispatches to sandbox-scoped hooks and forwards to the runtime
11 * sink.
12 * - `onFinish`/`onAbort`/`onError`: stop the watcher, snapshot (`after-run`)
13 * and/or destroy per lifecycle.
14 *
15 * NOTE: streamed sandbox lifecycle events (sandbox.created, workspace.setup.*)
16 * are emitted by the harness adapter's chatStream (which can yield CUSTOM
17 * chunks), not from here — middleware setup runs before streaming begins.
18 */
19import {
20 defineChatMiddleware,
21 isTerminalRunStatus,
22 provideDetachableRun,
23 provideRunDetached,
24 wasCancelRequested,
25} from '@tanstack/ai'
26import { InMemoryLockStore, LocksCapability } from '@tanstack/ai/locks'
27import {
28 getPendingTurn,
29 getRunDisconnect,
30 getSandboxRuntime,
31} from '@tanstack/ai/adapter-internals'
32import {
33 SandboxCapability,
34 provideSandbox,
35 provideSandboxPolicy,
36} from './capabilities'
37import {
38 provideSandboxDurability,
39 resolveSandboxDurability,
40} from './durability'
41import { SandboxInstanceStoreCapability } from './instance-store'
42import { computeWorkspaceHash } from './key'
43import { buildFileHookEvent, resolveFileEvents } from './file-diff'
44import { ProjectionCapability, provideWorkspaceProjection } from './projection'
45import { resolveAllSecrets, resolveSecret } from './secrets'
46import {
47 createToolHistoryRecorder,
48 stripObservedToolCalls,
49} from './tool-history'
50import { watchWorkspace } from './watch'
51import { DEFAULT_WORKSPACE_ROOT } from './bootstrap'
52import { resolveHarnessCwd } from './harness-cwd'
53import { ensureSandboxWithOutcome } from './sandbox'
54import {
55 restoreSandboxFiles,
56 captureSandboxFiles,
57 captureSandboxArtifacts,
58 resolveSandboxSnapshotPolicy,
59} from './snapshots'
60import type { SandboxSnapshotPolicy } from './snapshots'
61import type {
62 SandboxCheckpointStore,
63 SandboxCheckpointWriterLease,
64} from './checkpoint-store'
65import { SandboxCheckpointError } from './checkpoint-store'
66import type { InternalLogger } from '@tanstack/ai/adapter-internals'
67import type { LockStore } from '@tanstack/ai/locks'
68import type {
69 AbortInfo,
70 ChatMiddlewareContext,
71 DefinedChatMiddleware,
72 ModelMessage,
73 RunStore,
74 SandboxFileEvent,
75 SandboxFileHookEvent,
76} from '@tanstack/ai'
77import type {
78 SandboxDurabilityOptions,
79 SandboxRunDurability,
80} from './durability'
81import type { SandboxInstanceStore } from './instance-store'
82import type { ToolHistoryRecorder } from './tool-history'
83import type { SandboxHandle } from './contracts'
84import type {
85 SandboxDefinition,
86 SandboxEnsureContext,
87 SandboxHooks,
88} from './sandbox'
89import type { SandboxWatchHandle } from './watch'
90
91/** Per-request state we need to carry from `setup` to the terminal hooks. */
92interface SandboxRunState {
93 snapshotLease?: SandboxCheckpointWriterLease
94 snapshotRenewal?: ReturnType<typeof setTimeout>
95 snapshotRenewTask?: Promise<void>
96 snapshotCaptureTask?: Promise<void>
97 snapshotRenewalGeneration: number
98 snapshotStop?: Promise<void>
99 /** A detached or paused run cannot later publish portable state. */
100 snapshotClosed?: boolean
101 snapshotLost?: Error
102 snapshotCleaned?: boolean
103 /** The run paused at an interrupt (client tool, approval, or middleware wait). */
104 interrupted?: boolean
105 snapshotConfig?: NonNullable<SandboxMiddlewareOptions['snapshots']>
106 snapshotPolicy?: SandboxSnapshotPolicy
107 snapshotRuntime?: {
108 persistence: NonNullable<
109 SandboxMiddlewareOptions['snapshots']
110 >['persistence']
111 completion: { waitForRunCompletion: () => Promise<void> }
112 }
113 /**
114 * OPTIONAL because the state is registered BEFORE `definition.ensure()` is
115 * awaited, and `ensure` is the slowest thing in the whole run — cloning a repo
116 * into a fresh sandbox is minutes wide. That window is where the most common
117 * disconnect of all lands (a user starts a run and switches away while the UI
118 * still says "starting the sandbox"), so it is the one window the teardown and
119 * disconnect hooks most need to be able to act in. Registering only after the
120 * handle exists left exactly that window uncovered.
121 *
122 * Nothing the disconnect path does needs the handle: `detachedSince` and
123 * `sandboxKey` come from `ensureCtx`, which is built before `ensure` is called.
124 * Only `onFinish`'s snapshot needs it, and that cannot run before `setup` has
125 * completed.
126 */
127 handle?: SandboxHandle
128 privateHandle?: boolean
129 ensureCtx: SandboxEnsureContext
130 watcher?: SandboxWatchHandle
131 /** In-flight `enriched.diff()` promises queued by the `fileEvents.diff`
132 * watcher callback, awaited before teardown so a pending diff isn't
133 * dropped when the run finishes/aborts/errors mid-computation. */
134 pendingDiffs: Array<Promise<void>>
135 /** Logger captured at setup, so terminal hooks can log watcher teardown. */
136 logger?: InternalLogger
137 /**
138 * Durability resolved once at setup (absent when the run is not durable), so
139 * `onAbort` cannot reach a different verdict than the one `setup` published
140 * on the capability bus.
141 */
142 durability?: SandboxRunDurability
143 /**
144 * Records the harness's own tool calls into the transcript, so a finished run
145 * restores its tool cards from the message store instead of only from the (live,
146 * rejoin-only) delivery log. See `./tool-history`.
147 */
148 toolHistory: ToolHistoryRecorder
149}
150
151const runState = new WeakMap<object, SandboxRunState>()
152
153function stopSnapshotLease(
154 state: SandboxRunState,
155 options: { closePortable?: boolean } = {},
156): Promise<void> {
157 if (options.closePortable) state.snapshotClosed = true
158 if (state.snapshotStop) return state.snapshotStop
159 if (state.snapshotCleaned) return Promise.resolve()
160 state.snapshotCleaned = true
161 state.snapshotRenewalGeneration++
162 if (state.snapshotRenewal !== undefined) clearTimeout(state.snapshotRenewal)
163 state.snapshotRenewal = undefined
164 const renewTask = state.snapshotRenewTask
165 const captureTask = state.snapshotCaptureTask
166 const lease = state.snapshotLease
167 state.snapshotLease = undefined
168 state.snapshotStop = (async () => {
169 await renewTask?.catch(() => {})
170 await captureTask?.catch(() => {})
171 await lease?.release()
172 })()
173 return state.snapshotStop
174}
175
176function startSnapshotRenewal(state: SandboxRunState): void {
177 const lease = state.snapshotLease
178 if (!lease) return
179 const schedule = (): void => {
180 const generation = state.snapshotRenewalGeneration
181 state.snapshotRenewal = setTimeout(() => {
182 void (async (): Promise<void> => {
183 state.snapshotRenewal = undefined
184 if (
185 state.snapshotCleaned ||
186 generation !== state.snapshotRenewalGeneration
187 )
188 return
189 const renewal = Promise.resolve().then(async (): Promise<void> => {
190 await lease.renew()
191 })
192 state.snapshotRenewTask = renewal
193 try {
194 await renewal
195 } catch (error) {
196 state.snapshotLost =
197 error instanceof Error ? error : new Error(String(error))
198 } finally {
199 if (state.snapshotRenewTask === renewal)
200 state.snapshotRenewTask = undefined
201 }
202 if (state.snapshotLost) await stopSnapshotLease(state).catch(() => {})
203 else if (
204 !state.snapshotCleaned &&
205 generation === state.snapshotRenewalGeneration
206 )
207 schedule()
208 })()
209 }, lease.renewAfterMs)
210 }
211 schedule()
212}
213
214/**
215 * Stop the watcher and drain any in-flight `diff()` promises before teardown,
216 * so the final file's diff isn't dropped when a run finishes/aborts/errors
217 * mid-computation. The `pendingDiffs` await is the load-bearing line — without
218 * it a deferred diff resolves after the run is gone and its chunk is lost.
219 */
220async function drainWatcher(
221 state: SandboxRunState,
222 phase: 'finish' | 'pause' | 'abort' | 'error',
223): Promise<void> {
224 // Guard `stop()`: a rejecting watcher teardown must NOT propagate out of
225 // here, or the caller skips the `definition.destroy(...)` that follows —
226 // leaking the sandbox on exactly the abort path that must ALWAYS tear down.
227 try {
228 await state.watcher?.stop()
229 } catch (error) {
230 state.logger?.warn('sandbox watcher stop failed', { phase, error })
231 }
232 await Promise.allSettled(state.pendingDiffs)
233 if (state.watcher) state.logger?.sandbox('sandbox watcher stopped', { phase })
234}
235
236function canPublishPortableSnapshot(
237 state: SandboxRunState,
238 lease: SandboxCheckpointWriterLease,
239): boolean {
240 if (state.snapshotLost) throw state.snapshotLost
241 return (
242 !state.snapshotClosed &&
243 !state.snapshotCleaned &&
244 state.snapshotLease === lease
245 )
246}
247
248/**
249 * Record the two facts a later attach and the reaper both need, then publish the
250 * detach verdict core reads.
251 *
252 * Shared by the DISCONNECT subscriber registered in `setup` (the run is still
253 * going — the normal case) and `onAbort`'s detach branch (the run is being torn
254 * down while detachable), so the two can never write a different shape of detach.
255 *
256 * GUARDED, and reports failure rather than throwing. `update` is a documented
257 * no-op for an unknown runId, so a vanished record does not turn teardown into a
258 * throw; a genuinely rejecting store is the caller's to react to — `onAbort` falls
259 * through to destroying the sandbox, because a DESTROYED sandbox beats an
260 * unreachable one, while the disconnect subscriber has nothing to fall back to
261 * (the run is alive and still using the sandbox) and simply leaves the verdict
262 * unpublished.
263 *
264 * The verdict is published ONLY on success. Publishing it after a failed record
265 * write would leave core holding the log open for a takeover that can never be
266 * found, since nothing in the store points at the run.
267 */
268async function recordDetach(
269 definition: SandboxDefinition,
270 state: SandboxRunState,
271 durability: SandboxRunDurability,
272 ctx: ChatMiddlewareContext,
273 phase: 'disconnect' | 'abort',
274): Promise<boolean> {
275 try {
276 // A late abort from a superseded host can run after takeover has already
277 // completed the run. Re-stamping `detachedSince` then leaves a finished
278 // record looking detached. Skip the write; return true so `onAbort` does
279 // not treat this as a failed stamp and destroy the sandbox.
280 try {
281 const current = await durability.runs.get(ctx.runId)
282 if (current !== null && isTerminalRunStatus(current.status)) {
283 return true
284 }
285 } catch {
286 // Unreadable store: still try the update. A get() failure must not skip
287 // the stamp — that is how a cancel-probe rejection used to skip both
288 // detach and destroy.
289 }
290 // The record already exists: `setup` pre-creates it for every durable run
291 // BEFORE `ensure`, precisely so this stamp cannot land on a runId the store has
292 // never heard of — `RunStore.update` is a documented no-op for an unknown
293 // runId, which is how the detach used to be lost silently (measured against the
294 // browser repro: `detached_since` and `sandbox_key` both stayed NULL for a run
295 // that had genuinely detached). If it has since vanished, that no-op is the
296 // correct outcome and this must not throw.
297 await durability.runs.update(ctx.runId, {
298 detachedSince: Date.now(),
299 sandboxKey: definition.key(state.ensureCtx),
300 })
301 } catch (error) {
302 state.logger?.warn('sandbox detach record write failed', {
303 runId: ctx.runId,
304 phase,
305 error,
306 })
307 return false
308 }
309 // Core's durable delivery sink reads this (see `RunDetachedCapability`) and
310 // leaves the run's log OPEN instead of appending a synthetic terminal
311 // `RUN_ERROR` and closing it — a terminalized log ends a later attach's replay
312 // at the prefix and diverges the takeover's journal replay, which recorded a
313 // healthy detached run as `'failed'`.
314 provideRunDetached(ctx, true)
315 return true
316}
317
318/**
319 * Whether an out-of-band cancel has been recorded for this run, in EITHER band.
320 * A user pressing Stop and a user closing the tab produce the IDENTICAL
321 * connection close, so intent is never inferred from the disconnect itself: it
322 * arrives in-process (the abort reason carried the cancel sentinel) or durably
323 * (another host recorded it on the run record).
324 */
325async function cancelIntent(
326 durability: SandboxRunDurability | undefined,
327 runId: string,
328 inProcess: boolean,
329): Promise<boolean> {
330 if (inProcess) return true
331 if (durability === undefined) return false
332 // No guard needed here, and one would be dead code: `wasCancelRequested` already
333 // answers `false` for a store read that rejects. That matters on this path,
334 // because a rejection escaping into `onAbort` would skip BOTH of its branches at
335 // once, leaving a sandbox that is neither reclaimable nor destroyed. The test
336 // 'DETACHES when the cancel probe REJECTS' pins the composition.
337 return wasCancelRequested(durability.runs, runId)
338}
339
340/** Defensively pull tenant scoping out of the runtime context, if present. */
341function tenantFrom(
342 context: unknown,
343): { userId?: string; orgId?: string } | undefined {
344 if (context === null || typeof context !== 'object') return undefined
345 const c = context as Record<string, unknown>
346 const userId = typeof c.userId === 'string' ? c.userId : undefined
347 const orgId = typeof c.orgId === 'string' ? c.orgId : undefined
348 if (userId === undefined && orgId === undefined) return undefined
349 return { userId, orgId }
350}
351
352/**
353 * Durability seams for a sandboxed run. Both are optional; each independently
354 * falls back to a process-lifetime in-memory default, which is correct for a
355 * single process but NOT across replicas.
356 */
357export interface SandboxMiddlewareOptions<TOffset extends string = string> {
358 snapshots?: {
359 persistence: {
360 stores: {
361 messages: {
362 loadThread: (threadId: string) => Promise<ReadonlyArray<ModelMessage>>
363 }
364 artifacts: {
365 listForThread: (threadId: string) => Promise<
366 ReadonlyArray<{
367 artifactId: string
368 runId: string
369 threadId: string
370 blobKey: string
371 name: string
372 mimeType: string
373 size: number
374 createdAt: number
375 }>
376 >
377 }
378 blobs: {
379 get: (key: string) => Promise<{
380 arrayBuffer: () => Promise<ArrayBuffer>
381 } | null>
382 head: (key: string) => Promise<unknown>
383 put: (key: string, body: Uint8Array) => Promise<unknown>
384 }
385 }
386 }
387 checkpoints: SandboxCheckpointStore
388 policy?: SandboxSnapshotPolicy
389 }
390 /**
391 * Durable instance map (which provider sandbox to resume for a key). Pass
392 * your own store to make resume survive across processes/replicas.
393 *
394 * Takes precedence over a store provided on the capability bus (see
395 * `provideSandboxInstanceStore`), so the call site wins over ambient wiring.
396 */
397 instances?: SandboxInstanceStore
398 /**
399 * Distributed lock serializing resume-or-create for one key. Needed for
400 * multi-replica correctness so two concurrent runs don't both create.
401 *
402 * Prefer `withLocks` from `@tanstack/ai/locks` when other middleware also
403 * needs the lock; use this option to scope one to this sandbox. Takes
404 * precedence over a bus-provided lock.
405 */
406 locks?: LockStore
407 /**
408 * Run lifecycle records. Pair with `durability.adapter` to make a run
409 * DETACHABLE: a client disconnect then leaves the agent running and records
410 * `detachedSince` instead of destroying the sandbox.
411 *
412 * Pass the SAME store chat persistence uses (`persistence.stores.runs`) so
413 * one record describes the run instead of two that can disagree.
414 *
415 * Defaults to `undefined`: an app that passes neither this nor `durability`
416 * keeps today's destroy-on-disconnect behavior exactly.
417 */
418 runs?: RunStore
419 /**
420 * Delivery durability for the run's event log, plus the journal and detach
421 * knobs. Requires `runs`; either alone is not durable.
422 *
423 * `TOffset` is inferred from the adapter passed here, so a branded-cursor
424 * backend (`durableStream`) wires without a cast and without the call site
425 * ever naming the parameter.
426 */
427 durability?: SandboxDurabilityOptions<TOffset>
428}
429
430/**
431 * Resolve the ensure seams. Precedence is explicit option → capability bus →
432 * (in `ensure`) the in-memory fallback. The option wins because it is visible
433 * at the call site; the bus remains for platform/framework injection.
434 */
435function buildEnsureCtx(
436 ctx: ChatMiddlewareContext,
437 // Narrowed to the two seams it reads rather than taking the whole options
438 // object: `SandboxMiddlewareOptions` is now generic in the durability offset,
439 // and `SandboxMiddlewareOptions<TOffset>` is not assignable to
440 // `SandboxMiddlewareOptions<string>`. Both members here are offset-free, so
441 // the narrowing keeps this helper independent of that parameter entirely.
442 options: Pick<SandboxMiddlewareOptions, 'instances' | 'locks'> | undefined,
443): SandboxEnsureContext {
444 return {
445 threadId: ctx.threadId,
446 runId: ctx.runId,
447 store:
448 options?.instances ?? ctx.getOptional(SandboxInstanceStoreCapability),
449 locks: options?.locks ?? ctx.getOptional(LocksCapability),
450 tenant: tenantFrom(ctx.context),
451 signal: ctx.signal,
452 adapterName: ctx.provider,
453 }
454}
455
456/**
457 * Dispatch a sandbox file event to the per-type hooks declared on the
458 * definition. Errors in individual hooks are swallowed so one bad hook
459 * cannot break the run — but are logged under the `errors` category first, so
460 * a throwing hook is observable (matching the run-scoped path in the engine
461 * and the behavior the observability docs promise).
462 */
463async function dispatchDefinitionHooks(
464 hooks: SandboxHooks | undefined,
465 event: SandboxFileHookEvent,
466 logger?: InternalLogger,
467): Promise<void> {
468 if (!hooks) return
469 const typed = (
470 {
471 create: 'onFileCreate',
472 change: 'onFileChange',
473 delete: 'onFileDelete',
474 } as const
475 )[event.type]
476 for (const fn of [hooks.onFile, hooks[typed]]) {
477 if (!fn) continue
478 try {
479 await fn(event)
480 } catch (error) {
481 // swallowed — one bad hook must not break the run — but logged so the
482 // failure isn't invisible.
483 logger?.errors('sandbox file hook failed', {
484 path: event.path,
485 type: event.type,
486 error,
487 })
488 }
489 }
490}
491
492export function withSandbox<TOffset extends string = string>(
493 definition: SandboxDefinition,
494 options?: SandboxMiddlewareOptions<TOffset>,
495): DefinedChatMiddleware<
496 unknown,
497 readonly [],
498 readonly [typeof SandboxCapability, typeof ProjectionCapability]
499> {
500 return defineChatMiddleware({
501 name: 'sandbox',
502 provides: [SandboxCapability, ProjectionCapability],
503 // SandboxPolicyCapability is provided conditionally (only when the
504 // definition has a policy), so it is intentionally NOT declared here —
505 // consumers read it via `getOptional`. SandboxDurabilityCapability and
506 // DetachableRunCapability are conditional for the same reason (only when
507 // `runs` + `durability` are both wired), so they are intentionally NOT
508 // declared here either.
509 optionalRequires: [SandboxInstanceStoreCapability, LocksCapability],
510
511 async setup(ctx) {
512 const ensureCtx = buildEnsureCtx(ctx, options)
513 const snapshotConfig = options?.snapshots
514 const snapshotWorkspaceHash = definition.workspace
515 ? computeWorkspaceHash(definition.workspace)
516 : undefined
517 const snapshotPolicy = snapshotConfig
518 ? resolveSandboxSnapshotPolicy(
519 snapshotConfig.policy,
520 snapshotWorkspaceHash,
521 )
522 : undefined
523 let snapshotRuntime:
524 | {
525 persistence: {
526 stores: {
527 messages: {
528 loadThread: (
529 id: string,
530 ) => Promise<ReadonlyArray<ModelMessage>>
531 }
532 artifacts: {
533 listForThread: (id: string) => Promise<
534 ReadonlyArray<{
535 artifactId: string
536 runId: string
537 threadId: string
538 blobKey: string
539 name: string
540 mimeType: string
541 size: number
542 createdAt: number
543 }>
544 >
545 }
546 blobs: {
547 get: (key: string) => Promise<{
548 arrayBuffer: () => Promise<ArrayBuffer>
549 } | null>
550 head: (key: string) => Promise<unknown>
551 put: (key: string, body: Uint8Array) => Promise<unknown>
552 }
553 }
554 }
555 completion: { waitForRunCompletion: () => Promise<void> }
556 }
557 | undefined
558 let snapshotLease: SandboxCheckpointWriterLease | undefined
559 if (snapshotConfig) {
560 if (
561 !snapshotConfig.persistence?.stores?.messages ||
562 !snapshotConfig.persistence.stores.artifacts ||
563 !snapshotConfig.persistence.stores.blobs
564 )
565 throw new Error(
566 'Sandbox snapshots require persistence stores.messages, stores.artifacts, and stores.blobs',
567 )
568 const persistenceModule = await import('@tanstack/ai-persistence')
569 const persistence = ctx.getOptional(
570 persistenceModule.PersistenceCapability,
571 )
572 if (persistence === undefined)
573 throw new Error(
574 'Sandbox snapshots require withPersistence(snapshots.persistence) before withSandbox',
575 )
576 if (persistence !== snapshotConfig.persistence)
577 throw new Error(
578 'Sandbox snapshots require the same persistence instance passed to withPersistence',
579 )
580 const completion = ctx.getOptional(
581 persistenceModule.PersistenceCompletionCapability,
582 )
583 if (!completion)
584 throw new Error(
585 'Sandbox snapshots require withPersistence before withSandbox',
586 )
587 snapshotRuntime = {
588 persistence: snapshotConfig.persistence,
589 completion,
590 }
591 snapshotLease = await snapshotConfig.checkpoints.acquireWriter(
592 ctx.threadId,
593 )
594 }
595
596 // Resolving here (not lazily on the abort path) is what keeps `setup` and
597 // `onAbort` on one verdict: the payload the bus carries is the same object
598 // the teardown path consults.
599 // `TOffset` is passed explicitly: `options` is possibly `undefined` here,
600 // so inference has nothing to work from on that branch and would fall
601 // back to the `= string` default, re-erecting the very wall this
602 // parameter exists to remove.
603 const durability = resolveSandboxDurability<TOffset>(options)
604 if (durability !== undefined) {
605 provideSandboxDurability(ctx, durability)
606 // A neutral boolean core owns, so `@tanstack/ai-persistence` can ask
607 // "is this run detachable?" without depending on this package.
608 provideDetachableRun(ctx, true)
609 }
610
611 // Pull the runtime (and its logger) up front so `baseSha` capture and
612 // hook dispatch below can log through the same `sandbox`/`errors`
613 // categories the engine uses.
614 const runtime = getSandboxRuntime(ctx, { optional: true })
615 const logger = runtime?.logger
616
617 // REGISTER THE RUN STATE NOW — before `definition.ensure()`, not merely
618 // before the end of `setup`.
619 //
620 // `onAbort` and the disconnect subscriber both need this state, so until
621 // this map is populated they are silent no-ops. `ensure` is the LONGEST
622 // await in the entire run (create a sandbox, clone a repo — minutes), and it
623 // is where the most common disconnect of all lands: a user starts a run and
624 // switches away while the UI still says "starting the sandbox". Registering
625 // after `ensure` returned still left that whole window uncovered.
626 //
627 // Leaving it uncovered loses every teardown behavior at once: no
628 // `detachedSince`/`sandboxKey`, so `listReclaimable` can never surface the
629 // run and the reaper can never reclaim it; no `definition.destroy`, so the
630 // sandbox leaks; and no detach verdict for core to read.
631 //
632 // Everything those hooks read is already resolved above: the ensure context
633 // (which is all `definition.key` needs), the durability verdict, and the
634 // logger. The fields discovered later (`handle`, `watcher`) are ASSIGNED onto
635 // this same object as they become available, so the teardown path always
636 // sees the most complete state that exists at the moment it runs.
637 const state: SandboxRunState = {
638 ensureCtx,
639 snapshotRenewalGeneration: 0,
640 pendingDiffs: [],
641 toolHistory: createToolHistoryRecorder(),
642 ...(logger ? { logger } : {}),
643 ...(durability ? { durability } : {}),
644 }
645 runState.set(ctx, state)
646 if (snapshotLease) {
647 state.snapshotLease = snapshotLease
648 startSnapshotRenewal(state)
649 }
650
651 // MAKE THE RUN FINDABLE BEFORE `ensure`, not after the run finally streams.
652 //
653 // Chat persistence creates the run record from `onConfig`, which runs after
654 // EVERY middleware `setup` — so for the whole of `definition.ensure` (create a
655 // sandbox, clone a repo: minutes) the run has no record at all, and
656 // `findActiveRun` answers "no active run" for a run that is demonstrably
657 // starting. Measured: a status sidebar read straight off `findActiveRun`
658 // reported `idle` for 6.5 minutes while the sandbox was being built, and a
659 // client returning to the thread in that window had nothing to tell it a run
660 // was in flight — so it rendered an empty pane instead of "starting sandbox".
661 //
662 // A crash in the same window is worse: no record means `listReclaimable` can
663 // never surface the run, so the sandbox leaks with no recovery path.
664 //
665 // `createOrResume` is idempotent and never resurrects a finished run, so
666 // persistence's own later call stays correct and simply finds this record.
667 if (durability !== undefined) {
668 try {
669 await durability.runs.createOrResume({
670 runId: ctx.runId,
671 threadId: ctx.threadId,
672 startedAt: Date.now(),
673 })
674 } catch (error) {
675 // Best-effort: a store blip must not stop a run that is otherwise fine.
676 // The run is simply invisible until persistence's own `onConfig` call.
677 logger?.warn('sandbox run record pre-create failed', {
678 runId: ctx.runId,
679 error,
680 })
681 }
682
683 // NO ATTACH MARKER HERE. A joiner does need a chunk in the log before the
684 // harness has emitted anything — an empty log fails every joiner's
685 // fast-fail (`memoryStream`'s first-chunk deadline, the client's rejoin
686 // connect deadline) and flushes no HTTP headers, so a reload during
687 // `ensure` reads a live run as gone. Core does it: a fresh durable producer
688 // appends `RUN_ACCEPTED_EVENT` before the producer stream is first pulled,
689 // for EVERY durable run rather than only sandboxed ones, and never on an
690 // attach. A second marker from here would only land mid-stream in a run
691 // that is already producing.
692
693 // STORE THE USER'S TURN NOW, before `ensure` takes minutes.
694 //
695 // Chat persistence stores it from `onStart`, which runs after every
696 // middleware `setup` — so without this the thread holds NOTHING for the
697 // whole sandbox build. Measured: a reload during the build asked the server
698 // for the conversation and got `{"messages":[],…}`, so the user saw no sign
699 // of the message they had just sent, and a second device saw an empty
700 // thread.
701 //
702 // The persistence layer owns WHAT gets stored (see `PendingTurnCapability`):
703 // `saveThread` replaces the thread, so deciding the list here would risk
704 // deleting the history. Absent when the app wires no persistence, which is
705 // simply a run with no transcript to store.
706 try {
707 await getPendingTurn(ctx, { optional: true })?.snapshot()
708 } catch (error) {
709 // Best-effort: the run is still worth doing, and `onStart` stores the
710 // turn again once setup completes.
711 logger?.warn('sandbox pending-turn snapshot failed', {
712 runId: ctx.runId,
713 error,
714 })
715 }
716 }
717
718 // SUBSCRIBE BEFORE `ensure`, for the same reason the state is registered
719 // before it: `ensure` is the minutes-wide await a disconnect actually lands
720 // in. Core calls back immediately if the socket has already closed, so
721 // subscribing here cannot miss a disconnect that beat us to it.
722 //
723 // This is what makes a durable run SURVIVE losing its viewer. The only route
724 // a disconnect previously had into this middleware was the application
725 // mirroring `request.signal` into `chat()`'s `abortController` — which aborts
726 // the run, so `chat()` returned right after this `setup` and the harness
727 // adapter's `chatStream` was never called: the agent in the sandbox we just
728 // spent minutes creating was NEVER LAUNCHED, and no takeover could recover it
729 // because an agent that never ran wrote no journal to replay.
730 if (durability !== undefined && durability.detachOnDisconnect) {
731 getRunDisconnect(ctx, { optional: true })?.subscribe(async () => {
732 const snapshotStop = stopSnapshotLease(state, {
733 closePortable: true,
734 })
735 void snapshotStop.catch(() => {})
736 // BOOKKEEPING ONLY — the run is still executing. Deliberately absent:
737 // `drainWatcher` (would blind a live agent's file events for the whole
738 // remainder) and `definition.destroy` (the run is still using the
739 // sandbox). Both belong to the terminal hooks, which still run exactly
740 // once afterwards.
741 //
742 // A run with a cancel already recorded is left alone: that is `onAbort`'s
743 // path, and stamping `detachedSince` on a deliberately-stopped run would
744 // hand it to the reaper as reclaimable work.
745 if (await cancelIntent(durability, ctx.runId, false)) {
746 await snapshotStop.catch((error: unknown) => {
747 state.logger?.warn('sandbox snapshot writer release failed', {
748 runId: ctx.runId,
749 phase: 'disconnect',
750 error,
751 })
752 })
753 return
754 }
755 if (
756 await recordDetach(definition, state, durability, ctx, 'disconnect')
757 ) {
758 try {
759 await snapshotStop
760 } catch (error) {
761 state.logger?.warn('sandbox snapshot writer release failed', {
762 runId: ctx.runId,
763 phase: 'disconnect',
764 error,
765 })
766 }
767 state.logger?.sandbox(
768 'sandbox run detached on disconnect; the run continues',
769 { runId: ctx.runId },
770 )
771 } else {
772 await snapshotStop.catch((error: unknown) => {
773 state.logger?.warn('sandbox snapshot writer release failed', {
774 runId: ctx.runId,
775 phase: 'disconnect',
776 error,
777 })
778 })
779 }
780 })
781 }
782
783 let outcome: 'resumed' | 'native-restored' | 'created' = 'created'
784 let handle: SandboxHandle
785 try {
786 if (snapshotConfig)
787 ({ handle, outcome } = await ensureSandboxWithOutcome(
788 definition,
789 ensureCtx,
790 ))
791 else handle = await definition.ensure(ensureCtx)
792 state.handle = handle
793 state.privateHandle = snapshotConfig ? outcome !== 'resumed' : true
794 if (snapshotConfig && outcome !== 'resumed') {
795 const head = await snapshotConfig.checkpoints.getHead(ctx.threadId)
796 if (head) {
797 const checkpoint = await snapshotConfig.checkpoints.get(head)
798 if (!checkpoint)
799 throw new SandboxCheckpointError(
800 'SANDBOX_SNAPSHOT_CHECKPOINT_NOT_FOUND',
801 `Checkpoint '${head}' was not found`,
802 )
803 await restoreSandboxFiles(
804 handle,
805 {
806 blobs: snapshotConfig.persistence.stores.blobs,
807 workspaceRoot:
808 definition.workspace?.root ?? DEFAULT_WORKSPACE_ROOT,
809 },
810 checkpoint,
811 snapshotPolicy,
812 )
813 }
814 }
815 } catch (error) {
816 await stopSnapshotLease(state).catch(() => {})
817 if (state.handle && state.privateHandle)
818 await definition.destroy(ensureCtx).catch(() => {})
819 throw error
820 }
821 // MUTATE, don't re-`set`: a disconnect that landed during `ensure` already
822 // captured this object.
823 state.handle = handle
824 if (snapshotConfig) {
825 state.snapshotConfig = snapshotConfig
826 state.snapshotPolicy = snapshotPolicy
827 state.snapshotRuntime = snapshotRuntime
828 }
829 try {
830 provideSandbox(ctx, handle)
831 if (definition.policy) provideSandboxPolicy(ctx, definition.policy)
832
833 // Deliberately placed AFTER `logger` is in scope rather than next to the
834 // `provideSandboxDurability` call above — there is no logger to warn
835 // through until the runtime has been read.
836 //
837 // `ensureCtx.locks === undefined` counts as in-memory: `defineSandbox`'s
838 // `ensure` falls back to a process-lifetime `InMemoryLockStore` when no
839 // lock is wired, so an unwired lock has exactly the deficiency being
840 // warned about — it is the MOST in-memory case, not an exempt one.
841 if (
842 durability !== undefined &&
843 (ensureCtx.locks === undefined ||
844 ensureCtx.locks instanceof InMemoryLockStore)
845 ) {
846 logger?.warn(
847 'sandbox durability is wired over an InMemoryLockStore: run claims are ' +
848 'serialized within this process only and the lease never signals loss, ' +
849 'so two hosts can drive one run and duplicate its event log. Use a ' +
850 'distributed LockStore via withLocks for any multi-replica deploy.',
851 { runId: ctx.runId },
852 )
853 }
854
855 const watchRoot = definition.workspace?.root ?? DEFAULT_WORKSPACE_ROOT
856 let baseSha = ''
857 try {
858 const shaRes = await handle.process.exec('git rev-parse HEAD', {
859 cwd: watchRoot,
860 })
861 if (shaRes.exitCode === 0) {
862 baseSha = shaRes.stdout.trim()
863 logger?.sandbox('sandbox git baseline captured', {
864 root: watchRoot,
865 baseSha,
866 })
867 } else {
868 // Non-zero exit: either not a git repository (non-git workspace) or a
869 // repo with no commits (no HEAD). Expected, but it silently degrades
870 // every subsequent diff to a full-file add-patch, so surface it
871 // under `sandbox` (with stderr) rather than leaving nothing to grep.
872 logger?.sandbox(
873 'sandbox git baseline unavailable (non-zero exit)',
874 {
875 root: watchRoot,
876 exitCode: shaRes.exitCode,
877 stderr: shaRes.stderr,
878 },
879 )
880 }
881 } catch (error) {
882 // exec rejected (git not on PATH, exec seam broken) → baseSha stays ''
883 // and accessors fall back, but this is a real anomaly, not a plain
884 // non-git workspace, so warn.
885 logger?.warn('sandbox git baseline capture failed', {
886 root: watchRoot,
887 error,
888 })
889 }
890
891 const workspace = definition.workspace
892 if (workspace !== undefined) {
893 const virtualRoot = workspace.root ?? DEFAULT_WORKSPACE_ROOT
894 const root = resolveHarnessCwd(handle, virtualRoot)
895 const workspaceHash = computeWorkspaceHash(workspace)
896 const secrets = workspace.secrets
897 provideWorkspaceProjection(ctx, {
898 skills: workspace.skills ?? [],
899 plugins: workspace.plugins ?? [],
900 resolveSecret: (ref) => {
901 if (secrets === undefined) {
902 throw new Error(
903 `resolveSecret: no secrets defined on this workspace (ref: "${ref.__secretName}")`,
904 )
905 }
906 return resolveSecret(secrets, ref)
907 },
908 markerPath: `${root}/.tanstack-projected-${workspaceHash}`,
909 root,
910 ...(workspace.scripts !== undefined
911 ? { scripts: workspace.scripts }
912 : {}),
913 })
914 }
915
916 const hooks = definition.hooks
917 await hooks?.onReady?.(handle)
918
919 const fe = resolveFileEvents(definition.fileEvents)
920 // THE SAME array the run state already holds, not a fresh one. The watcher
921 // callback below closes over this reference, and `drainWatcher` awaits
922 // `state.pendingDiffs` — a second array would silently drop every in-flight
923 // diff from the teardown drain.
924 const pendingDiffs = state.pendingDiffs
925 let watcher: SandboxWatchHandle | undefined
926 if (fe.enabled) {
927 watcher = await watchWorkspace(handle, {
928 onEvent: (event: SandboxFileEvent) => {
929 const enriched = buildFileHookEvent(
930 handle,
931 watchRoot,
932 baseSha,
933 event,
934 logger,
935 )
936 void dispatchDefinitionHooks(hooks, enriched, logger)
937 runtime?.emit(enriched)
938 if (fe.diff) {
939 pendingDiffs.push(
940 enriched
941 .diff()
942 .then((diff) => {
943 runtime?.emitFileDiff({ path: event.path, diff })
944 })
945 .catch((error: unknown) => {
946 logger?.warn('sandbox file diff emit failed', {
947 path: event.path,
948 error,
949 })
950 }),
951 )
952 }
953 },
954 // Watch the SAME root the enrichment layer relativizes against
955 // (`buildFileHookEvent(handle, watchRoot, …)` and the `baseSha`
956 // capture). Without this the watcher defaults to `/workspace` while
957 // enrichment uses `watchRoot`, so a custom `workspace.root` makes the
958 // two look at different directories and git pathspecs break.
959 root: watchRoot,
960 ...(ctx.signal !== undefined ? { signal: ctx.signal } : {}),
961 ...(logger !== undefined ? { logger } : {}),
962 })
963 logger?.sandbox('sandbox watcher started', {
964 root: watchRoot,
965 diff: fe.diff,
966 })
967 }
968
969 // MUTATE the object registered above rather than `set`-ing a second one: an
970 // abort that landed mid-setup already captured a reference to it (and may
971 // already be draining `pendingDiffs`), so replacing the entry would hand the
972 // teardown path a different object than the watcher writes into.
973 // `pendingDiffs` needs no copying — it IS `state.pendingDiffs`.
974 if (watcher) state.watcher = watcher
975 } catch (error) {
976 await drainWatcher(state, 'error')
977 await stopSnapshotLease(state).catch(() => {})
978 if (state.privateHandle)
979 await definition.destroy(ensureCtx).catch(() => {})
980 throw error
981 }
982 },
983
984 // Keep the recorded tool history OUT of the request to the model. It is stored
985 // history for the next turn, it names tools the provider was never given, and one
986 // triage-sized run is hundreds of kilobytes — so replaying it is wasteful at best
987 // and rejected at worst. `ctx.messages` keeps it (that is what gets stored and
988 // rendered); only `config.messages` loses it.
989 onConfig(_ctx, config) {
990 const messages = stripObservedToolCalls(config.messages)
991 if (messages.length === config.messages.length) return
992 return { messages }
993 },
994
995 // The engine re-syncs `middlewareCtx.messages` from its own array once per agent
996 // iteration, which drops whatever the recorder appended during the previous
997 // iteration's stream. Restoring it here — AFTER that sync — is what makes a
998 // multi-iteration run keep its full history without depending on where this
999 // middleware sits relative to persistence in the middleware array.
1000 onIteration(ctx) {
1001 runState.get(ctx)?.toolHistory.reconcile(ctx)
1002 },
1003
1004 // Record the harness's own tool calls as transcript messages. Observe only:
1005 // returning nothing passes every chunk through untouched.
1006 async onChunk(ctx, chunk) {
1007 const state = runState.get(ctx)
1008 state?.toolHistory.observe(chunk, ctx)
1009 if (
1010 state &&
1011 chunk.type === 'RUN_FINISHED' &&
1012 chunk.outcome?.type === 'interrupt'
1013 ) {
1014 state.interrupted = true
1015 await drainWatcher(state, 'pause')
1016 await stopSnapshotLease(state, { closePortable: true })
1017 }
1018 },
1019
1020 async onFinish(ctx) {
1021 const state = runState.get(ctx)
1022 // `chat()` also calls `onFinish` when the run pauses at an interrupt. The
1023 // run is not complete, so keep the sandbox: no after-run snapshot and no
1024 // `destroyOnComplete`. `onChunk` already stopped the watcher and the lease.
1025 if (!state || state.interrupted) return
1026 const { handle, ensureCtx } = state
1027
1028 // Last chance before persistence writes the transcript. Only matters if a
1029 // config sync landed after the final tool chunk; the recorder is idempotent, so
1030 // in the normal case this changes nothing.
1031 state.toolHistory.reconcile(ctx)
1032
1033 await drainWatcher(state, 'finish')
1034
1035 let primaryError: unknown
1036 try {
1037 const snapshotCaptureTask = Promise.resolve().then(
1038 async (): Promise<void> => {
1039 const config = state.snapshotConfig
1040 const runtime = state.snapshotRuntime
1041 const lease = state.snapshotLease
1042 if (!config || !runtime || !handle || !lease) {
1043 if (state.snapshotLost) throw state.snapshotLost
1044 return
1045 }
1046 if (!canPublishPortableSnapshot(state, lease)) return
1047
1048 await runtime.completion.waitForRunCompletion()
1049 if (!canPublishPortableSnapshot(state, lease)) return
1050
1051 const conversation =
1052 await runtime.persistence.stores.messages.loadThread(ctx.threadId)
1053 if (!canPublishPortableSnapshot(state, lease)) return
1054
1055 const files = await captureSandboxFiles(
1056 handle,
1057 {
1058 blobs: config.persistence.stores.blobs,
1059 workspaceRoot:
1060 definition.workspace?.root ?? DEFAULT_WORKSPACE_ROOT,
1061 },
1062 state.snapshotPolicy,
1063 definition.workspace?.secrets !== undefined
1064 ? resolveAllSecrets(definition.workspace.secrets)
1065 : {},
1066 )
1067 if (!canPublishPortableSnapshot(state, lease)) return
1068
1069 const artifacts = await captureSandboxArtifacts(
1070 {
1071 blobs: config.persistence.stores.blobs,
1072 artifacts: config.persistence.stores.artifacts,
1073 },
1074 ctx.threadId,
1075 definition.workspace?.secrets !== undefined
1076 ? resolveAllSecrets(definition.workspace.secrets)
1077 : {},
1078 )
1079 if (!canPublishPortableSnapshot(state, lease)) return
1080
1081 const parentCheckpointId = await config.checkpoints.getHead(
1082 ctx.threadId,
1083 )
1084 if (!canPublishPortableSnapshot(state, lease)) return
1085
1086 try {
1087 await config.checkpoints.append({
1088 checkpoint: {
1089 id: `checkpoint-${ctx.runId}`,
1090 threadId: ctx.threadId,
1091 parentCheckpointId,
1092 createdAt: Date.now(),
1093 reason: 'automatic',
1094 sourceRunId: ctx.runId,
1095 files: files.files,
1096 conversation,
1097 artifacts,
1098 },
1099 expectedHeadId: parentCheckpointId,
1100 writer: lease,
1101 })
1102 } catch (error) {
1103 if (state.snapshotLost) throw state.snapshotLost
1104 throw error
1105 }
1106 if (state.snapshotLost) throw state.snapshotLost
1107 },
1108 )
1109 state.snapshotCaptureTask = snapshotCaptureTask
1110 try {
1111 await snapshotCaptureTask
1112 } finally {
1113 if (state.snapshotCaptureTask === snapshotCaptureTask)
1114 state.snapshotCaptureTask = undefined
1115 }
1116
1117 const lifecycle = definition.lifecycle
1118
1119 // `handle` is absent only if `setup` never got past `definition.ensure`, in
1120 // which case there is no sandbox to snapshot.
1121 if (
1122 lifecycle?.snapshot === 'after-run' &&
1123 handle?.capabilities.snapshots &&
1124 handle.snapshot
1125 ) {
1126 const snapshot = await handle.snapshot(`after-run-${ctx.runId}`)
1127 const store = ensureCtx.store
1128 if (store) {
1129 const key = definition.key(ensureCtx)
1130 const existing = await store.get(key)
1131 if (existing) {
1132 await store.upsert({
1133 ...existing,
1134 latestSnapshotId: snapshot.id,
1135 updatedAt: Date.now(),
1136 })
1137 }
1138 }
1139 }
1140
1141 if (lifecycle?.destroyOnComplete) {
1142 await definition.destroy(ensureCtx)
1143 await definition.hooks?.onDestroy?.()
1144 }
1145 } catch (error) {
1146 primaryError = error
1147 if (definition.lifecycle?.destroyOnComplete) {
1148 try {
1149 await definition.destroy(ensureCtx)
1150 await definition.hooks?.onDestroy?.()
1151 } catch (cleanupError) {
1152 state.logger?.warn(
1153 'sandbox destroy after terminal failure failed',
1154 {
1155 runId: ctx.runId,
1156 phase: 'finish',
1157 error: cleanupError,
1158 },
1159 )
1160 }
1161 }
1162 }
1163
1164 let snapshotCleanupError: unknown
1165 try {
1166 await stopSnapshotLease(state, { closePortable: true })
1167 } catch (error) {
1168 snapshotCleanupError = error
1169 }
1170 if (primaryError !== undefined) {
1171 if (snapshotCleanupError !== undefined)
1172 state.logger?.warn('sandbox snapshot writer release failed', {
1173 runId: ctx.runId,
1174 phase: 'finish',
1175 error: snapshotCleanupError,
1176 })
1177 throw primaryError
1178 }
1179 if (snapshotCleanupError !== undefined) throw snapshotCleanupError
1180 },
1181
1182 async onAbort(ctx, info: AbortInfo) {
1183 const state = runState.get(ctx)
1184 if (!state) return
1185
1186 // First on BOTH branches: a diff still in flight must be drained whether
1187 // the sandbox is about to be destroyed or merely detached, or the final
1188 // file's diff is dropped.
1189 await drainWatcher(state, 'abort')
1190 let releaseError: unknown
1191 try {
1192 await stopSnapshotLease(state, { closePortable: true })
1193 } catch (error) {
1194 releaseError = error
1195 }
1196
1197 const durability = state.durability
1198 const cancelled = await cancelIntent(
1199 durability,
1200 ctx.runId,
1201 info.cancelRequested === true,
1202 )
1203
1204 if (
1205 durability !== undefined &&
1206 !cancelled &&
1207 durability.detachOnDisconnect
1208 ) {
1209 // DETACH on the teardown path. Reached when the run is aborted for a
1210 // reason that is NOT an out-of-band cancel while detachable — a genuine
1211 // stop from elsewhere, or a host going down. The ordinary disconnect is
1212 // handled by the disconnect subscriber in `setup`, which does not end the
1213 // run at all.
1214 //
1215 // On a failed record write this branch is ABANDONED for the destroy one
1216 // below, because a rejection here is the worst shape available: the
1217 // verdict is unpublished, so core terminalizes the log and records a
1218 // healthy detached run as failed; `detachedSince`/`sandboxKey` are
1219 // unwritten, so `listReclaimable` can never surface the run and
1220 // `reapDetachedRuns` can never reclaim it. A DESTROYED sandbox beats an
1221 // unreachable one — the same reasoning `drainWatcher` applies to its own
1222 // guarded `stop()`.
1223 if (await recordDetach(definition, state, durability, ctx, 'abort')) {
1224 if (releaseError) throw releaseError
1225 return
1226 }
1227 await definition.destroy(state.ensureCtx)
1228 await definition.hooks?.onDestroy?.()
1229 if (releaseError) throw releaseError
1230 return
1231 }
1232
1233 // ALWAYS tear down on an explicit abort, regardless of `destroyOnComplete`.
1234 // The in-sandbox agent process is not killed by closing its IO stream
1235 // (e.g. a Docker exec survives client disconnect), so the only reliable way
1236 // to stop it — and the token/cost drain of its ongoing API calls — is to
1237 // destroy the sandbox (stop the container/VM). `keepAlive` /
1238 // `destroyOnComplete:false` governs *successful completion*, never cancel.
1239 await definition.destroy(state.ensureCtx)
1240 await definition.hooks?.onDestroy?.()
1241 if (releaseError) throw releaseError
1242 },
1243
1244 async onError(ctx, info) {
1245 const state = runState.get(ctx)
1246 if (!state) return
1247
1248 await drainWatcher(state, 'error')
1249 let releaseError: unknown
1250 try {
1251 await stopSnapshotLease(state)
1252 } catch (error) {
1253 releaseError = error
1254 }
1255 await definition.hooks?.onError?.(info.error)
1256
1257 // On failure, only tear down when the lifecycle says so; otherwise leave
1258 // the sandbox for a resumed retry.
1259 if (definition.lifecycle?.destroyOnComplete) {
1260 await definition.destroy(state.ensureCtx)
1261 await definition.hooks?.onDestroy?.()
1262 }
1263 if (releaseError) throw releaseError
1264 },
1265 })
1266}