@tanstack/ai-sandbox 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/bootstrap.js.map +1 -1
- package/dist/esm/journal-sweep.js +3 -2
- package/dist/esm/journal-sweep.js.map +1 -1
- package/dist/esm/middleware.js +2 -1
- package/dist/esm/middleware.js.map +1 -1
- package/dist/esm/reap.js +2 -1
- package/dist/esm/reap.js.map +1 -1
- package/dist/esm/sandbox.js +1 -1
- package/dist/esm/sandbox.js.map +1 -1
- package/dist/esm/shell.js +5 -4
- package/dist/esm/shell.js.map +1 -1
- package/dist/esm/testkit/conformance.js +4 -2
- package/dist/esm/testkit/conformance.js.map +1 -1
- package/dist/esm/testkit/journal-conformance.js +6 -3
- package/dist/esm/testkit/journal-conformance.js.map +1 -1
- package/dist/esm/testkit/reaper-conformance.js +13 -8
- package/dist/esm/testkit/reaper-conformance.js.map +1 -1
- package/dist/esm/testkit/takeover-conformance.js +4 -3
- package/dist/esm/testkit/takeover-conformance.js.map +1 -1
- package/package.json +4 -4
package/dist/esm/reap.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reap.js","names":[],"sources":["../../src/reap.ts"],"sourcesContent":["/**\n * The sweep `RunStore.listReclaimable` was always missing a consumer for: take a\n * detached run whose viewer never came back, save its transcript, terminalize its\n * record, and tear its sandbox down.\n *\n * THE ONE RULE THAT SHAPES EVERYTHING HERE: **never drive a run to find out\n * whether it finished.**\n *\n * The obvious design — hand the run to `pipeToRunLog` under a short\n * `runBudgetMs` and see whether it terminalizes — was measured and is broken.\n * `pipeToRunLog` is total by construction: it ALWAYS writes a terminal status and\n * ALWAYS calls `durability.close()`. Against a run that has not finished, all\n * three producer shapes are destructive:\n *\n * | producer's reaction to the budget signal | stored status | `close()` |\n * | ---------------------------------------- | ------------- | --------- |\n * | ignores it and keeps producing | `aborted` | called |\n * | returns on abort (the realistic `drive`) | `aborted` | called |\n * | throws an AbortError | `failed` | called |\n *\n * The middle row USED to read `completed`, which was the fatal one: a signal-aware\n * producer exits its loop NORMALLY, and `pipeToRunLog` only checked its signal\n * per chunk, so a healthy mid-flight run was recorded as `'completed'` with a\n * `finishedAt` — a false transcript. That gap is fixed (`run.ts` re-checks the\n * signal after the loop), so the status is now honest on all three rows. The rule\n * above is UNCHANGED, because the status was never the whole harm: every row\n * writes a terminal record and closes a log that commit `5a1f821c9` deliberately\n * leaves OPEN for takeover (ending every attached client's stream), and a terminal\n * record drops out of `listReclaimable` forever, so TTL expiry can never reclaim\n * that run's sandbox. A cost leak with no recovery path. There is therefore no\n * \"still running\" outcome in {@link ReapRunOutcome}: it is unreachable by\n * construction, not merely unlikely.\n *\n * So sentinel-reached is detected OUT OF BAND, through the in-sandbox journal\n * ({@link probeRunExit}), and `pipeToRunLog` is entered only for a run already\n * KNOWN to have finished, or for one whose TTL has expired (terminal either way).\n * On the FINALIZATION path `runBudgetMs` therefore degrades from a load-bearing\n * mechanism into a safety net whose expiry is a genuine anomaly — see\n * `'budget-exceeded'`. On the EXPIRY path it stays load-bearing: nothing polls the\n * cancel this module records, so the budget is what ends the drive of an expired\n * run whose agent is still producing, and its expiry there is the designed path.\n *\n * WHY THE PROBE IS INJECTED (`ReapOptions.hasFinished`) rather than resolved\n * here, exactly like `ReapOptions.reclaim`:\n *\n * - It cannot read `durability.snapshot()`. After a detach nothing appends to the\n * delivery log — the host that would have appended is the host that left — so\n * the log is frozen at the last delivered chunk while the JOURNAL keeps\n * growing. The log can only ever say \"no news\".\n * - It cannot resolve a `SandboxHandle` either. `SandboxInstanceStore` is\n * `get`/`upsert`/`delete` with no `list` (see `reclaim.ts` for why that is\n * deliberate), and only the application maps a `sandboxKey` to a live handle.\n *\n * NEVER REJECTS. This runs from a cron, an `alarm()`, or a `waitUntil` with\n * nobody to catch it, so every per-run failure is logged and folded into\n * {@link ReapResult} rather than escaping.\n *\n * NEVER CLEARS `detachedSince`. That field is what the reaper SELECTS on, and\n * `packages/ai/src/stream-to-response.ts`'s `startRunDriver` clears it because a\n * real viewer stopping the TTL clock is the opposite job. Its comment there names\n * borrowing that path \"the single most likely bug in this phase\"; clearing the\n * marker would reset the TTL on every sweep and a detached run would never\n * expire.\n */\nimport { isTerminalRunStatus, requestRunCancel } from '@tanstack/ai'\nimport {\n DEFAULT_FENCE_QUIET_MS,\n RunClaimLostError,\n // Thrown, not merely caught: the expiry re-derivation under the lock refuses\n // its own claim when the run's viewer has come back.\n RunClaimNotAcquiredError,\n awaitLogQuiescence,\n fenceDurability,\n fenceRunStore,\n withRunClaim,\n} from './claim'\nimport { pipeToRunLog } from './run'\nimport {\n journalExitProbeCommand,\n journalPaths,\n parseJournalExit,\n} from './journal'\nimport { decodeBase64Stream } from './journal-bytes'\nimport type { SandboxHandle } from './contracts'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type { LockStore } from '@tanstack/ai/locks'\nimport type {\n RunRecord,\n RunStatus,\n RunStore,\n StreamChunk,\n StreamDurability,\n} from '@tanstack/ai'\n\n/**\n * Safety net for a single run's drive. Not the mechanism that decides whether a\n * run finished — see the module doc for why that design was rejected — so this is\n * generous rather than tight: it only has to stop a drive that has genuinely\n * wedged on a run the journal already said was over.\n *\n * On the expiry path it is not merely a net: it is what stops a still-producing\n * agent, since nothing polls the cancel recorded before that drive. A caller that\n * expires live agents may want a tighter value there than a finalization replay\n * needs.\n */\nexport const DEFAULT_RUN_BUDGET_MS = 30_000\n\n/**\n * Runs one sweep will touch. A cron invocation is bounded (a Worker's CPU\n * budget, a Lambda timeout), and an unbounded sweep over a backlog of thousands\n * would be killed mid-run rather than finishing 25 and returning; the next tick\n * takes the next batch.\n */\nexport const DEFAULT_MAX_RUNS = 25\n\n/** Journal tail bytes {@link probeRunExit} reads. The sentinel is the last line. */\nexport const DEFAULT_EXIT_PROBE_BYTES = 4096\n\n/**\n * What the out-of-band probe learned about a detached run's agent.\n *\n * THREE ARMS, not a boolean, because \"could not tell\" must not be\n * indistinguishable from \"still working\": both leave the run alone, but only one\n * of them is a condition an operator should see. A two-valued probe would also\n * invite the caller to treat a provider `exec` failure as \"finished\" and drive a\n * live run — the exact defect this module exists to prevent.\n */\nexport type RunExitProbe =\n /** The `{\"__exit\":N}` sentinel is in the journal. The agent is over. */\n | { state: 'finished'; exitCode: number }\n /** No sentinel. The agent is mid-flight (or never started). LEAVE IT ALONE. */\n | { state: 'producing' }\n /** The probe could not answer — no sandbox, `exec` rejected, frame undecodable. */\n | { state: 'unknown'; error?: unknown }\n\n/** What one sweep did to one run. */\nexport type ReapRunOutcome =\n /**\n * The probe saw `{\"__exit\":N}`, the run was driven to a terminal status, and\n * its transcript is saved. The happy path.\n */\n | 'finalized'\n /**\n * Past `detachedRunTtlMs`. Cancelled first, then driven to terminal. The probe\n * is skipped: the outcome is terminal whether the agent finished or not.\n *\n * Reported even when {@link ReapOptions.runBudgetMs} is what ended the drive —\n * on this path that is the mechanism rather than an anomaly, so `'expired'` is\n * the truthful outcome. The run's own `status` distinguishes the two shapes:\n * an agent that had already finished replays to `'completed'`, while one still\n * producing when the budget fired is `'aborted'`.\n */\n | 'expired'\n /**\n * Still producing. `pipeToRunLog` was NEVER entered — nothing appended, no\n * terminal record written, `close()` not called, `detachedSince` untouched.\n */\n | 'producing'\n /** The probe could not answer. Left exactly as untouched as `'producing'`. */\n | 'unknown'\n /**\n * ANOMALY. The drive outran {@link ReapOptions.runBudgetMs} on a run the\n * journal already said was finished. The record IS terminal and the log IS\n * closed (`pipeToRunLog` guarantees both), so this is a diagnostic, not a leak\n * — but a finished run that would not replay in 30s means the journal read, the\n * translation, or the log is misbehaving.\n *\n * FINALIZATION ONLY. An expired run that outran its budget reports `'expired'`:\n * there was no probe on that path and the agent may legitimately still have been\n * producing, so the budget firing is the designed stop, not a misbehaving replay.\n */\n | 'budget-exceeded'\n /**\n * Another host holds the claim, or held it and superseded us mid-drive. Normal:\n * a real viewer attaching mid-sweep is exactly this. Also covers a run that\n * reached terminal in another host's hands between the listing and the claim.\n */\n | 'not-claimed'\n /**\n * The transcript IS saved and the record IS terminal — only\n * {@link ReapOptions.reclaim} threw, so the sandbox is still up.\n *\n * A DISTINCT outcome rather than `'failed'`, because the two need opposite\n * operator responses and `'failed'` cannot express this one: it carries no\n * `status` and no `exitCode`, so \"transcript saved, sandbox NOT reclaimed\"\n * read identically to \"the sweep failed and the run was never finalized\".\n *\n * NOT RETRYABLE BY THE SWEEP. The record is terminal by now, so the run has\n * left `listReclaimable` for good; the sandbox leaks until something else\n * tears it down. This entry, with its `error`, is the only notice of that.\n *\n * OVERWRITES `'budget-exceeded'` when both happened, because the leak is what\n * needs acting on — {@link ReapRunEntry.terminalizedAnyway} is what preserves\n * the budget half of that pair.\n *\n * `sandboxReclaimer` REJECTS on its `'destroy-failed'` arm precisely so this\n * outcome is reachable through the shipped reclaimer and not only through a\n * custom one; see `SandboxReclaimFailedError` in `reclaim.ts`.\n */\n | 'reclaim-failed'\n /** Something threw. Logged, recorded here, and the sweep continued. */\n | 'failed'\n\n/** One run's line in the sweep summary. */\nexport interface ReapRunEntry {\n runId: string\n outcome: ReapRunOutcome\n /** The run's status after the sweep, when the run was driven. */\n status?: RunStatus\n /** The agent's exit code, when the probe read one. */\n exitCode?: number\n /**\n * THE BUDGET ANOMALY MARKER, and the only field whose mere PRESENCE carries a\n * fact: it is set if and only if the drive outran\n * {@link ReapOptions.runBudgetMs} on the finalization path — the condition\n * `'budget-exceeded'` names. Its value is whether the record nonetheless\n * reached a terminal status, practically always `true` since `pipeToRunLog` is\n * total; it is reported rather than assumed so an operator does not have to\n * infer it.\n *\n * SURVIVES A FAILED RECLAIM. `reclaim` runs after the outcome is classified\n * and overwrites it with `'reclaim-failed'`, which is the more urgent fact (a\n * leaked sandbox nothing will retry) and so wins the single `outcome` slot.\n * This field is therefore what keeps the budget anomaly on the entry: an\n * operator seeing `'reclaim-failed'` WITH `terminalizedAnyway` present is\n * looking at a run that blew its budget and then leaked, and needs both halves.\n */\n terminalizedAnyway?: boolean\n error?: unknown\n}\n\nexport interface ReapResult {\n /** Runs in this batch — i.e. after the {@link ReapOptions.maxRuns} cap. */\n considered: number\n /** Runs {@link ReapOptions.hasFinished} was actually called for. */\n probed: number\n outcomes: Record<ReapRunOutcome, number>\n runs: Array<ReapRunEntry>\n}\n\nexport interface ReapOptions<TOffset extends string = string> {\n runs: RunStore\n locks: LockStore\n /**\n * Per-run event log factory, same shape `RunDeps.durability` takes.\n *\n * Generic in the offset type, defaulted to `string` so an existing call site\n * needs no change — see {@link SandboxRunDriverOptions.durability} for why\n * hardcoding the default locked out branded-cursor backends.\n */\n durability: (runId: string) => StreamDurability<TOffset>\n /**\n * The out-of-band \"did the agent reach its sentinel?\" probe. INJECTED, because\n * neither the delivery log nor this package can answer it — see the module doc.\n * {@link probeRunExit} is the implementation an application wires in once it has\n * resolved the run's `SandboxHandle`.\n */\n hasFinished: (record: RunRecord) => Promise<RunExitProbe>\n /** Produce the run's remaining events. Called only once the claim is held. */\n drive: (input: {\n runId: string\n threadId: string\n signal: AbortSignal\n }) => AsyncIterable<StreamChunk>\n /** Sweep clock, passed rather than read so a sweep is reproducible. */\n now: number\n /** Detached-run TTL; `detachedSince <= now - ttl` expires, INCLUSIVELY. */\n detachedRunTtlMs: number\n /** Safety net per drive. Defaults to {@link DEFAULT_RUN_BUDGET_MS}. */\n runBudgetMs?: number\n /** Batch cap. Defaults to {@link DEFAULT_MAX_RUNS}. */\n maxRuns?: number\n /** Quiescence window; defaults to `DEFAULT_FENCE_QUIET_MS`. */\n fenceQuietMs?: number\n /**\n * Tear the run's sandbox down. Called ONLY after the run reached a terminal\n * status, and with the ORIGINALLY LISTED record — see {@link reapDetachedRuns}.\n * `sandboxReclaimer` in `reclaim.ts` is the ready-made implementation.\n */\n reclaim?: (record: RunRecord) => Promise<void>\n logger?: InternalLogger\n}\n\nasync function* singleValue(value: string): AsyncIterable<string> {\n yield value\n}\n\n/** Decode the base64 frame `journalExitProbeCommand` emits. */\nasync function decodeFrame(stdout: string): Promise<string> {\n const decoder = new TextDecoder()\n let text = ''\n for await (const bytes of decodeBase64Stream(singleValue(stdout))) {\n text += decoder.decode(bytes, { stream: true })\n }\n return text + decoder.decode()\n}\n\n/**\n * Read the END of a run's journal and answer whether the agent reached its\n * `{\"__exit\":N}` sentinel. Read-only: no append, no record write, no `close()`.\n *\n * This is the whole reason the reaper is safe. It is the ONLY way to learn that a\n * detached run is over without driving it, because the delivery log stops growing\n * the moment the viewer leaves while the journal does not.\n *\n * ANY failure answers `'unknown'`, never `'finished'`: the caller drives a run it\n * is told finished, so a provider `exec` that rejected, a sandbox that is gone, or\n * a frame the provider truncated must never be read as \"the agent exited\".\n *\n * An EMPTY tail answers `'producing'` — the fail-safe direction. A journal that\n * does not exist yet is indistinguishable here from one with no sentinel, and both\n * mean \"do not touch this run\".\n */\nexport async function probeRunExit(input: {\n handle: SandboxHandle\n runId: string\n /** Journal directory; defaults to `DEFAULT_JOURNAL_DIR`, as `journalPaths` does. */\n dir?: string\n /** Tail bytes to read. Defaults to {@link DEFAULT_EXIT_PROBE_BYTES}. */\n maxBytes?: number\n}): Promise<RunExitProbe> {\n try {\n const paths = journalPaths(input.runId, input.dir)\n const result = await input.handle.process.exec(\n journalExitProbeCommand(\n paths,\n input.maxBytes ?? DEFAULT_EXIT_PROBE_BYTES,\n ),\n )\n // `paths` supplies the per-run sentinel nonce: without it a mid-flight\n // agent that printed any JSON object carrying `__exit` would read as\n // `'finished'` here, and the caller would drive and reclaim a LIVE run.\n const exitCode = parseJournalExit(await decodeFrame(result.stdout), paths)\n return exitCode === null\n ? { state: 'producing' }\n : { state: 'finished', exitCode }\n } catch (error) {\n return { state: 'unknown', error }\n }\n}\n\n/** Every outcome key present at zero, so a consumer can read any of them. */\nfunction emptyOutcomes(): Record<ReapRunOutcome, number> {\n return {\n finalized: 0,\n expired: 0,\n producing: 0,\n unknown: 0,\n 'budget-exceeded': 0,\n 'not-claimed': 0,\n 'reclaim-failed': 0,\n failed: 0,\n }\n}\n\n/**\n * Report through a consumer-supplied logger without letting it break the sweep.\n * Mirrors `run.ts`'s `safeLog`: this module's totality must not be defeated by a\n * sink that cannot serialize a thrown value.\n */\nfunction safeLog(\n logger: InternalLogger | undefined,\n level: 'errors' | 'sandbox',\n message: string,\n context: Record<string, unknown>,\n): void {\n try {\n if (level === 'errors') logger?.errors(message, context)\n else logger?.sandbox(message, context)\n } catch {\n // Intentionally empty: there is no second channel to report on.\n }\n}\n\n/** Resolved-once settings shared by every run in one sweep. */\ninterface ReapContext<TOffset extends string = string> {\n options: ReapOptions<TOffset>\n runBudgetMs: number\n fenceQuietMs: number\n /** Inclusive expiry cutoff: `detachedSince <= cutoff` is expired. */\n cutoff: number\n}\n\n/** Whether a thrown value means \"we do not own this run\", which is normal. */\nfunction isClaimRefusal(error: unknown): boolean {\n return (\n error instanceof RunClaimNotAcquiredError ||\n error instanceof RunClaimLostError\n )\n}\n\n/**\n * Sweep ONE run. Never rejects: the caller folds the returned entry into the\n * summary and moves on.\n *\n * The ORDER of the steps below is the contract, not an implementation detail:\n *\n * 1. **Classify expiry first**, because an expired run needs no probe — its\n * outcome is terminal whether or not the agent finished, so a probe would only\n * add a provider round-trip and a way to fail.\n * 2. **Otherwise probe BEFORE touching anything.** `'producing'` and `'unknown'`\n * return here, having made no claim, no append, no record write, and no\n * `close()`. Driving past this point is the whole defect described in the\n * module doc.\n * 3. Claim, so two hosts never drive one run.\n * 4. **Re-derive expiry from a record read INSIDE the lock**, and only then\n * record the cancel. The listed record is stale by the time the claim is\n * held, and the cancel is sticky.\n * 5. Quiesce, so a predecessor still writing is observed rather than raced.\n * 6. **Arm the run budget**, so it bounds the drive rather than the queue the\n * two steps above stood in.\n * 7. Pipe with BOTH authoritative seams fenced, mirroring `driver.ts`.\n * 8. Reclaim, and ONLY once the record actually reached terminal.\n */\nasync function reapOne<TOffset extends string>(\n record: RunRecord,\n ctx: ReapContext<TOffset>,\n counters: { probed: number },\n): Promise<ReapRunEntry> {\n const { runs, locks, logger } = ctx.options\n const { runId, threadId } = record\n\n try {\n // INCLUSIVE, exactly as `RunStore.listReclaimable` documents its own cutoff:\n // a run detached at precisely `now - ttlMs` IS expired. The two must agree,\n // or a run would be listed as reclaimable and then classified as fresh on\n // every single sweep, forever.\n const expired =\n record.detachedSince !== undefined && record.detachedSince <= ctx.cutoff\n\n let exitCode: number | undefined\n if (!expired) {\n counters.probed += 1\n const probe = await ctx.options.hasFinished(record)\n if (probe.state !== 'finished') {\n // THE LEAVE-ALONE PATH. Deliberately returns before `withRunClaim`, so\n // not even `driverEpoch` moves — and above all `detachedSince` is left\n // exactly as it was, since it is both this run's TTL evidence and the\n // field the next sweep selects on.\n safeLog(logger, 'sandbox', `reap: leaving run ${runId} alone`, {\n runId,\n state: probe.state,\n ...(probe.state === 'unknown' && probe.error !== undefined\n ? { error: probe.error }\n : {}),\n })\n return {\n runId,\n outcome: probe.state,\n ...(probe.state === 'unknown' && probe.error !== undefined\n ? { error: probe.error }\n : {}),\n }\n }\n exitCode = probe.exitCode\n }\n\n // Armed INSIDE the claim, below. Read after it for the outcome, so it is\n // hoisted here rather than declared in the callback.\n let budget: AbortSignal | undefined\n const final = await withRunClaim(\n {\n runs,\n locks,\n runId,\n fenceQuietMs: ctx.fenceQuietMs,\n ...(logger === undefined ? {} : { logger }),\n },\n async (claim) => {\n if (expired) {\n // RE-DERIVED FROM A RECORD READ INSIDE THE LOCK, never from the listed\n // one. `stream-to-response.ts`'s `startRunDriver` CLEARS\n // `detachedSince` when a real viewer attaches — deliberately stopping\n // the TTL clock — and it takes this same per-run lock, so an\n // expiry decided at listing time is stale by the time the claim is\n // held. Cancelling on the stale value poisoned a now-live run:\n // nothing in the tree ever clears `cancelRequested`, so on that\n // viewer's next ORDINARY disconnect `middleware.ts`'s\n // `wasCancelRequested` read skips the detach branch and destroys the\n // sandbox of a healthy, actively-viewed run.\n const current = await runs.get(runId)\n if (current === null) {\n throw new RunClaimNotAcquiredError(runId, 'unknown')\n }\n if (\n current.detachedSince === undefined ||\n current.detachedSince > ctx.cutoff\n ) {\n // The viewer came back. `'not-claimed'` already documents \"a real\n // viewer attaching mid-sweep is exactly this\", and refusing here\n // leaves the run as untouched as the leave-alone path does: no\n // cancel, no append, no terminal record, no `close()`.\n throw new RunClaimNotAcquiredError(runId, 'superseded')\n }\n // BEFORE the drive, never after — and never before the claim.\n // `withSandbox`'s `onAbort` resolves the out-of-band cancel band from\n // the record, so recording the intent first is what makes the teardown\n // an explicit cancel that DESTROYS the sandbox rather than a second\n // detach that re-arms `detachedSince` and leaves the run to be swept\n // again forever. Recorded after the drive it is pure bookkeeping on a\n // run that already tore down the wrong way. Recorded before the CLAIM\n // it is an unfenced, sticky write on a record this host does not own,\n // derived from a value the lock exists to make current.\n await requestRunCancel(runs, runId)\n }\n // Before the first append, never after: `pipeToRunLog` snapshots to align.\n await awaitLogQuiescence(\n ctx.options.durability(runId),\n ctx.fenceQuietMs,\n )\n // A safety net, not a mechanism (see the module doc). `AbortSignal.any`\n // is this package's idiom for linking one — see\n // `testkit/takeover-conformance.ts`.\n //\n // ARMED HERE, not before `withRunClaim`. Both the lock wait and the\n // quiescence wait consume a timer started earlier: quiescence always\n // sleeps at least one `fenceQuietMs` and may sleep six, and lock\n // acquisition waits behind whoever holds it, unbounded. The effective\n // budget was silently `runBudgetMs − fenceQuietMs − lockWait`, and once\n // it went negative the claim was acquired with the timer already fired:\n // `pipeToRunLog` hit its entry `signal.aborted` check before pulling one\n // chunk, so a FINISHED agent's transcript was recorded `'aborted'` and\n // its log closed — and a terminal record leaves `listReclaimable`\n // forever, so that transcript was then unreplayable while `reclaim`\n // destroyed the sandbox holding the only copy. The budget bounds the\n // DRIVE, not the queue.\n budget = AbortSignal.timeout(ctx.runBudgetMs)\n // `claim.signal` is in the composed signal because losing the lease MUST\n // stop the drive: a successor that took the run over is appending to the\n // same log, and this drive continuing would double every chunk.\n const signal = AbortSignal.any([claim.signal, budget])\n return pipeToRunLog(ctx.options.drive({ runId, threadId, signal }), {\n // BOTH seams, over the SAME claim, as `driver.ts` explains: fencing the\n // log alone just moves the harm to \"a dead host marks the successor's\n // live run failed\".\n runs: fenceRunStore(runs, claim, {\n ...(logger === undefined ? {} : { logger }),\n }),\n durability: (id) =>\n fenceDurability(ctx.options.durability(id), claim, { runs }),\n runId,\n threadId,\n signal,\n ...(logger === undefined ? {} : { logger }),\n })\n },\n )\n\n const terminal = isTerminalRunStatus(final.status)\n let outcome: ReapRunOutcome\n // `&& !expired` is the whole subtlety. The budget is an ANOMALY only on the\n // finalization path, where the probe already said the agent hit its sentinel\n // and a replay that will not finish in 30s means the journal read, the\n // translation, or the log is misbehaving. On the EXPIRY path there was no\n // probe and the agent may well be mid-sentence: `requestRunCancel` writes a\n // record field whose only reader is `withSandbox`'s `onAbort` (which runs\n // after something else has already aborted), so the budget is the sole thing\n // that ends the drive of a still-producing expired run. That is the designed\n // path, not a misbehaving one, and reporting it as the anomaly made\n // `'expired'` unreachable for exactly the runs the TTL exists to expire.\n // `budget` is armed inside the claim, so reaching here means it was armed;\n // `?? false` keeps the read total rather than asserting that.\n if ((budget?.aborted ?? false) && !expired) {\n outcome = 'budget-exceeded'\n } else if (!terminal) {\n // The terminal write was SUPPRESSED and `finish`'s re-read answered with a\n // live record, which `fenceRunStore` only does when this host lost the claim\n // to another one. That is the same fact as a refused claim, reported the\n // same way rather than as a success that wrote nothing.\n outcome = 'not-claimed'\n } else {\n outcome = expired ? 'expired' : 'finalized'\n }\n\n // CAPTURED BEFORE THE RECLAIM BLOCK, which may overwrite `outcome` with\n // `'reclaim-failed'`. Conditioning the `terminalizedAnyway` spread on the\n // post-reclaim `outcome` dropped the budget diagnostic from exactly the\n // entries that need it most: a run that blew its budget AND then failed to\n // reclaim reported neither fact but the leak, and an operator cannot\n // diagnose a leak on a run whose replay was already misbehaving without\n // knowing that it was.\n const budgetAnomaly = outcome === 'budget-exceeded'\n\n let reclaimError: unknown\n if (terminal && ctx.options.reclaim !== undefined) {\n try {\n // `record`, NOT `final`. When the terminal `update` fails, `finish` returns\n // a LOCALLY REBUILT record that carries only `runId`/`threadId`/`startedAt`\n // plus the terminal patch — no `sandboxKey` — so `reclaimSandbox` would see\n // `undefined`, answer `'no-sandbox-key'`, and the sandbox would leak\n // silently on exactly the path where something already went wrong.\n await ctx.options.reclaim(record)\n } catch (error) {\n // CAUGHT HERE rather than in the outer catch, which would report a bare\n // `'failed'` with no `status` and no `exitCode`. `reclaimSandbox`\n // deliberately does not guard `instances.get` (its contract is that the\n // CALLER records the failure) and neither does `sandboxReclaimer`, so a\n // throwing instance store landed there. By this point the record is\n // terminal and the log closed, so the run is out of `listReclaimable`\n // forever and no later sweep will retry: the sandbox leaks, and an\n // operator reading `'failed'` cannot tell \"transcript saved, sandbox NOT\n // reclaimed\" from \"the sweep failed and the run was never finalized\".\n reclaimError = error\n outcome = 'reclaim-failed'\n safeLog(logger, 'errors', `reap: reclaiming run ${runId} failed`, {\n runId,\n status: final.status,\n error,\n })\n }\n }\n\n return {\n runId,\n outcome,\n status: final.status,\n ...(exitCode === undefined ? {} : { exitCode }),\n ...(budgetAnomaly ? { terminalizedAnyway: terminal } : {}),\n ...(reclaimError === undefined ? {} : { error: reclaimError }),\n }\n } catch (error) {\n if (isClaimRefusal(error)) {\n safeLog(logger, 'sandbox', `reap: not driving run ${runId}`, {\n runId,\n error,\n })\n return { runId, outcome: 'not-claimed', error }\n }\n // Folded into the summary rather than rethrown: one bad run must not abandon\n // the rest of the batch, and there is no caller to receive a rejection.\n safeLog(logger, 'errors', `reap: sweeping run ${runId} failed`, {\n runId,\n error,\n })\n return { runId, outcome: 'failed', error }\n }\n}\n\n/**\n * Sweep the detached runs a `RunStore` surfaces, saving each finished run's\n * transcript and reclaiming its sandbox.\n *\n * A plain async function with no timer and no daemon: call it from a cron, a\n * queue consumer, a Durable Object `alarm()`, or a `waitUntil`. It NEVER rejects\n * — every failure is logged and counted in the returned {@link ReapResult}.\n *\n * ONE `listReclaimable({ now, ttlMs: 0 })` call, deliberately: `ttlMs: 0` is\n * every detached run, which is the candidate set for FINALIZATION (a run that hit\n * its sentinel one second after the viewer left has an unsaved transcript and\n * must not wait out the TTL), and expiry is then classified in-process against\n * the same inclusive cutoff. Listing twice with two TTLs would cost a second\n * store round-trip to compute a subset.\n *\n * `listReclaimable` is OPTIONAL on `RunStore`. A backend without it cannot be\n * reaped, which answers `{ considered: 0 }` plus one log line rather than\n * throwing — the same graceful degrade every other optional-method call site in\n * the repo does (`store.findActiveRun?.(threadId)`).\n */\nexport async function reapDetachedRuns<TOffset extends string = string>(\n options: ReapOptions<TOffset>,\n): Promise<ReapResult> {\n const logger = options.logger\n const outcomes = emptyOutcomes()\n const entries: Array<ReapRunEntry> = []\n const empty = (): ReapResult => ({\n considered: 0,\n probed: 0,\n outcomes,\n runs: entries,\n })\n\n const list = options.runs.listReclaimable?.bind(options.runs)\n if (list === undefined) {\n safeLog(\n logger,\n 'sandbox',\n 'reap: the run store does not implement listReclaimable; nothing to sweep',\n {},\n )\n return empty()\n }\n\n let candidates: Array<RunRecord>\n try {\n candidates = await list({ now: options.now, ttlMs: 0 })\n } catch (error) {\n safeLog(logger, 'errors', 'reap: listing reclaimable runs failed', {\n error,\n })\n return empty()\n }\n\n // Capped so one invocation cannot outlive its platform's budget and be killed\n // mid-drive. `slice` and not a `break`, so `considered` reports the batch the\n // sweep actually took responsibility for.\n const maxRuns = Math.max(0, Math.trunc(options.maxRuns ?? DEFAULT_MAX_RUNS))\n const batch = candidates.slice(0, maxRuns)\n\n const ctx: ReapContext<TOffset> = {\n options,\n runBudgetMs: options.runBudgetMs ?? DEFAULT_RUN_BUDGET_MS,\n fenceQuietMs: options.fenceQuietMs ?? DEFAULT_FENCE_QUIET_MS,\n cutoff: options.now - options.detachedRunTtlMs,\n }\n const counters = { probed: 0 }\n\n // Sequential on purpose: each run costs a lock, a provider round-trip, and a\n // full replay, and a cron invocation's budget is the scarce resource. Fanning\n // out would multiply peak load against the provider for no throughput a\n // subsequent tick cannot supply.\n for (const record of batch) {\n const entry = await reapOne(record, ctx, counters)\n outcomes[entry.outcome] += 1\n entries.push(entry)\n }\n\n return {\n considered: batch.length,\n probed: counters.probed,\n outcomes,\n runs: entries,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyGA,IAAa,wBAAwB;;;;;;;AAQrC,IAAa,mBAAmB;;AAGhC,IAAa,2BAA2B;AAuKxC,gBAAgB,YAAY,OAAsC;CAChE,MAAM;AACR;;AAGA,eAAe,YAAY,QAAiC;CAC1D,MAAM,UAAU,IAAI,YAAY;CAChC,IAAI,OAAO;CACX,WAAW,MAAM,SAAS,mBAAmB,YAAY,MAAM,CAAC,GAC9D,QAAQ,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;CAEhD,OAAO,OAAO,QAAQ,OAAO;AAC/B;;;;;;;;;;;;;;;;;AAkBA,eAAsB,aAAa,OAOT;CACxB,IAAI;EACF,MAAM,QAAQ,aAAa,MAAM,OAAO,MAAM,GAAG;EAUjD,MAAM,WAAW,iBAAiB,MAAM,aAAY,MAT/B,MAAM,OAAO,QAAQ,KACxC,wBACE,OACA,MAAM,YAAA,IACR,CACF,EAAA,CAI2D,MAAM,GAAG,KAAK;EACzE,OAAO,aAAa,OAChB,EAAE,OAAO,YAAY,IACrB;GAAE,OAAO;GAAY;EAAS;CACpC,SAAS,OAAO;EACd,OAAO;GAAE,OAAO;GAAW;EAAM;CACnC;AACF;;AAGA,SAAS,gBAAgD;CACvD,OAAO;EACL,WAAW;EACX,SAAS;EACT,WAAW;EACX,SAAS;EACT,mBAAmB;EACnB,eAAe;EACf,kBAAkB;EAClB,QAAQ;CACV;AACF;;;;;;AAOA,SAAS,QACP,QACA,OACA,SACA,SACM;CACN,IAAI;EACF,IAAI,UAAU,UAAU,QAAQ,OAAO,SAAS,OAAO;OAClD,QAAQ,QAAQ,SAAS,OA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Store.listReclaimable` was always missing a consumer for: take a\n * detached run whose viewer never came back, save its transcript, terminalize its\n * record, and tear its sandbox down.\n *\n * THE ONE RULE THAT SHAPES EVERYTHING HERE: **never drive a run to find out\n * whether it finished.**\n *\n * The obvious design — hand the run to `pipeToRunLog` under a short\n * `runBudgetMs` and see whether it terminalizes — was measured and is broken.\n * `pipeToRunLog` is total by construction: it ALWAYS writes a terminal status and\n * ALWAYS calls `durability.close()`. Against a run that has not finished, all\n * three producer shapes are destructive:\n *\n * | producer's reaction to the budget signal | stored status | `close()` |\n * | ---------------------------------------- | ------------- | --------- |\n * | ignores it and keeps producing | `aborted` | called |\n * | returns on abort (the realistic `drive`) | `aborted` | called |\n * | throws an AbortError | `failed` | called |\n *\n * The middle row USED to read `completed`, which was the fatal one: a signal-aware\n * producer exits its loop NORMALLY, and `pipeToRunLog` only checked its signal\n * per chunk, so a healthy mid-flight run was recorded as `'completed'` with a\n * `finishedAt` — a false transcript. That gap is fixed (`run.ts` re-checks the\n * signal after the loop), so the status is now honest on all three rows. The rule\n * above is UNCHANGED, because the status was never the whole harm: every row\n * writes a terminal record and closes a log that commit `5a1f821c9` deliberately\n * leaves OPEN for takeover (ending every attached client's stream), and a terminal\n * record drops out of `listReclaimable` forever, so TTL expiry can never reclaim\n * that run's sandbox. A cost leak with no recovery path. There is therefore no\n * \"still running\" outcome in {@link ReapRunOutcome}: it is unreachable by\n * construction, not merely unlikely.\n *\n * So sentinel-reached is detected OUT OF BAND, through the in-sandbox journal\n * ({@link probeRunExit}), and `pipeToRunLog` is entered only for a run already\n * KNOWN to have finished, or for one whose TTL has expired (terminal either way).\n * On the FINALIZATION path `runBudgetMs` therefore degrades from a load-bearing\n * mechanism into a safety net whose expiry is a genuine anomaly — see\n * `'budget-exceeded'`. On the EXPIRY path it stays load-bearing: nothing polls the\n * cancel this module records, so the budget is what ends the drive of an expired\n * run whose agent is still producing, and its expiry there is the designed path.\n *\n * WHY THE PROBE IS INJECTED (`ReapOptions.hasFinished`) rather than resolved\n * here, exactly like `ReapOptions.reclaim`:\n *\n * - It cannot read `durability.snapshot()`. After a detach nothing appends to the\n * delivery log — the host that would have appended is the host that left — so\n * the log is frozen at the last delivered chunk while the JOURNAL keeps\n * growing. The log can only ever say \"no news\".\n * - It cannot resolve a `SandboxHandle` either. `SandboxInstanceStore` is\n * `get`/`upsert`/`delete` with no `list` (see `reclaim.ts` for why that is\n * deliberate), and only the application maps a `sandboxKey` to a live handle.\n *\n * NEVER REJECTS. This runs from a cron, an `alarm()`, or a `waitUntil` with\n * nobody to catch it, so every per-run failure is logged and folded into\n * {@link ReapResult} rather than escaping.\n *\n * NEVER CLEARS `detachedSince`. That field is what the reaper SELECTS on, and\n * `packages/ai/src/stream-to-response.ts`'s `startRunDriver` clears it because a\n * real viewer stopping the TTL clock is the opposite job. Its comment there names\n * borrowing that path \"the single most likely bug in this phase\"; clearing the\n * marker would reset the TTL on every sweep and a detached run would never\n * expire.\n */\nimport { isTerminalRunStatus, requestRunCancel } from '@tanstack/ai'\nimport {\n DEFAULT_FENCE_QUIET_MS,\n RunClaimLostError,\n // Thrown, not merely caught: the expiry re-derivation under the lock refuses\n // its own claim when the run's viewer has come back.\n RunClaimNotAcquiredError,\n awaitLogQuiescence,\n fenceDurability,\n fenceRunStore,\n withRunClaim,\n} from './claim'\nimport { pipeToRunLog } from './run'\nimport {\n journalExitProbeCommand,\n journalPaths,\n parseJournalExit,\n} from './journal'\nimport { decodeBase64Stream } from './journal-bytes'\nimport type { SandboxHandle } from './contracts'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type { LockStore } from '@tanstack/ai/locks'\nimport type {\n RunRecord,\n RunStatus,\n RunStore,\n StreamChunk,\n StreamDurability,\n} from '@tanstack/ai'\n\n/**\n * Safety net for a single run's drive. Not the mechanism that decides whether a\n * run finished — see the module doc for why that design was rejected — so this is\n * generous rather than tight: it only has to stop a drive that has genuinely\n * wedged on a run the journal already said was over.\n *\n * On the expiry path it is not merely a net: it is what stops a still-producing\n * agent, since nothing polls the cancel recorded before that drive. A caller that\n * expires live agents may want a tighter value there than a finalization replay\n * needs.\n */\nexport const DEFAULT_RUN_BUDGET_MS = 30_000\n\n/**\n * Runs one sweep will touch. A cron invocation is bounded (a Worker's CPU\n * budget, a Lambda timeout), and an unbounded sweep over a backlog of thousands\n * would be killed mid-run rather than finishing 25 and returning; the next tick\n * takes the next batch.\n */\nexport const DEFAULT_MAX_RUNS = 25\n\n/** Journal tail bytes {@link probeRunExit} reads. The sentinel is the last line. */\nexport const DEFAULT_EXIT_PROBE_BYTES = 4096\n\n/**\n * What the out-of-band probe learned about a detached run's agent.\n *\n * THREE ARMS, not a boolean, because \"could not tell\" must not be\n * indistinguishable from \"still working\": both leave the run alone, but only one\n * of them is a condition an operator should see. A two-valued probe would also\n * invite the caller to treat a provider `exec` failure as \"finished\" and drive a\n * live run — the exact defect this module exists to prevent.\n */\nexport type RunExitProbe =\n /** The `{\"__exit\":N}` sentinel is in the journal. The agent is over. */\n | { state: 'finished'; exitCode: number }\n /** No sentinel. The agent is mid-flight (or never started). LEAVE IT ALONE. */\n | { state: 'producing' }\n /** The probe could not answer — no sandbox, `exec` rejected, frame undecodable. */\n | { state: 'unknown'; error?: unknown }\n\n/** What one sweep did to one run. */\nexport type ReapRunOutcome =\n /**\n * The probe saw `{\"__exit\":N}`, the run was driven to a terminal status, and\n * its transcript is saved. The happy path.\n */\n | 'finalized'\n /**\n * Past `detachedRunTtlMs`. Cancelled first, then driven to terminal. The probe\n * is skipped: the outcome is terminal whether the agent finished or not.\n *\n * Reported even when {@link ReapOptions.runBudgetMs} is what ended the drive —\n * on this path that is the mechanism rather than an anomaly, so `'expired'` is\n * the truthful outcome. The run's own `status` distinguishes the two shapes:\n * an agent that had already finished replays to `'completed'`, while one still\n * producing when the budget fired is `'aborted'`.\n */\n | 'expired'\n /**\n * Still producing. `pipeToRunLog` was NEVER entered — nothing appended, no\n * terminal record written, `close()` not called, `detachedSince` untouched.\n */\n | 'producing'\n /** The probe could not answer. Left exactly as untouched as `'producing'`. */\n | 'unknown'\n /**\n * ANOMALY. The drive outran {@link ReapOptions.runBudgetMs} on a run the\n * journal already said was finished. The record IS terminal and the log IS\n * closed (`pipeToRunLog` guarantees both), so this is a diagnostic, not a leak\n * — but a finished run that would not replay in 30s means the journal read, the\n * translation, or the log is misbehaving.\n *\n * FINALIZATION ONLY. An expired run that outran its budget reports `'expired'`:\n * there was no probe on that path and the agent may legitimately still have been\n * producing, so the budget firing is the designed stop, not a misbehaving replay.\n */\n | 'budget-exceeded'\n /**\n * Another host holds the claim, or held it and superseded us mid-drive. Normal:\n * a real viewer attaching mid-sweep is exactly this. Also covers a run that\n * reached terminal in another host's hands between the listing and the claim.\n */\n | 'not-claimed'\n /**\n * The transcript IS saved and the record IS terminal — only\n * {@link ReapOptions.reclaim} threw, so the sandbox is still up.\n *\n * A DISTINCT outcome rather than `'failed'`, because the two need opposite\n * operator responses and `'failed'` cannot express this one: it carries no\n * `status` and no `exitCode`, so \"transcript saved, sandbox NOT reclaimed\"\n * read identically to \"the sweep failed and the run was never finalized\".\n *\n * NOT RETRYABLE BY THE SWEEP. The record is terminal by now, so the run has\n * left `listReclaimable` for good; the sandbox leaks until something else\n * tears it down. This entry, with its `error`, is the only notice of that.\n *\n * OVERWRITES `'budget-exceeded'` when both happened, because the leak is what\n * needs acting on — {@link ReapRunEntry.terminalizedAnyway} is what preserves\n * the budget half of that pair.\n *\n * `sandboxReclaimer` REJECTS on its `'destroy-failed'` arm precisely so this\n * outcome is reachable through the shipped reclaimer and not only through a\n * custom one; see `SandboxReclaimFailedError` in `reclaim.ts`.\n */\n | 'reclaim-failed'\n /** Something threw. Logged, recorded here, and the sweep continued. */\n | 'failed'\n\n/** One run's line in the sweep summary. */\nexport interface ReapRunEntry {\n runId: string\n outcome: ReapRunOutcome\n /** The run's status after the sweep, when the run was driven. */\n status?: RunStatus\n /** The agent's exit code, when the probe read one. */\n exitCode?: number\n /**\n * THE BUDGET ANOMALY MARKER, and the only field whose mere PRESENCE carries a\n * fact: it is set if and only if the drive outran\n * {@link ReapOptions.runBudgetMs} on the finalization path — the condition\n * `'budget-exceeded'` names. Its value is whether the record nonetheless\n * reached a terminal status, practically always `true` since `pipeToRunLog` is\n * total; it is reported rather than assumed so an operator does not have to\n * infer it.\n *\n * SURVIVES A FAILED RECLAIM. `reclaim` runs after the outcome is classified\n * and overwrites it with `'reclaim-failed'`, which is the more urgent fact (a\n * leaked sandbox nothing will retry) and so wins the single `outcome` slot.\n * This field is therefore what keeps the budget anomaly on the entry: an\n * operator seeing `'reclaim-failed'` WITH `terminalizedAnyway` present is\n * looking at a run that blew its budget and then leaked, and needs both halves.\n */\n terminalizedAnyway?: boolean\n error?: unknown\n}\n\nexport interface ReapResult {\n /** Runs in this batch — i.e. after the {@link ReapOptions.maxRuns} cap. */\n considered: number\n /** Runs {@link ReapOptions.hasFinished} was actually called for. */\n probed: number\n outcomes: Record<ReapRunOutcome, number>\n runs: Array<ReapRunEntry>\n}\n\nexport interface ReapOptions<TOffset extends string = string> {\n runs: RunStore\n locks: LockStore\n /**\n * Per-run event log factory, same shape `RunDeps.durability` takes.\n *\n * Generic in the offset type, defaulted to `string` so an existing call site\n * needs no change — see {@link SandboxRunDriverOptions.durability} for why\n * hardcoding the default locked out branded-cursor backends.\n */\n durability: (runId: string) => StreamDurability<TOffset>\n /**\n * The out-of-band \"did the agent reach its sentinel?\" probe. INJECTED, because\n * neither the delivery log nor this package can answer it — see the module doc.\n * {@link probeRunExit} is the implementation an application wires in once it has\n * resolved the run's `SandboxHandle`.\n */\n hasFinished: (record: RunRecord) => Promise<RunExitProbe>\n /** Produce the run's remaining events. Called only once the claim is held. */\n drive: (input: {\n runId: string\n threadId: string\n signal: AbortSignal\n }) => AsyncIterable<StreamChunk>\n /** Sweep clock, passed rather than read so a sweep is reproducible. */\n now: number\n /** Detached-run TTL; `detachedSince <= now - ttl` expires, INCLUSIVELY. */\n detachedRunTtlMs: number\n /** Safety net per drive. Defaults to {@link DEFAULT_RUN_BUDGET_MS}. */\n runBudgetMs?: number\n /** Batch cap. Defaults to {@link DEFAULT_MAX_RUNS}. */\n maxRuns?: number\n /** Quiescence window; defaults to `DEFAULT_FENCE_QUIET_MS`. */\n fenceQuietMs?: number\n /**\n * Tear the run's sandbox down. Called ONLY after the run reached a terminal\n * status, and with the ORIGINALLY LISTED record — see {@link reapDetachedRuns}.\n * `sandboxReclaimer` in `reclaim.ts` is the ready-made implementation.\n */\n reclaim?: (record: RunRecord) => Promise<void>\n logger?: InternalLogger\n}\n\nasync function* singleValue(value: string): AsyncIterable<string> {\n yield value\n}\n\n/** Decode the base64 frame `journalExitProbeCommand` emits. */\nasync function decodeFrame(stdout: string): Promise<string> {\n const decoder = new TextDecoder()\n let text = ''\n for await (const bytes of decodeBase64Stream(singleValue(stdout))) {\n text += decoder.decode(bytes, { stream: true })\n }\n return text + decoder.decode()\n}\n\n/**\n * Read the END of a run's journal and answer whether the agent reached its\n * `{\"__exit\":N}` sentinel. Read-only: no append, no record write, no `close()`.\n *\n * This is the whole reason the reaper is safe. It is the ONLY way to learn that a\n * detached run is over without driving it, because the delivery log stops growing\n * the moment the viewer leaves while the journal does not.\n *\n * ANY failure answers `'unknown'`, never `'finished'`: the caller drives a run it\n * is told finished, so a provider `exec` that rejected, a sandbox that is gone, or\n * a frame the provider truncated must never be read as \"the agent exited\".\n *\n * An EMPTY tail answers `'producing'` — the fail-safe direction. A journal that\n * does not exist yet is indistinguishable here from one with no sentinel, and both\n * mean \"do not touch this run\".\n */\nexport async function probeRunExit(input: {\n handle: SandboxHandle\n runId: string\n /** Journal directory; defaults to `DEFAULT_JOURNAL_DIR`, as `journalPaths` does. */\n dir?: string\n /** Tail bytes to read. Defaults to {@link DEFAULT_EXIT_PROBE_BYTES}. */\n maxBytes?: number\n}): Promise<RunExitProbe> {\n try {\n const paths = journalPaths(input.runId, input.dir)\n const result = await input.handle.process.exec(\n journalExitProbeCommand(\n paths,\n input.maxBytes ?? DEFAULT_EXIT_PROBE_BYTES,\n ),\n )\n // `paths` supplies the per-run sentinel nonce: without it a mid-flight\n // agent that printed any JSON object carrying `__exit` would read as\n // `'finished'` here, and the caller would drive and reclaim a LIVE run.\n const exitCode = parseJournalExit(await decodeFrame(result.stdout), paths)\n return exitCode === null\n ? { state: 'producing' }\n : { state: 'finished', exitCode }\n } catch (error) {\n return { state: 'unknown', error }\n }\n}\n\n/** Every outcome key present at zero, so a consumer can read any of them. */\nfunction emptyOutcomes(): Record<ReapRunOutcome, number> {\n return {\n finalized: 0,\n expired: 0,\n producing: 0,\n unknown: 0,\n 'budget-exceeded': 0,\n 'not-claimed': 0,\n 'reclaim-failed': 0,\n failed: 0,\n }\n}\n\n/**\n * Report through a consumer-supplied logger without letting it break the sweep.\n * Mirrors `run.ts`'s `safeLog`: this module's totality must not be defeated by a\n * sink that cannot serialize a thrown value.\n */\nfunction safeLog(\n logger: InternalLogger | undefined,\n level: 'errors' | 'sandbox',\n message: string,\n context: Record<string, unknown>,\n): void {\n try {\n if (level === 'errors') logger?.errors(message, context)\n else logger?.sandbox(message, context)\n } catch {\n // Intentionally empty: there is no second channel to report on.\n }\n}\n\n/** Resolved-once settings shared by every run in one sweep. */\ninterface ReapContext<TOffset extends string = string> {\n options: ReapOptions<TOffset>\n runBudgetMs: number\n fenceQuietMs: number\n /** Inclusive expiry cutoff: `detachedSince <= cutoff` is expired. */\n cutoff: number\n}\n\n/** Whether a thrown value means \"we do not own this run\", which is normal. */\nfunction isClaimRefusal(error: unknown): boolean {\n return (\n error instanceof RunClaimNotAcquiredError ||\n error instanceof RunClaimLostError\n )\n}\n\n/**\n * Sweep ONE run. Never rejects: the caller folds the returned entry into the\n * summary and moves on.\n *\n * The ORDER of the steps below is the contract, not an implementation detail:\n *\n * 1. **Classify expiry first**, because an expired run needs no probe — its\n * outcome is terminal whether or not the agent finished, so a probe would only\n * add a provider round-trip and a way to fail.\n * 2. **Otherwise probe BEFORE touching anything.** `'producing'` and `'unknown'`\n * return here, having made no claim, no append, no record write, and no\n * `close()`. Driving past this point is the whole defect described in the\n * module doc.\n * 3. Claim, so two hosts never drive one run.\n * 4. **Re-derive expiry from a record read INSIDE the lock**, and only then\n * record the cancel. The listed record is stale by the time the claim is\n * held, and the cancel is sticky.\n * 5. Quiesce, so a predecessor still writing is observed rather than raced.\n * 6. **Arm the run budget**, so it bounds the drive rather than the queue the\n * two steps above stood in.\n * 7. Pipe with BOTH authoritative seams fenced, mirroring `driver.ts`.\n * 8. Reclaim, and ONLY once the record actually reached terminal.\n */\nasync function reapOne<TOffset extends string>(\n record: RunRecord,\n ctx: ReapContext<TOffset>,\n counters: { probed: number },\n): Promise<ReapRunEntry> {\n const { runs, locks, logger } = ctx.options\n const { runId, threadId } = record\n\n try {\n // INCLUSIVE, exactly as `RunStore.listReclaimable` documents its own cutoff:\n // a run detached at precisely `now - ttlMs` IS expired. The two must agree,\n // or a run would be listed as reclaimable and then classified as fresh on\n // every single sweep, forever.\n const expired =\n record.detachedSince !== undefined && record.detachedSince <= ctx.cutoff\n\n let exitCode: number | undefined\n if (!expired) {\n counters.probed += 1\n const probe = await ctx.options.hasFinished(record)\n if (probe.state !== 'finished') {\n // THE LEAVE-ALONE PATH. Deliberately returns before `withRunClaim`, so\n // not even `driverEpoch` moves — and above all `detachedSince` is left\n // exactly as it was, since it is both this run's TTL evidence and the\n // field the next sweep selects on.\n safeLog(logger, 'sandbox', `reap: leaving run ${runId} alone`, {\n runId,\n state: probe.state,\n ...(probe.state === 'unknown' && probe.error !== undefined\n ? { error: probe.error }\n : {}),\n })\n return {\n runId,\n outcome: probe.state,\n ...(probe.state === 'unknown' && probe.error !== undefined\n ? { error: probe.error }\n : {}),\n }\n }\n exitCode = probe.exitCode\n }\n\n // Armed INSIDE the claim, below. Read after it for the outcome, so it is\n // hoisted here rather than declared in the callback.\n let budget: AbortSignal | undefined\n const final = await withRunClaim(\n {\n runs,\n locks,\n runId,\n fenceQuietMs: ctx.fenceQuietMs,\n ...(logger === undefined ? {} : { logger }),\n },\n async (claim) => {\n if (expired) {\n // RE-DERIVED FROM A RECORD READ INSIDE THE LOCK, never from the listed\n // one. `stream-to-response.ts`'s `startRunDriver` CLEARS\n // `detachedSince` when a real viewer attaches — deliberately stopping\n // the TTL clock — and it takes this same per-run lock, so an\n // expiry decided at listing time is stale by the time the claim is\n // held. Cancelling on the stale value poisoned a now-live run:\n // nothing in the tree ever clears `cancelRequested`, so on that\n // viewer's next ORDINARY disconnect `middleware.ts`'s\n // `wasCancelRequested` read skips the detach branch and destroys the\n // sandbox of a healthy, actively-viewed run.\n const current = await runs.get(runId)\n if (current === null) {\n throw new RunClaimNotAcquiredError(runId, 'unknown')\n }\n if (\n current.detachedSince === undefined ||\n current.detachedSince > ctx.cutoff\n ) {\n // The viewer came back. `'not-claimed'` already documents \"a real\n // viewer attaching mid-sweep is exactly this\", and refusing here\n // leaves the run as untouched as the leave-alone path does: no\n // cancel, no append, no terminal record, no `close()`.\n throw new RunClaimNotAcquiredError(runId, 'superseded')\n }\n // BEFORE the drive, never after — and never before the claim.\n // `withSandbox`'s `onAbort` resolves the out-of-band cancel band from\n // the record, so recording the intent first is what makes the teardown\n // an explicit cancel that DESTROYS the sandbox rather than a second\n // detach that re-arms `detachedSince` and leaves the run to be swept\n // again forever. Recorded after the drive it is pure bookkeeping on a\n // run that already tore down the wrong way. Recorded before the CLAIM\n // it is an unfenced, sticky write on a record this host does not own,\n // derived from a value the lock exists to make current.\n await requestRunCancel(runs, runId)\n }\n // Before the first append, never after: `pipeToRunLog` snapshots to align.\n await awaitLogQuiescence(\n ctx.options.durability(runId),\n ctx.fenceQuietMs,\n )\n // A safety net, not a mechanism (see the module doc). `AbortSignal.any`\n // is this package's idiom for linking one — see\n // `testkit/takeover-conformance.ts`.\n //\n // ARMED HERE, not before `withRunClaim`. Both the lock wait and the\n // quiescence wait consume a timer started earlier: quiescence always\n // sleeps at least one `fenceQuietMs` and may sleep six, and lock\n // acquisition waits behind whoever holds it, unbounded. The effective\n // budget was silently `runBudgetMs − fenceQuietMs − lockWait`, and once\n // it went negative the claim was acquired with the timer already fired:\n // `pipeToRunLog` hit its entry `signal.aborted` check before pulling one\n // chunk, so a FINISHED agent's transcript was recorded `'aborted'` and\n // its log closed — and a terminal record leaves `listReclaimable`\n // forever, so that transcript was then unreplayable while `reclaim`\n // destroyed the sandbox holding the only copy. The budget bounds the\n // DRIVE, not the queue.\n budget = AbortSignal.timeout(ctx.runBudgetMs)\n // `claim.signal` is in the composed signal because losing the lease MUST\n // stop the drive: a successor that took the run over is appending to the\n // same log, and this drive continuing would double every chunk.\n const signal = AbortSignal.any([claim.signal, budget])\n return pipeToRunLog(ctx.options.drive({ runId, threadId, signal }), {\n // BOTH seams, over the SAME claim, as `driver.ts` explains: fencing the\n // log alone just moves the harm to \"a dead host marks the successor's\n // live run failed\".\n runs: fenceRunStore(runs, claim, {\n ...(logger === undefined ? {} : { logger }),\n }),\n durability: (id) =>\n fenceDurability(ctx.options.durability(id), claim, { runs }),\n runId,\n threadId,\n signal,\n ...(logger === undefined ? {} : { logger }),\n })\n },\n )\n\n const terminal = isTerminalRunStatus(final.status)\n let outcome: ReapRunOutcome\n // `&& !expired` is the whole subtlety. The budget is an ANOMALY only on the\n // finalization path, where the probe already said the agent hit its sentinel\n // and a replay that will not finish in 30s means the journal read, the\n // translation, or the log is misbehaving. On the EXPIRY path there was no\n // probe and the agent may well be mid-sentence: `requestRunCancel` writes a\n // record field whose only reader is `withSandbox`'s `onAbort` (which runs\n // after something else has already aborted), so the budget is the sole thing\n // that ends the drive of a still-producing expired run. That is the designed\n // path, not a misbehaving one, and reporting it as the anomaly made\n // `'expired'` unreachable for exactly the runs the TTL exists to expire.\n // `budget` is armed inside the claim, so reaching here means it was armed;\n // `?? false` keeps the read total rather than asserting that.\n if ((budget?.aborted ?? false) && !expired) {\n outcome = 'budget-exceeded'\n } else if (!terminal) {\n // The terminal write was SUPPRESSED and `finish`'s re-read answered with a\n // live record, which `fenceRunStore` only does when this host lost the claim\n // to another one. That is the same fact as a refused claim, reported the\n // same way rather than as a success that wrote nothing.\n outcome = 'not-claimed'\n } else {\n outcome = expired ? 'expired' : 'finalized'\n }\n\n // CAPTURED BEFORE THE RECLAIM BLOCK, which may overwrite `outcome` with\n // `'reclaim-failed'`. Conditioning the `terminalizedAnyway` spread on the\n // post-reclaim `outcome` dropped the budget diagnostic from exactly the\n // entries that need it most: a run that blew its budget AND then failed to\n // reclaim reported neither fact but the leak, and an operator cannot\n // diagnose a leak on a run whose replay was already misbehaving without\n // knowing that it was.\n const budgetAnomaly = outcome === 'budget-exceeded'\n\n let reclaimError: unknown\n if (terminal && ctx.options.reclaim !== undefined) {\n try {\n // `record`, NOT `final`. When the terminal `update` fails, `finish` returns\n // a LOCALLY REBUILT record that carries only `runId`/`threadId`/`startedAt`\n // plus the terminal patch — no `sandboxKey` — so `reclaimSandbox` would see\n // `undefined`, answer `'no-sandbox-key'`, and the sandbox would leak\n // silently on exactly the path where something already went wrong.\n await ctx.options.reclaim(record)\n } catch (error) {\n // CAUGHT HERE rather than in the outer catch, which would report a bare\n // `'failed'` with no `status` and no `exitCode`. `reclaimSandbox`\n // deliberately does not guard `instances.get` (its contract is that the\n // CALLER records the failure) and neither does `sandboxReclaimer`, so a\n // throwing instance store landed there. By this point the record is\n // terminal and the log closed, so the run is out of `listReclaimable`\n // forever and no later sweep will retry: the sandbox leaks, and an\n // operator reading `'failed'` cannot tell \"transcript saved, sandbox NOT\n // reclaimed\" from \"the sweep failed and the run was never finalized\".\n reclaimError = error\n outcome = 'reclaim-failed'\n safeLog(logger, 'errors', `reap: reclaiming run ${runId} failed`, {\n runId,\n status: final.status,\n error,\n })\n }\n }\n\n return {\n runId,\n outcome,\n status: final.status,\n ...(exitCode === undefined ? {} : { exitCode }),\n ...(budgetAnomaly ? { terminalizedAnyway: terminal } : {}),\n ...(reclaimError === undefined ? {} : { error: reclaimError }),\n }\n } catch (error) {\n if (isClaimRefusal(error)) {\n safeLog(logger, 'sandbox', `reap: not driving run ${runId}`, {\n runId,\n error,\n })\n return { runId, outcome: 'not-claimed', error }\n }\n // Folded into the summary rather than rethrown: one bad run must not abandon\n // the rest of the batch, and there is no caller to receive a rejection.\n safeLog(logger, 'errors', `reap: sweeping run ${runId} failed`, {\n runId,\n error,\n })\n return { runId, outcome: 'failed', error }\n }\n}\n\n/**\n * Sweep the detached runs a `RunStore` surfaces, saving each finished run's\n * transcript and reclaiming its sandbox.\n *\n * A plain async function with no timer and no daemon: call it from a cron, a\n * queue consumer, a Durable Object `alarm()`, or a `waitUntil`. It NEVER rejects\n * — every failure is logged and counted in the returned {@link ReapResult}.\n *\n * ONE `listReclaimable({ now, ttlMs: 0 })` call, deliberately: `ttlMs: 0` is\n * every detached run, which is the candidate set for FINALIZATION (a run that hit\n * its sentinel one second after the viewer left has an unsaved transcript and\n * must not wait out the TTL), and expiry is then classified in-process against\n * the same inclusive cutoff. Listing twice with two TTLs would cost a second\n * store round-trip to compute a subset.\n *\n * `listReclaimable` is OPTIONAL on `RunStore`. A backend without it cannot be\n * reaped, which answers `{ considered: 0 }` plus one log line rather than\n * throwing — the same graceful degrade every other optional-method call site in\n * the repo does (`store.findActiveRun?.(threadId)`).\n */\nexport async function reapDetachedRuns<TOffset extends string = string>(\n options: ReapOptions<TOffset>,\n): Promise<ReapResult> {\n const logger = options.logger\n const outcomes = emptyOutcomes()\n const entries: Array<ReapRunEntry> = []\n const empty = (): ReapResult => ({\n considered: 0,\n probed: 0,\n outcomes,\n runs: entries,\n })\n\n const list = options.runs.listReclaimable?.bind(options.runs)\n if (list === undefined) {\n safeLog(\n logger,\n 'sandbox',\n 'reap: the run store does not implement listReclaimable; nothing to sweep',\n {},\n )\n return empty()\n }\n\n let candidates: Array<RunRecord>\n try {\n candidates = await list({ now: options.now, ttlMs: 0 })\n } catch (error) {\n safeLog(logger, 'errors', 'reap: listing reclaimable runs failed', {\n error,\n })\n return empty()\n }\n\n // Capped so one invocation cannot outlive its platform's budget and be killed\n // mid-drive. `slice` and not a `break`, so `considered` reports the batch the\n // sweep actually took responsibility for.\n const maxRuns = Math.max(0, Math.trunc(options.maxRuns ?? DEFAULT_MAX_RUNS))\n const batch = candidates.slice(0, maxRuns)\n\n const ctx: ReapContext<TOffset> = {\n options,\n runBudgetMs: options.runBudgetMs ?? DEFAULT_RUN_BUDGET_MS,\n fenceQuietMs: options.fenceQuietMs ?? DEFAULT_FENCE_QUIET_MS,\n cutoff: options.now - options.detachedRunTtlMs,\n }\n const counters = { probed: 0 }\n\n // Sequential on purpose: each run costs a lock, a provider round-trip, and a\n // full replay, and a cron invocation's budget is the scarce resource. Fanning\n // out would multiply peak load against the provider for no throughput a\n // subsequent tick cannot supply.\n for (const record of batch) {\n const entry = await reapOne(record, ctx, counters)\n outcomes[entry.outcome] += 1\n entries.push(entry)\n }\n\n return {\n considered: batch.length,\n probed: counters.probed,\n outcomes,\n runs: entries,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyGA,IAAa,wBAAwB;;;;;;;AAQrC,IAAa,mBAAmB;;AAGhC,IAAa,2BAA2B;AAuKxC,gBAAgB,YAAY,OAAsC;CAChE,MAAM;AACR;;AAGA,eAAe,YAAY,QAAiC;CAC1D,MAAM,UAAU,IAAI,YAAY;CAChC,IAAI,OAAO;CACX,WAAW,MAAM,SAAS,mBAAmB,YAAY,MAAM,CAAC,GAC9D,QAAQ,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;CAEhD,OAAO,OAAO,QAAQ,OAAO;AAC/B;;;;;;;;;;;;;;;;;AAkBA,eAAsB,aAAa,OAOT;CACxB,IAAI;EACF,MAAM,QAAQ,aAAa,MAAM,OAAO,MAAM,GAAG;EACjD,MAAM,SAAS,MAAM,MAAM,OAAO,QAAQ,KACxC,wBACE,OACA,MAAM,YAAA,IACR,CACF;EAIA,MAAM,WAAW,iBAAiB,MAAM,YA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;EAChC;EACA,aAAa,QAAQ,eAAA;EACrB,cAAc,QAAQ,gBAAA;EACtB,QAAQ,QAAQ,MAAM,QAAQ;CAChC;CACA,MAAM,WAAW,EAAE,QAAQ,EAAE;CAM7B,KAAK,MAAM,UAAU,OAAO;EAC1B,MAAM,QAAQ,MAAM,QAAQ,QAAQ,KAAK,QAAQ;EACjD,SAAS,MAAM,YAAY;EAC3B,QAAQ,KAAK,KAAK;CACpB;CAEA,OAAO;EACL,YAAY,MAAM;EAClB,QAAQ,SAAS;EACjB;EACA,MAAM;CACR;AACF"}
|
package/dist/esm/sandbox.js
CHANGED
|
@@ -29,7 +29,7 @@ function parseMaxAgeMs(value) {
|
|
|
29
29
|
* enough that a slow provider API still completes, short enough that a wedged
|
|
30
30
|
* one cannot pin the process forever.
|
|
31
31
|
*/
|
|
32
|
-
var DESTROY_TIMEOUT_MS =
|
|
32
|
+
var DESTROY_TIMEOUT_MS = 6e4;
|
|
33
33
|
var fallbackStore = new InMemorySandboxInstanceStore();
|
|
34
34
|
var fallbackLocks = new InMemoryLockStore();
|
|
35
35
|
/**
|
package/dist/esm/sandbox.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox.js","names":[],"sources":["../../src/sandbox.ts"],"sourcesContent":["/**\n * `defineSandbox()` returns a LAZY controller — it never creates a sandbox at\n * definition time. `withSandbox()` (and advanced users) call `ensure()` to\n * resume-or-create, following: provider.resume → provider.restoreSnapshot →\n * create + bootstrap. The controller folds provider/workspace/policy/lifecycle\n * into a stable instance key and coordinates through the (optional) lock +\n * sandbox stores.\n */\nimport { bootstrapWorkspace } from './bootstrap'\nimport { resolveAllSecrets } from './secrets'\nimport { computeSandboxKey } from './key'\nimport { InMemoryLockStore } from '@tanstack/ai/locks'\nimport type { LockStore } from '@tanstack/ai/locks'\nimport type { SandboxFileHookEvent } from '@tanstack/ai'\nimport { InMemorySandboxInstanceStore } from './instance-store'\nimport type { SandboxInstanceStore } from './instance-store'\nimport type { SandboxHandle, SandboxProvider } from './contracts'\nimport type { SandboxKeyInput } from './key'\nimport type { SandboxPolicy } from './policy'\nimport type { WorkspaceDefinition } from './workspace'\n\n/**\n * Sandbox-scoped hooks declared on `defineSandbox`. File hooks fire for every\n * create/change/delete during a chat run; lifecycle hooks fire server-side.\n */\nexport interface SandboxHooks {\n onFile?: (e: SandboxFileHookEvent) => void | Promise<void>\n onFileCreate?: (e: SandboxFileHookEvent) => void | Promise<void>\n onFileChange?: (e: SandboxFileHookEvent) => void | Promise<void>\n onFileDelete?: (e: SandboxFileHookEvent) => void | Promise<void>\n onReady?: (handle: SandboxHandle) => void | Promise<void>\n onError?: (err: unknown) => void | Promise<void>\n onDestroy?: () => void | Promise<void>\n}\n\nexport type ReuseStrategy = 'thread' | 'none'\nexport type SnapshotStrategy = 'after-setup' | 'after-run' | 'none'\n\nexport interface SandboxLifecycle {\n /** `'thread'` resumes one sandbox per thread; `'none'` is fresh per run. */\n reuse?: ReuseStrategy\n /** When to snapshot (provider-permitting). */\n snapshot?: SnapshotStrategy\n /** Hint for how long a provider should keep the sandbox warm between runs. */\n keepAlive?: string\n /** Destroy the sandbox after the run completes. */\n destroyOnComplete?: boolean\n /**\n * Maximum age of a sandbox record before it is discarded and re-created\n * instead of resumed. Accepts `'<n>h'` (hours) or `'<n>m'` (minutes),\n * e.g. `'2h'` or `'30m'`.\n */\n snapshotMaxAge?: string\n}\n\nexport interface SandboxConfig {\n id: string\n provider: SandboxProvider\n workspace?: WorkspaceDefinition\n policy?: SandboxPolicy\n lifecycle?: SandboxLifecycle\n /** Sandbox-scoped file/lifecycle hooks. */\n hooks?: SandboxHooks\n /** Watch the workspace for file events (default true). `false` disables the\n * watcher; `{ diff: true }` also emits a per-file `sandbox.file.diff` event. */\n fileEvents?: boolean | { diff?: boolean }\n}\n\n/** Context passed to `ensure()` by `withSandbox` (or advanced callers). */\nexport interface SandboxEnsureContext {\n threadId: string\n runId: string\n /** Persistence seam; falls back to an in-memory store when absent. */\n store?: SandboxInstanceStore\n /** Lock seam; falls back to an in-memory lock when absent. */\n locks?: LockStore\n tenant?: { userId?: string; orgId?: string }\n signal?: AbortSignal\n /** Harness adapter name (`grok-build`, `claude-code`, `codex`, `opencode`). Optional. */\n adapterName?: string\n}\n\nexport interface SandboxDefinition {\n readonly id: string\n readonly provider: SandboxProvider\n readonly workspace?: WorkspaceDefinition\n readonly policy?: SandboxPolicy\n readonly lifecycle?: SandboxLifecycle\n /** Sandbox-scoped file/lifecycle hooks. */\n readonly hooks?: SandboxHooks\n /** Watch the workspace for file events (default true). `false` disables the\n * watcher; `{ diff: true }` also emits a per-file `sandbox.file.diff` event. */\n readonly fileEvents?: boolean | { diff?: boolean }\n /** Compound instance key for a given run context. */\n key: (ctx: SandboxEnsureContext) => string\n /** Resume-or-create the sandbox for this thread/run. */\n ensure: (ctx: SandboxEnsureContext) => Promise<SandboxHandle>\n /** Tear down the sandbox recorded for this key. */\n destroy: (ctx: SandboxEnsureContext) => Promise<void>\n}\n\n/**\n * Parse a human-readable duration string into milliseconds.\n * Supports `'<n>h'` (hours) and `'<n>m'` (minutes).\n * Returns `undefined` when the input is undefined or the format is unrecognised.\n */\nfunction parseMaxAgeMs(value: string | undefined): number | undefined {\n if (value === undefined) return undefined\n const hourMatch = /^(\\d+)h$/.exec(value)\n if (hourMatch) return Number(hourMatch[1]) * 60 * 60 * 1000\n const minuteMatch = /^(\\d+)m$/.exec(value)\n if (minuteMatch) return Number(minuteMatch[1]) * 60 * 1000\n return undefined\n}\n\n/**\n * Bound for the unfenced teardown `destroy` call (see `destroy` below). Long\n * enough that a slow provider API still completes, short enough that a wedged\n * one cannot pin the process forever.\n */\nconst DESTROY_TIMEOUT_MS = 60 * 1000\n\n// Process-lifetime fallbacks shared across all definitions so concurrent\n// ensures for the same key serialize even without an injected store/lock.\nconst fallbackStore = new InMemorySandboxInstanceStore()\nconst fallbackLocks = new InMemoryLockStore()\n\n/**\n * Put workspace secrets onto a live handle. Resume and snapshot restore skip\n * bootstrap, so this is the only path that re-injects them after reconnect.\n * Create injects secrets via `provider.create({ env })`, but resume/restore\n * return a handle whose process env is empty unless we set it here. sbx in\n * particular has no Docker Env on resume, so this is the only way secrets\n * come back for that provider.\n */\nasync function applyWorkspaceSecrets(\n handle: SandboxHandle,\n workspace: WorkspaceDefinition | undefined,\n): Promise<void> {\n if (workspace?.secrets === undefined) return\n const resolved = resolveAllSecrets(workspace.secrets)\n if (Object.keys(resolved).length === 0) return\n await handle.env.set(resolved)\n}\n\nexport function defineSandbox(config: SandboxConfig): SandboxDefinition {\n const keyInputFor = (ctx: SandboxEnsureContext): SandboxKeyInput => ({\n threadId:\n config.lifecycle?.reuse === 'none'\n ? `${ctx.threadId}:${ctx.runId}`\n : ctx.threadId,\n sandboxId: config.id,\n providerName: config.provider.name,\n workspace: config.workspace,\n tenant: ctx.tenant,\n })\n\n const ensure = async (ctx: SandboxEnsureContext): Promise<SandboxHandle> => {\n const store = ctx.store ?? fallbackStore\n const locks = ctx.locks ?? fallbackLocks\n const key = computeSandboxKey(keyInputFor(ctx))\n const caps = config.provider.capabilities()\n\n return locks.withLock(`sandbox:${key}`, async () => {\n const effectiveSnapshot: SnapshotStrategy =\n config.lifecycle?.snapshot ?? (caps.snapshots ? 'after-setup' : 'none')\n const maxAgeMs = parseMaxAgeMs(config.lifecycle?.snapshotMaxAge)\n\n const existing = await store.get(key)\n if (existing) {\n // Check whether the record has exceeded snapshotMaxAge; if so,\n // discard and fall through to a fresh create.\n const tooOld =\n maxAgeMs !== undefined && Date.now() - existing.updatedAt > maxAgeMs\n\n if (!tooOld) {\n // 1) Try to reconnect to the still-running sandbox.\n const resumed = await config.provider.resume({\n id: existing.providerSandboxId,\n signal: ctx.signal,\n })\n if (resumed) {\n await applyWorkspaceSecrets(resumed, config.workspace)\n await store.upsert({\n ...existing,\n latestRunId: ctx.runId,\n updatedAt: Date.now(),\n })\n return resumed\n }\n // 2) Else restore from the latest snapshot, if supported.\n if (\n existing.latestSnapshotId &&\n caps.snapshots &&\n config.provider.restoreSnapshot\n ) {\n const restored = await config.provider.restoreSnapshot({\n snapshotId: existing.latestSnapshotId,\n workspace: config.workspace,\n policy: config.policy,\n env:\n config.workspace?.secrets !== undefined\n ? resolveAllSecrets(config.workspace.secrets)\n : undefined,\n signal: ctx.signal,\n })\n await applyWorkspaceSecrets(restored, config.workspace)\n await store.upsert({\n ...existing,\n providerSandboxId: restored.id,\n latestRunId: ctx.runId,\n updatedAt: Date.now(),\n })\n return restored\n }\n }\n // 3) Else fall through and re-create under the same identity\n // (capability-aware degradation for ephemeral-disk providers, or\n // snapshotMaxAge TTL exceeded).\n }\n\n const created = await config.provider.create({\n // Deterministic id so consumers can reconstruct the provider sandbox\n // address from run context (not just from the store record).\n id: key,\n workspace: config.workspace,\n policy: config.policy,\n env:\n config.workspace?.secrets !== undefined\n ? resolveAllSecrets(config.workspace.secrets)\n : undefined,\n signal: ctx.signal,\n adapterName: ctx.adapterName,\n })\n\n if (config.workspace) {\n try {\n await bootstrapWorkspace(created, config.workspace, {\n signal: ctx.signal,\n })\n } catch (error) {\n // Bootstrap failed after the sandbox was created but before it was\n // recorded — destroy the orphan so a failed/retried run doesn't leak\n // a (billed) sandbox, then surface the original error.\n await created.destroy().catch(() => {})\n throw error\n }\n }\n\n let latestSnapshotId: string | undefined\n if (\n effectiveSnapshot === 'after-setup' &&\n caps.snapshots &&\n created.snapshot\n ) {\n latestSnapshotId = (await created.snapshot('after-setup')).id\n }\n\n await store.upsert({\n key,\n provider: config.provider.name,\n providerSandboxId: created.id,\n latestSnapshotId,\n threadId: ctx.threadId,\n latestRunId: ctx.runId,\n updatedAt: Date.now(),\n })\n return created\n })\n }\n\n const destroy = async (ctx: SandboxEnsureContext): Promise<void> => {\n const store = ctx.store ?? fallbackStore\n const key = computeSandboxKey(keyInputFor(ctx))\n const existing = await store.get(key)\n if (!existing) return\n /*\n * TEARDOWN IS DELIBERATELY NOT FENCED BY `ctx.signal`.\n *\n * `destroy` runs on every teardown path INCLUDING the one caused by that\n * very signal aborting, so forwarding it hands the provider a signal that is\n * already aborted: a provider that honors it does nothing and returns\n * successfully, and `store.delete` below then removes the only pointer to a\n * live, billed sandbox. `SandboxInstanceStore` has no `list` (see the note\n * at the top of `reclaim.ts`), so that sandbox is unreachable from then on.\n *\n * Same reasoning as `close()` never being fenced by the run claim (see\n * `fenceDurability` in `claim.ts`): cleanup must outlive whatever cancelled\n * the work. A fresh controller with its own bounded timeout keeps the call\n * from hanging forever without letting the caller's abort cancel it.\n */\n const teardown = new AbortController()\n const timer = setTimeout(() => teardown.abort(), DESTROY_TIMEOUT_MS)\n try {\n await config.provider.destroy({\n id: existing.providerSandboxId,\n signal: teardown.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n await store.delete(key)\n }\n\n return {\n id: config.id,\n provider: config.provider,\n workspace: config.workspace,\n policy: config.policy,\n lifecycle: config.lifecycle,\n hooks: config.hooks,\n fileEvents: config.fileEvents,\n key: (ctx) => computeSandboxKey(keyInputFor(ctx)),\n ensure,\n destroy,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA0GA,SAAS,cAAc,OAA+C;CACpE,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,YAAY,WAAW,KAAK,KAAK;CACvC,IAAI,WAAW,OAAO,OAAO,UAAU,EAAE,IAAI,KAAK,KAAK;CACvD,MAAM,cAAc,WAAW,KAAK,KAAK;CACzC,IAAI,aAAa,OAAO,OAAO,YAAY,EAAE,IAAI,KAAK;AAExD;;;;;;AAOA,IAAM,qBAAqB,KAAK;AAIhC,IAAM,gBAAgB,IAAI,6BAA6B;AACvD,IAAM,gBAAgB,IAAI,kBAAkB;;;;;;;;;AAU5C,eAAe,sBACb,QACA,WACe;CACf,IAAI,WAAW,YAAY,KAAA,GAAW;CACtC,MAAM,WAAW,kBAAkB,UAAU,OAAO;CACpD,IAAI,OAAO,KAAK,QAAQ,CAAC,CAAC,WAAW,GAAG;CACxC,MAAM,OAAO,IA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,GAAG;CACxB;CAEA,OAAO;EACL,IAAI,OAAO;EACX,UAAU,OAAO;EACjB,WAAW,OAAO;EAClB,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB,OAAO,OAAO;EACd,YAAY,OAAO;EACnB,MAAM,QAAQ,kBAAkB,YAAY,GAAG,CAAC;EAChD;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"sandbox.js","names":[],"sources":["../../src/sandbox.ts"],"sourcesContent":["/**\n * `defineSandbox()` returns a LAZY controller — it never creates a sandbox at\n * definition time. `withSandbox()` (and advanced users) call `ensure()` to\n * resume-or-create, following: provider.resume → provider.restoreSnapshot →\n * create + bootstrap. The controller folds provider/workspace/policy/lifecycle\n * into a stable instance key and coordinates through the (optional) lock +\n * sandbox stores.\n */\nimport { bootstrapWorkspace } from './bootstrap'\nimport { resolveAllSecrets } from './secrets'\nimport { computeSandboxKey } from './key'\nimport { InMemoryLockStore } from '@tanstack/ai/locks'\nimport type { LockStore } from '@tanstack/ai/locks'\nimport type { SandboxFileHookEvent } from '@tanstack/ai'\nimport { InMemorySandboxInstanceStore } from './instance-store'\nimport type { SandboxInstanceStore } from './instance-store'\nimport type { SandboxHandle, SandboxProvider } from './contracts'\nimport type { SandboxKeyInput } from './key'\nimport type { SandboxPolicy } from './policy'\nimport type { WorkspaceDefinition } from './workspace'\n\n/**\n * Sandbox-scoped hooks declared on `defineSandbox`. File hooks fire for every\n * create/change/delete during a chat run; lifecycle hooks fire server-side.\n */\nexport interface SandboxHooks {\n onFile?: (e: SandboxFileHookEvent) => void | Promise<void>\n onFileCreate?: (e: SandboxFileHookEvent) => void | Promise<void>\n onFileChange?: (e: SandboxFileHookEvent) => void | Promise<void>\n onFileDelete?: (e: SandboxFileHookEvent) => void | Promise<void>\n onReady?: (handle: SandboxHandle) => void | Promise<void>\n onError?: (err: unknown) => void | Promise<void>\n onDestroy?: () => void | Promise<void>\n}\n\nexport type ReuseStrategy = 'thread' | 'none'\nexport type SnapshotStrategy = 'after-setup' | 'after-run' | 'none'\n\nexport interface SandboxLifecycle {\n /** `'thread'` resumes one sandbox per thread; `'none'` is fresh per run. */\n reuse?: ReuseStrategy\n /** When to snapshot (provider-permitting). */\n snapshot?: SnapshotStrategy\n /** Hint for how long a provider should keep the sandbox warm between runs. */\n keepAlive?: string\n /** Destroy the sandbox after the run completes. */\n destroyOnComplete?: boolean\n /**\n * Maximum age of a sandbox record before it is discarded and re-created\n * instead of resumed. Accepts `'<n>h'` (hours) or `'<n>m'` (minutes),\n * e.g. `'2h'` or `'30m'`.\n */\n snapshotMaxAge?: string\n}\n\nexport interface SandboxConfig {\n id: string\n provider: SandboxProvider\n workspace?: WorkspaceDefinition\n policy?: SandboxPolicy\n lifecycle?: SandboxLifecycle\n /** Sandbox-scoped file/lifecycle hooks. */\n hooks?: SandboxHooks\n /** Watch the workspace for file events (default true). `false` disables the\n * watcher; `{ diff: true }` also emits a per-file `sandbox.file.diff` event. */\n fileEvents?: boolean | { diff?: boolean }\n}\n\n/** Context passed to `ensure()` by `withSandbox` (or advanced callers). */\nexport interface SandboxEnsureContext {\n threadId: string\n runId: string\n /** Persistence seam; falls back to an in-memory store when absent. */\n store?: SandboxInstanceStore\n /** Lock seam; falls back to an in-memory lock when absent. */\n locks?: LockStore\n tenant?: { userId?: string; orgId?: string }\n signal?: AbortSignal\n /** Harness adapter name (`grok-build`, `claude-code`, `codex`, `opencode`). Optional. */\n adapterName?: string\n}\n\nexport interface SandboxDefinition {\n readonly id: string\n readonly provider: SandboxProvider\n readonly workspace?: WorkspaceDefinition\n readonly policy?: SandboxPolicy\n readonly lifecycle?: SandboxLifecycle\n /** Sandbox-scoped file/lifecycle hooks. */\n readonly hooks?: SandboxHooks\n /** Watch the workspace for file events (default true). `false` disables the\n * watcher; `{ diff: true }` also emits a per-file `sandbox.file.diff` event. */\n readonly fileEvents?: boolean | { diff?: boolean }\n /** Compound instance key for a given run context. */\n key: (ctx: SandboxEnsureContext) => string\n /** Resume-or-create the sandbox for this thread/run. */\n ensure: (ctx: SandboxEnsureContext) => Promise<SandboxHandle>\n /** Tear down the sandbox recorded for this key. */\n destroy: (ctx: SandboxEnsureContext) => Promise<void>\n}\n\n/**\n * Parse a human-readable duration string into milliseconds.\n * Supports `'<n>h'` (hours) and `'<n>m'` (minutes).\n * Returns `undefined` when the input is undefined or the format is unrecognised.\n */\nfunction parseMaxAgeMs(value: string | undefined): number | undefined {\n if (value === undefined) return undefined\n const hourMatch = /^(\\d+)h$/.exec(value)\n if (hourMatch) return Number(hourMatch[1]) * 60 * 60 * 1000\n const minuteMatch = /^(\\d+)m$/.exec(value)\n if (minuteMatch) return Number(minuteMatch[1]) * 60 * 1000\n return undefined\n}\n\n/**\n * Bound for the unfenced teardown `destroy` call (see `destroy` below). Long\n * enough that a slow provider API still completes, short enough that a wedged\n * one cannot pin the process forever.\n */\nconst DESTROY_TIMEOUT_MS = 60 * 1000\n\n// Process-lifetime fallbacks shared across all definitions so concurrent\n// ensures for the same key serialize even without an injected store/lock.\nconst fallbackStore = new InMemorySandboxInstanceStore()\nconst fallbackLocks = new InMemoryLockStore()\n\n/**\n * Put workspace secrets onto a live handle. Resume and snapshot restore skip\n * bootstrap, so this is the only path that re-injects them after reconnect.\n * Create injects secrets via `provider.create({ env })`, but resume/restore\n * return a handle whose process env is empty unless we set it here. sbx in\n * particular has no Docker Env on resume, so this is the only way secrets\n * come back for that provider.\n */\nasync function applyWorkspaceSecrets(\n handle: SandboxHandle,\n workspace: WorkspaceDefinition | undefined,\n): Promise<void> {\n if (workspace?.secrets === undefined) return\n const resolved = resolveAllSecrets(workspace.secrets)\n if (Object.keys(resolved).length === 0) return\n await handle.env.set(resolved)\n}\n\nexport function defineSandbox(config: SandboxConfig): SandboxDefinition {\n const keyInputFor = (ctx: SandboxEnsureContext): SandboxKeyInput => ({\n threadId:\n config.lifecycle?.reuse === 'none'\n ? `${ctx.threadId}:${ctx.runId}`\n : ctx.threadId,\n sandboxId: config.id,\n providerName: config.provider.name,\n workspace: config.workspace,\n tenant: ctx.tenant,\n })\n\n const ensure = async (ctx: SandboxEnsureContext): Promise<SandboxHandle> => {\n const store = ctx.store ?? fallbackStore\n const locks = ctx.locks ?? fallbackLocks\n const key = computeSandboxKey(keyInputFor(ctx))\n const caps = config.provider.capabilities()\n\n return locks.withLock(`sandbox:${key}`, async () => {\n const effectiveSnapshot: SnapshotStrategy =\n config.lifecycle?.snapshot ?? (caps.snapshots ? 'after-setup' : 'none')\n const maxAgeMs = parseMaxAgeMs(config.lifecycle?.snapshotMaxAge)\n\n const existing = await store.get(key)\n if (existing) {\n // Check whether the record has exceeded snapshotMaxAge; if so,\n // discard and fall through to a fresh create.\n const tooOld =\n maxAgeMs !== undefined && Date.now() - existing.updatedAt > maxAgeMs\n\n if (!tooOld) {\n // 1) Try to reconnect to the still-running sandbox.\n const resumed = await config.provider.resume({\n id: existing.providerSandboxId,\n signal: ctx.signal,\n })\n if (resumed) {\n await applyWorkspaceSecrets(resumed, config.workspace)\n await store.upsert({\n ...existing,\n latestRunId: ctx.runId,\n updatedAt: Date.now(),\n })\n return resumed\n }\n // 2) Else restore from the latest snapshot, if supported.\n if (\n existing.latestSnapshotId &&\n caps.snapshots &&\n config.provider.restoreSnapshot\n ) {\n const restored = await config.provider.restoreSnapshot({\n snapshotId: existing.latestSnapshotId,\n workspace: config.workspace,\n policy: config.policy,\n env:\n config.workspace?.secrets !== undefined\n ? resolveAllSecrets(config.workspace.secrets)\n : undefined,\n signal: ctx.signal,\n })\n await applyWorkspaceSecrets(restored, config.workspace)\n await store.upsert({\n ...existing,\n providerSandboxId: restored.id,\n latestRunId: ctx.runId,\n updatedAt: Date.now(),\n })\n return restored\n }\n }\n // 3) Else fall through and re-create under the same identity\n // (capability-aware degradation for ephemeral-disk providers, or\n // snapshotMaxAge TTL exceeded).\n }\n\n const created = await config.provider.create({\n // Deterministic id so consumers can reconstruct the provider sandbox\n // address from run context (not just from the store record).\n id: key,\n workspace: config.workspace,\n policy: config.policy,\n env:\n config.workspace?.secrets !== undefined\n ? resolveAllSecrets(config.workspace.secrets)\n : undefined,\n signal: ctx.signal,\n adapterName: ctx.adapterName,\n })\n\n if (config.workspace) {\n try {\n await bootstrapWorkspace(created, config.workspace, {\n signal: ctx.signal,\n })\n } catch (error) {\n // Bootstrap failed after the sandbox was created but before it was\n // recorded — destroy the orphan so a failed/retried run doesn't leak\n // a (billed) sandbox, then surface the original error.\n await created.destroy().catch(() => {})\n throw error\n }\n }\n\n let latestSnapshotId: string | undefined\n if (\n effectiveSnapshot === 'after-setup' &&\n caps.snapshots &&\n created.snapshot\n ) {\n latestSnapshotId = (await created.snapshot('after-setup')).id\n }\n\n await store.upsert({\n key,\n provider: config.provider.name,\n providerSandboxId: created.id,\n latestSnapshotId,\n threadId: ctx.threadId,\n latestRunId: ctx.runId,\n updatedAt: Date.now(),\n })\n return created\n })\n }\n\n const destroy = async (ctx: SandboxEnsureContext): Promise<void> => {\n const store = ctx.store ?? fallbackStore\n const key = computeSandboxKey(keyInputFor(ctx))\n const existing = await store.get(key)\n if (!existing) return\n /*\n * TEARDOWN IS DELIBERATELY NOT FENCED BY `ctx.signal`.\n *\n * `destroy` runs on every teardown path INCLUDING the one caused by that\n * very signal aborting, so forwarding it hands the provider a signal that is\n * already aborted: a provider that honors it does nothing and returns\n * successfully, and `store.delete` below then removes the only pointer to a\n * live, billed sandbox. `SandboxInstanceStore` has no `list` (see the note\n * at the top of `reclaim.ts`), so that sandbox is unreachable from then on.\n *\n * Same reasoning as `close()` never being fenced by the run claim (see\n * `fenceDurability` in `claim.ts`): cleanup must outlive whatever cancelled\n * the work. A fresh controller with its own bounded timeout keeps the call\n * from hanging forever without letting the caller's abort cancel it.\n */\n const teardown = new AbortController()\n const timer = setTimeout(() => teardown.abort(), DESTROY_TIMEOUT_MS)\n try {\n await config.provider.destroy({\n id: existing.providerSandboxId,\n signal: teardown.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n await store.delete(key)\n }\n\n return {\n id: config.id,\n provider: config.provider,\n workspace: config.workspace,\n policy: config.policy,\n lifecycle: config.lifecycle,\n hooks: config.hooks,\n fileEvents: config.fileEvents,\n key: (ctx) => computeSandboxKey(keyInputFor(ctx)),\n ensure,\n destroy,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA0GA,SAAS,cAAc,OAA+C;CACpE,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,YAAY,WAAW,KAAK,KAAK;CACvC,IAAI,WAAW,OAAO,OAAO,UAAU,EAAE,IAAI,KAAK,KAAK;CACvD,MAAM,cAAc,WAAW,KAAK,KAAK;CACzC,IAAI,aAAa,OAAO,OAAO,YAAY,EAAE,IAAI,KAAK;AAExD;;;;;;AAOA,IAAM,qBAAqB;AAI3B,IAAM,gBAAgB,IAAI,6BAA6B;AACvD,IAAM,gBAAgB,IAAI,kBAAkB;;;;;;;;;AAU5C,eAAe,sBACb,QACA,WACe;CACf,IAAI,WAAW,YAAY,KAAA,GAAW;CACtC,MAAM,WAAW,kBAAkB,UAAU,OAAO;CACpD,IAAI,OAAO,KAAK,QAAQ,CAAC,CAAC,WAAW,GAAG;CACxC,MAAM,OAAO,IAAI,IAAI,QAAQ;AAC/B;AAEA,SAAgB,cAAc,QAA0C;CACtE,MAAM,eAAe,SAAgD;EACnE,UACE,OAAO,WAAW,UAAU,SACxB,GAAG,IAAI,SAAS,GAAG,IAAI,UACvB,IAAI;EACV,WAAW,OAAO;EAClB,cAAc,OAAO,SAAS;EAC9B,WAAW,OAAO;EAClB,QAAQ,IAAI;CACd;CAEA,MAAM,SAAS,OAAO,QAAsD;EAC1E,MAAM,QAAQ,IAAI,SAAS;EAC3B,MAAM,QAAQ,IAAI,SAAS;EAC3B,MAAM,MAAM,kBAAkB,YAAY,GAAG,CAAC;EAC9C,MAAM,OAAO,OAAO,SAAS,aAAa;EAE1C,OAAO,MAAM,SAAS,WAAW,OAAO,YAAY;GAClD,MAAM,oBACJ,OAAO,WAAW,aAAa,KAAK,YAAY,gBAAgB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,CAAC;IACtC,MAAM;GACR;GAGF,IAAI;GACJ,IACE,sBAAsB,iBACtB,KAAK,aACL,QAAQ,UAER,oBAAoB,MAAM,QAAQ,SAAS,aAAa,EAAA,CAAG;GAG7D,MAAM,MAAM,OAAO;IACjB;IACA,UAAU,OAAO,SAAS;IAC1B,mBAAmB,QAAQ;IAC3B;IACA,UAAU,IAAI;IACd,aAAa,IAAI;IACjB,WAAW,KAAK,IAAI;GACtB,CAAC;GACD,OAAO;EACT,CAAC;CACH;CAEA,MAAM,UAAU,OAAO,QAA6C;EAClE,MAAM,QAAQ,IAAI,SAAS;EAC3B,MAAM,MAAM,kBAAkB,YAAY,GAAG,CAAC;EAC9C,MAAM,WAAW,MAAM,MAAM,IAAI,GAAG;EACpC,IAAI,CAAC,UAAU;EAgBf,MAAM,WAAW,IAAI,gBAAgB;EACrC,MAAM,QAAQ,iBAAiB,SAAS,MAAM,GAAG,kBAAkB;EACnE,IAAI;GACF,MAAM,OAAO,SAAS,QAAQ;IAC5B,IAAI,SAAS;IACb,QAAQ,SAAS;GACnB,CAAC;EACH,UAAU;GACR,aAAa,KAAK;EACpB;EACA,MAAM,MAAM,OAAO,GAAG;CACxB;CAEA,OAAO;EACL,IAAI,OAAO;EACX,UAAU,OAAO;EACjB,WAAW,OAAO;EAClB,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB,OAAO,OAAO;EACd,YAAY,OAAO;EACnB,MAAM,QAAQ,kBAAkB,YAAY,GAAG,CAAC;EAChD;EACA;CACF;AACF"}
|
package/dist/esm/shell.js
CHANGED
|
@@ -18,7 +18,7 @@ function parseExports(output) {
|
|
|
18
18
|
return env;
|
|
19
19
|
}
|
|
20
20
|
/** Default {@link BootstrapShellOptions.commandTimeoutMs} — 30 minutes. */
|
|
21
|
-
var DEFAULT_COMMAND_TIMEOUT_MS =
|
|
21
|
+
var DEFAULT_COMMAND_TIMEOUT_MS = 18e5;
|
|
22
22
|
/** Race marker for the per-command deadline. A symbol cannot collide with a
|
|
23
23
|
* literal stdout line (a line of text `'timeout'` would). */
|
|
24
24
|
var TIMED_OUT = Symbol("bootstrap-shell-timeout");
|
|
@@ -170,9 +170,10 @@ function createExecBootstrapShell(handle, opts = {}) {
|
|
|
170
170
|
cmdOut.push(line);
|
|
171
171
|
} else if (phase === "await-cwd") {
|
|
172
172
|
if (line === `${sentinel}_CWD`) phase = "cwd";
|
|
173
|
-
} else if (phase === "cwd")
|
|
174
|
-
|
|
175
|
-
|
|
173
|
+
} else if (phase === "cwd") {
|
|
174
|
+
if (line === `${sentinel}_ENV`) phase = "env";
|
|
175
|
+
else cwdLines.push(line);
|
|
176
|
+
} else envLines.push(line);
|
|
176
177
|
const newCwd = cwdLines.map((l) => l.trim()).filter(Boolean).pop();
|
|
177
178
|
if (newCwd) cwd = newCwd;
|
|
178
179
|
const newEnv = parseExports(envLines.join("\n"));
|
package/dist/esm/shell.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell.js","names":[],"sources":["../../src/shell.ts"],"sourcesContent":["/**\n * Internal persistent bootstrap shell.\n *\n * Spawns a single `sh` process via {@link SandboxHandle.process.spawn} and\n * drives it over stdin/stdout with a sentinel-echo protocol. Commands run\n * sequentially inside the same shell so `cd`, exported variables, etc. persist\n * across calls — exactly the exec model the bootstrap setup plan needs.\n *\n * Providers WITHOUT a writable host→process stdin (`capabilities.writableStdin\n * === false`, e.g. Cloudflare / Daytona / Vercel) can't be driven over stdin, so\n * {@link createBootstrapShell} transparently falls back to an exec-backed shell\n * ({@link createExecBootstrapShell}) that threads `cwd`/env across `exec` calls\n * to reproduce the same persistent-shell semantics.\n *\n * This module is internal-only and must NOT be re-exported from\n * `packages/ai-sandbox/src/index.ts`.\n */\nimport type { SandboxHandle } from './contracts'\n\n/**\n * Parse the output of `export -p` (or `declare -x`) into a plain env map.\n * Shared by the stdin shell's `forkState` and the exec-backed shell.\n */\nfunction parseExports(output: string): Record<string, string> {\n const env: Record<string, string> = {}\n for (const line of output.split('\\n')) {\n const trimmed = line.trim()\n // Match `declare -x KEY=...` or `export KEY=...` forms.\n const match =\n /^(?:declare\\s+-x\\s+|export\\s+)([A-Za-z_][A-Za-z0-9_]*)(?:=\"((?:[^\"\\\\]|\\\\.)*)\")?$/.exec(\n trimmed,\n )\n if (match === null) continue\n const key = match[1]\n if (key === undefined) continue\n // Value may be absent for exported-but-unset vars; skip those.\n const raw = match[2]\n if (raw === undefined) continue\n // Unescape backslash-escaped chars inside double quotes.\n env[key] = raw.replace(/\\\\(.)/g, '$1')\n }\n return env\n}\n\n/** The surface the bootstrap engine uses. */\nexport interface BootstrapShell {\n /** Run a shell command and capture its stdout + exit code. */\n run: (command: string) => Promise<{ exitCode: number; stdout: string }>\n /**\n * Snapshot the shell's current working directory and exported environment.\n * Used to fork parallel exec calls that inherit the serial shell's state.\n */\n forkState: () => Promise<{ cwd: string; env: Record<string, string> }>\n /** End the shell session (closes stdin, kills the process). */\n dispose: () => Promise<void>\n}\n\n/** Options for {@link createBootstrapShell}. */\nexport interface BootstrapShellOptions {\n /** Working directory to start the shell in (passed as ProcessOptions.cwd). */\n cwd?: string\n /**\n * Belt-and-braces deadline for a single `run()` to see its sentinel. The\n * primary termination condition is the stdout stream ending (see\n * {@link createBootstrapShell}); this only catches a shell that is alive,\n * silent, and never going to answer. Generous by default because setup steps\n * legitimately run for a long time (`npm install`, image pulls).\n */\n commandTimeoutMs?: number\n}\n\n/** Default {@link BootstrapShellOptions.commandTimeoutMs} — 30 minutes. */\nconst DEFAULT_COMMAND_TIMEOUT_MS = 30 * 60 * 1000\n\n/** Race marker for the per-command deadline. A symbol cannot collide with a\n * literal stdout line (a line of text `'timeout'` would). */\nconst TIMED_OUT = Symbol('bootstrap-shell-timeout')\n\n/**\n * Spawn one `sh` process and return a {@link BootstrapShell} that drives it\n * via the sentinel-echo protocol.\n *\n * Protocol: for each `run(cmd)` call, we write\n * `<cmd>; printf \"\\n__BSSH_<N>__ $?\\n\"` to stdin, then read stdout lines\n * until we see a line matching `__BSSH_<N>__ <exitCode>`. Everything before\n * that line is the command's stdout; the trailing integer is the exit code.\n * The counter `N` is a module-level monotonic integer — no Date.now / random.\n */\nexport async function createBootstrapShell(\n handle: SandboxHandle,\n opts: BootstrapShellOptions = {},\n): Promise<BootstrapShell> {\n // Providers without a writable host→process stdin can't run the sentinel-echo\n // protocol below (it feeds commands over stdin), so use the exec-backed shell.\n if (!handle.capabilities.writableStdin) {\n return createExecBootstrapShell(handle, opts)\n }\n const proc = await handle.process.spawn('sh', { cwd: opts.cwd })\n\n /*\n * We need to read stdout lines across multiple run() calls while keeping\n * the iterator open. Buffer chunks into lines manually.\n */\n const lineBuffer: Array<string> = []\n // `null` means \"the stdout stream ended\" — distinct from an empty line, which\n // `sh` emits constantly. Collapsing the two is what let a dead shell feed an\n // infinite supply of `''` into a sentinel-hunting loop.\n let pending: Array<(line: string | null) => void> = []\n let streamDone = false\n let streamError: unknown\n\n /** Feed the stdout async-iterable into the shared line queue. */\n async function drainStdout(): Promise<void> {\n let partial = ''\n try {\n for await (const chunk of proc.stdout) {\n partial += chunk\n const parts = partial.split('\\n')\n // All but the last element are complete lines.\n for (let i = 0; i < parts.length - 1; i++) {\n const line = parts[i] as string\n const resolver = pending.shift()\n if (resolver !== undefined) {\n resolver(line)\n } else {\n lineBuffer.push(line)\n }\n }\n partial = parts[parts.length - 1] as string\n }\n // Flush any trailing partial line.\n if (partial.length > 0) {\n const line = partial\n const resolver = pending.shift()\n if (resolver !== undefined) {\n resolver(line)\n } else {\n lineBuffer.push(line)\n }\n }\n } catch (error) {\n // A throw while iterating stdout (transport reset, provider stream error)\n // must NOT leave waiters parked on a promise nobody resolves. Record it so\n // `run()` can name the cause, and fall through to the `finally` that\n // unblocks everyone.\n streamError = error\n } finally {\n streamDone = true\n // Unblock any remaining waiters with the end-of-stream marker.\n for (const resolver of pending) {\n resolver(null)\n }\n pending = []\n }\n }\n\n /*\n * Start draining immediately; do NOT await — runs concurrently. The `try/catch`\n * inside `drainStdout` means this promise never rejects, so there is no\n * unhandled rejection while nothing is awaiting it, and `dispose()` can await\n * it unconditionally.\n */\n const drainPromise = drainStdout()\n\n /** Read the next line from the shared queue, or `null` once stdout ended. */\n function nextLine(): Promise<string | null> {\n const buffered = lineBuffer.shift()\n if (buffered !== undefined) {\n return Promise.resolve(buffered)\n }\n if (streamDone) {\n return Promise.resolve(null)\n }\n return new Promise<string | null>((resolve) => {\n pending.push(resolve)\n })\n }\n\n let counter = 0\n\n async function run(\n command: string,\n ): Promise<{ exitCode: number; stdout: string }> {\n const id = counter\n counter += 1\n const sentinel = `__BSSH_${id}__`\n\n // Write the command followed by a sentinel printf to stdin. Merge the\n // command's stderr into stdout (`{ … ; } 2>&1`) so a failing setup step's\n // error text is captured and can be surfaced — otherwise only the exit code\n // is visible. `$?` after the group is still the command's own exit code.\n await proc.stdin.write(\n `{ ${command} ; } 2>&1; printf \"\\\\n${sentinel} $?\\\\n\"\\n`,\n )\n\n const outputLines: Array<string> = []\n\n /*\n * Read lines until we find the sentinel — but the wait MUST be able to end\n * without one. `sh` can exit before it ever prints the sentinel (a missing\n * binary, an OOM kill, the provider reaping the sandbox mid-bootstrap), and\n * a loop whose only exit is the sentinel then spins on end-of-stream\n * forever, pushing into `outputLines` until the host process dies of memory\n * exhaustion. Two independent terminators:\n * 1. `nextLine()` yields `null` the moment stdout is done — the real fix,\n * it fires as soon as the shell is gone.\n * 2. A deadline, for a shell that stays alive and simply never answers.\n */\n let timer: ReturnType<typeof setTimeout> | undefined\n const deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(\n () => resolve(TIMED_OUT),\n opts.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS,\n )\n })\n\n try {\n for (;;) {\n const line = await Promise.race([nextLine(), deadline])\n if (line === TIMED_OUT) {\n throw new Error(\n `bootstrap shell: timed out after ${\n opts.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS\n }ms waiting for the sentinel of command: ${command}`,\n )\n }\n if (line === null) {\n throw new Error(\n `bootstrap shell: the shell exited before the sentinel was printed; command: ${command}`,\n streamError === undefined ? undefined : { cause: streamError },\n )\n }\n if (line.startsWith(`${sentinel} `)) {\n const codeStr = line.slice(sentinel.length + 1).trim()\n const exitCode = parseInt(codeStr, 10)\n return {\n exitCode: Number.isFinite(exitCode) ? exitCode : 1,\n stdout: outputLines.join('\\n'),\n }\n }\n outputLines.push(line)\n }\n } finally {\n clearTimeout(timer)\n }\n }\n\n async function forkState(): Promise<{\n cwd: string\n env: Record<string, string>\n }> {\n const pwdResult = await run('pwd')\n const cwd = pwdResult.stdout.trim()\n\n const exportResult = await run('export -p')\n return { cwd, env: parseExports(exportResult.stdout) }\n }\n\n async function dispose(): Promise<void> {\n await proc.stdin.end()\n await proc.kill()\n // Drain the stdout iterator to completion so there are no dangling promises.\n await drainPromise\n }\n\n return { run, forkState, dispose }\n}\n\n/**\n * Exec-backed {@link BootstrapShell} for providers WITHOUT a writable stdin.\n *\n * There is no persistent process to feed commands into, so persistence of `cd`\n * and exported variables is reproduced by threading state across discrete\n * {@link SandboxHandle.process.exec} calls: each `run()` executes the command in\n * the tracked cwd+env, then captures the resulting `pwd` and `export -p` (via\n * marker lines) so the NEXT command inherits any directory change or exports.\n */\nexport function createExecBootstrapShell(\n handle: SandboxHandle,\n opts: BootstrapShellOptions = {},\n): BootstrapShell {\n let cwd = opts.cwd ?? '/'\n let env: Record<string, string> = {}\n let counter = 0\n\n async function run(\n command: string,\n ): Promise<{ exitCode: number; stdout: string }> {\n const id = counter\n counter += 1\n const sentinel = `__BSSH_${id}__`\n\n // Run the command, then emit its exit code, cwd and exported env behind\n // marker lines so we can recover state even when the command itself fails\n // (no `set -e`). Capturing `$?` immediately after the command keeps the\n // reported exit code the command's own, not the trailing introspection's.\n const script = [\n command,\n `__bssh_rc=$?`,\n `printf '\\\\n%s %s\\\\n' '${sentinel}' \"$__bssh_rc\"`,\n `printf '%s\\\\n' '${sentinel}_CWD'`,\n `pwd`,\n `printf '%s\\\\n' '${sentinel}_ENV'`,\n `export -p`,\n ].join('\\n')\n\n const res = await handle.process.exec(script, { cwd, env })\n\n const cmdOut: Array<string> = []\n const cwdLines: Array<string> = []\n const envLines: Array<string> = []\n let exitCode = res.exitCode\n let phase: 'cmd' | 'await-cwd' | 'cwd' | 'env' = 'cmd'\n\n for (const line of res.stdout.split('\\n')) {\n if (phase === 'cmd') {\n if (line.startsWith(`${sentinel} `)) {\n const parsed = parseInt(line.slice(sentinel.length + 1).trim(), 10)\n exitCode = Number.isFinite(parsed) ? parsed : res.exitCode\n phase = 'await-cwd'\n continue\n }\n cmdOut.push(line)\n } else if (phase === 'await-cwd') {\n if (line === `${sentinel}_CWD`) phase = 'cwd'\n } else if (phase === 'cwd') {\n if (line === `${sentinel}_ENV`) phase = 'env'\n else cwdLines.push(line)\n } else {\n envLines.push(line)\n }\n }\n\n // `pwd` prints a single line; the last non-empty one is the new cwd.\n const newCwd = cwdLines\n .map((l) => l.trim())\n .filter(Boolean)\n .pop()\n if (newCwd) cwd = newCwd\n const newEnv = parseExports(envLines.join('\\n'))\n if (Object.keys(newEnv).length > 0) env = newEnv\n\n return { exitCode, stdout: cmdOut.join('\\n') }\n }\n\n function forkState(): Promise<{ cwd: string; env: Record<string, string> }> {\n return Promise.resolve({ cwd, env: { ...env } })\n }\n\n function dispose(): Promise<void> {\n // Nothing to tear down — there is no persistent process.\n return Promise.resolve()\n }\n\n return { run, forkState, dispose }\n}\n"],"mappings":";;;;;AAuBA,SAAS,aAAa,QAAwC;CAC5D,MAAM,MAA8B,CAAC;CACrC,KAAK,MAAM,QAAQ,OAAO,MAAM,IAAI,GAAG;EACrC,MAAM,UAAU,KAAK,KAAK;EAE1B,MAAM,QACJ,mFAAmF,KACjF,OACF;EACF,IAAI,UAAU,MAAM;EACpB,MAAM,MAAM,MAAM;EAClB,IAAI,QAAQ,KAAA,GAAW;EAEvB,MAAM,MAAM,MAAM;EAClB,IAAI,QAAQ,KAAA,GAAW;E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AAO,KAAK,MAAM,CAAC,CAAC,SAAS,GAAG,MAAM;EAE1C,OAAO;GAAE;GAAU,QAAQ,OAAO,KAAK,IAAI;EAAE;CAC/C;CAEA,SAAS,YAAmE;EAC1E,OAAO,QAAQ,QAAQ;GAAE;GAAK,KAAK,EAAE,GAAG,IAAI;EAAE,CAAC;CACjD;CAEA,SAAS,UAAyB;EAEhC,OAAO,QAAQ,QAAQ;CACzB;CAEA,OAAO;EAAE;EAAK;EAAW;CAAQ;AACnC"}
|
|
1
|
+
{"version":3,"file":"shell.js","names":[],"sources":["../../src/shell.ts"],"sourcesContent":["/**\n * Internal persistent bootstrap shell.\n *\n * Spawns a single `sh` process via {@link SandboxHandle.process.spawn} and\n * drives it over stdin/stdout with a sentinel-echo protocol. Commands run\n * sequentially inside the same shell so `cd`, exported variables, etc. persist\n * across calls — exactly the exec model the bootstrap setup plan needs.\n *\n * Providers WITHOUT a writable host→process stdin (`capabilities.writableStdin\n * === false`, e.g. Cloudflare / Daytona / Vercel) can't be driven over stdin, so\n * {@link createBootstrapShell} transparently falls back to an exec-backed shell\n * ({@link createExecBootstrapShell}) that threads `cwd`/env across `exec` calls\n * to reproduce the same persistent-shell semantics.\n *\n * This module is internal-only and must NOT be re-exported from\n * `packages/ai-sandbox/src/index.ts`.\n */\nimport type { SandboxHandle } from './contracts'\n\n/**\n * Parse the output of `export -p` (or `declare -x`) into a plain env map.\n * Shared by the stdin shell's `forkState` and the exec-backed shell.\n */\nfunction parseExports(output: string): Record<string, string> {\n const env: Record<string, string> = {}\n for (const line of output.split('\\n')) {\n const trimmed = line.trim()\n // Match `declare -x KEY=...` or `export KEY=...` forms.\n const match =\n /^(?:declare\\s+-x\\s+|export\\s+)([A-Za-z_][A-Za-z0-9_]*)(?:=\"((?:[^\"\\\\]|\\\\.)*)\")?$/.exec(\n trimmed,\n )\n if (match === null) continue\n const key = match[1]\n if (key === undefined) continue\n // Value may be absent for exported-but-unset vars; skip those.\n const raw = match[2]\n if (raw === undefined) continue\n // Unescape backslash-escaped chars inside double quotes.\n env[key] = raw.replace(/\\\\(.)/g, '$1')\n }\n return env\n}\n\n/** The surface the bootstrap engine uses. */\nexport interface BootstrapShell {\n /** Run a shell command and capture its stdout + exit code. */\n run: (command: string) => Promise<{ exitCode: number; stdout: string }>\n /**\n * Snapshot the shell's current working directory and exported environment.\n * Used to fork parallel exec calls that inherit the serial shell's state.\n */\n forkState: () => Promise<{ cwd: string; env: Record<string, string> }>\n /** End the shell session (closes stdin, kills the process). */\n dispose: () => Promise<void>\n}\n\n/** Options for {@link createBootstrapShell}. */\nexport interface BootstrapShellOptions {\n /** Working directory to start the shell in (passed as ProcessOptions.cwd). */\n cwd?: string\n /**\n * Belt-and-braces deadline for a single `run()` to see its sentinel. The\n * primary termination condition is the stdout stream ending (see\n * {@link createBootstrapShell}); this only catches a shell that is alive,\n * silent, and never going to answer. Generous by default because setup steps\n * legitimately run for a long time (`npm install`, image pulls).\n */\n commandTimeoutMs?: number\n}\n\n/** Default {@link BootstrapShellOptions.commandTimeoutMs} — 30 minutes. */\nconst DEFAULT_COMMAND_TIMEOUT_MS = 30 * 60 * 1000\n\n/** Race marker for the per-command deadline. A symbol cannot collide with a\n * literal stdout line (a line of text `'timeout'` would). */\nconst TIMED_OUT = Symbol('bootstrap-shell-timeout')\n\n/**\n * Spawn one `sh` process and return a {@link BootstrapShell} that drives it\n * via the sentinel-echo protocol.\n *\n * Protocol: for each `run(cmd)` call, we write\n * `<cmd>; printf \"\\n__BSSH_<N>__ $?\\n\"` to stdin, then read stdout lines\n * until we see a line matching `__BSSH_<N>__ <exitCode>`. Everything before\n * that line is the command's stdout; the trailing integer is the exit code.\n * The counter `N` is a module-level monotonic integer — no Date.now / random.\n */\nexport async function createBootstrapShell(\n handle: SandboxHandle,\n opts: BootstrapShellOptions = {},\n): Promise<BootstrapShell> {\n // Providers without a writable host→process stdin can't run the sentinel-echo\n // protocol below (it feeds commands over stdin), so use the exec-backed shell.\n if (!handle.capabilities.writableStdin) {\n return createExecBootstrapShell(handle, opts)\n }\n const proc = await handle.process.spawn('sh', { cwd: opts.cwd })\n\n /*\n * We need to read stdout lines across multiple run() calls while keeping\n * the iterator open. Buffer chunks into lines manually.\n */\n const lineBuffer: Array<string> = []\n // `null` means \"the stdout stream ended\" — distinct from an empty line, which\n // `sh` emits constantly. Collapsing the two is what let a dead shell feed an\n // infinite supply of `''` into a sentinel-hunting loop.\n let pending: Array<(line: string | null) => void> = []\n let streamDone = false\n let streamError: unknown\n\n /** Feed the stdout async-iterable into the shared line queue. */\n async function drainStdout(): Promise<void> {\n let partial = ''\n try {\n for await (const chunk of proc.stdout) {\n partial += chunk\n const parts = partial.split('\\n')\n // All but the last element are complete lines.\n for (let i = 0; i < parts.length - 1; i++) {\n const line = parts[i] as string\n const resolver = pending.shift()\n if (resolver !== undefined) {\n resolver(line)\n } else {\n lineBuffer.push(line)\n }\n }\n partial = parts[parts.length - 1] as string\n }\n // Flush any trailing partial line.\n if (partial.length > 0) {\n const line = partial\n const resolver = pending.shift()\n if (resolver !== undefined) {\n resolver(line)\n } else {\n lineBuffer.push(line)\n }\n }\n } catch (error) {\n // A throw while iterating stdout (transport reset, provider stream error)\n // must NOT leave waiters parked on a promise nobody resolves. Record it so\n // `run()` can name the cause, and fall through to the `finally` that\n // unblocks everyone.\n streamError = error\n } finally {\n streamDone = true\n // Unblock any remaining waiters with the end-of-stream marker.\n for (const resolver of pending) {\n resolver(null)\n }\n pending = []\n }\n }\n\n /*\n * Start draining immediately; do NOT await — runs concurrently. The `try/catch`\n * inside `drainStdout` means this promise never rejects, so there is no\n * unhandled rejection while nothing is awaiting it, and `dispose()` can await\n * it unconditionally.\n */\n const drainPromise = drainStdout()\n\n /** Read the next line from the shared queue, or `null` once stdout ended. */\n function nextLine(): Promise<string | null> {\n const buffered = lineBuffer.shift()\n if (buffered !== undefined) {\n return Promise.resolve(buffered)\n }\n if (streamDone) {\n return Promise.resolve(null)\n }\n return new Promise<string | null>((resolve) => {\n pending.push(resolve)\n })\n }\n\n let counter = 0\n\n async function run(\n command: string,\n ): Promise<{ exitCode: number; stdout: string }> {\n const id = counter\n counter += 1\n const sentinel = `__BSSH_${id}__`\n\n // Write the command followed by a sentinel printf to stdin. Merge the\n // command's stderr into stdout (`{ … ; } 2>&1`) so a failing setup step's\n // error text is captured and can be surfaced — otherwise only the exit code\n // is visible. `$?` after the group is still the command's own exit code.\n await proc.stdin.write(\n `{ ${command} ; } 2>&1; printf \"\\\\n${sentinel} $?\\\\n\"\\n`,\n )\n\n const outputLines: Array<string> = []\n\n /*\n * Read lines until we find the sentinel — but the wait MUST be able to end\n * without one. `sh` can exit before it ever prints the sentinel (a missing\n * binary, an OOM kill, the provider reaping the sandbox mid-bootstrap), and\n * a loop whose only exit is the sentinel then spins on end-of-stream\n * forever, pushing into `outputLines` until the host process dies of memory\n * exhaustion. Two independent terminators:\n * 1. `nextLine()` yields `null` the moment stdout is done — the real fix,\n * it fires as soon as the shell is gone.\n * 2. A deadline, for a shell that stays alive and simply never answers.\n */\n let timer: ReturnType<typeof setTimeout> | undefined\n const deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(\n () => resolve(TIMED_OUT),\n opts.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS,\n )\n })\n\n try {\n for (;;) {\n const line = await Promise.race([nextLine(), deadline])\n if (line === TIMED_OUT) {\n throw new Error(\n `bootstrap shell: timed out after ${\n opts.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS\n }ms waiting for the sentinel of command: ${command}`,\n )\n }\n if (line === null) {\n throw new Error(\n `bootstrap shell: the shell exited before the sentinel was printed; command: ${command}`,\n streamError === undefined ? undefined : { cause: streamError },\n )\n }\n if (line.startsWith(`${sentinel} `)) {\n const codeStr = line.slice(sentinel.length + 1).trim()\n const exitCode = parseInt(codeStr, 10)\n return {\n exitCode: Number.isFinite(exitCode) ? exitCode : 1,\n stdout: outputLines.join('\\n'),\n }\n }\n outputLines.push(line)\n }\n } finally {\n clearTimeout(timer)\n }\n }\n\n async function forkState(): Promise<{\n cwd: string\n env: Record<string, string>\n }> {\n const pwdResult = await run('pwd')\n const cwd = pwdResult.stdout.trim()\n\n const exportResult = await run('export -p')\n return { cwd, env: parseExports(exportResult.stdout) }\n }\n\n async function dispose(): Promise<void> {\n await proc.stdin.end()\n await proc.kill()\n // Drain the stdout iterator to completion so there are no dangling promises.\n await drainPromise\n }\n\n return { run, forkState, dispose }\n}\n\n/**\n * Exec-backed {@link BootstrapShell} for providers WITHOUT a writable stdin.\n *\n * There is no persistent process to feed commands into, so persistence of `cd`\n * and exported variables is reproduced by threading state across discrete\n * {@link SandboxHandle.process.exec} calls: each `run()` executes the command in\n * the tracked cwd+env, then captures the resulting `pwd` and `export -p` (via\n * marker lines) so the NEXT command inherits any directory change or exports.\n */\nexport function createExecBootstrapShell(\n handle: SandboxHandle,\n opts: BootstrapShellOptions = {},\n): BootstrapShell {\n let cwd = opts.cwd ?? '/'\n let env: Record<string, string> = {}\n let counter = 0\n\n async function run(\n command: string,\n ): Promise<{ exitCode: number; stdout: string }> {\n const id = counter\n counter += 1\n const sentinel = `__BSSH_${id}__`\n\n // Run the command, then emit its exit code, cwd and exported env behind\n // marker lines so we can recover state even when the command itself fails\n // (no `set -e`). Capturing `$?` immediately after the command keeps the\n // reported exit code the command's own, not the trailing introspection's.\n const script = [\n command,\n `__bssh_rc=$?`,\n `printf '\\\\n%s %s\\\\n' '${sentinel}' \"$__bssh_rc\"`,\n `printf '%s\\\\n' '${sentinel}_CWD'`,\n `pwd`,\n `printf '%s\\\\n' '${sentinel}_ENV'`,\n `export -p`,\n ].join('\\n')\n\n const res = await handle.process.exec(script, { cwd, env })\n\n const cmdOut: Array<string> = []\n const cwdLines: Array<string> = []\n const envLines: Array<string> = []\n let exitCode = res.exitCode\n let phase: 'cmd' | 'await-cwd' | 'cwd' | 'env' = 'cmd'\n\n for (const line of res.stdout.split('\\n')) {\n if (phase === 'cmd') {\n if (line.startsWith(`${sentinel} `)) {\n const parsed = parseInt(line.slice(sentinel.length + 1).trim(), 10)\n exitCode = Number.isFinite(parsed) ? parsed : res.exitCode\n phase = 'await-cwd'\n continue\n }\n cmdOut.push(line)\n } else if (phase === 'await-cwd') {\n if (line === `${sentinel}_CWD`) phase = 'cwd'\n } else if (phase === 'cwd') {\n if (line === `${sentinel}_ENV`) phase = 'env'\n else cwdLines.push(line)\n } else {\n envLines.push(line)\n }\n }\n\n // `pwd` prints a single line; the last non-empty one is the new cwd.\n const newCwd = cwdLines\n .map((l) => l.trim())\n .filter(Boolean)\n .pop()\n if (newCwd) cwd = newCwd\n const newEnv = parseExports(envLines.join('\\n'))\n if (Object.keys(newEnv).length > 0) env = newEnv\n\n return { exitCode, stdout: cmdOut.join('\\n') }\n }\n\n function forkState(): Promise<{ cwd: string; env: Record<string, string> }> {\n return Promise.resolve({ cwd, env: { ...env } })\n }\n\n function dispose(): Promise<void> {\n // Nothing to tear down — there is no persistent process.\n return Promise.resolve()\n }\n\n return { run, forkState, dispose }\n}\n"],"mappings":";;;;;AAuBA,SAAS,aAAa,QAAwC;CAC5D,MAAM,MAA8B,CAAC;CACrC,KAAK,MAAM,QAAQ,OAAO,MAAM,IAAI,GAAG;EACrC,MAAM,UAAU,KAAK,KAAK;EAE1B,MAAM,QACJ,mFAAmF,KACjF,OACF;EACF,IAAI,UAAU,MAAM;EACpB,MAAM,MAAM,MAAM;EAClB,IAAI,QAAQ,KAAA,GAAW;EAEvB,MAAM,MAAM,MAAM;EAClB,IAAI,QAAQ,KAAA,GAAW;EAEvB,IAAI,OAAO,IAAI,QAAQ,UAAU,IAAI;CACvC;CACA,OAAO;AACT;;AA8BA,IAAM,6BAA6B;;;AAInC,IAAM,YAAY,OAAO,yBAAyB;;;;;;;;;;;AAYlD,eAAsB,qBACpB,QACA,OAA8B,CAAC,GACN;CAGzB,IAAI,CAAC,OAAO,aAAa,eACvB,OAAO,yBAAyB,QAAQ,IAAI;CAE9C,MAAM,OAAO,MAAM,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ACzB;CAEA,OAAO;EAAE;EAAK;EAAW;CAAQ;AACnC"}
|
|
@@ -34,7 +34,8 @@ function makeRecord(overrides) {
|
|
|
34
34
|
function runSandboxInstanceStoreConformance(name, makeStore) {
|
|
35
35
|
describe(`SandboxInstanceStore conformance: ${name}`, () => {
|
|
36
36
|
it("returns null for a missing key", async () => {
|
|
37
|
-
|
|
37
|
+
const store = await makeStore();
|
|
38
|
+
expect(await store.get("absent")).toBeNull();
|
|
38
39
|
});
|
|
39
40
|
it("round-trips an upserted record with all fields", async () => {
|
|
40
41
|
const store = await makeStore();
|
|
@@ -87,7 +88,8 @@ function runSandboxInstanceStoreConformance(name, makeStore) {
|
|
|
87
88
|
expect(await store.get("thread-1")).toBeNull();
|
|
88
89
|
});
|
|
89
90
|
it("delete of a missing key is a no-op", async () => {
|
|
90
|
-
|
|
91
|
+
const store = await makeStore();
|
|
92
|
+
await expect(store.delete("absent")).resolves.toBeUndefined();
|
|
91
93
|
});
|
|
92
94
|
});
|
|
93
95
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conformance.js","names":[],"sources":["../../../src/testkit/conformance.ts"],"sourcesContent":["/**\n * Conformance suite for a {@link SandboxInstanceStore} implementation.\n *\n * Run this against a fresh BYO store (or the in-memory reference) to prove it\n * satisfies the get / upsert / delete contract `@tanstack/ai-sandbox`'s ensure\n * algorithm relies on — including insert-vs-overwrite and optional-field\n * handling (full replace must clear omitted optionals).\n *\n * Vitest is an OPTIONAL peer dependency: this module is imported only from test\n * files, which already run under Vitest.\n */\nimport { describe, expect, it } from 'vitest'\nimport type {\n SandboxInstanceRecord,\n SandboxInstanceStore,\n} from '../instance-store'\n\n// The `./testkit` package.json subpath resolves to THIS module's build output\n// only (`dist/esm/testkit/conformance.js`), not a barrel over `src/testkit/`.\n// Re-export the journal, takeover, and reaper conformance suites here so they\n// are reachable from `@tanstack/ai-sandbox/testkit` without changing that\n// mapping.\nexport { runJournalConformance } from './journal-conformance'\nexport type { JournalConformanceConfig } from './journal-conformance'\nexport { runTakeoverConformance } from './takeover-conformance'\nexport type { TakeoverConformanceConfig } from './takeover-conformance'\nexport { runReaperConformance } from './reaper-conformance'\nexport type { ReaperConformanceConfig } from './reaper-conformance'\nexport { runDurableRunFieldsConformance } from './durable-run-fields-conformance'\nexport type { MakeRunStore } from './durable-run-fields-conformance'\nexport { makeFakeShellSpawn } from './shell-spawn'\n\nfunction makeRecord(\n overrides?: Partial<SandboxInstanceRecord>,\n): SandboxInstanceRecord {\n return {\n key: 'thread-1',\n provider: 'fake',\n providerSandboxId: 'sb-1',\n threadId: 'thread-1',\n updatedAt: 1,\n ...overrides,\n }\n}\n\n/**\n * Assert `makeStore()` produces a spec-compliant {@link SandboxInstanceStore}. Each\n * `it` gets a fresh store, so implementations may share process state across\n * calls without cross-test bleed only if `makeStore` returns an isolated store.\n */\nexport function runSandboxInstanceStoreConformance(\n name: string,\n makeStore: () => SandboxInstanceStore | Promise<SandboxInstanceStore>,\n): void {\n describe(`SandboxInstanceStore conformance: ${name}`, () => {\n it('returns null for a missing key', async () => {\n const store = await makeStore()\n expect(await store.get('absent')).toBeNull()\n })\n\n it('round-trips an upserted record with all fields', async () => {\n const store = await makeStore()\n const record = makeRecord({\n latestSnapshotId: 'snap-1',\n latestRunId: 'run-1',\n })\n await store.upsert(record)\n expect(await store.get(record.key)).toEqual(record)\n })\n\n it('omits absent optional fields on read', async () => {\n const store = await makeStore()\n const record = makeRecord()\n await store.upsert(record)\n const loaded = await store.get(record.key)\n expect(loaded).toEqual(record)\n expect(loaded && 'latestSnapshotId' in loaded).toBe(false)\n expect(loaded && 'latestRunId' in loaded).toBe(false)\n })\n\n it('overwrites an existing record on re-upsert', async () => {\n const store = await makeStore()\n await store.upsert(makeRecord({ latestSnapshotId: 'snap-1' }))\n await store.upsert(\n makeRecord({ providerSandboxId: 'sb-2', updatedAt: 2 }),\n )\n const loaded = await store.get('thread-1')\n expect(loaded?.providerSandboxId).toBe('sb-2')\n expect(loaded?.updatedAt).toBe(2)\n // The overwrite dropped latestSnapshotId — a durable store must clear it,\n // not retain the prior value.\n expect(loaded && 'latestSnapshotId' in loaded).toBe(false)\n })\n\n it('isolates records by key', async () => {\n const store = await makeStore()\n await store.upsert(makeRecord({ key: 'a', threadId: 'a' }))\n await store.upsert(\n makeRecord({ key: 'b', threadId: 'b', providerSandboxId: 'sb-b' }),\n )\n expect((await store.get('a'))?.providerSandboxId).toBe('sb-1')\n expect((await store.get('b'))?.providerSandboxId).toBe('sb-b')\n })\n\n it('deletes a record', async () => {\n const store = await makeStore()\n await store.upsert(makeRecord())\n await store.delete('thread-1')\n expect(await store.get('thread-1')).toBeNull()\n })\n\n it('delete of a missing key is a no-op', async () => {\n const store = await makeStore()\n await expect(store.delete('absent')).resolves.toBeUndefined()\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,SAAS,WACP,WACuB;CACvB,OAAO;EACL,KAAK;EACL,UAAU;EACV,mBAAmB;EACnB,UAAU;EACV,WAAW;EACX,GAAG;CACL;AACF;;;;;;AAOA,SAAgB,mCACd,MACA,WACM;CACN,SAAS,qCAAqC,cAAc;EAC1D,GAAG,kCAAkC,YAAY;
|
|
1
|
+
{"version":3,"file":"conformance.js","names":[],"sources":["../../../src/testkit/conformance.ts"],"sourcesContent":["/**\n * Conformance suite for a {@link SandboxInstanceStore} implementation.\n *\n * Run this against a fresh BYO store (or the in-memory reference) to prove it\n * satisfies the get / upsert / delete contract `@tanstack/ai-sandbox`'s ensure\n * algorithm relies on — including insert-vs-overwrite and optional-field\n * handling (full replace must clear omitted optionals).\n *\n * Vitest is an OPTIONAL peer dependency: this module is imported only from test\n * files, which already run under Vitest.\n */\nimport { describe, expect, it } from 'vitest'\nimport type {\n SandboxInstanceRecord,\n SandboxInstanceStore,\n} from '../instance-store'\n\n// The `./testkit` package.json subpath resolves to THIS module's build output\n// only (`dist/esm/testkit/conformance.js`), not a barrel over `src/testkit/`.\n// Re-export the journal, takeover, and reaper conformance suites here so they\n// are reachable from `@tanstack/ai-sandbox/testkit` without changing that\n// mapping.\nexport { runJournalConformance } from './journal-conformance'\nexport type { JournalConformanceConfig } from './journal-conformance'\nexport { runTakeoverConformance } from './takeover-conformance'\nexport type { TakeoverConformanceConfig } from './takeover-conformance'\nexport { runReaperConformance } from './reaper-conformance'\nexport type { ReaperConformanceConfig } from './reaper-conformance'\nexport { runDurableRunFieldsConformance } from './durable-run-fields-conformance'\nexport type { MakeRunStore } from './durable-run-fields-conformance'\nexport { makeFakeShellSpawn } from './shell-spawn'\n\nfunction makeRecord(\n overrides?: Partial<SandboxInstanceRecord>,\n): SandboxInstanceRecord {\n return {\n key: 'thread-1',\n provider: 'fake',\n providerSandboxId: 'sb-1',\n threadId: 'thread-1',\n updatedAt: 1,\n ...overrides,\n }\n}\n\n/**\n * Assert `makeStore()` produces a spec-compliant {@link SandboxInstanceStore}. Each\n * `it` gets a fresh store, so implementations may share process state across\n * calls without cross-test bleed only if `makeStore` returns an isolated store.\n */\nexport function runSandboxInstanceStoreConformance(\n name: string,\n makeStore: () => SandboxInstanceStore | Promise<SandboxInstanceStore>,\n): void {\n describe(`SandboxInstanceStore conformance: ${name}`, () => {\n it('returns null for a missing key', async () => {\n const store = await makeStore()\n expect(await store.get('absent')).toBeNull()\n })\n\n it('round-trips an upserted record with all fields', async () => {\n const store = await makeStore()\n const record = makeRecord({\n latestSnapshotId: 'snap-1',\n latestRunId: 'run-1',\n })\n await store.upsert(record)\n expect(await store.get(record.key)).toEqual(record)\n })\n\n it('omits absent optional fields on read', async () => {\n const store = await makeStore()\n const record = makeRecord()\n await store.upsert(record)\n const loaded = await store.get(record.key)\n expect(loaded).toEqual(record)\n expect(loaded && 'latestSnapshotId' in loaded).toBe(false)\n expect(loaded && 'latestRunId' in loaded).toBe(false)\n })\n\n it('overwrites an existing record on re-upsert', async () => {\n const store = await makeStore()\n await store.upsert(makeRecord({ latestSnapshotId: 'snap-1' }))\n await store.upsert(\n makeRecord({ providerSandboxId: 'sb-2', updatedAt: 2 }),\n )\n const loaded = await store.get('thread-1')\n expect(loaded?.providerSandboxId).toBe('sb-2')\n expect(loaded?.updatedAt).toBe(2)\n // The overwrite dropped latestSnapshotId — a durable store must clear it,\n // not retain the prior value.\n expect(loaded && 'latestSnapshotId' in loaded).toBe(false)\n })\n\n it('isolates records by key', async () => {\n const store = await makeStore()\n await store.upsert(makeRecord({ key: 'a', threadId: 'a' }))\n await store.upsert(\n makeRecord({ key: 'b', threadId: 'b', providerSandboxId: 'sb-b' }),\n )\n expect((await store.get('a'))?.providerSandboxId).toBe('sb-1')\n expect((await store.get('b'))?.providerSandboxId).toBe('sb-b')\n })\n\n it('deletes a record', async () => {\n const store = await makeStore()\n await store.upsert(makeRecord())\n await store.delete('thread-1')\n expect(await store.get('thread-1')).toBeNull()\n })\n\n it('delete of a missing key is a no-op', async () => {\n const store = await makeStore()\n await expect(store.delete('absent')).resolves.toBeUndefined()\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,SAAS,WACP,WACuB;CACvB,OAAO;EACL,KAAK;EACL,UAAU;EACV,mBAAmB;EACnB,UAAU;EACV,WAAW;EACX,GAAG;CACL;AACF;;;;;;AAOA,SAAgB,mCACd,MACA,WACM;CACN,SAAS,qCAAqC,cAAc;EAC1D,GAAG,kCAAkC,YAAY;GAC/C,MAAM,QAAQ,MAAM,UAAU;GAC9B,OAAO,MAAM,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,SAAS;EAC7C,CAAC;EAED,GAAG,kDAAkD,YAAY;GAC/D,MAAM,QAAQ,MAAM,UAAU;GAC9B,MAAM,SAAS,WAAW;IACxB,kBAAkB;IAClB,aAAa;GACf,CAAC;GACD,MAAM,MAAM,OAAO,MAAM;GACzB,OAAO,MAAM,MAAM,IAAI,OAAO,GAAG,CAAC,CAAC,CAAC,QAAQ,MAAM;EACpD,CAAC;EAED,GAAG,wCAAwC,YAAY;GACrD,MAAM,QAAQ,MAAM,UAAU;GAC9B,M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,CAAC,CAAC,CAAC,SAAS;EAC/C,CAAC;EAED,GAAG,sCAAsC,YAAY;GACnD,MAAM,QAAQ,MAAM,UAAU;GAC9B,MAAM,OAAO,MAAM,OAAO,QAAQ,CAAC,CAAC,CAAC,SAAS,cAAc;EAC9D,CAAC;CACH,CAAC;AACH"}
|
|
@@ -213,8 +213,10 @@ function runJournalConformance(config) {
|
|
|
213
213
|
expectDeclaredStrategy(handle, config);
|
|
214
214
|
const paths = journalPaths(`conf-${Date.now()}`);
|
|
215
215
|
const command = journaledCommand(`printf '{"a":1}\\n{"b":2}\\n'`, paths);
|
|
216
|
-
|
|
217
|
-
expect(
|
|
216
|
+
const proc = await handle.process.spawn(command);
|
|
217
|
+
expect(await proc.wait()).toBe(0);
|
|
218
|
+
const text = decodeJournalRead((await handle.process.exec(journalReadCommand(paths, 0))).stdout);
|
|
219
|
+
expect(text).toBe(`{"a":1}\n{"b":2}\n${exitSentinelLine(paths, 0)}\n`);
|
|
218
220
|
} finally {
|
|
219
221
|
await dispose();
|
|
220
222
|
}
|
|
@@ -224,7 +226,8 @@ function runJournalConformance(config) {
|
|
|
224
226
|
try {
|
|
225
227
|
const paths = journalPaths(`conf-exit-${Date.now()}`);
|
|
226
228
|
await (await handle.process.spawn(journaledCommand("exit 7", paths))).wait();
|
|
227
|
-
|
|
229
|
+
const text = decodeJournalRead((await handle.process.exec(journalReadCommand(paths, 0))).stdout);
|
|
230
|
+
expect(text).toBe(`${exitSentinelLine(paths, 7)}\n`);
|
|
228
231
|
} finally {
|
|
229
232
|
await dispose();
|
|
230
233
|
}
|