@tangle-network/agent-runtime 0.94.13 → 0.95.0
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/agent.d.ts +2 -25
- package/dist/agent.js +9 -12
- package/dist/agent.js.map +1 -1
- package/dist/{agentic-generator-DDMM45kZ.d.ts → agentic-generator-hCaQRAes.d.ts} +0 -1
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/candidate-execution/index.d.ts +43 -16
- package/dist/candidate-execution/index.js +18 -8
- package/dist/{chunk-VYA2YEKA.js → chunk-2KGAN2HM.js} +83 -14
- package/dist/chunk-2KGAN2HM.js.map +1 -0
- package/dist/{chunk-TVJQAYQM.js → chunk-6YBA64Z2.js} +120 -716
- package/dist/chunk-6YBA64Z2.js.map +1 -0
- package/dist/{chunk-HGRW27YY.js → chunk-AP7CPGMZ.js} +139 -19
- package/dist/chunk-AP7CPGMZ.js.map +1 -0
- package/dist/{chunk-XP5KDM3R.js → chunk-BPGXIKK7.js} +3 -3
- package/dist/{chunk-D3H7F6L2.js → chunk-DHCHL6OG.js} +2 -3
- package/dist/chunk-DHCHL6OG.js.map +1 -0
- package/dist/{chunk-PCURO3DL.js → chunk-G55QE4IQ.js} +512 -36
- package/dist/chunk-G55QE4IQ.js.map +1 -0
- package/dist/{chunk-C3UKLQ54.js → chunk-IADLKE7I.js} +14 -4
- package/dist/chunk-IADLKE7I.js.map +1 -0
- package/dist/{chunk-WIPGQ4GT.js → chunk-IMSNJSXH.js} +1 -1
- package/dist/{chunk-WIPGQ4GT.js.map → chunk-IMSNJSXH.js.map} +1 -1
- package/dist/{chunk-VSWBYWFK.js → chunk-M6MD6JBS.js} +20 -27
- package/dist/chunk-M6MD6JBS.js.map +1 -0
- package/dist/chunk-MKGRLDWB.js +684 -0
- package/dist/chunk-MKGRLDWB.js.map +1 -0
- package/dist/{chunk-AEG3NGJ2.js → chunk-Q2JSAVQ3.js} +34 -2
- package/dist/chunk-Q2JSAVQ3.js.map +1 -0
- package/dist/{chunk-CNH7DF7Z.js → chunk-WTZ37EQY.js} +922 -504
- package/dist/chunk-WTZ37EQY.js.map +1 -0
- package/dist/{chunk-U33YZ7B2.js → chunk-YLUOTX6U.js} +4 -4
- package/dist/{chunk-33OG2NN3.js → chunk-Z5I642SY.js} +2 -2
- package/dist/{completion-gate-D1gX1-hg.d.ts → completion-gate-C80jiRfN.d.ts} +1 -1
- package/dist/conversation.d.ts +12 -1
- package/dist/conversation.js +2 -2
- package/dist/{coordination-Dr_axlAf.d.ts → coordination-BFE3Den7.d.ts} +10 -11
- package/dist/environment-provider.d.ts +2 -2
- package/dist/environment-provider.js +1 -1
- package/dist/{improve-BN3HyXIO.d.ts → improve-B-UYaEH5.d.ts} +3 -3
- package/dist/index.d.ts +22 -25
- package/dist/index.js +45 -50
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +177 -119
- package/dist/intelligence.js +501 -342
- package/dist/intelligence.js.map +1 -1
- package/dist/knowledge.d.ts +22 -11
- package/dist/knowledge.js +9 -4
- package/dist/lifecycle.d.ts +2 -2
- package/dist/lifecycle.js +1 -1
- package/dist/{loop-runner-bin-BRQSQdHa.d.ts → loop-runner-bin-BIQldFS8.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +5 -5
- package/dist/loop-runner-bin.js +6 -6
- package/dist/loops.d.ts +12 -12
- package/dist/loops.js +5 -5
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +6 -6
- package/dist/mcp/index.js +6 -6
- package/dist/{mcp-serve-verifier-DQQDbuyz.d.ts → mcp-serve-verifier-Bs_n0xPc.d.ts} +1 -1
- package/dist/primeintellect/index.js +1 -1
- package/dist/profile-DbfaMTdk.d.ts +233 -0
- package/dist/profiles.d.ts +1 -1
- package/dist/{supervise-DmYOug5f.d.ts → supervise-BLPI50-w.d.ts} +3 -3
- package/dist/{types-ByAYqlVb.d.ts → types-B3vAW0Oq.d.ts} +1 -1
- package/dist/{prepare-CtdtsFNG.d.ts → types-CWqfCO8s.d.ts} +67 -298
- package/dist/{types-1d5QGK3t.d.ts → types-CmnA2iL3.d.ts} +3 -3
- package/dist/{worktree-fanout-CPprU-qI.d.ts → worktree-fanout-DCA3G4bO.d.ts} +3 -3
- package/package.json +13 -10
- package/dist/chunk-AEG3NGJ2.js.map +0 -1
- package/dist/chunk-C3UKLQ54.js.map +0 -1
- package/dist/chunk-CNH7DF7Z.js.map +0 -1
- package/dist/chunk-D3H7F6L2.js.map +0 -1
- package/dist/chunk-HGRW27YY.js.map +0 -1
- package/dist/chunk-PCURO3DL.js.map +0 -1
- package/dist/chunk-TVJQAYQM.js.map +0 -1
- package/dist/chunk-VSWBYWFK.js.map +0 -1
- package/dist/chunk-VYA2YEKA.js.map +0 -1
- /package/dist/{chunk-XP5KDM3R.js.map → chunk-BPGXIKK7.js.map} +0 -0
- /package/dist/{chunk-U33YZ7B2.js.map → chunk-YLUOTX6U.js.map} +0 -0
- /package/dist/{chunk-33OG2NN3.js.map → chunk-Z5I642SY.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/durable/spawn-journal.ts"],"sourcesContent":["/**\n *\n * Event-sourced spawn journal for the recursive execution atom (build steps 3 + 7).\n *\n * The supervision tree is journaled as an append-only event log: every `spawned`,\n * `settled`, and `cancelled` is recorded AFTER it is observed-committed (never\n * speculative), mirroring `ConversationJournal`'s begin/append/load shape. The log\n * holds only the THIN decision record — ids, parentage, budget, the spend a decision\n * consumed, and a content-addressed `outRef`. The payloads the driver branched on\n * (the `out` artifacts) live in a separate `ResultBlobStore`, keyed by `outRef`, so\n * the journal stays small (decisions) and replay rehydrates the exact `Settled` from\n * the blob store (evidence). This is the decision/payload split the replay argument\n * rests on (B1/B2).\n *\n * Replay determinism (B2): `seq` is the monotonic cursor order `scope.next()` yielded\n * each settlement — NOT wall-clock. `replaySpawnTree` sorts strictly by `seq` before\n * touching the blob store, so the order in which rehydration `get`s resolve can never\n * reorder the replayed `Settled[]`; the result is identical regardless of blob latency.\n *\n * @experimental\n */\n\nimport { createHash } from 'node:crypto'\nimport type {\n NodeId,\n NodeSnapshot,\n NodeStatus,\n ResultBlobStore,\n Runtime,\n Settled,\n SpawnEvent,\n SpawnJournal,\n Spend,\n TreeView,\n} from '../runtime/supervise/types'\nimport { zeroTokenUsage } from '../runtime/util'\n\n// ── Content addressing ──────────────────────────────────────────────────────\n\n/**\n * Mint the content-addressed `outRef` for a result artifact: `sha256:<hex>` over a\n * stable JSON encoding. Producers call this to derive the `outRef` they journal and\n * `put`; the FS/in-mem stores re-derive it on `put` to verify the supplied ref\n * matches (fail loud on a mismatch — a forged ref breaks the replay invariant).\n *\n * Stable encoding: object keys are sorted recursively so two structurally-equal\n * artifacts hash identically regardless of key insertion order.\n */\nexport function contentAddress(artifact: unknown): string {\n const hex = createHash('sha256').update(stableStringify(artifact), 'utf-8').digest('hex')\n return `sha256:${hex}`\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n\n// ── Result blob store ─────────────────────────────────────────────────────────\n\n/**\n * In-memory `ResultBlobStore`. Content-addressed: `put` verifies the supplied\n * `outRef` matches the artifact's hash so a stale/forged ref fails loud rather than\n * silently rehydrating the wrong payload. Idempotent on an identical re-put.\n */\nexport class InMemoryResultBlobStore implements ResultBlobStore {\n private readonly blobs = new Map<string, unknown>()\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n this.blobs.set(outRef, artifact)\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n return this.blobs.has(outRef) ? this.blobs.get(outRef) : undefined\n }\n}\n\n/**\n * FS `ResultBlobStore`. One JSON file per artifact under `dir`, named by a\n * filesystem-safe encoding of the `outRef` (`sha256:<hex>` → `sha256-<hex>.json`).\n * `put` fsyncs so a crash between writes never loses an acknowledged blob.\n */\nexport class FileResultBlobStore implements ResultBlobStore {\n constructor(private readonly dir: string) {}\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n const fs = await import('node:fs/promises')\n await fs.mkdir(this.dir, { recursive: true })\n const fh = await fs.open(this.blobPath(outRef), 'w')\n try {\n await fh.write(JSON.stringify(artifact))\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.blobPath(outRef), 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n return JSON.parse(text)\n }\n\n private blobPath(outRef: string): string {\n return `${this.dir}/${outRef.replace(/:/g, '-')}.json`\n }\n}\n\nfunction assertContentAddress(outRef: string, artifact: unknown): void {\n const expected = contentAddress(artifact)\n if (outRef !== expected) {\n throw new Error(\n `blob outRef '${outRef}' does not match the artifact content hash '${expected}'; ` +\n 'a content-addressed store refuses a mismatched ref (breaks the replay invariant)',\n )\n }\n}\n\n// ── Spawn journal ──────────────────────────────────────────────────────────────\n\n/**\n * In-memory `SpawnJournal`. Appends are observed-committed only; the impl enforces\n * the corruption guards a durable replay rests on:\n * - an event before `beginTree` is a corrupted tree (fail loud),\n * - a duplicate `seq` within a tree is a corrupted cursor (fail loud) — two\n * settlements cannot share the cursor position replay orders by.\n */\nexport class InMemorySpawnJournal implements SpawnJournal {\n private readonly trees = new Map<NodeId, { begunAt: string; events: SpawnEvent[] }>()\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const tree = this.trees.get(root)\n if (!tree) return undefined\n return tree.events.map((ev) => ({ ...ev }))\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = this.trees.get(root)\n if (existing) {\n if (existing.begunAt !== at) {\n throw new Error(\n `spawn tree '${root}' already begun at ${existing.begunAt}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n this.trees.set(root, { begunAt: at, events: [] })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const tree = this.trees.get(root)\n if (!tree) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, tree.events, ev)\n tree.events.push({ ...ev })\n }\n}\n\n/**\n * JSONL on disk. One line per record: the first record is `begin`, subsequent records\n * are `event` envelopes wrapping a `SpawnEvent`. `loadTree` replays the whole file,\n * filtering by `root`, and applies the same begin-precedes-events + unique-seq\n * corruption guards as the in-memory impl. Each append fsyncs so a crash between\n * writes never loses an acknowledged event.\n */\nexport class FileSpawnJournal implements SpawnJournal {\n constructor(private readonly path: string) {}\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n let begun = false\n const events: SpawnEvent[] = []\n for (const line of lines) {\n const record = JSON.parse(line) as SpawnJournalRecord\n if (record.root !== root) continue\n if (record.kind === 'begin') {\n begun = true\n } else {\n if (!begun) {\n throw new Error(\n `spawn journal corrupted: event for tree '${root}' precedes its begin record`,\n )\n }\n assertSeqUnique(root, events, record.event)\n events.push(record.event)\n }\n }\n return begun ? events : undefined\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = await this.loadTreeBegin(root)\n if (existing) {\n if (existing !== at) {\n throw new Error(\n `spawn tree '${root}' already begun in ${this.path} at ${existing}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n await this.appendRecord({ kind: 'begin', root, at })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const events = await this.loadTree(root)\n if (events === undefined) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, events, ev)\n await this.appendRecord({ kind: 'event', root, event: ev })\n }\n\n private async loadTreeBegin(root: NodeId): Promise<string | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n for (const line of lines) {\n const record = JSON.parse(line) as SpawnJournalRecord\n if (record.root === root && record.kind === 'begin') return record.at\n }\n return undefined\n }\n\n private async appendRecord(record: SpawnJournalRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const fh = await fs.open(this.path, 'a')\n try {\n await fh.write(`${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n}\n\ntype SpawnJournalRecord =\n | { kind: 'begin'; root: NodeId; at: string }\n | { kind: 'event'; root: NodeId; event: SpawnEvent }\n\n/**\n * Two `seq` namespaces share the journal: a `spawned` event's `seq` is the spawn ordinal\n * (the order children were created), and a `settled`/`cancelled` event's `seq` is the\n * monotonic CURSOR order `scope.next()` yielded that settlement (B2). The uniqueness\n * replay rests on is the cursor namespace — two settlements cannot share the position\n * replay orders by — so the guard checks only settled/cancelled events. A `spawned`\n * ordinal legitimately equals a later `settled` cursor seq and is not a collision.\n */\nfunction assertSeqUnique(root: NodeId, events: SpawnEvent[], ev: SpawnEvent): void {\n // `spawned` (ordinal namespace) and `metered` (informational spend, no settlement order) live\n // outside the cursor-uniqueness namespace replay relies on.\n if (ev.kind === 'spawned' || ev.kind === 'metered') return\n if (events.some((e) => e.kind !== 'spawned' && e.kind !== 'metered' && e.seq === ev.seq)) {\n throw new Error(\n `spawn journal corrupted: duplicate cursor seq ${ev.seq} in tree '${root}'; ` +\n 'the cursor order replay relies on is not unique',\n )\n }\n}\n\n// ── Replay executor (build step 7) ───────────────────────────────────────────────\n\n/**\n * Re-feed a journaled spawn tree in strict `seq` order, rehydrating each settled\n * child's `out` from the blob store by `outRef`, and return the `Settled[]` exactly\n * as `scope.next()` originally delivered them.\n *\n * Determinism (B2): the events are sorted by `seq` BEFORE any blob `get`, so the\n * replay order is the recorded cursor order regardless of how fast each rehydration\n * resolves. `at` (wall-clock) is never a replay input. Fail loud on a tree that was\n * never begun, a settled-done event missing its `outRef`, or a blob the store can't\n * rehydrate — a silent gap would let `act` branch on the wrong evidence.\n */\nexport async function replaySpawnTree(\n journal: SpawnJournal,\n blobs: ResultBlobStore,\n root: NodeId,\n): Promise<Settled<unknown>[]> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new Error(`replaySpawnTree: no journaled tree for root '${root}'`)\n }\n const ordered = [...events].sort((a, b) => a.seq - b.seq)\n const labels = new Map<NodeId, string>()\n for (const ev of ordered) {\n if (ev.kind === 'spawned') labels.set(ev.id, ev.label)\n }\n const settled: Settled<unknown>[] = []\n for (const ev of ordered) {\n if (ev.kind === 'spawned') continue\n if (ev.kind === 'metered') continue // a spend record, not a settlement — irrelevant to replay\n if (ev.kind === 'cancelled') {\n settled.push({\n kind: 'down',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'cancelled'),\n reason: ev.reason,\n infra: false,\n restartCount: 0,\n seq: ev.seq,\n })\n continue\n }\n if (ev.status === 'down') {\n settled.push({\n kind: 'down',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'failed'),\n reason: ev.verdict?.notes ?? 'child down',\n infra: ev.infra === true,\n restartCount: 0,\n seq: ev.seq,\n })\n continue\n }\n if (ev.outRef === undefined) {\n throw new Error(\n `replaySpawnTree: settled-done event for '${ev.id}' (seq ${ev.seq}) has no outRef; ` +\n 'cannot rehydrate the result the driver branched on',\n )\n }\n const out = await blobs.get(ev.outRef)\n if (out === undefined) {\n throw new Error(\n `replaySpawnTree: blob store has no artifact for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`,\n )\n }\n settled.push({\n kind: 'done',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'done'),\n out,\n outRef: ev.outRef,\n verdict: ev.verdict,\n spent: ev.spent,\n seq: ev.seq,\n })\n }\n return settled\n}\n\nfunction replayHandle(id: NodeId, label: string, status: NodeStatus) {\n return {\n id,\n label,\n status,\n abort() {\n throw new Error(`cannot abort node '${id}': replayed handles are terminal, not live`)\n },\n }\n}\n\n/**\n * Materialize the live tree (`TreeView`) from a journaled event list for resume. Folds\n * `spawned`/`settled`/`cancelled` into a per-node snapshot in `seq` order, then adds each\n * `metered` event's driver-inference spend onto its node in a separate additive pass — so the\n * resumed view matches what `scope.view` showed at the recorded cursor position.\n */\nexport function materializeTreeView(events: SpawnEvent[]): TreeView {\n const nodes = new Map<NodeId, MutableSnapshot>()\n let root: NodeId | undefined\n // `spawned` (ordinal namespace) and `settled`/`cancelled` (cursor namespace) carry\n // overlapping `seq` values, so create every node before any update — process spawns in\n // ordinal order, then settlements/cancellations in cursor order. A settle/cancel for an\n // un-spawned node is a corrupted log (fail loud via requireNode).\n const spawns = events\n .filter((ev): ev is Extract<SpawnEvent, { kind: 'spawned' }> => ev.kind === 'spawned')\n .sort((a, b) => a.seq - b.seq)\n const settlements = events\n .filter((ev) => ev.kind !== 'spawned' && ev.kind !== 'metered')\n .sort((a, b) => a.seq - b.seq)\n for (const ev of spawns) {\n if (ev.parent === undefined && root === undefined) root = ev.id\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n status: 'pending',\n runtime: ev.runtime,\n budget: ev.budget,\n spent: zeroSpend(),\n })\n }\n for (const ev of settlements) {\n if (ev.kind === 'settled') {\n const node = requireNode(nodes, ev.id)\n node.status = ev.status === 'done' ? 'done' : 'failed'\n node.spent = ev.spent\n node.outRef = ev.outRef\n } else {\n const node = requireNode(nodes, ev.id)\n node.status = 'cancelled'\n }\n }\n // Driver inference: a separate pass so it accumulates ONTO the settled child-work base (no\n // dependence on metered-vs-settled seq order) without touching node status.\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n const node = requireNode(nodes, ev.id)\n node.spent = addJournalSpend(node.spent, ev.spend)\n }\n const snapshots = [...nodes.values()].map(freezeSnapshot)\n return {\n root: root ?? snapshots[0]?.id ?? '',\n nodes: snapshots,\n inFlight: snapshots.filter((n) => n.status === 'running' || n.status === 'acquiring').length,\n }\n}\n\ninterface MutableSnapshot {\n id: NodeId\n parent?: NodeId\n label: string\n status: NodeStatus\n runtime: Runtime\n budget: NodeSnapshot['budget']\n spent: Spend\n outRef?: string\n}\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n/** Add a `metered` spend record onto a node's accumulated spend (per channel). */\nfunction addJournalSpend(a: Spend, b: Spend): Spend {\n return {\n iterations: a.iterations + b.iterations,\n tokens: { input: a.tokens.input + b.tokens.input, output: a.tokens.output + b.tokens.output },\n usd: a.usd + b.usd,\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ms: a.ms + b.ms,\n }\n}\n\nfunction requireNode(nodes: Map<NodeId, MutableSnapshot>, id: NodeId): MutableSnapshot {\n const node = nodes.get(id)\n if (!node) {\n throw new Error(`spawn journal corrupted: settle/cancel for node '${id}' with no prior spawn`)\n }\n return node\n}\n\nfunction freezeSnapshot(node: MutableSnapshot): NodeSnapshot {\n return {\n id: node.id,\n parent: node.parent,\n label: node.label,\n status: node.status,\n runtime: node.runtime,\n budget: node.budget,\n spent: node.spent,\n outRef: node.outRef,\n }\n}\n\nfunction isNoEntError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";AAsBA,SAAS,kBAAkB;AA0BpB,SAAS,eAAe,UAA2B;AACxD,QAAM,MAAM,WAAW,QAAQ,EAAE,OAAO,gBAAgB,QAAQ,GAAG,OAAO,EA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AClB,WAAO,KAAK,OAAO,IAAI,CAAC,QAAQ,EAAE,GAAG,GAAG,EAAE;AAAA,EAC5C;AAAA,EAEA,MAAM,UAAU,MAAc,IAA2B;AACvD,UAAM,WAAW,KAAK,MAAM,IAAI,IAAI;AACpC,QAAI,UAAU;AACZ,UAAI,SAAS,YAAY,IAAI;AAC3B,cAAM,IAAI;AAAA,UACR,eAAe,IAAI,sBAAsB,SAAS,OAAO,gCAAgC,EAAE;AAAA,QAC7F;AAAA,MACF;AACA;AAAA,IACF;AACA,SAAK,MAAM,IAAI,MAAM,EAAE,SAAS,IAAI,QAAQ,CAAC,EAAE,CAAC;AAAA,EAClD;AAAA,EAEA,MAAM,YAAY,MAAc,IAA+B;AAC7D,UAAM,OAAO,KAAK,MAAM,IAAI,IAAI;AAChC,QAAI,CAAC,MAAM;AACT,YAAM,IAAI,MAAM,8CAA8C,IAAI,yBAAyB;AAAA,IAC7F;AACA,oBAAgB,MAAM,KAAK,QAAQ,EAAE;AACrC,SAAK,OAAO,KAAK,EAAE,GAAG,GAAG,CAAC;AAAA,EAC5B;AACF;AA2GA,SAAS,gBAAgB,MAAc,QAAsB,IAAsB;AAGjF,MAAI,GAAG,SAAS,aAAa,GAAG,SAAS,UAAW;AACpD,MAAI,OAAO,KAAK,CAAC,MAAM,EAAE,SAAS,aAAa,EAAE,SAAS,aAAa,EAAE,QAAQ,GAAG,GAAG,GAAG;AACxF,UAAM,IAAI;AAAA,MACR,iDAAiD,GAAG,GAAG,aAAa,IAAI;AAAA,IAE1E;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/durable/spawn-journal.ts"],"sourcesContent":["/**\n *\n * Event-sourced spawn journal for the recursive execution atom (build steps 3 + 7).\n *\n * The supervision tree is journaled as an append-only event log: every `spawned`,\n * `settled`, and `cancelled` is recorded AFTER it is observed-committed (never\n * speculative), mirroring `ConversationJournal`'s begin/append/load shape. The log\n * holds only the THIN decision record — ids, parentage, budget, the spend a decision\n * consumed, and a content-addressed `outRef`. The payloads the driver branched on\n * (the `out` artifacts) live in a separate `ResultBlobStore`, keyed by `outRef`, so\n * the journal stays small (decisions) and replay rehydrates the exact `Settled` from\n * the blob store (evidence). This is the decision/payload split the replay argument\n * rests on (B1/B2).\n *\n * Replay determinism (B2): `seq` is the monotonic cursor order `scope.next()` yielded\n * each settlement — NOT wall-clock. `replaySpawnTree` sorts strictly by `seq` before\n * touching the blob store, so the order in which rehydration `get`s resolve can never\n * reorder the replayed `Settled[]`; the result is identical regardless of blob latency.\n *\n * @experimental\n */\n\nimport { createHash } from 'node:crypto'\nimport type {\n NodeId,\n NodeSnapshot,\n NodeStatus,\n ResultBlobStore,\n Runtime,\n Settled,\n SpawnEvent,\n SpawnJournal,\n Spend,\n TreeView,\n} from '../runtime/supervise/types'\nimport { zeroTokenUsage } from '../runtime/util'\n\n// ── Content addressing ──────────────────────────────────────────────────────\n\n/**\n * Mint the content-addressed `outRef` for a result artifact: `sha256:<hex>` over a\n * stable JSON encoding. Producers call this to derive the `outRef` they journal and\n * `put`; the FS/in-mem stores re-derive it on `put` to verify the supplied ref\n * matches (fail loud on a mismatch — a forged ref breaks the replay invariant).\n *\n * Stable encoding: object keys are sorted recursively so two structurally-equal\n * artifacts hash identically regardless of key insertion order.\n */\nexport function contentAddress(artifact: unknown): string {\n const hex = createHash('sha256').update(stableStringify(artifact), 'utf-8').digest('hex')\n return `sha256:${hex}`\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n\n// ── Result blob store ─────────────────────────────────────────────────────────\n\n/**\n * In-memory `ResultBlobStore`. Content-addressed: `put` verifies the supplied\n * `outRef` matches the artifact's hash so a stale/forged ref fails loud rather than\n * silently rehydrating the wrong payload. Idempotent on an identical re-put.\n */\nexport class InMemoryResultBlobStore implements ResultBlobStore {\n private readonly blobs = new Map<string, unknown>()\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n this.blobs.set(outRef, artifact)\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n return this.blobs.has(outRef) ? this.blobs.get(outRef) : undefined\n }\n}\n\n/**\n * FS `ResultBlobStore`. One JSON file per artifact under `dir`, named by a\n * filesystem-safe encoding of the `outRef` (`sha256:<hex>` → `sha256-<hex>.json`).\n * `put` fsyncs so a crash between writes never loses an acknowledged blob.\n */\nexport class FileResultBlobStore implements ResultBlobStore {\n constructor(private readonly dir: string) {}\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n const fs = await import('node:fs/promises')\n await fs.mkdir(this.dir, { recursive: true })\n const fh = await fs.open(this.blobPath(outRef), 'w')\n try {\n await fh.write(JSON.stringify(artifact))\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.blobPath(outRef), 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n return JSON.parse(text)\n }\n\n private blobPath(outRef: string): string {\n return `${this.dir}/${outRef.replace(/:/g, '-')}.json`\n }\n}\n\nfunction assertContentAddress(outRef: string, artifact: unknown): void {\n const expected = contentAddress(artifact)\n if (outRef !== expected) {\n throw new Error(\n `blob outRef '${outRef}' does not match the artifact content hash '${expected}'; ` +\n 'a content-addressed store refuses a mismatched ref (breaks the replay invariant)',\n )\n }\n}\n\n// ── Spawn journal ──────────────────────────────────────────────────────────────\n\n/**\n * In-memory `SpawnJournal`. Appends are observed-committed only; the impl enforces\n * the corruption guards a durable replay rests on:\n * - an event before `beginTree` is a corrupted tree (fail loud),\n * - a duplicate `seq` within a tree is a corrupted cursor (fail loud) — two\n * settlements cannot share the cursor position replay orders by.\n */\nexport class InMemorySpawnJournal implements SpawnJournal {\n private readonly trees = new Map<NodeId, { begunAt: string; events: SpawnEvent[] }>()\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const tree = this.trees.get(root)\n if (!tree) return undefined\n return tree.events.map((ev) => ({ ...ev }))\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = this.trees.get(root)\n if (existing) {\n if (existing.begunAt !== at) {\n throw new Error(\n `spawn tree '${root}' already begun at ${existing.begunAt}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n this.trees.set(root, { begunAt: at, events: [] })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const tree = this.trees.get(root)\n if (!tree) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, tree.events, ev)\n tree.events.push({ ...ev })\n }\n}\n\n/**\n * JSONL on disk. One line per record: the first record is `begin`, subsequent records\n * are `event` envelopes wrapping a `SpawnEvent`. `loadTree` replays the whole file,\n * filtering by `root`, and applies the same begin-precedes-events + unique-seq\n * corruption guards as the in-memory impl. Each append fsyncs so a crash between\n * writes never loses an acknowledged event.\n */\nexport class FileSpawnJournal implements SpawnJournal {\n constructor(private readonly path: string) {}\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n let begun = false\n const events: SpawnEvent[] = []\n for (const line of lines) {\n const record = JSON.parse(line) as SpawnJournalRecord\n if (record.root !== root) continue\n if (record.kind === 'begin') {\n begun = true\n } else {\n if (!begun) {\n throw new Error(\n `spawn journal corrupted: event for tree '${root}' precedes its begin record`,\n )\n }\n assertSeqUnique(root, events, record.event)\n events.push(record.event)\n }\n }\n return begun ? events : undefined\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = await this.loadTreeBegin(root)\n if (existing) {\n if (existing !== at) {\n throw new Error(\n `spawn tree '${root}' already begun in ${this.path} at ${existing}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n await this.appendRecord({ kind: 'begin', root, at })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const events = await this.loadTree(root)\n if (events === undefined) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, events, ev)\n await this.appendRecord({ kind: 'event', root, event: ev })\n }\n\n private async loadTreeBegin(root: NodeId): Promise<string | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n for (const line of lines) {\n const record = JSON.parse(line) as SpawnJournalRecord\n if (record.root === root && record.kind === 'begin') return record.at\n }\n return undefined\n }\n\n private async appendRecord(record: SpawnJournalRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const fh = await fs.open(this.path, 'a')\n try {\n await fh.write(`${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n}\n\ntype SpawnJournalRecord =\n | { kind: 'begin'; root: NodeId; at: string }\n | { kind: 'event'; root: NodeId; event: SpawnEvent }\n\n/**\n * Two `seq` namespaces share the journal: a `spawned` event's `seq` is the spawn ordinal\n * (the order children were created), and a `settled`/`cancelled` event's `seq` is the\n * monotonic CURSOR order `scope.next()` yielded that settlement (B2). The uniqueness\n * replay rests on is the cursor namespace — two settlements cannot share the position\n * replay orders by — so the guard checks only settled/cancelled events. A `spawned`\n * ordinal legitimately equals a later `settled` cursor seq and is not a collision.\n */\nfunction assertSeqUnique(root: NodeId, events: SpawnEvent[], ev: SpawnEvent): void {\n // `spawned` (ordinal namespace) and `metered` (informational spend, no settlement order) live\n // outside the cursor-uniqueness namespace replay relies on.\n if (ev.kind === 'spawned' || ev.kind === 'metered') return\n if (events.some((e) => e.kind !== 'spawned' && e.kind !== 'metered' && e.seq === ev.seq)) {\n throw new Error(\n `spawn journal corrupted: duplicate cursor seq ${ev.seq} in tree '${root}'; ` +\n 'the cursor order replay relies on is not unique',\n )\n }\n}\n\n// ── Replay executor (build step 7) ───────────────────────────────────────────────\n\n/**\n * Re-feed a journaled spawn tree in strict `seq` order, rehydrating each settled\n * child's `out` from the blob store by `outRef`, and return the `Settled[]` exactly\n * as `scope.next()` originally delivered them.\n *\n * Determinism (B2): the events are sorted by `seq` BEFORE any blob `get`, so the\n * replay order is the recorded cursor order regardless of how fast each rehydration\n * resolves. `at` (wall-clock) is never a replay input. Fail loud on a tree that was\n * never begun, a settled-done event missing its `outRef`, or a blob the store can't\n * rehydrate — a silent gap would let `act` branch on the wrong evidence.\n */\nexport async function replaySpawnTree(\n journal: SpawnJournal,\n blobs: ResultBlobStore,\n root: NodeId,\n): Promise<Settled<unknown>[]> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new Error(`replaySpawnTree: no journaled tree for root '${root}'`)\n }\n const ordered = [...events].sort((a, b) => a.seq - b.seq)\n const labels = new Map<NodeId, string>()\n for (const ev of ordered) {\n if (ev.kind === 'spawned') labels.set(ev.id, ev.label)\n }\n const settled: Settled<unknown>[] = []\n for (const ev of ordered) {\n if (ev.kind === 'spawned') continue\n if (ev.kind === 'metered') continue // a spend record, not a settlement — irrelevant to replay\n if (ev.kind === 'cancelled') {\n settled.push({\n kind: 'down',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'cancelled'),\n reason: ev.reason,\n infra: false,\n restartCount: 0,\n seq: ev.seq,\n })\n continue\n }\n if (ev.status === 'down') {\n settled.push({\n kind: 'down',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'failed'),\n reason: ev.verdict?.notes ?? 'child down',\n infra: ev.infra === true,\n restartCount: 0,\n seq: ev.seq,\n })\n continue\n }\n if (ev.outRef === undefined) {\n throw new Error(\n `replaySpawnTree: settled-done event for '${ev.id}' (seq ${ev.seq}) has no outRef; ` +\n 'cannot rehydrate the result the driver branched on',\n )\n }\n const out = await blobs.get(ev.outRef)\n if (out === undefined) {\n throw new Error(\n `replaySpawnTree: blob store has no artifact for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`,\n )\n }\n settled.push({\n kind: 'done',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'done'),\n out,\n outRef: ev.outRef,\n verdict: ev.verdict,\n spent: ev.spent,\n seq: ev.seq,\n })\n }\n return settled\n}\n\nfunction replayHandle(id: NodeId, label: string, status: NodeStatus) {\n return {\n id,\n label,\n status,\n abort() {\n throw new Error(`cannot abort node '${id}': replayed handles are terminal, not live`)\n },\n }\n}\n\n/**\n * Materialize a recorded `TreeView` from a journaled event list for inspection. Folds\n * `spawned`/`settled`/`cancelled` into a per-node snapshot in `seq` order, then adds each\n * `metered` event's driver-inference spend onto its node in a separate additive pass so the view\n * matches the recorded cursor. It does not recover live executors or driver state after restart.\n */\nexport function materializeTreeView(events: SpawnEvent[]): TreeView {\n const nodes = new Map<NodeId, MutableSnapshot>()\n let root: NodeId | undefined\n // `spawned` (ordinal namespace) and `settled`/`cancelled` (cursor namespace) carry\n // overlapping `seq` values, so create every node before any update — process spawns in\n // ordinal order, then settlements/cancellations in cursor order. A settle/cancel for an\n // un-spawned node is a corrupted log (fail loud via requireNode).\n const spawns = events\n .filter((ev): ev is Extract<SpawnEvent, { kind: 'spawned' }> => ev.kind === 'spawned')\n .sort((a, b) => a.seq - b.seq)\n const settlements = events\n .filter((ev) => ev.kind !== 'spawned' && ev.kind !== 'metered')\n .sort((a, b) => a.seq - b.seq)\n for (const ev of spawns) {\n if (ev.parent === undefined && root === undefined) root = ev.id\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n status: 'pending',\n runtime: ev.runtime,\n budget: ev.budget,\n spent: zeroSpend(),\n })\n }\n for (const ev of settlements) {\n if (ev.kind === 'settled') {\n const node = requireNode(nodes, ev.id)\n node.status = ev.status === 'done' ? 'done' : 'failed'\n node.spent = ev.spent\n node.outRef = ev.outRef\n } else {\n const node = requireNode(nodes, ev.id)\n node.status = 'cancelled'\n }\n }\n // Driver inference: a separate pass so it accumulates ONTO the settled child-work base (no\n // dependence on metered-vs-settled seq order) without touching node status.\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n const node = requireNode(nodes, ev.id)\n node.spent = addJournalSpend(node.spent, ev.spend)\n }\n const snapshots = [...nodes.values()].map(freezeSnapshot)\n return {\n root: root ?? snapshots[0]?.id ?? '',\n nodes: snapshots,\n inFlight: snapshots.filter((n) => n.status === 'running' || n.status === 'acquiring').length,\n }\n}\n\ninterface MutableSnapshot {\n id: NodeId\n parent?: NodeId\n label: string\n status: NodeStatus\n runtime: Runtime\n budget: NodeSnapshot['budget']\n spent: Spend\n outRef?: string\n}\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n/** Add a `metered` spend record onto a node's accumulated spend (per channel). */\nfunction addJournalSpend(a: Spend, b: Spend): Spend {\n return {\n iterations: a.iterations + b.iterations,\n tokens: { input: a.tokens.input + b.tokens.input, output: a.tokens.output + b.tokens.output },\n usd: a.usd + b.usd,\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ms: a.ms + b.ms,\n }\n}\n\nfunction requireNode(nodes: Map<NodeId, MutableSnapshot>, id: NodeId): MutableSnapshot {\n const node = nodes.get(id)\n if (!node) {\n throw new Error(`spawn journal corrupted: settle/cancel for node '${id}' with no prior spawn`)\n }\n return node\n}\n\nfunction freezeSnapshot(node: MutableSnapshot): NodeSnapshot {\n return {\n id: node.id,\n parent: node.parent,\n label: node.label,\n status: node.status,\n runtime: node.runtime,\n budget: node.budget,\n spent: node.spent,\n outRef: node.outRef,\n }\n}\n\nfunction isNoEntError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";AAsBA,SAAS,kBAAkB;AA0BpB,SAAS,eAAe,UAA2B;AACxD,QAAM,MAAM,WAAW,QAAQ,EAAE,OAAO,gBAAgB,QAAQ,GAAG,OAAO,EAAE,OAAO,KAAK;AACxF,SAAO,UAAU,GAAG;AACtB;AAEA,SAAS,gBAAgB,OAAwB;AAC/C,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO,KAAK,UAAU,KAAK,KAAK;AACjF,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,IAAI,MAAM,IAAI,eAAe,EAAE,KAAK,GAAG,CAAC;AACzE,QAAM,UAAU,OAAO,QAAQ,KAAgC,EAC5D,OAAO,CAAC,CAAC,EAAE,CAAC,MAAM,MAAM,MAAS,EACjC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE;AAClD,SAAO,IAAI,QAAQ,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,KAAK,UAAU,CAAC,CAAC,IAAI,gBAAgB,CAAC,CAAC,EAAE,EAAE,KAAK,GAAG,CAAC;AAC5F;AASO,IAAM,0BAAN,MAAyD;AAAA,EAC7C,QAAQ,oBAAI,IAAqB;AAAA,EAElD,MAAM,IAAI,QAAgB,UAAkC;AAC1D,yBAAqB,QAAQ,QAAQ;AACrC,SAAK,MAAM,IAAI,QAAQ,QAAQ;AAAA,EACjC;AAAA,EAEA,MAAM,IAAI,QAA8C;AACtD,WAAO,KAAK,MAAM,IAAI,MAAM,IAAI,KAAK,MAAM,IAAI,MAAM,IAAI;AAAA,EAC3D;AACF;AAwCA,SAAS,qBAAqB,QAAgB,UAAyB;AACrE,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AAI;AAAA,IAE1E;AAAA,EACF;AACF;","names":[]}
|
|
@@ -387,18 +387,25 @@ function sandboxInstanceAsEnvironment(box, providerName, client) {
|
|
|
387
387
|
return execResultFromSandboxExecResult(await box.exec(command, options));
|
|
388
388
|
}
|
|
389
389
|
} : {},
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
390
|
+
async checkpoint(options) {
|
|
391
|
+
const result = await box.snapshot({
|
|
392
|
+
...options?.name ? { tags: [options.name] } : {}
|
|
393
|
+
});
|
|
394
|
+
return {
|
|
395
|
+
id: result.snapshotId,
|
|
396
|
+
provider: providerName,
|
|
397
|
+
...options?.metadata ? { metadata: options.metadata } : {}
|
|
398
|
+
};
|
|
399
|
+
},
|
|
400
|
+
async fork(checkpoint, options) {
|
|
401
|
+
const forked = await client.create({
|
|
402
|
+
fromSnapshot: checkpoint.id,
|
|
403
|
+
fromSandboxId: String(box.id),
|
|
404
|
+
...options?.name ? { name: options.name } : {},
|
|
405
|
+
...options?.metadata ? { metadata: options.metadata } : {}
|
|
406
|
+
});
|
|
407
|
+
return sandboxInstanceAsEnvironment(forked, providerName, client);
|
|
408
|
+
},
|
|
402
409
|
async placement() {
|
|
403
410
|
return placementInfoFromLoopPlacement(client.describePlacement?.(box), box);
|
|
404
411
|
},
|
|
@@ -705,14 +712,6 @@ function placementInfoFromLoopPlacement(placement, box) {
|
|
|
705
712
|
...placement.machineId ? { machineId: placement.machineId } : {}
|
|
706
713
|
};
|
|
707
714
|
}
|
|
708
|
-
function checkpointIdFromResult(result) {
|
|
709
|
-
const record = result && typeof result === "object" ? result : {};
|
|
710
|
-
const id = record.checkpointId ?? record.id;
|
|
711
|
-
if (typeof id !== "string" || id.length === 0) {
|
|
712
|
-
throw new ValidationError("sandboxClientAsProvider: checkpoint returned no checkpoint id");
|
|
713
|
-
}
|
|
714
|
-
return id;
|
|
715
|
-
}
|
|
716
715
|
function defaultTangleSandboxCapabilities() {
|
|
717
716
|
return {
|
|
718
717
|
profile: {
|
|
@@ -790,12 +789,6 @@ function hasWrite(box) {
|
|
|
790
789
|
function hasExec(box) {
|
|
791
790
|
return typeof box.exec === "function";
|
|
792
791
|
}
|
|
793
|
-
function hasCheckpoint(box) {
|
|
794
|
-
return typeof box.checkpoint === "function";
|
|
795
|
-
}
|
|
796
|
-
function hasFork(box) {
|
|
797
|
-
return typeof box.fork === "function";
|
|
798
|
-
}
|
|
799
792
|
|
|
800
793
|
export {
|
|
801
794
|
createAgentEnvironmentProviderRegistry,
|
|
@@ -804,4 +797,4 @@ export {
|
|
|
804
797
|
sandboxClientAsProvider,
|
|
805
798
|
providerAsExecutor
|
|
806
799
|
};
|
|
807
|
-
//# sourceMappingURL=chunk-
|
|
800
|
+
//# sourceMappingURL=chunk-M6MD6JBS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/runtime/environment-provider.ts"],"sourcesContent":["import type {\n AgentProfile,\n AgentProfileValidationResult,\n InputPart,\n TokenUsage,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n AgentEnvironmentEvent,\n AgentEnvironmentProvider,\n AgentEnvironmentQuery,\n AgentEnvironmentStatus,\n AgentEnvironmentSummary,\n AgentProfileRef,\n AgentSession,\n AgentSessionRef,\n AgentSessionStatus,\n AgentTurnInput,\n AgentTurnResult,\n CheckpointRef,\n CheckpointRequest,\n CreateAgentEnvironmentInput,\n ExecRequest,\n ExecResult,\n ForkRequest,\n PlacementInfo,\n ResourceRequest,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type {\n BackendType,\n CreateSandboxOptions,\n PromptOptions,\n PromptResult,\n SandboxEvent,\n ExecResult as SandboxExecResult,\n SandboxInstance,\n} from '@tangle-network/sandbox'\nimport type {\n Executor,\n ExecutorContext,\n ExecutorFactory,\n ExecutorResult,\n Runtime,\n Spend,\n UsageEvent,\n} from './supervise/types'\nimport type { LoopSandboxPlacement, SandboxClient } from './types'\nimport { zeroTokenUsage } from './util'\n\n// Keep this file loadable from the lean `./environment-provider` export without agent-eval installed.\nclass ValidationError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = 'ValidationError'\n }\n}\n\nexport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n AgentEnvironmentEvent,\n AgentEnvironmentProvider,\n AgentEnvironmentQuery,\n AgentEnvironmentStatus,\n AgentEnvironmentSummary,\n AgentProfileRef,\n AgentSession,\n AgentSessionRef,\n AgentSessionStatus,\n AgentTurnInput,\n AgentTurnResult,\n CheckpointRef,\n CheckpointRequest,\n CreateAgentEnvironmentInput,\n ExecRequest,\n ExecResult,\n ForkRequest,\n PlacementInfo,\n ResourceRequest,\n WorkspaceRequest,\n} from '@tangle-network/agent-interface/environment-provider'\n\n/** Provider object or registry name accepted by runtime provider adapters.\n * @experimental */\nexport type AgentEnvironmentProviderRef = AgentEnvironmentProvider | string\n\n/** In-memory registry for named `AgentEnvironmentProvider` instances.\n * @experimental */\nexport interface AgentEnvironmentProviderRegistry {\n register(provider: AgentEnvironmentProvider, options?: { replace?: boolean }): void\n has(name: string): boolean\n get(name: string): AgentEnvironmentProvider | undefined\n require(name: string): AgentEnvironmentProvider\n names(): string[]\n providers(): AgentEnvironmentProvider[]\n capabilities(name: string): Promise<AgentEnvironmentCapabilities>\n}\n\n/** Create a registry that resolves provider names to concrete provider instances.\n * @experimental */\nexport function createAgentEnvironmentProviderRegistry(\n providers: Iterable<AgentEnvironmentProvider> = [],\n): AgentEnvironmentProviderRegistry {\n const entries = new Map<string, AgentEnvironmentProvider>()\n\n const registry: AgentEnvironmentProviderRegistry = {\n register(provider, options = {}): void {\n if (!provider.name) {\n throw new ValidationError('agent environment provider registry: provider.name required')\n }\n if (!options.replace && entries.has(provider.name)) {\n throw new ValidationError(\n `agent environment provider registry: provider \"${provider.name}\" already registered`,\n )\n }\n entries.set(provider.name, provider)\n },\n has(name): boolean {\n return entries.has(name)\n },\n get(name): AgentEnvironmentProvider | undefined {\n return entries.get(name)\n },\n require(name): AgentEnvironmentProvider {\n const provider = entries.get(name)\n if (!provider) {\n const available = Array.from(entries.keys()).sort()\n const suffix = available.length > 0 ? `; available: ${available.join(', ')}` : ''\n throw new ValidationError(\n `agent environment provider registry: provider \"${name}\" is not registered${suffix}`,\n )\n }\n return provider\n },\n names(): string[] {\n return Array.from(entries.keys()).sort()\n },\n providers(): AgentEnvironmentProvider[] {\n return registry.names().map((name) => registry.require(name))\n },\n async capabilities(name): Promise<AgentEnvironmentCapabilities> {\n return registry.require(name).capabilities()\n },\n }\n\n for (const provider of providers) registry.register(provider)\n return registry\n}\n\n/** Resolve a provider instance or registry name, failing loudly when a name is unknown.\n * @experimental */\nexport function resolveAgentEnvironmentProvider(\n provider: AgentEnvironmentProviderRef,\n registry?: AgentEnvironmentProviderRegistry,\n): AgentEnvironmentProvider {\n if (typeof provider !== 'string') return provider\n if (!registry) {\n throw new ValidationError(\n `agent environment provider \"${provider}\" requires an AgentEnvironmentProviderRegistry`,\n )\n }\n return registry.require(provider)\n}\n\n/** Options for exposing an `AgentEnvironmentProvider` through the legacy sandbox client port.\n * @experimental */\nexport interface ProviderAsSandboxClientOptions {\n defaults?: Partial<CreateAgentEnvironmentInput>\n requireTerminalEvent?: boolean\n mapCreateOptions?: (\n options: CreateSandboxOptions | undefined,\n ) => Partial<CreateAgentEnvironmentInput>\n}\n\n/** Adapt a neutral environment provider to the `SandboxClient` interface used by existing loop paths.\n * @experimental */\nexport function providerAsSandboxClient(\n provider: AgentEnvironmentProvider,\n options: ProviderAsSandboxClientOptions = {},\n): SandboxClient {\n return {\n async create(createOptions?: CreateSandboxOptions): Promise<SandboxInstance> {\n const mapped = {\n ...(options.defaults ?? {}),\n ...createInputFromSandboxOptions(createOptions),\n ...(options.mapCreateOptions?.(createOptions) ?? {}),\n }\n if (mapped.profile === undefined) {\n throw new ValidationError(\n `providerAsSandboxClient(${provider.name}): profile required in defaults or CreateSandboxOptions.backend.profile`,\n )\n }\n const environment = await provider.create(mapped as CreateAgentEnvironmentInput)\n return environmentAsSandboxInstance(environment, {\n requireTerminalEvent: options.requireTerminalEvent ?? true,\n })\n },\n }\n}\n\n/** Options for wrapping the current Tangle sandbox client as an environment provider.\n * @experimental */\nexport interface SandboxClientProviderOptions {\n name?: string\n defaultBackend?: BackendType\n capabilities?:\n | AgentEnvironmentCapabilities\n | (() => AgentEnvironmentCapabilities | Promise<AgentEnvironmentCapabilities>)\n validateProfile?: (\n profile: AgentProfileRef,\n ) => AgentProfileValidationResult | Promise<AgentProfileValidationResult>\n mapCreateInput?: (input: CreateAgentEnvironmentInput) => CreateSandboxOptions\n}\n\n/** Adapt a `SandboxClient` into the shared `AgentEnvironmentProvider` contract.\n * @experimental */\nexport function sandboxClientAsProvider(\n client: SandboxClient,\n options: SandboxClientProviderOptions = {},\n): AgentEnvironmentProvider {\n const providerName = options.name ?? 'tangle-sandbox'\n return {\n name: providerName,\n capabilities: async () => {\n if (options.capabilities) {\n return typeof options.capabilities === 'function'\n ? options.capabilities()\n : options.capabilities\n }\n return defaultTangleSandboxCapabilities()\n },\n ...(options.validateProfile ? { validateProfile: options.validateProfile } : {}),\n async create(input: CreateAgentEnvironmentInput): Promise<AgentEnvironment> {\n const createOptions =\n options.mapCreateInput?.(input) ??\n sandboxOptionsFromCreateInput(input, options.defaultBackend ?? 'opencode')\n const box = await client.create(createOptions)\n return sandboxInstanceAsEnvironment(box, providerName, client)\n },\n ...(hasGet(client)\n ? {\n async get(id: string): Promise<AgentEnvironment | null> {\n const box = await client.get(id)\n return box ? sandboxInstanceAsEnvironment(box, providerName, client) : null\n },\n }\n : {}),\n ...(hasList(client)\n ? {\n async list(query?: AgentEnvironmentQuery): Promise<AgentEnvironmentSummary[]> {\n const boxes = await client.list(query?.providerOptions)\n return boxes.map((box) => ({\n id: String(box.id),\n provider: providerName,\n name: typeof box.name === 'string' ? box.name : undefined,\n status: statusFromUnknown(readBoxStatus(box)),\n metadata: readBoxMetadata(box),\n }))\n },\n }\n : {}),\n }\n}\n\n/** Options for running a provider as a supervise-mode executor.\n * @experimental */\nexport interface ProviderExecutorOptions {\n defaults?: Partial<CreateAgentEnvironmentInput>\n runtime?: Runtime\n destroyOnSettle?: boolean\n requireTerminalEvent?: boolean\n taskToTurn?: (task: unknown, specProfile: AgentProfile) => AgentTurnInput\n}\n\n/** Adapt an environment provider into an `ExecutorFactory` for `createExecutor`.\n * @experimental */\nexport function providerAsExecutor(\n provider: AgentEnvironmentProvider,\n options: ProviderExecutorOptions = {},\n): ExecutorFactory<unknown> {\n return (spec, ctx) => createProviderExecutor(provider, spec.profile, ctx, options)\n}\n\nfunction createProviderExecutor(\n provider: AgentEnvironmentProvider,\n profile: AgentProfile,\n ctx: ExecutorContext,\n options: ProviderExecutorOptions,\n): Executor<unknown> {\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n let environment: AgentEnvironment | undefined\n let artifact: ExecutorResult<unknown> | undefined\n\n return {\n runtime: options.runtime ?? (provider.name as Runtime),\n execute(task, signal): AsyncIterable<UsageEvent> {\n return streamProviderExecutor({\n provider,\n profile,\n task,\n signal,\n controller,\n options,\n onEnvironment: (env) => {\n environment = env\n },\n onArtifact: (next) => {\n artifact = next\n },\n })\n },\n async teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n await environment?.destroy?.()\n return { destroyed: true }\n },\n resultArtifact(): ExecutorResult<unknown> {\n if (!artifact) {\n throw new ValidationError(\n `providerAsExecutor(${provider.name}): resultArtifact() read before stream drained`,\n )\n }\n return artifact\n },\n }\n}\n\ninterface StreamProviderExecutorArgs {\n provider: AgentEnvironmentProvider\n profile: AgentProfile\n task: unknown\n signal: AbortSignal\n controller: AbortController\n options: ProviderExecutorOptions\n onEnvironment: (environment: AgentEnvironment) => void\n onArtifact: (artifact: ExecutorResult<unknown>) => void\n}\n\nasync function* streamProviderExecutor(\n args: StreamProviderExecutorArgs,\n): AsyncIterable<UsageEvent> {\n const started = Date.now()\n const linked = mergeAbortSignals(args.signal, args.controller.signal)\n const environment = await args.provider.create({\n ...(args.options.defaults ?? {}),\n profile: args.profile,\n signal: linked,\n })\n args.onEnvironment(environment)\n\n const turn =\n args.options.taskToTurn?.(args.task, args.profile) ?? taskToTurnInput(args.task, linked)\n const events: AgentEnvironmentEvent[] = []\n const tokens = zeroTokenUsage()\n let usd = 0\n let text = ''\n let terminal = false\n try {\n for await (const event of environment.stream({ ...turn, signal: linked })) {\n events.push(event)\n text += textFromEnvironmentEvent(event)\n const usage = usageFromEnvironmentEvent(event)\n if (usage.input || usage.output) {\n tokens.input += usage.input\n tokens.output += usage.output\n yield { kind: 'tokens', input: usage.input, output: usage.output }\n }\n if (usage.usd) {\n usd += usage.usd\n yield { kind: 'cost', usd: usage.usd }\n }\n if (isTerminalEnvironmentEvent(event)) terminal = true\n }\n if ((args.options.requireTerminalEvent ?? true) && !terminal) {\n throw new ValidationError(\n `providerAsExecutor(${args.provider.name}): stream ended without a terminal result/done/status event`,\n )\n }\n yield { kind: 'iteration' }\n const result = resultFromEvents(events, text)\n const spent: Spend = {\n iterations: 1,\n tokens,\n usd,\n ms: Date.now() - started,\n }\n args.onArtifact({\n outRef: contentRef(`provider:${args.provider.name}`, result),\n out: result,\n spent,\n })\n } finally {\n if (args.options.destroyOnSettle ?? true) await environment.destroy?.()\n }\n}\n\nfunction createInputFromSandboxOptions(\n options: CreateSandboxOptions | undefined,\n): Partial<CreateAgentEnvironmentInput> {\n const profile = options?.backend?.profile as AgentProfileRef | undefined\n const backend = options?.backend?.type\n return {\n ...(profile !== undefined ? { profile } : {}),\n ...(backend ? { backend } : {}),\n workspace: {\n ...(options?.environment ? { environment: options.environment } : {}),\n ...(options?.image ? { image: options.image } : {}),\n ...(options?.git?.url ? { repoUrl: options.git.url } : {}),\n ...(options?.git?.ref ? { gitRef: options.git.ref } : {}),\n },\n ...(options?.resources ? { resources: options.resources as ResourceRequest } : {}),\n ...(options?.env ? { env: options.env } : {}),\n ...(options?.secrets ? { secrets: options.secrets } : {}),\n ...(options?.metadata ? { metadata: options.metadata } : {}),\n ...(options?.name ? { name: options.name } : {}),\n ...(options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),\n providerOptions: { sandboxCreateOptions: options ?? {} },\n }\n}\n\nfunction sandboxOptionsFromCreateInput(\n input: CreateAgentEnvironmentInput,\n defaultBackend: BackendType,\n): CreateSandboxOptions {\n const backendType = (input.backend ?? defaultBackend) as BackendType\n const workspace = input.workspace ?? {}\n const providerOptions = input.providerOptions?.sandboxCreateOptions\n const base =\n providerOptions && typeof providerOptions === 'object'\n ? ({ ...(providerOptions as CreateSandboxOptions) } as CreateSandboxOptions)\n : ({} satisfies CreateSandboxOptions)\n return {\n ...base,\n ...(workspace.environment ? { environment: workspace.environment } : {}),\n ...(workspace.image ? { image: workspace.image } : {}),\n ...(workspace.repoUrl ? { git: { url: workspace.repoUrl, ref: workspace.gitRef } } : {}),\n ...(input.resources ? { resources: input.resources as CreateSandboxOptions['resources'] } : {}),\n ...(input.env ? { env: input.env } : {}),\n ...(Array.isArray(input.secrets) ? { secrets: input.secrets } : {}),\n ...(input.metadata ? { metadata: input.metadata } : {}),\n ...(input.name ? { name: input.name } : {}),\n ...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),\n backend: {\n ...(base.backend ?? {}),\n type: backendType,\n profile: input.profile,\n },\n }\n}\n\nfunction environmentAsSandboxInstance(\n environment: AgentEnvironment,\n options: { requireTerminalEvent: boolean },\n): SandboxInstance {\n const box = {\n id: environment.id,\n name: environment.name,\n status: 'running',\n async refresh(): Promise<void> {\n await environment.refresh?.()\n },\n async *streamPrompt(\n message: string | InputPart[],\n promptOptions?: PromptOptions,\n ): AsyncGenerator<SandboxEvent> {\n let terminal = false\n const input = turnInputFromPrompt(message, promptOptions)\n for await (const event of environment.stream(input)) {\n if (isTerminalEnvironmentEvent(event)) terminal = true\n const usageEvent = usageSandboxEvent(event)\n if (usageEvent) yield usageEvent\n yield sandboxEventFromEnvironmentEvent(event)\n }\n if (options.requireTerminalEvent && !terminal) {\n throw new ValidationError(\n `providerAsSandboxClient(${environment.provider}): stream ended without a terminal result/done/status event`,\n )\n }\n },\n async prompt(\n message: string | InputPart[],\n promptOptions?: PromptOptions,\n ): Promise<PromptResult> {\n const events: AgentEnvironmentEvent[] = []\n let text = ''\n let usage: TokenUsage | undefined\n let terminal = false\n for await (const event of environment.stream(turnInputFromPrompt(message, promptOptions))) {\n events.push(event)\n if (isTerminalEnvironmentEvent(event)) terminal = true\n text += textFromEnvironmentEvent(event)\n usage = mergeTokenUsage(usage, event.usage)\n }\n if (options.requireTerminalEvent && !terminal) {\n throw new ValidationError(\n `providerAsSandboxClient(${environment.provider}): prompt ended without a terminal result/done/status event`,\n )\n }\n return promptResultCompat(\n {\n response: resultFromEvents(events, text).content,\n success: true,\n durationMs: 0,\n ...(usage ? { usage } : {}),\n },\n 'success',\n )\n },\n ...(environment.dispatch\n ? {\n async dispatchPrompt(message: string | InputPart[], promptOptions?: PromptOptions) {\n const session = await environment.dispatch?.(\n turnInputFromPrompt(message, promptOptions),\n )\n if (!session)\n throw new ValidationError('providerAsSandboxClient: dispatch returned no session')\n return sandboxDispatchResultFromSessionRef(session)\n },\n }\n : {}),\n ...(environment.session\n ? {\n session(id: string) {\n return sessionAsSandboxSession(environment.session?.(id))\n },\n }\n : {}),\n ...(environment.read ? { read: environment.read.bind(environment) } : {}),\n ...(environment.write ? { write: environment.write.bind(environment) } : {}),\n ...(environment.exec\n ? {\n exec: environment.exec.bind(environment),\n }\n : {}),\n ...(environment.checkpoint\n ? {\n async checkpoint(checkpointOptions?: CheckpointRequest) {\n const checkpoint = await environment.checkpoint?.(checkpointOptions)\n return { checkpointId: checkpoint?.id, id: checkpoint?.id }\n },\n }\n : {}),\n ...(environment.fork\n ? {\n async fork(checkpointId: string, forkOptions?: ForkRequest) {\n const forked = await environment.fork?.({ id: checkpointId }, forkOptions)\n if (!forked)\n throw new ValidationError('providerAsSandboxClient: fork returned no environment')\n return environmentAsSandboxInstance(forked, options)\n },\n }\n : {}),\n async delete(): Promise<void> {\n await environment.destroy?.()\n },\n }\n return box as unknown as SandboxInstance\n}\n\nfunction sandboxInstanceAsEnvironment(\n box: SandboxInstance,\n providerName: string,\n client: SandboxClient,\n): AgentEnvironment {\n const environment: AgentEnvironment = {\n id: String(box.id),\n provider: providerName,\n ...(typeof box.name === 'string' ? { name: box.name } : {}),\n async status(): Promise<AgentEnvironmentStatus> {\n await maybeRefresh(box)\n return statusFromUnknown(readBoxStatus(box))\n },\n async *stream(input: AgentTurnInput): AsyncIterable<AgentEnvironmentEvent> {\n for await (const event of box.streamPrompt(\n promptFromTurnInput(input),\n promptOptionsFromTurnInput(input),\n )) {\n yield environmentEventFromSandboxEvent(event)\n }\n },\n ...(hasDispatchPrompt(box)\n ? {\n async dispatch(input: AgentTurnInput): Promise<AgentSessionRef> {\n const dispatched = await box.dispatchPrompt(\n promptFromTurnInput(input),\n promptOptionsFromTurnInput(input),\n )\n return sessionRefFromSandboxDispatch(dispatched, providerName)\n },\n }\n : {}),\n ...(hasSession(box)\n ? {\n session(id: string): AgentSession {\n return sandboxSessionAsAgentSession(box.session(id))\n },\n }\n : {}),\n ...(hasRead(box) ? { read: box.read.bind(box) } : {}),\n ...(hasWrite(box) ? { write: box.write.bind(box) } : {}),\n ...(hasExec(box)\n ? {\n async exec(command: string, options?: ExecRequest): Promise<ExecResult> {\n return execResultFromSandboxExecResult(await box.exec(command, options as never))\n },\n }\n : {}),\n async checkpoint(options?: CheckpointRequest): Promise<CheckpointRef> {\n const result = await box.snapshot({\n ...(options?.name ? { tags: [options.name] } : {}),\n })\n return {\n id: result.snapshotId,\n provider: providerName,\n ...(options?.metadata ? { metadata: options.metadata } : {}),\n }\n },\n async fork(checkpoint: CheckpointRef, options?: ForkRequest): Promise<AgentEnvironment> {\n const forked = await client.create({\n fromSnapshot: checkpoint.id,\n fromSandboxId: String(box.id),\n ...(options?.name ? { name: options.name } : {}),\n ...(options?.metadata ? { metadata: options.metadata } : {}),\n })\n return sandboxInstanceAsEnvironment(forked, providerName, client)\n },\n async placement(): Promise<PlacementInfo> {\n return placementInfoFromLoopPlacement(client.describePlacement?.(box), box)\n },\n async refresh(): Promise<void> {\n await maybeRefresh(box)\n },\n async destroy(): Promise<void> {\n await destroyBox(box)\n },\n }\n return environment\n}\n\nfunction sandboxSessionAsAgentSession(session: SandboxSessionLike): AgentSession {\n return {\n id: session.id,\n async status(): Promise<AgentSessionStatus | null> {\n const status = await session.status()\n if (!status) return null\n return sessionStatusFromUnknown((status as { status?: unknown }).status)\n },\n async *events(options?: {\n since?: string\n signal?: AbortSignal\n }): AsyncIterable<AgentEnvironmentEvent> {\n for await (const event of session.events(options))\n yield environmentEventFromSandboxEvent(event)\n },\n async result(): Promise<AgentTurnResult> {\n return agentTurnResultFromPromptResult(await session.result())\n },\n async prompt(input: AgentTurnInput): Promise<AgentTurnResult> {\n return agentTurnResultFromPromptResult(\n await session.prompt(promptFromTurnInput(input), promptOptionsFromTurnInput(input)),\n )\n },\n cancel(): Promise<void> {\n return session.cancel()\n },\n }\n}\n\nfunction sessionAsSandboxSession(session: AgentSession | undefined): unknown {\n if (!session) throw new ValidationError('providerAsSandboxClient: session(id) returned undefined')\n return {\n id: session.id,\n status: session.status.bind(session),\n async *events(options?: {\n since?: string\n signal?: AbortSignal\n }): AsyncGenerator<SandboxEvent> {\n for await (const event of session.events(options))\n yield sandboxEventFromEnvironmentEvent(event)\n },\n async result(): Promise<PromptResult> {\n return promptResultFromAgentTurnResult(await session.result())\n },\n async prompt(message: string | InputPart[], options?: PromptOptions): Promise<PromptResult> {\n return promptResultFromAgentTurnResult(\n await session.prompt(turnInputFromPrompt(message, options)),\n )\n },\n cancel: session.cancel.bind(session),\n }\n}\n\nfunction environmentEventFromSandboxEvent(event: SandboxEvent): AgentEnvironmentEvent {\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n return {\n type: String(event.type),\n data,\n ...(event.id ? { id: event.id } : {}),\n usage: tokenUsageFromData(data),\n providerEvent: event,\n }\n}\n\nfunction sandboxEventFromEnvironmentEvent(event: AgentEnvironmentEvent): SandboxEvent {\n return {\n type: event.type,\n data: {\n ...event.data,\n ...(event.usage ? { usage: tokenUsageData(event.usage) } : {}),\n },\n ...(event.id ? { id: event.id } : {}),\n }\n}\n\nfunction usageSandboxEvent(event: AgentEnvironmentEvent): SandboxEvent | undefined {\n if (!event.usage || isUsageType(event.type)) return undefined\n const usage = tokenUsageData(event.usage)\n if (\n usage.inputTokens === undefined &&\n usage.outputTokens === undefined &&\n usage.totalCostUsd === undefined\n ) {\n return undefined\n }\n return { type: 'llm_call', data: usage }\n}\n\nfunction tokenUsageData(usage: TokenUsage): Record<string, number | undefined> {\n return {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n totalCostUsd: usage.cost,\n }\n}\n\nfunction turnInputFromPrompt(\n message: string | InputPart[],\n options?: PromptOptions,\n): AgentTurnInput {\n return {\n ...(typeof message === 'string' ? { prompt: message } : { parts: message }),\n ...(options?.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options?.model ? { model: options.model } : {}),\n ...(options?.timeoutMs ? { timeoutMs: options.timeoutMs } : {}),\n ...(options?.executionId ? { executionId: options.executionId } : {}),\n ...(options?.lastEventId ? { lastEventId: options.lastEventId } : {}),\n ...(options?.turnId ? { turnId: options.turnId } : {}),\n ...(options?.detach !== undefined ? { detach: options.detach } : {}),\n ...(options?.context ? { context: options.context } : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(options?.backend ? { providerOptions: { backend: options.backend } } : {}),\n }\n}\n\nfunction promptFromTurnInput(input: AgentTurnInput): string | InputPart[] {\n if (input.parts) return input.parts\n return input.prompt ?? ''\n}\n\nfunction promptOptionsFromTurnInput(input: AgentTurnInput): PromptOptions {\n return {\n ...(input.sessionId ? { sessionId: input.sessionId } : {}),\n ...(input.model ? { model: input.model } : {}),\n ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),\n ...(input.context ? { context: input.context } : {}),\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.executionId ? { executionId: input.executionId } : {}),\n ...(input.lastEventId ? { lastEventId: input.lastEventId } : {}),\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.detach !== undefined ? { detach: input.detach } : {}),\n }\n}\n\nfunction taskToTurnInput(task: unknown, signal: AbortSignal): AgentTurnInput {\n return { prompt: taskToPrompt(task), signal }\n}\n\nfunction taskToPrompt(task: unknown): string {\n if (typeof task === 'string') return task\n if (task && typeof task === 'object') {\n const record = task as Record<string, unknown>\n for (const key of ['prompt', 'content', 'task', 'message']) {\n if (typeof record[key] === 'string') return record[key]\n }\n }\n return JSON.stringify(task)\n}\n\nfunction resultFromEvents(\n events: AgentEnvironmentEvent[],\n fallbackText: string,\n): { content: string; events: AgentEnvironmentEvent[] } {\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n const text = event ? resultTextFromData(event.data) : undefined\n if (text !== undefined) return { content: text, events }\n }\n return { content: fallbackText, events }\n}\n\nfunction textFromEnvironmentEvent(event: AgentEnvironmentEvent): string {\n if (\n typeof event.normalized === 'object' &&\n event.normalized &&\n event.normalized.type === 'message.part.updated'\n ) {\n return typeof event.normalized.delta === 'string' ? event.normalized.delta : ''\n }\n const data = event.data\n for (const key of ['delta', 'chunk', 'content', 'text']) {\n if (typeof data[key] === 'string' && !isTerminalEnvironmentEvent(event)) return data[key]\n }\n return ''\n}\n\nfunction resultTextFromData(data: Record<string, unknown>): string | undefined {\n for (const key of ['finalText', 'text', 'response', 'resultSummary', 'content']) {\n if (typeof data[key] === 'string') return data[key]\n }\n return undefined\n}\n\nfunction isTerminalEnvironmentEvent(event: AgentEnvironmentEvent): boolean {\n if (event.type === 'result' || event.type === 'done' || event.type === 'final') return true\n if (event.type.endsWith('.completed') || event.type.endsWith('.failed')) return true\n if (event.type === 'status') {\n const status = event.data.status\n return status === 'completed' || status === 'failed' || status === 'cancelled'\n }\n return false\n}\n\nfunction isUsageType(type: string): boolean {\n return type === 'llm_call' || type === 'usage' || type === 'cost.usage'\n}\n\nfunction usageFromEnvironmentEvent(event: AgentEnvironmentEvent): {\n input: number\n output: number\n usd: number\n} {\n const usage = event.usage ?? tokenUsageFromData(event.data)\n return {\n input: finiteNumber(usage?.inputTokens) ?? 0,\n output: finiteNumber(usage?.outputTokens) ?? 0,\n usd:\n finiteNumber(usage?.cost) ??\n finiteNumber(event.data.costUsd) ??\n finiteNumber(event.data.totalCostUsd) ??\n 0,\n }\n}\n\nfunction tokenUsageFromData(data: Record<string, unknown>): TokenUsage | undefined {\n const usageRecord =\n data.usage && typeof data.usage === 'object'\n ? (data.usage as Record<string, unknown>)\n : data.tokenUsage && typeof data.tokenUsage === 'object'\n ? (data.tokenUsage as Record<string, unknown>)\n : data\n const inputTokens =\n finiteNumber(usageRecord.inputTokens) ??\n finiteNumber(usageRecord.tokensIn) ??\n finiteNumber(usageRecord.prompt_tokens)\n const outputTokens =\n finiteNumber(usageRecord.outputTokens) ??\n finiteNumber(usageRecord.tokensOut) ??\n finiteNumber(usageRecord.completion_tokens)\n const cost =\n finiteNumber(usageRecord.cost) ??\n finiteNumber(usageRecord.costUsd) ??\n finiteNumber(usageRecord.totalCostUsd) ??\n finiteNumber(data.costUsd) ??\n finiteNumber(data.totalCostUsd)\n if (inputTokens === undefined && outputTokens === undefined && cost === undefined)\n return undefined\n return {\n inputTokens: inputTokens ?? 0,\n outputTokens: outputTokens ?? 0,\n ...(cost !== undefined ? { cost } : {}),\n }\n}\n\nfunction mergeTokenUsage(\n left: TokenUsage | undefined,\n right: TokenUsage | undefined,\n): TokenUsage | undefined {\n if (!left) return right\n if (!right) return left\n return {\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n ...(left.cost !== undefined || right.cost !== undefined\n ? { cost: (left.cost ?? 0) + (right.cost ?? 0) }\n : {}),\n }\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\ntype PromptResultCompatInput = {\n response?: string\n success: boolean\n error?: string\n traceId?: string\n durationMs: number\n usage?: PromptResult['usage']\n}\n\nfunction promptResultCompat(\n input: PromptResultCompatInput,\n status: 'success' | 'failed',\n): PromptResult {\n // sandbox 0.8 omitted `status`; sandbox 0.9 requires it. Emit it at runtime\n // while keeping this adapter type-checkable across the supported peer range.\n return { ...input, status } as unknown as PromptResult\n}\n\nfunction promptResultFromAgentTurnResult(result: AgentTurnResult): PromptResult {\n return promptResultCompat(\n {\n response: result.text,\n success: result.success,\n durationMs: 0,\n ...(result.error ? { error: result.error } : {}),\n ...(result.usage ? { usage: result.usage } : {}),\n },\n result.success ? 'success' : 'failed',\n )\n}\n\nfunction agentTurnResultFromPromptResult(result: PromptResult): AgentTurnResult {\n const record = result as unknown as Record<string, unknown>\n const text =\n typeof record.response === 'string'\n ? record.response\n : typeof record.text === 'string'\n ? record.text\n : typeof record.finalText === 'string'\n ? record.finalText\n : ''\n const success = typeof record.success === 'boolean' ? record.success : true\n return {\n text,\n success,\n ...(typeof record.error === 'string' ? { error: record.error } : {}),\n usage: tokenUsageFromData(record),\n }\n}\n\nfunction sandboxDispatchResultFromSessionRef(session: AgentSessionRef): Record<string, unknown> {\n const hasStatus = session.metadata && Object.hasOwn(session.metadata, 'status')\n const status = hasStatus ? sessionStatusFromUnknown(session.metadata?.status) : 'running'\n return {\n sessionId: session.id,\n status,\n alreadyExisted: session.metadata?.alreadyExisted === true,\n }\n}\n\nfunction sessionRefFromSandboxDispatch(dispatched: unknown, providerName: string): AgentSessionRef {\n const record =\n dispatched && typeof dispatched === 'object'\n ? (dispatched as Record<string, unknown>)\n : undefined\n const id = record?.sessionId ?? record?.id\n if (typeof id !== 'string' || id.length === 0) {\n throw new ValidationError('sandboxClientAsProvider: dispatch returned no session id')\n }\n if (!record) {\n throw new ValidationError('sandboxClientAsProvider: dispatch returned no session record')\n }\n return {\n id,\n provider: providerName,\n metadata: {\n ...(record.status ? { status: record.status } : {}),\n ...(record.alreadyExisted !== undefined ? { alreadyExisted: record.alreadyExisted } : {}),\n },\n }\n}\n\nfunction execResultFromSandboxExecResult(result: SandboxExecResult): ExecResult {\n const record = result as unknown as Record<string, unknown>\n const exitCode = finiteNumber(record.exitCode) ?? finiteNumber(record.code)\n if (exitCode === undefined) {\n throw new ValidationError('sandboxClientAsProvider: exec returned no exit code')\n }\n return {\n exitCode,\n stdout: typeof record.stdout === 'string' ? record.stdout : '',\n stderr: typeof record.stderr === 'string' ? record.stderr : '',\n }\n}\n\nfunction statusFromUnknown(status: unknown): AgentEnvironmentStatus {\n if (status === 'pending' || status === 'provisioning' || status === 'running') return status\n if (status === 'stopped' || status === 'failed' || status === 'expired') return status\n if (status === 'completed') return 'stopped'\n if (status === 'cancelled') return 'stopped'\n return 'unknown'\n}\n\nfunction sessionStatusFromUnknown(status: unknown): AgentSessionStatus | null {\n if (status === 'completed' || status === 'cancelled') return status\n return statusFromUnknown(status)\n}\n\nfunction readBoxStatus(box: SandboxInstance): unknown {\n return (box as unknown as { status?: unknown }).status\n}\n\nfunction readBoxMetadata(box: SandboxInstance): Record<string, unknown> | undefined {\n const metadata = (box as unknown as { metadata?: unknown }).metadata\n return metadata && typeof metadata === 'object'\n ? (metadata as Record<string, unknown>)\n : undefined\n}\n\nasync function maybeRefresh(box: SandboxInstance): Promise<void> {\n const refresh = (box as unknown as { refresh?: () => Promise<void> }).refresh\n if (typeof refresh === 'function') await refresh.call(box)\n}\n\nasync function destroyBox(box: SandboxInstance): Promise<void> {\n const deleteBox = (box as unknown as { delete?: () => Promise<void> }).delete\n if (typeof deleteBox === 'function') await deleteBox.call(box)\n}\n\nfunction placementInfoFromLoopPlacement(\n placement: LoopSandboxPlacement | undefined,\n box: SandboxInstance,\n): PlacementInfo {\n if (!placement) return { kind: 'sandbox', sandboxId: String(box.id) }\n return {\n kind: placement.kind === 'fleet' ? 'fleet' : 'sandbox',\n ...(placement.sandboxId ? { sandboxId: placement.sandboxId } : { sandboxId: String(box.id) }),\n ...(placement.fleetId ? { fleetId: placement.fleetId } : {}),\n ...(placement.machineId ? { machineId: placement.machineId } : {}),\n }\n}\n\nfunction defaultTangleSandboxCapabilities(): AgentEnvironmentCapabilities {\n return {\n profile: {\n namedProfiles: true,\n systemPrompt: true,\n instructions: true,\n tools: true,\n permissions: true,\n mcp: true,\n subagents: true,\n resources: {\n files: true,\n instructions: true,\n tools: true,\n skills: true,\n agents: true,\n commands: true,\n },\n hooks: true,\n modes: true,\n runtimeUpdate: true,\n validation: true,\n },\n streaming: { live: true, replay: true, detach: true, turnIdempotency: true },\n sessions: { continue: true, list: true, messages: true },\n workspace: { read: true, write: true, exec: true, git: true, upload: true, download: true },\n branching: { checkpoint: true, fork: true },\n placement: true,\n usage: true,\n confidential: true,\n }\n}\n\nfunction mergeAbortSignals(a: AbortSignal, b: AbortSignal): AbortSignal {\n const controller = new AbortController()\n const abort = () => controller.abort()\n if (a.aborted || b.aborted) controller.abort()\n else {\n a.addEventListener('abort', abort, { once: true })\n b.addEventListener('abort', abort, { once: true })\n }\n return controller.signal\n}\n\nfunction contentRef(prefix: string, value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(value) ?? String(value)\n } catch {\n str = String(value)\n }\n let hash = 0x811c9dc5\n for (let i = 0; i < str.length; i += 1) {\n hash ^= str.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return `${prefix}:${(hash >>> 0).toString(16).padStart(8, '0')}`\n}\n\nfunction hasGet(\n client: SandboxClient,\n): client is SandboxClient & { get(id: string): Promise<SandboxInstance | null> } {\n return typeof (client as { get?: unknown }).get === 'function'\n}\n\nfunction hasList(\n client: SandboxClient,\n): client is SandboxClient & { list(options?: unknown): Promise<SandboxInstance[]> } {\n return typeof (client as { list?: unknown }).list === 'function'\n}\n\nfunction hasDispatchPrompt(box: SandboxInstance): box is SandboxInstance & {\n dispatchPrompt(message: string | InputPart[], options?: PromptOptions): Promise<unknown>\n} {\n return typeof (box as { dispatchPrompt?: unknown }).dispatchPrompt === 'function'\n}\n\nfunction hasSession(\n box: SandboxInstance,\n): box is SandboxInstance & { session(id: string): SandboxSessionLike } {\n return typeof (box as { session?: unknown }).session === 'function'\n}\n\nfunction hasRead(box: SandboxInstance): box is SandboxInstance & {\n read(path: string, options?: { sessionId?: string }): Promise<string>\n} {\n return typeof (box as { read?: unknown }).read === 'function'\n}\n\nfunction hasWrite(\n box: SandboxInstance,\n): box is SandboxInstance & { write(path: string, content: string): Promise<void> } {\n return typeof (box as { write?: unknown }).write === 'function'\n}\n\nfunction hasExec(box: SandboxInstance): box is SandboxInstance & {\n exec(command: string, options?: unknown): Promise<SandboxExecResult>\n} {\n return typeof (box as { exec?: unknown }).exec === 'function'\n}\n\ninterface SandboxSessionLike {\n readonly id: string\n status(): Promise<unknown | null>\n events(options?: { since?: string; signal?: AbortSignal }): AsyncIterable<SandboxEvent>\n result(): Promise<PromptResult>\n prompt(message: string | InputPart[], options?: PromptOptions): Promise<PromptResult>\n cancel(): Promise<void>\n}\n"],"mappings":";;;;;AAmDA,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAClC,YAAY,SAAiB,SAA+B;AAC1D,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AA6CO,SAAS,uCACd,YAAgD,CAAC,GACf;AAClC,QAAM,UAAU,oBAAI,IAAsC;AAE1D,QAAM,WAA6C;AAAA,IACjD,SAAS,UAAU,UAAU,CAAC,GAAS;AACrC,UAAI,CAAC,SAAS,MAAM;AAClB,cAAM,IAAI,gBAAgB,6DAA6D;AAAA,MACzF;AACA,UAAI,CAAC,QAAQ,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