@tangle-network/agent-runtime 0.90.1 → 0.92.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.
Files changed (86) hide show
  1. package/README.md +4 -2
  2. package/dist/agent.d.ts +3 -3
  3. package/dist/agent.js +88 -9
  4. package/dist/agent.js.map +1 -1
  5. package/dist/{mcp-serve-verifier-XsX8rkB9.d.ts → agentic-generator-B8oeE2Yv.d.ts} +6 -33
  6. package/dist/analyst-loop.d.ts +1 -1
  7. package/dist/candidate-execution/index.d.ts +104 -0
  8. package/dist/candidate-execution/index.js +34 -0
  9. package/dist/candidate-execution/index.js.map +1 -0
  10. package/dist/chunk-3BE7KTMU.js +1229 -0
  11. package/dist/chunk-3BE7KTMU.js.map +1 -0
  12. package/dist/chunk-3D2RHC4K.js +73 -0
  13. package/dist/chunk-3D2RHC4K.js.map +1 -0
  14. package/dist/chunk-3MDZX7YU.js +125 -0
  15. package/dist/chunk-3MDZX7YU.js.map +1 -0
  16. package/dist/{chunk-RYBVU4M3.js → chunk-6O5USWVH.js} +32 -1413
  17. package/dist/chunk-6O5USWVH.js.map +1 -0
  18. package/dist/chunk-6O73TRHW.js +142 -0
  19. package/dist/chunk-6O73TRHW.js.map +1 -0
  20. package/dist/{chunk-R2VAJGR3.js → chunk-7VJJJ2T2.js} +2 -2
  21. package/dist/chunk-A62TP7SK.js +4784 -0
  22. package/dist/chunk-A62TP7SK.js.map +1 -0
  23. package/dist/chunk-APVPRF4Y.js +2166 -0
  24. package/dist/chunk-APVPRF4Y.js.map +1 -0
  25. package/dist/{chunk-QK4DV5PR.js → chunk-AUEIDTR3.js} +2 -2
  26. package/dist/{chunk-OOL3675H.js → chunk-FRBHUNQ7.js} +2 -139
  27. package/dist/chunk-FRBHUNQ7.js.map +1 -0
  28. package/dist/{chunk-7ON74BQO.js → chunk-GDAQUFG6.js} +2 -2
  29. package/dist/{chunk-ZV4LXYCJ.js → chunk-I7WVPJBZ.js} +23 -1231
  30. package/dist/chunk-I7WVPJBZ.js.map +1 -0
  31. package/dist/{chunk-WRUSWK4F.js → chunk-IGGZGKJD.js} +3 -3
  32. package/dist/chunk-PH65PR4F.js +860 -0
  33. package/dist/chunk-PH65PR4F.js.map +1 -0
  34. package/dist/chunk-RSWM2ZKM.js +659 -0
  35. package/dist/chunk-RSWM2ZKM.js.map +1 -0
  36. package/dist/{chunk-BZF3KQ6G.js → chunk-VSWBYWFK.js} +4 -122
  37. package/dist/chunk-VSWBYWFK.js.map +1 -0
  38. package/dist/{completion-gate-DkAnUmpb.d.ts → completion-gate-BLaiN0-X.d.ts} +1 -1
  39. package/dist/{coordination-rRj5hjJK.d.ts → coordination-DxJ83oZA.d.ts} +12 -5
  40. package/dist/environment-provider.d.ts +2 -2
  41. package/dist/environment-provider.js +2 -1
  42. package/dist/improve-CUVCq7xg.d.ts +152 -0
  43. package/dist/{improvement-adapter-CDR8QNVM.d.ts → improvement-adapter-BieWeK5J.d.ts} +16 -0
  44. package/dist/index.d.ts +27 -291
  45. package/dist/index.js +70 -889
  46. package/dist/index.js.map +1 -1
  47. package/dist/intelligence.d.ts +160 -13
  48. package/dist/intelligence.js +535 -59
  49. package/dist/intelligence.js.map +1 -1
  50. package/dist/knowledge.d.ts +6 -6
  51. package/dist/knowledge.js +6 -4
  52. package/dist/lifecycle.d.ts +2 -1
  53. package/dist/lifecycle.js +5 -3
  54. package/dist/lifecycle.js.map +1 -1
  55. package/dist/{loop-runner-bin-DTbZVGfM.d.ts → loop-runner-bin-kKUNGLyV.d.ts} +2 -2
  56. package/dist/loop-runner-bin.d.ts +5 -5
  57. package/dist/loop-runner-bin.js +8 -5
  58. package/dist/loops.d.ts +16 -16
  59. package/dist/loops.js +47 -41
  60. package/dist/mcp/bin.js +6 -4
  61. package/dist/mcp/bin.js.map +1 -1
  62. package/dist/mcp/index.d.ts +8 -8
  63. package/dist/mcp/index.js +9 -6
  64. package/dist/mcp/index.js.map +1 -1
  65. package/dist/mcp-serve-verifier-Bg4C3p5S.d.ts +34 -0
  66. package/dist/{openai-tools-C4ZfUD4L.d.ts → openai-tools-E3woykz9.d.ts} +1 -1
  67. package/dist/prepare-Z08a4heC.d.ts +713 -0
  68. package/dist/profiles.d.ts +1 -1
  69. package/dist/{router-client-DJImUDlm.d.ts → sanitize-C9go6tXj.d.ts} +113 -1
  70. package/dist/{structural-rollout-MwlpgQ-6.d.ts → structural-rollout-DHGDbhvR.d.ts} +3 -3
  71. package/dist/{supervise-DPmYPk0j.d.ts → supervise-T2pazU3G.d.ts} +4 -4
  72. package/dist/{types-SyuwunY_.d.ts → types-B00NtbCs.d.ts} +1 -1
  73. package/dist/{types-eMNgWgFi.d.ts → types-DAdIm4AC.d.ts} +1 -1
  74. package/dist/{worktree-fanout-BDFQIO-Y.d.ts → worktree-fanout-BUb2Ag02.d.ts} +3 -3
  75. package/package.json +26 -36
  76. package/skills/build-with-agent-runtime/SKILL.md +1 -1
  77. package/dist/chunk-BZF3KQ6G.js.map +0 -1
  78. package/dist/chunk-IVGYLCFH.js +0 -381
  79. package/dist/chunk-IVGYLCFH.js.map +0 -1
  80. package/dist/chunk-OOL3675H.js.map +0 -1
  81. package/dist/chunk-RYBVU4M3.js.map +0 -1
  82. package/dist/chunk-ZV4LXYCJ.js.map +0 -1
  83. /package/dist/{chunk-R2VAJGR3.js.map → chunk-7VJJJ2T2.js.map} +0 -0
  84. /package/dist/{chunk-QK4DV5PR.js.map → chunk-AUEIDTR3.js.map} +0 -0
  85. /package/dist/{chunk-7ON74BQO.js.map → chunk-GDAQUFG6.js.map} +0 -0
  86. /package/dist/{chunk-WRUSWK4F.js.map → chunk-IGGZGKJD.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/improvement/improvement-driver.ts","../src/improvement/raw-trace-distiller.ts","../src/improvement/rollout-policy.ts","../src/improvement/improve.ts"],"sourcesContent":["/**\n *\n * `improvementDriver` — the ONE reflective/agentic improvement proposer for\n * agent-eval's improvement loop. It implements `SurfaceProposer` and owns\n * the candidate lifecycle (worktree create → generate → finalize/discard,\n * × populationSize); it delegates the only thing that genuinely varies — HOW\n * a candidate change is produced — to a pluggable `CandidateGenerator`.\n *\n * There is no separate \"analyst driver\" vs \"autoresearch driver\": those are\n * the SAME driver at two settings of a dial.\n * - cheap reflective path → `reflectiveGenerator` (shots=1, no sandbox;\n * applies pre-drafted patches)\n * - full agentic path → `agenticGenerator` (shots=N, multi-shot\n * verify-in-session loop; an agent reads code +\n * report, edits, and re-tries on verifier failure)\n * Both emit changes into a worktree the driver finalizes into a\n * `CodeSurface{ worktreeRef }` the loop measures on the holdout. See\n * agent-eval's `docs/design/self-improvement-engine.md`.\n *\n * @experimental\n */\n\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\nimport type {\n CodeSurface,\n LabeledScenarioStore,\n ProposeContext,\n SurfaceProposer,\n Worktree,\n WorktreeAdapter,\n} from '@tangle-network/agent-eval/campaign'\n\n/** The byte-producing seam — the ONE thing that differs between the cheap\n * reflective path and the full agentic path. A generator makes (uncommitted)\n * changes inside `worktreePath`; the driver commits them via the worktree\n * adapter's `finalize`. */\nexport interface CandidateGenerator {\n kind: string\n /** Whether this generator can produce a candidate from an EMPTY findings set\n * and no phase-2 report — i.e. it draws its change signal from the repo and\n * the raw-trace filesystem context on disk, not only from pre-summarized\n * findings. An agentic coder (`agenticGenerator`) sets this: the seed repo +\n * raw traces ARE the signal, so it must still run the full `populationSize`\n * when the distiller yielded nothing (this is the meta-harness contract — the\n * agent diagnoses from the raw traces itself). A patch-applier\n * (`reflectiveGenerator`) leaves it unset — with no findings there is no\n * patch to draft, so the driver short-circuits rather than spin up worktrees\n * for a guaranteed no-op. Default `false`. */\n proposesWithoutFindings?: boolean\n generate(args: {\n /** The candidate worktree — a fresh checkout of baseRef. Write changes here. */\n worktreePath: string\n /** Phase-2 research report (analyst findings + diff), opaque. */\n report: unknown\n /** Findings resolved from the report or the loop context. */\n findings: AnalystFinding[]\n /** Handle to all captured data, to ground the change. */\n dataset?: LabeledScenarioStore\n /** DEPTH: max iterations the generator may take (agentic uses this; the\n * reflective generator ignores it). */\n maxShots: number\n signal: AbortSignal\n }): Promise<{ applied: boolean; summary: string }>\n}\n\nexport interface ImprovementDriverOptions {\n worktree: WorktreeAdapter\n generator: CandidateGenerator\n /** Base ref candidate worktrees fork from. Default `main`. */\n baseRef?: string\n}\n\nexport interface ManagedImprovementDriver extends SurfaceProposer<AnalystFinding> {\n /** Remove every finalized candidate except explicitly retained winners. */\n cleanup(retainWorktreeRefs?: readonly string[]): Promise<void>\n}\n\n/** The one reflective/agentic improvement proposer (`SurfaceProposer`): owns the candidate worktree lifecycle and delegates HOW a change is produced to a pluggable `CandidateGenerator`. */\nexport function improvementDriver(opts: ImprovementDriverOptions): ManagedImprovementDriver {\n const baseRef = opts.baseRef ?? 'main'\n const finalized = new Map<string, Worktree>()\n\n return {\n kind: `improvement:${opts.generator.kind}`,\n async propose(ctx: ProposeContext<AnalystFinding>) {\n const findings = resolveFindings(ctx)\n // No findings AND no report AND a generator that can only act on findings\n // (the reflective patch-applier) — propose nothing rather than spin up\n // worktrees for a guaranteed no-op. An agentic coder draws its signal from\n // the repo + raw traces on disk, so it opts in via `proposesWithoutFindings`\n // and still runs the full populationSize even on an empty findings set —\n // otherwise the FIRST generation (whose seed findings are empty and whose\n // rawTraceDistiller has not run yet) would always generate ZERO candidates.\n if (\n findings.length === 0 &&\n ctx.report === undefined &&\n !opts.generator.proposesWithoutFindings\n ) {\n return []\n }\n\n const surfaces: CodeSurface[] = []\n for (let i = 0; i < ctx.populationSize; i++) {\n if (ctx.signal.aborted) break\n const wt = await opts.worktree.create({\n baseRef,\n label: `${opts.generator.kind}-gen${ctx.generation}-cand${i}`,\n })\n // Once a worktree exists it MUST be accounted for: finalized into a\n // surface, or discarded. A throw from generate()/finalize() must not\n // leak the worktree + branch — discard best-effort, then rethrow loud.\n try {\n const { applied, summary } = await opts.generator.generate({\n worktreePath: wt.path,\n report: ctx.report,\n findings,\n dataset: ctx.dataset,\n maxShots: ctx.maxImprovementShots ?? 1,\n signal: ctx.signal,\n })\n if (!applied) {\n await opts.worktree.discard(wt)\n continue\n }\n const surface = await opts.worktree.finalize(wt, summary)\n surfaces.push(surface)\n finalized.set(surface.worktreeRef, wt)\n } catch (err) {\n // Best-effort cleanup; never mask the original failure.\n await opts.worktree.discard(wt).catch(() => {})\n throw err\n }\n }\n return surfaces\n },\n async cleanup(retainWorktreeRefs = []) {\n const retained = new Set(retainWorktreeRefs)\n const errors: unknown[] = []\n for (const [worktreeRef, worktree] of finalized) {\n if (retained.has(worktreeRef)) continue\n try {\n await opts.worktree.discard(worktree)\n finalized.delete(worktreeRef)\n } catch (cause) {\n errors.push(cause)\n }\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, 'improvementDriver: failed to discard candidate worktrees')\n }\n },\n }\n}\n\n/** Phase-2 report carries `findings` when present; else fall back to the\n * loop's `ctx.findings`. The report is opaque to the substrate, so probe it\n * structurally. */\nfunction resolveFindings(ctx: ProposeContext<AnalystFinding>): AnalystFinding[] {\n const report = ctx.report\n if (report && typeof report === 'object' && 'findings' in report) {\n const f = (report as { findings: unknown }).findings\n if (Array.isArray(f) && f.length > 0) return f as AnalystFinding[]\n }\n return ctx.findings\n}\n","/**\n *\n * `rawTraceDistiller` — the meta-harness `analyzeGeneration` producer.\n *\n * The default `generationFailureDistiller` (in `improve.ts`) COMPRESSES each\n * generation's failing cells into ~400-char structured findings before the next\n * proposal round. That is the ACE-style recipe: a small summary is the proposer's\n * whole view of what went wrong. This producer does the opposite — the\n * meta-harness recipe (yoonholee.com/meta-harness): it does NOT summarize. It\n * points the coding-agent proposer at the generation's RAW run traces already on\n * disk under `runDir` — the durable per-cell `spans.jsonl` event logs,\n * `cached-result.json` scores, and any artifacts the substrate persisted — and\n * instructs the agent to `grep`/`cat`/`ls` them to diagnose the failures itself\n * (up to the harness's full context, ~millions of tokens, vs a ~400-char digest).\n *\n * It emits `AnalystFinding[]` so it drops into the SAME `opts.analyzeGeneration`\n * slot the default distiller uses, and renders through the same\n * `agenticGenerator` prompt path (`claim` + `recommended_action`). The findings\n * carry ABSOLUTE paths — the coding harness runs with `cwd` = a candidate\n * worktree, so a relative `runDir` would be uncattable from there.\n *\n * Runtime layout it reads (written by agent-eval's optimization loop):\n *\n * <runDir>/gen-<N>/ ← the generation dir (input.runDir)\n * candidate-<i>/ ← one candidate campaign (campaign.runDir)\n * <sanitized cellId>/ ← one scenario×rep cell\n * spans.jsonl ← the raw trace (event/span log)\n * cached-result.json ← the cell's score + artifact ref\n * <artifacts…> ← whatever the dispatch wrote\n *\n * @experimental\n */\n\nimport { type Dirent, existsSync, readdirSync } from 'node:fs'\nimport { basename, join, resolve } from 'node:path'\nimport { type AnalystFinding, makeFinding } from '@tangle-network/agent-eval'\nimport type { Scenario, SelfImproveOptions } from '@tangle-network/agent-eval/contract'\n\nconst ANALYST_ID = 'raw-trace-distiller'\n/** A cell counts as \"failing\" below this mean composite (matches the default\n * distiller's near-perfect threshold) or when it recorded an `error`. */\nconst PASS_THRESHOLD = 0.999\n\nexport interface RawTraceDistillerOptions {\n /** Anchor the emitted paths at this run root instead of the generation `runDir`\n * the loop passes in. Normally unset — each call points at that generation's\n * own directory (`input.runDir`). Pass an absolute path when you construct the\n * producer ahead of the loop and want a fixed anchor (e.g. a test fixture). */\n runDir?: string\n /** Max candidates to surface trace paths for, worst-scoring first. Default 12. */\n maxCandidates?: number\n /** Max failing cells to enumerate per candidate before collapsing the rest into\n * an \"ls the candidate dir\" pointer. Default 8. */\n maxCellsPerCandidate?: number\n /** Max concrete file paths to list per cell (the agent can always `ls` the dir\n * for the rest). Default 24. */\n maxFilesPerCell?: number\n /** Findings to fall back to when the generation had NO failing cells, so a\n * clean round never wipes the proposer's steering context. Mirrors the default\n * distiller's static-seed fallback. Default: a single instruction finding. */\n fallbackFindings?: unknown[]\n}\n\ninterface CellTrace {\n scenarioId: string\n composite: number\n error?: string\n cellDir: string\n files: string[]\n truncatedFiles: boolean\n}\n\n/**\n * Build an `analyzeGeneration` producer that feeds the proposer RAW-TRACE\n * FILESYSTEM CONTEXT — paths into the prior generation's real run traces plus a\n * grep/cat-to-diagnose instruction — instead of a pre-summarized digest.\n *\n * Drop-in for `opts.analyzeGeneration` on `improve()` / `selfImprove()`:\n *\n * await improve(profile, seedFindings, {\n * surface: 'code',\n * code: { repoRoot },\n * runDir: '/abs/run', // MUST be a real path — the traces live here\n * analyzeGeneration: rawTraceDistiller(),\n * scenarios, judge, agent,\n * })\n */\nexport function rawTraceDistiller<TScenario extends Scenario = Scenario, TArtifact = unknown>(\n options: RawTraceDistillerOptions = {},\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const maxCandidates = options.maxCandidates ?? 12\n const maxCellsPerCandidate = options.maxCellsPerCandidate ?? 8\n const maxFilesPerCell = options.maxFilesPerCell ?? 24\n\n return async (input) => {\n const genRoot = absoluteRunDir(options.runDir ?? input.runDir)\n const durable = isDurable(genRoot)\n\n // Rank candidates worst-first; the worst failures are the highest-signal\n // context for the next edit. Stable sort keeps equal-composite order.\n const ranked = [...input.candidates]\n .map((c) => ({\n surfaceHash: c.surfaceHash,\n composite: c.composite,\n campaignDir: absoluteRunDir(c.campaign.runDir),\n cells: failingCells(c.campaign, maxCellsPerCandidate, maxFilesPerCell),\n }))\n .sort((a, b) => a.composite - b.composite)\n .slice(0, maxCandidates)\n\n const totalFailingCells = ranked.reduce((n, c) => n + c.cells.length, 0)\n\n // A clean generation: keep the proposer's steering context rather than\n // wiping it (parity with the default distiller's static-seed fallback). An\n // EMPTY fallback array means there is no STATIC seed to preserve — it must NOT\n // wipe the context to nothing. Fall through to the default raw-trace\n // instruction so the meta-harness discipline stays live (the agent still\n // inspects the on-disk traces next round, and the finding's `raw-trace-context`\n // area keeps the agenticGenerator's diagnosis-evidence gate armed). A bare\n // `??` would return the empty array and silently disable both.\n if (totalFailingCells === 0) {\n if (options.fallbackFindings && options.fallbackFindings.length > 0) {\n return options.fallbackFindings\n }\n return [\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: 'info',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} had no failing cells. The full raw run traces are on disk under ${genRoot}.`,\n recommended_action: `To keep improving, grep/cat the raw traces under ${genRoot} (per-cell spans.jsonl + cached-result.json) to find the weakest passing runs, then make a targeted harness-code edit.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: { generation: input.generation, runDir: genRoot, failingCells: 0 },\n }),\n ]\n }\n\n const findings: AnalystFinding[] = []\n\n // 1. The meta-harness instruction: diagnose from the RAW traces, not a digest.\n findings.push(\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: 'high',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} produced ${totalFailingCells} failing/low-scoring cell(s) across ${ranked.length} candidate(s). Their FULL RAW run traces are on disk under ${genRoot} — the actual event logs (spans.jsonl), scores (cached-result.json), and artifacts, not a summary.${\n durable\n ? ''\n : ' (WARNING: this run root does not exist on disk — it looks like an in-memory run; pass a real runDir to improve() to get raw-trace context.)'\n }`,\n recommended_action: `Do NOT rely on a pre-summarized finding. Before editing, DIAGNOSE from the raw traces: run \\`grep\\`/\\`cat\\`/\\`ls\\` over the trace files and directories named in the following findings to see exactly what each failing run did and why it scored low, then make the smallest harness-code edit that fixes the dominant failure. Start with \\`grep -rIn \"error\" ${genRoot}\\` then \\`cat\\` the spans.jsonl of the worst cell.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: {\n generation: input.generation,\n runDir: genRoot,\n failingCells: totalFailingCells,\n candidates: ranked.length,\n },\n }),\n )\n\n // 2. One finding per failing candidate: its campaign dir + the concrete raw\n // trace files to grep/cat.\n for (const cand of ranked) {\n if (cand.cells.length === 0) continue\n const scenarioList = cand.cells.map((c) => c.scenarioId).join(', ')\n const fileLines = cand.cells\n .map((c) => {\n const header = ` cell ${c.scenarioId} (composite ${c.composite.toFixed(3)}${\n c.error ? `, error: ${truncate(c.error, 160)}` : ''\n }) — dir ${c.cellDir}`\n const files = c.files.map((f) => ` - ${f}`).join('\\n')\n const more = c.truncatedFiles ? `\\n - …(ls ${c.cellDir} for the rest)` : ''\n return c.files.length > 0 ? `${header}\\n${files}${more}` : header\n })\n .join('\\n')\n\n findings.push(\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: cand.composite < 0.5 ? 'critical' : 'high',\n area: 'raw-trace-context',\n confidence: 1,\n subject: cand.surfaceHash,\n claim: `Candidate ${cand.surfaceHash} scored composite ${cand.composite.toFixed(3)} with ${cand.cells.length} failing cell(s) [${scenarioList}]. Its raw traces are under ${cand.campaignDir}.`,\n recommended_action: `grep/cat these raw trace files to diagnose WHY this candidate failed before editing:\\n${fileLines}\\nOr scan the whole candidate at once: \\`grep -rIn . ${cand.campaignDir}\\` and \\`ls -R ${cand.campaignDir}\\`.`,\n evidence_refs: [\n { kind: 'artifact', uri: cand.campaignDir },\n ...cand.cells.flatMap((c) =>\n c.files.map((f) => ({ kind: 'artifact' as const, uri: f })),\n ),\n ],\n metadata: {\n surfaceHash: cand.surfaceHash,\n composite: cand.composite,\n campaignDir: cand.campaignDir,\n cells: cand.cells.map((c) => ({\n scenarioId: c.scenarioId,\n composite: c.composite,\n cellDir: c.cellDir,\n files: c.files,\n ...(c.error ? { error: c.error } : {}),\n })),\n },\n }),\n )\n }\n\n return findings\n }\n}\n\n/** The failing cells of a candidate campaign, each with its on-disk trace files.\n * Mirrors the default distiller's per-cell composite (mean of judge composites,\n * 0 when a cell produced no judge score) and its failing predicate. */\nfunction failingCells(\n campaign: {\n runDir: string\n cells: ReadonlyArray<{\n cellId: string\n scenarioId: string\n error?: string\n judgeScores: Record<string, { composite?: number }>\n }>\n artifactsByPath?: Record<string, string>\n },\n maxCells: number,\n maxFiles: number,\n): CellTrace[] {\n const campaignDir = absoluteRunDir(campaign.runDir)\n const durable = isDurable(campaignDir)\n const out: CellTrace[] = []\n for (const cell of campaign.cells) {\n const scores = Object.values(cell.judgeScores ?? {})\n const composite =\n scores.length === 0\n ? 0\n : scores.reduce((sum, s) => sum + (s.composite ?? 0), 0) / scores.length\n if (!cell.error && composite >= PASS_THRESHOLD) continue\n\n const cellDir = join(campaignDir, sanitizeCellId(cell.cellId))\n const artifactPaths = artifactPathsForCell(campaign.artifactsByPath, cell.cellId)\n const discovered = durable ? listTraceFiles(cellDir) : []\n // Canonical anchors the substrate always writes, kept even when a mem:// run\n // never flushed them to disk (so the agent still learns the expected path).\n const canonical = [join(cellDir, 'spans.jsonl'), join(cellDir, 'cached-result.json')]\n const files = dedupeSorted([...discovered, ...artifactPaths, ...canonical])\n\n out.push({\n scenarioId: cell.scenarioId,\n composite: Number(composite.toFixed(3)),\n ...(cell.error ? { error: cell.error } : {}),\n cellDir,\n files: files.slice(0, maxFiles),\n truncatedFiles: files.length > maxFiles,\n })\n if (out.length >= maxCells) break\n }\n return out\n}\n\n/** Absolute paths of artifacts the campaign recorded for a cell. `artifactsByPath`\n * is keyed `${cellId}/${relPath}` → absolute path. */\nfunction artifactPathsForCell(\n artifactsByPath: Record<string, string> | undefined,\n cellId: string,\n): string[] {\n if (!artifactsByPath) return []\n const prefix = `${cellId}/`\n return Object.entries(artifactsByPath)\n .filter(([key]) => key.startsWith(prefix))\n .map(([, absPath]) => resolve(absPath))\n}\n\n/** Real files directly under `dir` and one level of sub-directories (artifacts\n * are sometimes nested). Absolute paths, sorted. `[]` when the dir is absent,\n * stale, unreadable, or contains symlinked dirs — trace context is advisory and\n * the canonical anchors below still tell the proposer where to inspect. */\nfunction listTraceFiles(dir: string): string[] {\n const out: string[] = []\n for (const entry of safeReadDir(dir)) {\n const full = join(dir, entry.name)\n if (entry.isFile()) {\n out.push(full)\n } else if (!entry.isSymbolicLink() && entry.isDirectory()) {\n for (const sub of safeReadDir(full)) {\n if (sub.isFile()) out.push(join(full, sub.name))\n }\n }\n }\n return out\n}\n\nfunction safeReadDir(dir: string): Dirent[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n } catch {\n return []\n }\n}\n\n/** Substrate cell-dir sanitization — must match agent-eval's\n * `cellId.replace(/[^a-zA-Z0-9_-]/g, '_')` so the computed dir matches disk. */\nfunction sanitizeCellId(cellId: string): string {\n return cellId.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\n/** A run root is durable (has real files) when it is not an in-memory sentinel\n * and exists on disk. `mem://` runs keep everything in-process — no traces. */\nfunction isDurable(runDir: string): boolean {\n return !runDir.startsWith('mem://') && existsSync(runDir)\n}\n\n/** Resolve a run dir to absolute (the coding harness runs from a worktree cwd, so\n * relative paths are uncattable there). `mem://` sentinels pass through untouched. */\nfunction absoluteRunDir(runDir: string): string {\n return runDir.startsWith('mem://') ? runDir : resolve(runDir)\n}\n\nfunction dedupeSorted(paths: string[]): string[] {\n return [...new Set(paths)].sort((a, b) => {\n // Group by directory then filename for a stable, readable listing.\n const da = a.slice(0, a.length - basename(a).length)\n const db = b.slice(0, b.length - basename(b).length)\n return da === db ? basename(a).localeCompare(basename(b)) : da.localeCompare(db)\n })\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n","/**\n * `rolloutPolicyProposer` — the `'rollout-policy'` surface for `improve()`: the\n * inference-time `StructuralRolloutPolicy` dials { k, repairRounds, testgen } as a\n * held-out-gated optimizable surface.\n *\n * Why this seam: agent-eval's loop contract is already generic — `MutableSurface`\n * admits any string, documented as \"serialized tool config\" — so the policy rides\n * the SAME serialize→propose→gate→parse-back cycle the tools/mcp/hooks surfaces\n * use. No agent-eval changes; the only net-new piece is this proposer.\n *\n * Why deterministic: prompt-wording proposals are a measured zero on this stack,\n * and the policy space is tiny and fully enumerable. The proposer emits bounded\n * single-dial neighbors (k±2 in [1,10], repairRounds±1 in [0,3], testgen±3 in\n * [0,10], ≤4 per generation) and lets the held-out gate do ALL the deciding — an\n * LLM proposer would add cost and nondeterminism with nothing to reason about.\n *\n * Persistence: the policy lives in `profile.extensions['structural-rollout']`\n * (AgentProfile's designed slot for runtime-specific config). A gated winner is\n * written back there by `improve()`, the same profile-field write-back every other\n * config surface gets; `structuralRolloutPolicyFromProfile` is the read side a\n * runtime caller feeds to `structuralRollout({ policy })`.\n *\n * @experimental\n */\n\nimport type {\n MutableSurface,\n ProposeContext,\n ProposedCandidate,\n SurfaceProposer,\n} from '@tangle-network/agent-eval/campaign'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n defaultStructuralRolloutPolicy,\n type StructuralRolloutPolicy,\n} from '../runtime/structural-rollout'\n\n/** The profile extensions namespace the policy persists under. */\nexport const ROLLOUT_POLICY_EXTENSION = 'structural-rollout'\n\n/** Proposal bounds per dial. These are the SEARCH bounds (what the proposer may\n * explore), chosen so every reachable value is a measured-sane recipe: k=1 is the\n * low-compute preset, testgen=0 disables check authoring, repairRounds caps where\n * the measured increment flattens (+1–3pp beyond round 2). */\nexport const ROLLOUT_POLICY_BOUNDS = {\n k: { min: 1, max: 10, step: 2 },\n repairRounds: { min: 0, max: 3, step: 1 },\n testgen: { min: 0, max: 10, step: 3 },\n} as const\n\n/** Max candidates per generation — the search space is 3 dials, so a small\n * neighborhood per generation converges without burning gate budget. */\nconst MAX_CANDIDATES_PER_GENERATION = 4\n\nconst clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v))\n\nconst isBoundedInt = (v: unknown, min: number): v is number =>\n typeof v === 'number' && Number.isInteger(v) && v >= min\n\n/** Parse a serialized policy surface. Defensive by design — the proposer reads\n * `ctx.currentSurface`, which the loop types as `string | CodeSurface`. Returns\n * `undefined` (never throws) for non-strings, malformed JSON, or a shape that\n * violates the policy's own invariants: the no-op signal. Unknown dials are\n * dropped; `diverse`/`temperature` ride through untouched (the proposer never\n * mutates them — `diverse` is a measured paired null). */\nexport function parseRolloutPolicy(surface: MutableSurface): StructuralRolloutPolicy | undefined {\n if (typeof surface !== 'string' || surface.trim().length === 0) return undefined\n let raw: unknown\n try {\n raw = JSON.parse(surface)\n } catch {\n return undefined\n }\n return normalizeRolloutPolicy(raw)\n}\n\n/** Normalize an untyped policy bag (a parsed surface or a profile extension) into\n * a full `StructuralRolloutPolicy`, defaults merged. Returns `undefined` when any\n * present dial violates the policy invariants (mirrors `resolvePolicy`: integer\n * k ≥ 1, repairRounds ≥ 0, testgen ≥ 0) — a corrupt config must read as \"not\n * configured\", never as a fabricated recipe. */\nexport function normalizeRolloutPolicy(raw: unknown): StructuralRolloutPolicy | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const bag = raw as Record<string, unknown>\n const k = bag.k ?? defaultStructuralRolloutPolicy.k\n const repairRounds = bag.repairRounds ?? defaultStructuralRolloutPolicy.repairRounds\n const testgen = bag.testgen ?? defaultStructuralRolloutPolicy.testgen\n if (!isBoundedInt(k, 1) || !isBoundedInt(repairRounds, 0) || !isBoundedInt(testgen, 0)) {\n return undefined\n }\n return {\n k,\n repairRounds,\n testgen,\n ...(typeof bag.diverse === 'boolean' ? { diverse: bag.diverse } : {}),\n ...(typeof bag.temperature === 'number' ? { temperature: bag.temperature } : {}),\n }\n}\n\n/** Stable serialization — dial order is fixed so identical policies produce\n * identical surfaces (the loop dedupes/hashes candidates by surface content). */\nexport function serializeRolloutPolicy(policy: StructuralRolloutPolicy): string {\n return JSON.stringify({\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n ...(policy.temperature !== undefined ? { temperature: policy.temperature } : {}),\n })\n}\n\n/** Read the persisted policy off the profile. `undefined` when the profile does\n * not opt into structural rollout — the improve() surface no-ops then, because\n * tuning dials nothing consumes would ship dead config. */\nexport function structuralRolloutPolicyFromProfile(\n profile: AgentProfile,\n): StructuralRolloutPolicy | undefined {\n const bag = profile.extensions?.[ROLLOUT_POLICY_EXTENSION]\n if (bag === undefined) return undefined\n return normalizeRolloutPolicy(bag)\n}\n\n/** Persist a policy into the profile's extensions namespace. Shallow copy; never\n * mutates the input profile (the applyWinnerToProfile contract). */\nexport function applyRolloutPolicyToProfile(\n profile: AgentProfile,\n policy: StructuralRolloutPolicy,\n): AgentProfile {\n const bag: Record<string, unknown> = {\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n ...(policy.temperature !== undefined ? { temperature: policy.temperature } : {}),\n }\n return {\n ...profile,\n extensions: { ...profile.extensions, [ROLLOUT_POLICY_EXTENSION]: bag },\n }\n}\n\n/** All bounded single-dial neighbors of `policy`, in a fixed priority order: k\n * first (selection breadth carries 85–92% of the measured effect), then\n * repairRounds, then testgen. Steps clamp to the dial's bounds; clamped-to-no-op\n * and duplicate policies are dropped. */\nexport function enumerateNeighborPolicies(\n policy: StructuralRolloutPolicy,\n): StructuralRolloutPolicy[] {\n const moves: Array<{ dial: 'k' | 'repairRounds' | 'testgen'; delta: 1 | -1 }> = [\n { dial: 'k', delta: 1 },\n { dial: 'k', delta: -1 },\n { dial: 'repairRounds', delta: 1 },\n { dial: 'repairRounds', delta: -1 },\n { dial: 'testgen', delta: 1 },\n { dial: 'testgen', delta: -1 },\n ]\n const seen = new Set<string>([serializeRolloutPolicy(policy)])\n const neighbors: StructuralRolloutPolicy[] = []\n for (const move of moves) {\n const bounds = ROLLOUT_POLICY_BOUNDS[move.dial]\n const next = clamp(policy[move.dial] + move.delta * bounds.step, bounds.min, bounds.max)\n const candidate: StructuralRolloutPolicy = { ...policy, [move.dial]: next }\n const key = serializeRolloutPolicy(candidate)\n if (seen.has(key)) continue\n seen.add(key)\n neighbors.push(candidate)\n }\n return neighbors\n}\n\nfunction candidateLabel(base: StructuralRolloutPolicy, next: StructuralRolloutPolicy): string {\n for (const dial of ['k', 'repairRounds', 'testgen'] as const) {\n if (next[dial] !== base[dial]) return `${dial} ${base[dial]}→${next[dial]}`\n }\n return 'unchanged'\n}\n\n/**\n * The deterministic `SurfaceProposer` for the `'rollout-policy'` surface.\n *\n * Each generation: parse the current policy surface, enumerate its bounded\n * single-dial neighbors, and return at most `min(populationSize, 4)` of them,\n * rotating the enumeration window by generation so successive generations explore\n * different neighbors when nothing promoted. Proposes NOTHING when the surface\n * carries no policy (the profile never opted in) — an empty proposal is the\n * loop-native no-op, mirroring `improvementDriver`'s no-findings behavior.\n */\nexport function rolloutPolicyProposer(): SurfaceProposer {\n return {\n kind: 'rollout-policy',\n async propose(ctx: ProposeContext): Promise<ProposedCandidate[]> {\n const policy = parseRolloutPolicy(ctx.currentSurface)\n if (!policy) return []\n const neighbors = enumerateNeighborPolicies(policy)\n if (neighbors.length === 0) return []\n const cap = Math.max(1, Math.min(ctx.populationSize, MAX_CANDIDATES_PER_GENERATION))\n const start = (ctx.generation * cap) % neighbors.length\n const window: StructuralRolloutPolicy[] = []\n for (let i = 0; i < Math.min(cap, neighbors.length); i += 1) {\n window.push(neighbors[(start + i) % neighbors.length] as StructuralRolloutPolicy)\n }\n return window.map((candidate) => ({\n surface: serializeRolloutPolicy(candidate),\n label: candidateLabel(policy, candidate),\n rationale:\n 'bounded single-dial neighbor of the current structuralRollout policy; ' +\n 'the held-out gate decides (deterministic enumeration — the dial space is tiny ' +\n 'and prompt-style reflective proposals are a measured zero here)',\n }))\n },\n }\n}\n","/**\n *\n * `improve` — the ONE public, surface-pluggable RSI verb.\n *\n * A thin facade over agent-eval's `selfImprove` (the held-out-gated closed\n * loop). It removes the two things a caller otherwise has to know to drive the\n * loop by hand: WHICH `MutableSurface` of the profile is being optimized, and\n * WHICH `SurfaceProposer` mutates that surface. You name a `surface`; the\n * facade picks the matching default proposer, extracts the baseline surface from\n * the profile, runs `selfImprove`, and (on a ship verdict) writes the promoted\n * winner back into the corresponding profile field.\n *\n * - `surface: 'prompt'` → `gepaProposer` mutates `profile.prompt.systemPrompt`.\n * - `surface: 'skills'` → `skillOptProposer` mutates a skills document string.\n * - `surface: 'agent-profile'` → caller-supplied proposer mutates the complete\n * canonical AgentProfile JSON in one candidate.\n * - `surface: 'rollout-policy'` → `rolloutPolicyProposer` mutates the\n * inference-time `StructuralRolloutPolicy` dials ({ k, repairRounds, testgen })\n * persisted in `profile.extensions['structural-rollout']` — deterministic\n * bounded neighbor enumeration; the held-out gate does the deciding. No-op\n * (nothing proposed, nothing shipped) when the profile has no such extension.\n * - `surface` ∈ {`tools`, `mcp`, `hooks`, `subagents`, `workflow`, `agent-profile`, `code`} → no zero-config default\n * proposer exists (a code/config proposer needs caller-supplied wiring — a\n * worktree repo root, a candidate generator, a serializer). The facade\n * requires an explicit `opts.generator` for these and throws a `ConfigError`\n * otherwise. This is a designed boundary, not a missing default: there is\n * no safe value the facade could invent for those surfaces. Code also\n * requires `opts.code.repoRoot` so its incumbent is a real isolated checkout.\n *\n * Everything else (`scenarios`, `judge`, `agent`, `budget`, `llm`) passes\n * straight through to `selfImprove`.\n *\n * @experimental\n */\n\nimport {\n gepaProposer,\n gitWorktreeAdapter,\n skillOptProposer,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type CodeSurface,\n type MutableSurface,\n type Scenario,\n type SelfImproveBudget,\n type SelfImproveLlm,\n type SelfImproveOptions,\n type SelfImproveResult,\n type SurfaceProposer,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../errors'\nimport type { LocalHarness } from '../mcp/local-harness'\nimport { assertModelAllowed } from '../runtime/supervise/model-policy'\nimport { agenticGenerator, type Verifier } from './agentic-generator'\nimport {\n type CandidateGenerator,\n improvementDriver,\n type ManagedImprovementDriver,\n} from './improvement-driver'\nimport { rawTraceDistiller } from './raw-trace-distiller'\nimport {\n applyRolloutPolicyToProfile,\n normalizeRolloutPolicy,\n rolloutPolicyProposer,\n serializeRolloutPolicy,\n structuralRolloutPolicyFromProfile,\n} from './rollout-policy'\n\n/** The agent-profile lever `improve` optimizes. Mirrors the AgentProfile-law\n * profile levers; `code` is the implementation-tier surface, `rollout-policy`\n * the inference-time structuralRollout dials\n * (`profile.extensions['structural-rollout']`). */\nexport type ImproveSurface =\n | 'prompt'\n | 'skills'\n | 'tools'\n | 'mcp'\n | 'hooks'\n | 'subagents'\n | 'workflow'\n | 'agent-profile'\n | 'code'\n | 'rollout-policy'\n\nexport type ImproveOptions<TScenario extends Scenario, TArtifact> = Omit<\n SelfImproveOptions<TScenario, TArtifact>,\n 'analyzeGeneration' | 'baselineSurface' | 'findings' | 'gate' | 'proposer'\n> & {\n /** Which profile lever to optimize. Default `'prompt'`. Selects the default\n * generator + the baseline-surface extraction shape. */\n surface?: ImproveSurface\n /** The `SurfaceProposer` that mutates the surface. When unset, the facade\n * picks the default for `surface` (`gepaProposer` for prompt, `skillOptProposer`\n * for skills); surfaces with no default REQUIRE this (fail-loud otherwise). */\n generator?: SurfaceProposer\n /** Gate mode. `'holdout'` (default) runs the held-out promotion gate;\n * `'none'` is a baseline-only run (`budget.generations = 0`). */\n gate?: 'holdout' | 'none'\n /** Restrict the run to this subset of models. When set, the reflection model\n * (`llm.model`, or the default when unset) must be a member, or `improve()` throws\n * a `ConfigError` before the generator is built. Unset = unrestricted. */\n allowedModels?: readonly string[]\n /** Per-generation findings producer passthrough (see selfImprove.analyzeGeneration).\n * DEFAULT: the built-in failure distiller — after each generation it turns the\n * worst-scoring/errored cells into structured findings ({ scenario, composite,\n * notes, error }) for the NEXT proposal round, so the proposer reasons over what\n * actually failed instead of a static seed. Pass your own producer (e.g. a\n * trace-analyst over the runDir's traces) to replace it; pass `null` to disable\n * and keep the static `findings` all the way through. */\n analyzeGeneration?: SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration'] | null\n /** META-HARNESS mode: instead of the ~400-char distilled findings, feed the\n * proposer RAW-TRACE FILESYSTEM CONTEXT — the PATHS into the prior generation's\n * real run traces under `runDir` (per-cell `spans.jsonl` event logs +\n * `cached-result.json` scores + artifacts) plus a `grep`/`cat`-to-diagnose\n * instruction — so the coding agent reads the actual failures itself rather than\n * a pre-summary. Requires a REAL `runDir` (that is where the traces live).\n * Ignored when `analyzeGeneration` is set explicitly (that wins) or is `null`\n * (disabled). Equivalent to `analyzeGeneration: rawTraceDistiller()`; this flag\n * is the one-line enable. Default `false` (the distiller stays the default). */\n rawTraceContext?: boolean\n /** CODE-surface wiring: name `surface: 'code'`, point at a repo, and the\n * facade assembles the whole candidate pipeline — an isolated incumbent plus git worktrees\n * (`gitWorktreeAdapter`) driven by `improvementDriver` with the full agentic\n * generator (a real coding harness edits each candidate worktree; a `verify`\n * hook gates candidates before they are ever measured). Ignored when\n * `opts.generator` is supplied. Required for every code run because a real\n * repository and base ref are necessary to measure the incumbent. */\n code?: ImproveCodeOptions\n /** SKILLS-surface wiring for real skill-DOCUMENT optimization. Without this,\n * `surface: 'skills'` optimizes the profile's skills REFS array (file pointers)\n * — which `skillOptProposer` (a document patcher) cannot meaningfully edit.\n * Provide the document CONTENT to optimize + a `writeBack` to persist the\n * shipped winner (the profile ref points at a file the caller owns). This is\n * what makes skillOpt reachable through improve(). */\n skills?: ImproveSkillsOptions\n /** Custom held-back-exam decision. The string `gate` above controls whether\n * the exam runs; this callback controls how its evidence decides promotion. */\n promotionGate?: SelfImproveOptions<TScenario, TArtifact>['gate']\n}\n\nexport interface ImproveSkillsOptions {\n /** The skill document's current text — the baseline `skillOptProposer` patches. */\n document: string\n /** Persist the shipped winner document (write the file the profile ref points at).\n * Called only on a ship verdict. When omitted, the winner is still returned in\n * `result.raw.winner.surface` for the caller to materialize. */\n writeBack?: (winnerDocument: string) => void\n}\n\nexport interface ImproveCodeOptions {\n /** Repo root candidate worktrees fork from. */\n repoRoot: string\n /** Base ref candidates fork from. Default `main`. */\n baseRef?: string\n /** Directory worktrees are created under. Default `<repoRoot>/.worktrees`. */\n worktreeDir?: string\n /** Coding harness the agentic generator runs in each worktree. Default `claude`. */\n harness?: LocalHarness\n /** Verify a candidate worktree before it becomes a measurable surface; failures\n * feed the next shot (see `agenticGenerator.verify` / `commandVerifier`). */\n verify?: Verifier\n /** Per-shot wall-clock timeout for the harness (ms). */\n timeoutMs?: number\n /** Byte-producer override — the test seam and the escape hatch for custom\n * candidate production. When set, `harness`/`verify`/`timeoutMs` are unused. */\n generator?: CandidateGenerator\n}\n\nexport interface ImproveResult<TScenario extends Scenario, TArtifact> {\n /** The profile after improvement: the winner surface applied back into the\n * matching field when the gate shipped, else the input profile unchanged. */\n profile: AgentProfile\n /** True when `gateDecision === 'ship'`. */\n shipped: boolean\n /** Held-out lift (`winner − baseline` composite). */\n lift: number\n /** The five-valued gate verdict from `selfImprove`. */\n gateDecision: SelfImproveResult<TScenario, TArtifact>['gateDecision']\n /** Full `selfImprove` result for advanced inspection. */\n raw: SelfImproveResult<TScenario, TArtifact>\n}\n\n/** Default model id for the reflective drivers when `llm.model` is unset — a model the Tangle\n * router actually serves (callers should pass their own `llm.model`). */\nconst defaultReflectionModel = 'deepseek-v4-flash'\nconst workflowExtension = 'tangle.workflow'\n\n/** The reflective proposers (`gepaProposer`/`skillOptProposer`) take a full\n * `LlmClientOptions`; `SelfImproveLlm` is the thin user-facing subset. */\nfunction llmClientOptions(llm: SelfImproveLlm | undefined): { baseUrl?: string; apiKey?: string } {\n return { baseUrl: llm?.baseUrl, apiKey: llm?.apiKey }\n}\n\n/** The default proposer for a surface, or `undefined` when the surface has no\n * zero-config default (the caller must supply `opts.generator`). */\nfunction defaultGeneratorFor(\n surface: ImproveSurface,\n llm: SelfImproveLlm | undefined,\n): SurfaceProposer | undefined {\n const model = llm?.model ?? defaultReflectionModel\n switch (surface) {\n case 'prompt':\n return gepaProposer({ llm: llmClientOptions(llm), model, target: 'agent system prompt' })\n case 'skills':\n return skillOptProposer({ llm: llmClientOptions(llm), model, target: 'agent skill document' })\n case 'rollout-policy':\n // Deterministic bounded enumeration — no LLM, so `llm` is unused here.\n return rolloutPolicyProposer()\n default:\n return undefined\n }\n}\n\n/** Extract the baseline surface a driver mutates from the profile field that\n * backs `surface`. `prompt`/`skills` are string surfaces; the config surfaces\n * serialize the matching profile record. */\nfunction baselineSurfaceFor(\n profile: AgentProfile,\n surface: ImproveSurface,\n skills?: ImproveSkillsOptions,\n): MutableSurface {\n switch (surface) {\n case 'prompt':\n return profile.prompt?.systemPrompt ?? ''\n case 'skills':\n // With a document supplied, optimize its CONTENT (the real skillOpt path);\n // otherwise fall back to the refs-array surface for back-compat.\n return skills?.document ?? JSON.stringify(profile.resources?.skills ?? [])\n case 'tools':\n return JSON.stringify(profile.tools ?? {})\n case 'mcp':\n return JSON.stringify(profile.mcp ?? {})\n case 'hooks':\n return JSON.stringify(profile.hooks ?? {})\n case 'subagents':\n return JSON.stringify(profile.subagents ?? {})\n case 'workflow':\n return JSON.stringify(profile.extensions?.[workflowExtension] ?? {})\n case 'agent-profile':\n return JSON.stringify(profile)\n case 'rollout-policy': {\n // Empty surface when the profile never opted into structural rollout: the\n // proposer reads it as \"propose nothing\", so the loop runs baseline-only and\n // holds — tuning dials nothing consumes would ship dead config.\n const policy = structuralRolloutPolicyFromProfile(profile)\n return policy ? serializeRolloutPolicy(policy) : ''\n }\n case 'code':\n throw new ConfigError(\n 'improve(): code requires the isolated baseline created from opts.code.repoRoot',\n )\n }\n}\n\n/** The default `analyzeGeneration`: distill each generation's failing cells into\n * findings for the next proposal round. Deliberately dependency-free — judge notes\n * and errors are already the domain's own diagnosis (executable gates put their\n * reasons there); a trace-analyst can replace this wholesale via\n * `opts.analyzeGeneration`. Falls back to the static seed findings when the\n * generation had no failures, so a clean round never wipes the seed context. */\nfunction generationFailureDistiller<TScenario extends Scenario, TArtifact>(\n staticFindings: unknown[],\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const CAP = 12\n return async (input) => {\n const failures: Array<{ scenario: string; composite: number; notes: string; error?: string }> =\n []\n for (const candidate of input.candidates) {\n for (const rawCell of candidate.campaign.cells) {\n const cell = rawCell as unknown as Record<string, unknown>\n const scenario = String(cell.scenarioId ?? 'unknown')\n const error = typeof cell.error === 'string' ? cell.error : undefined\n const judgeScores =\n cell.judgeScores && typeof cell.judgeScores === 'object'\n ? Object.values(\n cell.judgeScores as Record<string, { composite?: number; notes?: string }>,\n )\n : []\n const composite =\n judgeScores.length === 0\n ? 0\n : judgeScores.reduce((sum, j) => sum + (j.composite ?? 0), 0) / judgeScores.length\n if (!error && composite >= 0.999) continue\n const notes = judgeScores\n .map((j) => j.notes)\n .filter((n): n is string => typeof n === 'string' && n.length > 0)\n .join('; ')\n .slice(0, 400)\n failures.push({\n scenario,\n composite: Number(composite.toFixed(3)),\n notes,\n ...(error ? { error: error.slice(0, 200) } : {}),\n })\n }\n }\n if (failures.length === 0) return staticFindings\n failures.sort((a, b) => a.composite - b.composite)\n return failures.slice(0, CAP)\n }\n}\n\ninterface PreparedCodeRun {\n baseline: CodeSurface\n proposer: SurfaceProposer\n cleanup(retainedWinner?: MutableSurface): Promise<void>\n}\n\nfunction isCodeSurface(surface: MutableSurface | undefined): surface is CodeSurface {\n return typeof surface === 'object' && surface !== null && surface.kind === 'code'\n}\n\n/** Create a clean incumbent checkout and the candidate producer for a code run. */\nasync function prepareCodeRun(\n code: ImproveCodeOptions,\n proposerOverride?: SurfaceProposer,\n): Promise<PreparedCodeRun> {\n const baseRef = code.baseRef ?? 'main'\n const worktree = gitWorktreeAdapter({\n repoRoot: code.repoRoot,\n ...(code.worktreeDir ? { worktreeDir: code.worktreeDir } : {}),\n })\n const baselineWorktree = await worktree.create({ baseRef, label: 'incumbent-baseline' })\n const baseline = await worktree.finalize(baselineWorktree, 'Incumbent code checkout')\n let managed: ManagedImprovementDriver | undefined\n if (!proposerOverride) {\n const generator =\n code.generator ??\n agenticGenerator({\n ...(code.harness ? { harness: code.harness } : {}),\n ...(code.verify ? { verify: code.verify } : {}),\n ...(code.timeoutMs ? { timeoutMs: code.timeoutMs } : {}),\n })\n managed = improvementDriver({ worktree, generator, baseRef })\n }\n const proposer = proposerOverride ?? managed\n if (!proposer) {\n throw new ConfigError('improve(): code candidate generator could not be constructed')\n }\n\n return {\n baseline,\n proposer,\n async cleanup(retainedWinner) {\n const errors: unknown[] = []\n try {\n await managed?.cleanup(isCodeSurface(retainedWinner) ? [retainedWinner.worktreeRef] : [])\n } catch (cause) {\n errors.push(cause)\n }\n try {\n await worktree.discard(baselineWorktree)\n } catch (cause) {\n errors.push(cause)\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, 'improve(): failed to clean code improvement worktrees')\n }\n },\n }\n}\n\n/** Parse a JSON winner surface (`skills`/`tools`/`mcp`/`hooks`/`subagents`/`workflow`/`agent-profile`) with a typed,\n * contextual error. A malformed generator output must fail loud here, not throw\n * a raw `SyntaxError` to the caller after a ship verdict. */\nfunction parseWinnerJson<T>(winner: string, surface: ImproveSurface): T {\n try {\n return JSON.parse(winner) as T\n } catch (cause) {\n throw new ConfigError(\n `improve(): the shipped '${surface}' winner is not valid JSON, so it cannot be applied back to the profile: ${\n (cause as Error).message\n }`,\n )\n }\n}\n\n/** Apply a promoted winner surface back into the profile field for `surface`.\n * Returns a shallow copy; never mutates the input profile. */\nfunction applyWinnerToProfile(\n profile: AgentProfile,\n surface: ImproveSurface,\n winner: MutableSurface,\n): AgentProfile {\n // Only string surfaces map cleanly back onto a profile field. A `CodeSurface`\n // winner (the `code` lever) is a worktree ref, not a profile value — the\n // caller materializes it from `raw.winner.surface`; the returned profile is\n // unchanged for that lever.\n if (typeof winner !== 'string') return profile\n let candidate: AgentProfile\n switch (surface) {\n case 'prompt':\n candidate = { ...profile, prompt: { ...profile.prompt, systemPrompt: winner } }\n break\n case 'skills':\n candidate = {\n ...profile,\n resources: { ...profile.resources, skills: parseWinnerJson(winner, surface) },\n }\n break\n case 'tools':\n candidate = { ...profile, tools: parseWinnerJson(winner, surface) }\n break\n case 'mcp':\n candidate = { ...profile, mcp: parseWinnerJson(winner, surface) }\n break\n case 'hooks':\n candidate = { ...profile, hooks: parseWinnerJson(winner, surface) }\n break\n case 'subagents':\n candidate = { ...profile, subagents: parseWinnerJson(winner, surface) }\n break\n case 'workflow':\n candidate = {\n ...profile,\n extensions: {\n ...profile.extensions,\n [workflowExtension]: parseWinnerJson(winner, surface),\n },\n }\n break\n case 'agent-profile':\n candidate = parseWinnerJson(winner, surface)\n break\n case 'rollout-policy': {\n // Parse + re-validate the winner against the policy's own invariants — a\n // custom generator's malformed dial must fail loud, not persist silently.\n const policy = normalizeRolloutPolicy(parseWinnerJson(winner, surface))\n if (!policy) {\n throw new ConfigError(\n `improve(): the shipped 'rollout-policy' winner is not a valid StructuralRolloutPolicy ` +\n `(integer k >= 1, repairRounds >= 0, testgen >= 0), so it cannot be applied: ${winner}`,\n )\n }\n candidate = applyRolloutPolicyToProfile(profile, policy)\n break\n }\n case 'code':\n return profile\n }\n const parsed = agentProfileSchema.safeParse(candidate)\n if (!parsed.success) {\n throw new ConfigError(\n `improve(): the shipped '${surface}' winner does not produce a valid AgentProfile: ${parsed.error.message}`,\n )\n }\n return parsed.data\n}\n\n/**\n * Run the held-out-gated self-improvement loop on ONE profile surface.\n *\n * @example Optimize the system prompt, default holdout gate:\n *\n * const out = await improve(profile, findings, {\n * surface: 'prompt',\n * scenarios,\n * judge,\n * agent: (surface, scenario, ctx) => runAgent(surface, scenario, ctx.signal),\n * })\n * if (out.shipped) deploy(out.profile)\n */\nexport async function improve<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n findings: unknown[],\n opts: ImproveOptions<TScenario, TArtifact>,\n): Promise<ImproveResult<TScenario, TArtifact>> {\n const {\n surface = 'prompt',\n gate = 'holdout',\n generator,\n allowedModels,\n rawTraceContext,\n code,\n skills,\n promotionGate,\n analyzeGeneration,\n ...sharedOptions\n } = opts\n\n const parsedProfile = agentProfileSchema.safeParse(profile)\n if (!parsedProfile.success) {\n throw new ConfigError(\n `improve(): input is not a valid AgentProfile: ${parsedProfile.error.message}`,\n )\n }\n if (surface === 'skills' && !generator && !skills) {\n throw new ConfigError(\n 'improve(): the default skills optimizer requires opts.skills.document; pass the skill text or an explicit generator that understands resource refs',\n )\n }\n const usesReflectionModel = !generator && (surface === 'prompt' || surface === 'skills')\n if (usesReflectionModel) {\n assertModelAllowed(sharedOptions.llm?.model ?? defaultReflectionModel, allowedModels)\n }\n\n let preparedCode: PreparedCodeRun | undefined\n if (surface === 'code') {\n if (!code) {\n throw new ConfigError(\n \"improve(): surface 'code' requires opts.code.repoRoot so the incumbent can run from an isolated checkout\",\n )\n }\n preparedCode = await prepareCodeRun(code, generator)\n }\n const proposer =\n preparedCode?.proposer ?? generator ?? defaultGeneratorFor(surface, sharedOptions.llm)\n if (!proposer) {\n throw new ConfigError(\n `improve(): surface '${surface}' has no default generator — pass opts.generator (a SurfaceProposer) explicitly`,\n )\n }\n\n const budget: SelfImproveBudget =\n gate === 'none' ? { ...sharedOptions.budget, generations: 0 } : { ...sharedOptions.budget }\n\n let raw: SelfImproveResult<TScenario, TArtifact>\n try {\n raw = await selfImprove<TScenario, TArtifact>({\n ...sharedOptions,\n baselineSurface: preparedCode?.baseline ?? baselineSurfaceFor(profile, surface, skills),\n proposer,\n budget,\n findings,\n ...(promotionGate !== undefined ? { gate: promotionGate } : {}),\n ...(analyzeGeneration === null\n ? {}\n : {\n analyzeGeneration:\n analyzeGeneration ??\n (rawTraceContext\n ? rawTraceDistiller<TScenario, TArtifact>({ fallbackFindings: findings })\n : generationFailureDistiller<TScenario, TArtifact>(findings)),\n }),\n })\n } catch (cause) {\n if (!preparedCode) throw cause\n try {\n await preparedCode.cleanup()\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n 'improve(): code improvement failed and its worktrees could not be cleaned',\n )\n }\n throw cause\n }\n\n const shipped = raw.gateDecision === 'ship'\n await preparedCode?.cleanup(shipped ? raw.winner.surface : undefined)\n // When a skill DOCUMENT was optimized, the winner is document text — persist it\n // via writeBack (the profile ref points at the caller's file, unchanged) rather\n // than parsing it as a refs array. Otherwise use the standard field write-back.\n const usedSkillDocument = surface === 'skills' && skills !== undefined\n if (shipped && usedSkillDocument && typeof raw.winner.surface === 'string') {\n skills?.writeBack?.(raw.winner.surface)\n }\n const nextProfile =\n shipped && !usedSkillDocument\n ? applyWinnerToProfile(profile, surface, raw.winner.surface)\n : profile\n\n return { profile: nextProfile, shipped, lift: raw.lift, gateDecision: raw.gateDecision, raw }\n}\n"],"mappings":";;;;;;;;;;;;;;AA8EO,SAAS,kBAAkB,MAA0D;AAC1F,QAAM,UAAU,KAAK,WAAW;AAChC,QAAM,YAAY,oBAAI,IAAsB;AAE5C,SAAO;AAAA,IACL,MAAM,eAAe,KAAK,UAAU,IAAI;AAAA,IACxC,MAAM,QAAQ,KAAqC;AACjD,YAAM,WAAW,gBAAgB,GAAG;AAQpC,UACE,SAAS,WAAW,KACpB,IAAI,WAAW,UACf,CAAC,KAAK,UAAU,yBAChB;AACA,eAAO,CAAC;AAAA,MACV;AAEA,YAAM,WAA0B,CAAC;AACjC,eAAS,IAAI,GAAG,IAAI,IAAI,gBAAgB,KAAK;AAC3C,YAAI,IAAI,OAAO,QAAS;AACxB,cAAM,KAAK,MAAM,KAAK,SAAS,OAAO;AAAA,UACpC;AAAA,UACA,OAAO,GAAG,KAAK,UAAU,IAAI,OAAO,IAAI,UAAU,QAAQ,CAAC;AAAA,QAC7D,CAAC;AAID,YAAI;AACF,gBAAM,EAAE,SAAS,QAAQ,IAAI,MAAM,KAAK,UAAU,SAAS;AAAA,YACzD,cAAc,GAAG;AAAA,YACjB,QAAQ,IAAI;AAAA,YACZ;AAAA,YACA,SAAS,IAAI;AAAA,YACb,UAAU,IAAI,uBAAuB;AAAA,YACrC,QAAQ,IAAI;AAAA,UACd,CAAC;AACD,cAAI,CAAC,SAAS;AACZ,kBAAM,KAAK,SAAS,QAAQ,EAAE;AAC9B;AAAA,UACF;AACA,gBAAM,UAAU,MAAM,KAAK,SAAS,SAAS,IAAI,OAAO;AACxD,mBAAS,KAAK,OAAO;AACrB,oBAAU,IAAI,QAAQ,aAAa,EAAE;AAAA,QACvC,SAAS,KAAK;AAEZ,gBAAM,KAAK,SAAS,QAAQ,EAAE,EAAE,MAAM,MAAM;AAA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,IAAI,OAAO,UAAU,MAAS;AAIpE,QAAM,oBAAoB,YAAY,YAAY,WAAW;AAC7D,MAAI,WAAW,qBAAqB,OAAO,IAAI,OAAO,YAAY,UAAU;AAC1E,YAAQ,YAAY,IAAI,OAAO,OAAO;AAAA,EACxC;AACA,QAAM,cACJ,WAAW,CAAC,oBACR,qBAAqB,SAAS,SAAS,IAAI,OAAO,OAAO,IACzD;AAEN,SAAO,EAAE,SAAS,aAAa,SAAS,MAAM,IAAI,MAAM,cAAc,IAAI,cAAc,IAAI;AAC9F;","names":[]}
@@ -1,112 +1,6 @@
1
- // src/runtime/util.ts
2
- async function deleteBoxSafe(box) {
3
- if (!box || typeof box.delete !== "function") return true;
4
- try {
5
- await box.delete();
6
- return true;
7
- } catch {
8
- return false;
9
- }
10
- }
11
- function randomSuffix(len = 8) {
12
- return Math.random().toString(36).slice(2, 2 + len);
13
- }
14
- function randomUuid() {
15
- return crypto.randomUUID();
16
- }
17
- function abortError() {
18
- const err = new Error("aborted");
19
- err.name = "AbortError";
20
- return err;
21
- }
22
- function throwAbort() {
23
- throw abortError();
24
- }
25
- function throwIfAborted(signal) {
26
- if (signal?.aborted) throw abortError();
27
- }
28
- function isAbortError(err) {
29
- return err instanceof Error && err.name === "AbortError";
30
- }
31
- function sleep(ms, signal) {
32
- return new Promise((resolve) => {
33
- if (signal?.aborted) {
34
- resolve();
35
- return;
36
- }
37
- let onAbort;
38
- const timer = setTimeout(() => {
39
- if (onAbort && signal) signal.removeEventListener("abort", onAbort);
40
- resolve();
41
- }, ms);
42
- if (signal) {
43
- onAbort = () => {
44
- clearTimeout(timer);
45
- resolve();
46
- };
47
- signal.addEventListener("abort", onAbort, { once: true });
48
- }
49
- });
50
- }
51
- function withTimeout(promise, ms) {
52
- return new Promise((resolve) => {
53
- const timer = setTimeout(() => resolve(void 0), ms);
54
- promise.then(
55
- (value) => {
56
- clearTimeout(timer);
57
- resolve(value);
58
- },
59
- () => {
60
- clearTimeout(timer);
61
- resolve(void 0);
62
- }
63
- );
64
- });
65
- }
66
- function stringifySafe(value, opts = {}) {
67
- let s;
68
- try {
69
- if (typeof value === "string") {
70
- s = value;
71
- } else {
72
- const json = opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);
73
- s = json ?? String(value);
74
- }
75
- } catch {
76
- s = String(value);
77
- }
78
- if (opts.max !== void 0 && s.length > opts.max) return `${s.slice(0, opts.max)}\u2026`;
79
- return s;
80
- }
81
- function zeroTokenUsage() {
82
- return { input: 0, output: 0 };
83
- }
84
- function addTokenUsage(acc, delta) {
85
- acc.input += delta.input ?? 0;
86
- acc.output += delta.output ?? 0;
87
- }
88
- async function mapWithConcurrency(items, limit, fn) {
89
- const bound = Math.max(1, Math.floor(limit));
90
- const results = new Array(items.length);
91
- let next = 0;
92
- let failed = false;
93
- const worker = async () => {
94
- while (!failed) {
95
- const i = next;
96
- next += 1;
97
- if (i >= items.length) return;
98
- try {
99
- results[i] = await fn(items[i], i);
100
- } catch (err) {
101
- failed = true;
102
- throw err;
103
- }
104
- }
105
- };
106
- const workerCount = Math.min(bound, items.length);
107
- await Promise.all(Array.from({ length: workerCount }, () => worker()));
108
- return results;
109
- }
1
+ import {
2
+ zeroTokenUsage
3
+ } from "./chunk-3MDZX7YU.js";
110
4
 
111
5
  // src/runtime/environment-provider.ts
112
6
  var ValidationError = class extends Error {
@@ -904,22 +798,10 @@ function hasFork(box) {
904
798
  }
905
799
 
906
800
  export {
907
- deleteBoxSafe,
908
- randomSuffix,
909
- randomUuid,
910
- throwAbort,
911
- throwIfAborted,
912
- isAbortError,
913
- sleep,
914
- withTimeout,
915
- stringifySafe,
916
- zeroTokenUsage,
917
- addTokenUsage,
918
- mapWithConcurrency,
919
801
  createAgentEnvironmentProviderRegistry,
920
802
  resolveAgentEnvironmentProvider,
921
803
  providerAsSandboxClient,
922
804
  sandboxClientAsProvider,
923
805
  providerAsExecutor
924
806
  };
925
- //# sourceMappingURL=chunk-BZF3KQ6G.js.map
807
+ //# sourceMappingURL=chunk-VSWBYWFK.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 ...(hasCheckpoint(box)\n ? {\n async checkpoint(options?: CheckpointRequest): Promise<CheckpointRef> {\n const result = await box.checkpoint(options as never)\n return { id: checkpointIdFromResult(result), provider: providerName }\n },\n }\n : {}),\n ...(hasFork(box)\n ? {\n async fork(checkpoint: CheckpointRef, options?: ForkRequest): Promise<AgentEnvironment> {\n const forked = await box.fork(checkpoint.id, options as never)\n return sandboxInstanceAsEnvironment(forked, providerName, client)\n },\n }\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 checkpointIdFromResult(result: unknown): string {\n const record = result && typeof result === 'object' ? (result as Record<string, unknown>) : {}\n const id = record.checkpointId ?? record.id\n if (typeof id !== 'string' || id.length === 0) {\n throw new ValidationError('sandboxClientAsProvider: checkpoint returned no checkpoint id')\n }\n return id\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\nfunction hasCheckpoint(\n box: SandboxInstance,\n): box is SandboxInstance & { checkpoint(options?: unknown): Promise<unknown> } {\n return typeof (box as { checkpoint?: unknown }).checkpoint === 'function'\n}\n\nfunction hasFork(box: SandboxInstance): box is SandboxInstance & {\n fork(checkpointId: string, options?: unknown): Promise<SandboxInstance>\n} {\n return typeof (box as { fork?: unknown }).fork === '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,WAAW,QAAQ,IAAI,SAAS,IAAI,GAAG;AAClD,cAAM,IAAI;AAAA,UACR,kDAAkD,SAAS,IAAI;AAAA,QACjE;AAAA,MACF;AACA,cAAQ,IAAI,SAAS,MAAM,QAAQ;AAAA,IACrC;AAAA,IACA,IAAI,MAAe;AACjB,aAAO,QAAQ,IAAI,IAAI;AAAA,IACzB;AAAA,IACA,IAAI,MAA4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AW;AACpB;AAEA,SAAS,WAAW,QAAgB,OAAwB;AAC1D,MAAI;AACJ,MAAI;AACF,UAAM,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;AAAA,EAC7C,QAAQ;AACN,UAAM,OAAO,KAAK;AAAA,EACpB;AACA,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GAAG;AACtC,YAAQ,IAAI,WAAW,CAAC;AACxB,WAAO,KAAK,KAAK,MAAM,QAAU;AAAA,EACnC;AACA,SAAO,GAAG,MAAM,KAAK,SAAS,GAAG,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC;AAChE;AAEA,SAAS,OACP,QACgF;AAChF,SAAO,OAAQ,OAA6B,QAAQ;AACtD;AAEA,SAAS,QACP,QACmF;AACnF,SAAO,OAAQ,OAA8B,SAAS;AACxD;AAEA,SAAS,kBAAkB,KAEzB;AACA,SAAO,OAAQ,IAAqC,mBAAmB;AACzE;AAEA,SAAS,WACP,KACsE;AACtE,SAAO,OAAQ,IAA8B,YAAY;AAC3D;AAEA,SAAS,QAAQ,KAEf;AACA,SAAO,OAAQ,IAA2B,SAAS;AACrD;AAEA,SAAS,SACP,KACkF;AAClF,SAAO,OAAQ,IAA4B,UAAU;AACvD;AAEA,SAAS,QAAQ,KAEf;AACA,SAAO,OAAQ,IAA2B,SAAS;AACrD;AAEA,SAAS,cACP,KAC8E;AAC9E,SAAO,OAAQ,IAAiC,eAAe;AACjE;AAEA,SAAS,QAAQ,KAEf;AACA,SAAO,OAAQ,IAA2B,SAAS;AACrD;","names":[]}
@@ -1,5 +1,5 @@
1
1
  import { L as LocalHarness } from './local-harness-dcD5WTTr.js';
2
- import { c as Executor } from './types-eMNgWgFi.js';
2
+ import { c as Executor } from './types-DAdIm4AC.js';
3
3
 
4
4
  /**
5
5
  *
@@ -1,11 +1,11 @@
1
- import { E as ExecutorFactory, h as ExecutorRegistry, e as Spend, A as Agent, S as Scope, a as ResultBlobStore, B as Budget } from './types-eMNgWgFi.js';
1
+ import { E as ExecutorFactory, h as ExecutorRegistry, e as Spend, A as Agent, S as Scope, a as ResultBlobStore, B as Budget } from './types-DAdIm4AC.js';
2
2
  import { AgentProfile } from '@tangle-network/agent-interface';
3
3
  import { U as UiLens, a as UiFinding, C as CoderTask } from './substrate-DO2GHNg2.js';
4
- import { S as SandboxClient, E as ExecCtx, f as LoopTraceEmitter, d as LoopTraceEvent, A as AgentRunSpec } from './types-SyuwunY_.js';
4
+ import { S as SandboxClient, E as ExecCtx, h as LoopTraceEmitter, g as LoopTraceEvent, b as RuntimeStreamEvent, e as AgentRunSpec } from './types-B00NtbCs.js';
5
5
  import { BackendType, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox';
6
6
  import { AgentEvalError } from '@tangle-network/agent-eval';
7
- import { b as ToolSpec, R as RouterConfig } from './router-client-DJImUDlm.js';
8
- import { G as GitRunner, a as WorktreeCheckRunner, D as DeliverableSpec } from './completion-gate-DkAnUmpb.js';
7
+ import { b as ToolSpec, c as RuntimeTelemetryOptions, R as RouterConfig } from './sanitize-C9go6tXj.js';
8
+ import { G as GitRunner, a as WorktreeCheckRunner, D as DeliverableSpec } from './completion-gate-BLaiN0-X.js';
9
9
  import { L as LocalHarness } from './local-harness-dcD5WTTr.js';
10
10
  import { ProviderExecutorOptions, AgentEnvironmentProviderRegistry } from './environment-provider.js';
11
11
  import { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider';
@@ -570,6 +570,7 @@ declare function composeLoopTraceEmitters(...emitters: ReadonlyArray<LoopTraceEm
570
570
  * The exporter accepts both raw OtelSpan objects and LoopTraceEvents
571
571
  * (which get converted to OTLP spans automatically).
572
572
  */
573
+
573
574
  interface OtelExportConfig {
574
575
  /** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */
575
576
  endpoint?: string;
@@ -628,6 +629,12 @@ declare function loopEventToOtelSpan(event: {
628
629
  timestamp: number;
629
630
  payload: object;
630
631
  }, traceId: string, parentSpanId?: string): OtelSpan;
632
+ interface RuntimeEventOtelOptions extends RuntimeTelemetryOptions {
633
+ /** Final customer redactor applied after the schema-aware runtime sanitizer. */
634
+ redact?: (value: unknown) => unknown;
635
+ }
636
+ /** Convert normalized runtime events into lossless, redacted child spans. */
637
+ declare function buildRuntimeEventOtelSpans(events: ReadonlyArray<RuntimeStreamEvent>, traceId: string, parentSpanId?: string, options?: RuntimeEventOtelOptions): OtelSpan[];
631
638
  /**
632
639
  * Sink-neutral node in a reconstructed loop span tree. The root node's
633
640
  * `parentSpanId` is `undefined` — sinks decide how to parent it (the OTEL
@@ -2314,4 +2321,4 @@ interface CoordinationTools {
2314
2321
  /** Build the driver's MCP tools over a live scope. */
2315
2322
  declare function createCoordinationTools(opts: CoordinationToolsOptions): CoordinationTools;
2316
2323
 
2317
- export { type DelegationStatus as $, type AnalystRegistry as A, type DelegateResearchArgs as B, type CappedDelegationTrace as C, type DelegationExecutor as D, type ExecutorConfig as E, type FleetHandle as F, type DelegateResearchConfig as G, type DelegateResearchResult as H, type DelegateResult as I, type DelegateRunCtx as J, type DelegateUiAuditConfig as K, type DelegateUiAuditRoute as L, type MakeWorkerAgent as M, type DelegationError as N, type DelegationFeedbackSnapshot as O, type DelegationHistoryEntry as P, DelegationPersistenceError as Q, type DelegationProfile as R, type DelegationProgress as S, type DelegationRecord as T, type UiAuditorDelegate as U, type DelegationResultPayload as V, type DelegationResumeContext as W, type DelegationResumeDriver as X, type DelegationResumeTick as Y, type DelegationRunContext as Z, DelegationStateCorruptError as _, DelegationTaskQueue as a, validateDelegateArgs as a$, type DelegationStore as a0, type DelegationTaskQueueOptions as a1, type DelegationTraceCaps as a2, type DelegationTraceCollector as a3, type DelegationTraceSpan as a4, type DetachedSessionDelegateOptions as a5, type DetachedSessionRefParts as a6, type DetachedTurn as a7, type DetachedTurnResumeDriverOptions as a8, type DetachedWinnerSelection as a9, type SubmitInput as aA, type SubmitOutput as aB, type TraceContext as aC, type UiAuditorDelegationOutput as aD, buildDelegationTraceSpans as aE, capDelegationTrace as aF, coderTaskFromArgs as aG, composeLoopTraceEmitters as aH, createCoordinationTools as aI, createDelegateHandler as aJ, createDelegationTraceCollector as aK, createDetachedTurnResumeDriver as aL, createFleetWorkspaceExecutor as aM, createInProcessTransport as aN, createMcpServer as aO, createPropagatingTraceEmitter as aP, createSiblingSandboxExecutor as aQ, detachedSessionDelegate as aR, detachedTurnEvents as aS, eventToSnapshot as aT, formatDetachedSessionRef as aU, hashIdempotencyInput as aV, parseDetachedSessionRef as aW, readTraceContextFromEnv as aX, runDetachedTurn as aY, settleDetachedCoderTurn as aZ, traceContextToEnv as a_, type DriveTurnCapableBox as aa, type DriveTurnTick as ab, type FeedbackEvent as ac, type FeedbackRating as ad, type FeedbackRefersTo as ae, FileDelegationStore as af, type FileDelegationStoreOptions as ag, type FleetWorkspaceExecutorOptions as ah, InMemoryDelegationStore as ai, InMemoryFeedbackStore as aj, type JsonRpcMessage as ak, type JsonRpcResponse as al, type McpServer as am, type McpServerOptions as an, type McpToolDescriptor as ao, type McpTransport as ap, type Question as aq, type QuestionDecision as ar, type QuestionPolicy as as, type QuestionRecord as at, type ResearchOutputShape as au, type ResearchSource as av, type RunDetachedTurnOptions as aw, type SettleDetachedCoderTurnOptions as ax, type SettledWorker as ay, type SiblingSandboxExecutorOptions as az, type FeedbackStore as b, type EvalRunEvent as b0, type EvalRunGeneration as b1, type EvalRunsExportConfig as b2, type EvalRunsExportResult as b3, INTELLIGENCE_WIRE_VERSION as b4, type LoopSpanNode as b5, type OtelAttribute as b6, type OtelExportConfig as b7, type OtelExporter as b8, type OtelSpan as b9, buildLoopOtelSpans as ba, buildLoopSpanNodes as bb, createOtelExporter as bc, exportEvalRuns as bd, loopEventToOtelSpan as be, type BusEvent as bf, type BusRecord as bg, type BusStats as bh, type EventBus as bi, type ProviderSeam as bj, type PublishOptions as bk, cliWorktreeExecutor as bl, createEventBus as bm, createExecutor as bn, createExecutorRegistry as bo, type DelegateFeedbackResult as c, type DelegateFeedbackArgs as d, type DelegateUiAuditArgs as e, type DelegateUiAuditResult as f, type DelegationHistoryResult as g, type DelegationHistoryArgs as h, type DelegationStatusResult as i, type DelegationStatusArgs as j, type CoderDelegate as k, type CoderReview as l, type CoderReviewer as m, type CoordinationEvent as n, type CoordinationTools as o, type CoordinationToolsOptions as p, DELEGATE_DESCRIPTION as q, DELEGATE_INPUT_SCHEMA as r, DELEGATE_TOOL_NAME as s, DELEGATION_TRACE_MAX_BYTES as t, DELEGATION_TRACE_MAX_SPANS as u, type DelegateArgs as v, type DelegateCodeArgs as w, type DelegateCodeConfig as x, type DelegateCodeResult as y, type DelegateHandlerOptions as z };
2324
+ export { type DelegationStatus as $, type AnalystRegistry as A, type DelegateResearchArgs as B, type CappedDelegationTrace as C, type DelegationExecutor as D, type ExecutorConfig as E, type FleetHandle as F, type DelegateResearchConfig as G, type DelegateResearchResult as H, type DelegateResult as I, type DelegateRunCtx as J, type DelegateUiAuditConfig as K, type DelegateUiAuditRoute as L, type MakeWorkerAgent as M, type DelegationError as N, type DelegationFeedbackSnapshot as O, type DelegationHistoryEntry as P, DelegationPersistenceError as Q, type DelegationProfile as R, type DelegationProgress as S, type DelegationRecord as T, type UiAuditorDelegate as U, type DelegationResultPayload as V, type DelegationResumeContext as W, type DelegationResumeDriver as X, type DelegationResumeTick as Y, type DelegationRunContext as Z, DelegationStateCorruptError as _, DelegationTaskQueue as a, validateDelegateArgs as a$, type DelegationStore as a0, type DelegationTaskQueueOptions as a1, type DelegationTraceCaps as a2, type DelegationTraceCollector as a3, type DelegationTraceSpan as a4, type DetachedSessionDelegateOptions as a5, type DetachedSessionRefParts as a6, type DetachedTurn as a7, type DetachedTurnResumeDriverOptions as a8, type DetachedWinnerSelection as a9, type SubmitInput as aA, type SubmitOutput as aB, type TraceContext as aC, type UiAuditorDelegationOutput as aD, buildDelegationTraceSpans as aE, capDelegationTrace as aF, coderTaskFromArgs as aG, composeLoopTraceEmitters as aH, createCoordinationTools as aI, createDelegateHandler as aJ, createDelegationTraceCollector as aK, createDetachedTurnResumeDriver as aL, createFleetWorkspaceExecutor as aM, createInProcessTransport as aN, createMcpServer as aO, createPropagatingTraceEmitter as aP, createSiblingSandboxExecutor as aQ, detachedSessionDelegate as aR, detachedTurnEvents as aS, eventToSnapshot as aT, formatDetachedSessionRef as aU, hashIdempotencyInput as aV, parseDetachedSessionRef as aW, readTraceContextFromEnv as aX, runDetachedTurn as aY, settleDetachedCoderTurn as aZ, traceContextToEnv as a_, type DriveTurnCapableBox as aa, type DriveTurnTick as ab, type FeedbackEvent as ac, type FeedbackRating as ad, type FeedbackRefersTo as ae, FileDelegationStore as af, type FileDelegationStoreOptions as ag, type FleetWorkspaceExecutorOptions as ah, InMemoryDelegationStore as ai, InMemoryFeedbackStore as aj, type JsonRpcMessage as ak, type JsonRpcResponse as al, type McpServer as am, type McpServerOptions as an, type McpToolDescriptor as ao, type McpTransport as ap, type Question as aq, type QuestionDecision as ar, type QuestionPolicy as as, type QuestionRecord as at, type ResearchOutputShape as au, type ResearchSource as av, type RunDetachedTurnOptions as aw, type SettleDetachedCoderTurnOptions as ax, type SettledWorker as ay, type SiblingSandboxExecutorOptions as az, type FeedbackStore as b, type EvalRunEvent as b0, type EvalRunGeneration as b1, type EvalRunsExportConfig as b2, type EvalRunsExportResult as b3, INTELLIGENCE_WIRE_VERSION as b4, type LoopSpanNode as b5, type OtelAttribute as b6, type OtelExportConfig as b7, type OtelExporter as b8, type OtelSpan as b9, type RuntimeEventOtelOptions as ba, buildLoopOtelSpans as bb, buildLoopSpanNodes as bc, buildRuntimeEventOtelSpans as bd, createOtelExporter as be, exportEvalRuns as bf, loopEventToOtelSpan as bg, type BusEvent as bh, type BusRecord as bi, type BusStats as bj, type EventBus as bk, type ProviderSeam as bl, type PublishOptions as bm, cliWorktreeExecutor as bn, createEventBus as bo, createExecutor as bp, createExecutorRegistry as bq, type DelegateFeedbackResult as c, type DelegateFeedbackArgs as d, type DelegateUiAuditArgs as e, type DelegateUiAuditResult as f, type DelegationHistoryResult as g, type DelegationHistoryArgs as h, type DelegationStatusResult as i, type DelegationStatusArgs as j, type CoderDelegate as k, type CoderReview as l, type CoderReviewer as m, type CoordinationEvent as n, type CoordinationTools as o, type CoordinationToolsOptions as p, DELEGATE_DESCRIPTION as q, DELEGATE_INPUT_SCHEMA as r, DELEGATE_TOOL_NAME as s, DELEGATION_TRACE_MAX_BYTES as t, DELEGATION_TRACE_MAX_SPANS as u, type DelegateArgs as v, type DelegateCodeArgs as w, type DelegateCodeConfig as x, type DelegateCodeResult as y, type DelegateHandlerOptions as z };
@@ -2,8 +2,8 @@ import { AgentProfile, AgentProfileValidationResult } from '@tangle-network/agen
2
2
  import { CreateAgentEnvironmentInput, AgentTurnInput, AgentEnvironmentProvider, AgentEnvironmentCapabilities, AgentProfileRef } from '@tangle-network/agent-interface/environment-provider';
3
3
  export { AgentEnvironment, AgentEnvironmentCapabilities, AgentEnvironmentEvent, AgentEnvironmentProvider, AgentEnvironmentQuery, AgentEnvironmentStatus, AgentEnvironmentSummary, AgentProfileRef, AgentSession, AgentSessionRef, AgentSessionStatus, AgentTurnInput, AgentTurnResult, CheckpointRef, CheckpointRequest, CreateAgentEnvironmentInput, ExecRequest, ExecResult, ForkRequest, PlacementInfo, ResourceRequest, WorkspaceRequest } from '@tangle-network/agent-interface/environment-provider';
4
4
  import { CreateSandboxOptions, BackendType } from '@tangle-network/sandbox';
5
- import { R as Runtime, E as ExecutorFactory } from './types-eMNgWgFi.js';
6
- import { S as SandboxClient } from './types-SyuwunY_.js';
5
+ import { R as Runtime, E as ExecutorFactory } from './types-DAdIm4AC.js';
6
+ import { S as SandboxClient } from './types-B00NtbCs.js';
7
7
  import '@tangle-network/agent-eval';
8
8
 
9
9
  /** Provider object or registry name accepted by runtime provider adapters.
@@ -4,7 +4,8 @@ import {
4
4
  providerAsSandboxClient,
5
5
  resolveAgentEnvironmentProvider,
6
6
  sandboxClientAsProvider
7
- } from "./chunk-BZF3KQ6G.js";
7
+ } from "./chunk-VSWBYWFK.js";
8
+ import "./chunk-3MDZX7YU.js";
8
9
  import "./chunk-DGUM43GV.js";
9
10
  export {
10
11
  createAgentEnvironmentProviderRegistry,