@tangle-network/agent-runtime 0.94.6 → 0.94.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +4 -4
- package/dist/{agentic-generator-CL1q0H91.d.ts → agentic-generator-1g7GDba7.d.ts} +73 -6
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/analyst-loop.js +2 -2
- package/dist/{chunk-GKZ6DFDN.js → chunk-7HH22XN4.js} +105 -27
- package/dist/chunk-7HH22XN4.js.map +1 -0
- package/dist/{chunk-JMT5VYY3.js → chunk-7NCP74SL.js} +174 -48
- package/dist/chunk-7NCP74SL.js.map +1 -0
- package/dist/{chunk-WQA5Y6PD.js → chunk-EP6RVHMX.js} +3 -3
- package/dist/chunk-EP6RVHMX.js.map +1 -0
- package/dist/{chunk-LWNMCOEA.js → chunk-FRXDOBFP.js} +3 -3
- package/dist/chunk-GHXW56PO.js +526 -0
- package/dist/chunk-GHXW56PO.js.map +1 -0
- package/dist/{chunk-63TIZHMI.js → chunk-KYPVUEJ4.js} +4 -4
- package/dist/{chunk-FVJ7M3DA.js → chunk-M22PL4GH.js} +1 -1
- package/dist/chunk-M22PL4GH.js.map +1 -0
- package/dist/{chunk-4VMRCEI6.js → chunk-MSUWXCHD.js} +2 -2
- package/dist/{chunk-ZQZX77MM.js → chunk-QDSOD7RC.js} +2 -2
- package/dist/{chunk-RNWDH5Z3.js → chunk-TNUBPPZA.js} +2 -2
- package/dist/{completion-gate-CfX2thvL.d.ts → completion-gate-tzwyyD-E.d.ts} +2 -2
- package/dist/{coordination-pOGZuYS7.d.ts → coordination-o0TzS7Ms.d.ts} +5 -5
- package/dist/environment-provider.d.ts +2 -2
- package/dist/{improve-Ciuvu2jh.d.ts → improve-DZeatcs7.d.ts} +19 -8
- package/dist/index.d.ts +20 -17
- package/dist/index.js +37 -20
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +6 -6
- package/dist/intelligence.js +41 -17
- package/dist/intelligence.js.map +1 -1
- package/dist/knowledge.d.ts +7 -7
- package/dist/knowledge.js +4 -4
- package/dist/lifecycle.d.ts +3 -3
- package/dist/lifecycle.js +2 -2
- package/dist/{local-harness-CePtFrwu.d.ts → local-harness-ZLMkKdZc.d.ts} +1 -1
- package/dist/{loop-runner-bin-B4PwjVaF.d.ts → loop-runner-bin-iTSxSmpv.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +6 -6
- package/dist/loop-runner-bin.js +6 -6
- package/dist/loops.d.ts +36 -23
- package/dist/loops.js +4 -4
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +10 -10
- package/dist/mcp/index.js +5 -5
- package/dist/{mcp-serve-verifier-D7hCZIkT.d.ts → mcp-serve-verifier-BO4MEsR3.d.ts} +1 -1
- package/dist/{openai-tools-BMOu1t3A.d.ts → openai-tools-0wACz8f8.d.ts} +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/{sanitize-Dr3SliRC.d.ts → sanitize-Dcbjp0tU.d.ts} +1 -1
- package/dist/{supervise-Y3w878fN.d.ts → supervise-CRwaJIkd.d.ts} +4 -4
- package/dist/{types-Kjr5W6OF.d.ts → types-CKmyZ9TP.d.ts} +4 -7
- package/dist/{types-DHLXdLVN.d.ts → types-CogNCaw7.d.ts} +1 -1
- package/dist/{worktree-fanout-DmBvR-_O.d.ts → worktree-fanout-BJy24LYe.d.ts} +4 -4
- package/package.json +3 -3
- package/dist/chunk-4WWSICFY.js +0 -210
- package/dist/chunk-4WWSICFY.js.map +0 -1
- package/dist/chunk-FVJ7M3DA.js.map +0 -1
- package/dist/chunk-GKZ6DFDN.js.map +0 -1
- package/dist/chunk-JMT5VYY3.js.map +0 -1
- package/dist/chunk-WQA5Y6PD.js.map +0 -1
- /package/dist/{chunk-LWNMCOEA.js.map → chunk-FRXDOBFP.js.map} +0 -0
- /package/dist/{chunk-63TIZHMI.js.map → chunk-KYPVUEJ4.js.map} +0 -0
- /package/dist/{chunk-4VMRCEI6.js.map → chunk-MSUWXCHD.js.map} +0 -0
- /package/dist/{chunk-ZQZX77MM.js.map → chunk-QDSOD7RC.js.map} +0 -0
- /package/dist/{chunk-RNWDH5Z3.js.map → chunk-TNUBPPZA.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/improvement/improvement-driver.ts","../src/improvement/raw-trace-distiller.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 *\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: 'memory'` → `memoryCurationProposer` curates a bounded durable\n * lesson document supplied through `opts.memory`.\n * - `surface: 'agent-profile'` → caller-supplied proposer mutates the complete\n * canonical AgentProfile JSON in one candidate.\n * - `surface` ∈ {`tools`, `mcp`, `hooks`, `subagents`, `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 { canonicalJson } from '@tangle-network/agent-eval'\nimport {\n gepaProposer,\n gitWorktreeAdapter,\n memoryCurationProposer,\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'\n\n/** The executable agent lever `improve` optimizes. Profile fields remain\n * portable AgentProfile coordinates; implementation and orchestration files\n * use the code surface so a winner can be sealed into an exact candidate. */\nexport type ImproveSurface =\n | 'prompt'\n | 'skills'\n | 'tools'\n | 'mcp'\n | 'hooks'\n | 'subagents'\n | 'agent-profile'\n | 'memory'\n | 'code'\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 prompt, skills, and memory; surfaces\n * 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 /** MEMORY-surface wiring for a curated durable memory document. The default\n * deterministic proposer deduplicates and ranks lessons from findings, then\n * replaces its managed block instead of growing memory without bound. */\n memory?: ImproveMemoryOptions\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 | Promise<void>\n}\n\nexport interface ImproveMemoryOptions {\n /** Current durable memory text used as the measured baseline. */\n document: string\n /** Persist the promoted memory document. Never called on hold or error. */\n writeBack?: (winnerDocument: string) => void | Promise<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'\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 'memory':\n return memoryCurationProposer()\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, and memory are text surfaces; config\n * surfaces serialize the matching profile record. */\nfunction baselineSurfaceFor(\n profile: AgentProfile,\n surface: ImproveSurface,\n skills?: ImproveSkillsOptions,\n memory?: ImproveMemoryOptions,\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 'agent-profile':\n return canonicalJson(profile)\n case 'memory':\n if (!memory) {\n throw new ConfigError(\"improve(): surface 'memory' requires opts.memory.document\")\n }\n return memory.document\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<{\n scenario: string\n composite: number\n notes: string\n claim?: string\n 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 const claim = notes || (error ? `Scenario ${scenario} failed: ${error.slice(0, 200)}` : '')\n failures.push({\n scenario,\n composite: Number(composite.toFixed(3)),\n notes,\n ...(claim ? { claim } : {}),\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\n/** Memory accumulates durable lessons, so keep the caller's seed findings while\n * adding fresh judge failures. Curator proposers consume `claim`; the generic\n * distiller retains the richer diagnostic fields for reflective proposers. */\nfunction memoryGenerationDistiller<TScenario extends Scenario, TArtifact>(\n staticFindings: unknown[],\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const distillFailures = generationFailureDistiller<TScenario, TArtifact>(staticFindings)\n return async (input) => {\n const fresh = await distillFailures(input)\n return fresh === staticFindings ? staticFindings : [...staticFindings, ...fresh]\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 (`tools`/`mcp`/`hooks`/`subagents`/`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. */\nexport function applyImprovementWinnerToProfile(\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 'agent-profile':\n candidate = parseWinnerJson(winner, surface)\n break\n case 'memory':\n return profile\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 memory,\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 if (surface === 'memory' && !memory) {\n throw new ConfigError(\"improve(): surface 'memory' requires opts.memory.document\")\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:\n preparedCode?.baseline ?? baselineSurfaceFor(profile, surface, skills, memory),\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 : surface === 'memory'\n ? memoryGenerationDistiller<TScenario, TArtifact>(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 const winnerSurface = raw.winner.surface\n await preparedCode?.cleanup(shipped ? winnerSurface : 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 externalDocument =\n surface === 'skills' && skills ? skills : surface === 'memory' && memory ? memory : undefined\n if (shipped && externalDocument) {\n if (typeof winnerSurface !== 'string') {\n throw new ConfigError(\n `improve(): the shipped '${surface}' winner must be text before it can be persisted`,\n )\n }\n await externalDocument.writeBack?.(winnerSurface)\n }\n const nextProfile =\n shipped && !externalDocument\n ? applyImprovementWinnerToProfile(profile, surface, winnerSurface)\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;AAA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AAiD,QAAQ;AAAA,MACnE;AAAA,IACN,CAAC;AAAA,EACH,SAAS,OAAO;AACd,QAAI,CAAC,aAAc,OAAM;AACzB,QAAI;AACF,YAAM,aAAa,QAAQ;AAAA,IAC7B,SAAS,cAAc;AACrB,YAAM,IAAI;AAAA,QACR,CAAC,OAAO,YAAY;AAAA,QACpB;AAAA,MACF;AAAA,IACF;AACA,UAAM;AAAA,EACR;AAEA,QAAM,UAAU,IAAI,iBAAiB;AACrC,QAAM,gBAAgB,IAAI,OAAO;AACjC,QAAM,cAAc,QAAQ,UAAU,gBAAgB,MAAS;AAI/D,QAAM,mBACJ,YAAY,YAAY,SAAS,SAAS,YAAY,YAAY,SAAS,SAAS;AACtF,MAAI,WAAW,kBAAkB;AAC/B,QAAI,OAAO,kBAAkB,UAAU;AACrC,YAAM,IAAI;AAAA,QACR,2BAA2B,OAAO;AAAA,MACpC;AAAA,IACF;AACA,UAAM,iBAAiB,YAAY,aAAa;AAAA,EAClD;AACA,QAAM,cACJ,WAAW,CAAC,mBACR,gCAAgC,SAAS,SAAS,aAAa,IAC/D;AAEN,SAAO,EAAE,SAAS,aAAa,SAAS,MAAM,IAAI,MAAM,cAAc,IAAI,cAAc,IAAI;AAC9F;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/codex-diagnostics.ts","../src/mcp/local-harness.ts"],"sourcesContent":["import { constants } from 'node:fs'\nimport { open } from 'node:fs/promises'\nimport { stripVTControlCharacters } from 'node:util'\n\n/** Bounded, credential-redacted process context attached when reproducible Codex output fails\n * validation. The process still fails closed; this only preserves enough evidence to diagnose it. */\nexport interface CodexExecutionFailureDiagnostic {\n exitCode: number | null\n killedBySignal: NodeJS.Signals | null\n timedOut: boolean\n durationMs: number\n stdout: string\n stderr: string\n stdoutTruncated: boolean\n stderrTruncated: boolean\n}\n\n/** Thrown when reproducible Codex exits without one valid terminal usage event. */\nexport class CodexExecutionDiagnosticError extends Error {\n readonly code = 'CODEX_EXECUTION_DIAGNOSTIC'\n\n constructor(\n readonly reason: string,\n readonly diagnostic: CodexExecutionFailureDiagnostic,\n cause?: unknown,\n ) {\n super(\n `runLocalHarness: reproducible Codex execution failed: ${reason}; diagnostic=${JSON.stringify(diagnostic)}`,\n { cause },\n )\n this.name = 'CodexExecutionDiagnosticError'\n }\n}\n\nconst CODEX_FAILURE_STREAM_MAX_CHARS = 4096\nconst CODEX_AUTH_MAX_BYTES = 1024 * 1024\nconst CODEX_REDACTED = '<REDACTED_CREDENTIAL>'\nexport const codexSensitiveEnvironmentName = /(TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|AUTH|COOKIE)/i\n\nexport function createCodexExecutionDiagnosticError(opts: {\n reason: string\n exitCode: number | null\n killedBySignal: NodeJS.Signals | null\n timedOut: boolean\n durationMs: number\n stdout: string\n stderr: string\n codexHome: string | undefined\n redactionValues: string[]\n cause: unknown\n}): CodexExecutionDiagnosticError {\n const redact = (value: string) =>\n redactCodexDiagnostic(value, opts.codexHome, opts.redactionValues)\n const boundedStdout = boundCodexDiagnostic(redact(opts.stdout))\n const boundedStderr = boundCodexDiagnostic(redact(opts.stderr))\n const diagnostic: CodexExecutionFailureDiagnostic = {\n exitCode: opts.exitCode,\n killedBySignal: opts.killedBySignal,\n timedOut: opts.timedOut,\n durationMs: opts.durationMs,\n stdout: boundedStdout.value,\n stderr: boundedStderr.value,\n stdoutTruncated: boundedStdout.truncated,\n stderrTruncated: boundedStderr.truncated,\n }\n const safeReason = boundCodexDiagnostic(redact(opts.reason), 1024).value\n return new CodexExecutionDiagnosticError(\n safeReason,\n diagnostic,\n redactCodexErrorCause(opts.cause, safeReason, redact),\n )\n}\n\nexport function redactCodexHome(value: string, codexHome: string | undefined): string {\n return codexHome ? value.replaceAll(codexHome, '<ISOLATED_CODEX_HOME>') : value\n}\n\nexport function collectCodexDiagnosticRedactionValues(\n env: NodeJS.ProcessEnv,\n authText: string,\n): string[] {\n const values = Object.entries(env)\n .filter(\n ([name, value]) => codexSensitiveEnvironmentName.test(name) && typeof value === 'string',\n )\n .map(([, value]) => value as string)\n try {\n collectStringLeaves(JSON.parse(authText), values)\n } catch {\n // Invalid auth JSON is diagnosed by Codex; generic credential patterns still redact it.\n }\n const encoded = values\n .filter((value) => value.length >= 8)\n .flatMap((value) => [\n Buffer.from(value, 'utf8').toString('base64'),\n Buffer.from(value, 'utf8').toString('base64url'),\n encodeURIComponent(value),\n JSON.stringify(value).slice(1, -1),\n ])\n return [...new Set([...values, ...encoded])]\n}\n\nexport async function readCodexAuthRedactionText(path: string): Promise<string> {\n const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK)\n try {\n const stats = await handle.stat()\n if (!stats.isFile() || !Number.isSafeInteger(stats.size) || stats.size > CODEX_AUTH_MAX_BYTES) {\n throw new Error('Codex auth.json must be a regular file no larger than 1 MiB')\n }\n const buffer = Buffer.alloc(stats.size)\n let offset = 0\n while (offset < buffer.length) {\n const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset)\n if (bytesRead === 0) break\n offset += bytesRead\n }\n return buffer.subarray(0, offset).toString('utf8')\n } finally {\n await handle.close()\n }\n}\n\nfunction boundCodexDiagnostic(\n value: string,\n maxChars = CODEX_FAILURE_STREAM_MAX_CHARS,\n): { value: string; truncated: boolean } {\n if (value.length <= maxChars) return { value, truncated: false }\n const marker = '\\n<... OUTPUT TRUNCATED ...>\\n'\n const contentChars = maxChars - marker.length\n const headChars = Math.floor(contentChars / 2)\n const tailChars = contentChars - headChars\n return {\n value: `${value.slice(0, headChars)}${marker}${value.slice(-tailChars)}`,\n truncated: true,\n }\n}\n\nfunction redactCodexDiagnostic(\n value: string,\n codexHome: string | undefined,\n protectedValues: ReadonlyArray<string>,\n): string {\n let redacted = redactCodexHome(stripVTControlCharacters(value), codexHome)\n const exactValues = [...new Set(protectedValues.filter((item) => item.length >= 6))].sort(\n (a, b) => b.length - a.length,\n )\n for (const secret of exactValues) redacted = redacted.replaceAll(secret, CODEX_REDACTED)\n redacted = redacted\n .replace(/(\\bBearer\\s+)[A-Za-z0-9._~+/=-]{6,}/gi, `$1${CODEX_REDACTED}`)\n .replace(/\\b(?:sk|rk|pk)-[A-Za-z0-9._-]{8,}\\b/g, CODEX_REDACTED)\n .replace(/\\beyJ[A-Za-z0-9_-]{6,}\\.[A-Za-z0-9_-]{6,}\\.[A-Za-z0-9_-]{6,}\\b/g, CODEX_REDACTED)\n .replace(\n /((?:[\"']?(?:api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|private[-_]?key|session[-_]?(?:id|token)|secret|password|passwd|authorization|credential|cookie)[\"']?)\\s*[:=]\\s*)([\"'])[^\"'\\r\\n]*\\2/gi,\n `$1$2${CODEX_REDACTED}$2`,\n )\n .replace(\n /((?:[\"']?(?:api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|private[-_]?key|session[-_]?(?:id|token)|secret|password|passwd|authorization|credential|cookie)[\"']?)\\s*[:=]\\s*)([^\\s,;}]+)/gi,\n `$1${CODEX_REDACTED}`,\n )\n for (const secret of exactValues) redacted = redacted.replaceAll(secret, CODEX_REDACTED)\n return redacted\n}\n\nfunction redactCodexErrorCause(\n cause: unknown,\n safeReason: string,\n redact: (value: string) => string,\n): Error | undefined {\n if (!(cause instanceof Error)) return undefined\n const safeCause = new Error(safeReason)\n safeCause.name = cause.name\n if (cause.stack) safeCause.stack = boundCodexDiagnostic(redact(cause.stack)).value\n return safeCause\n}\n\nfunction collectStringLeaves(value: unknown, output: string[]): void {\n if (typeof value === 'string') {\n output.push(value)\n return\n }\n if (Array.isArray(value)) {\n for (const item of value) collectStringLeaves(item, output)\n return\n }\n if (value !== null && typeof value === 'object') {\n for (const item of Object.values(value)) collectStringLeaves(item, output)\n }\n}\n","/**\n *\n * Subprocess wrappers for the local coding-harness CLIs installed in the\n * sandbox image (claude-code, codex, opencode). Used by the in-process\n * delegation executor (`createInProcessExecutor`) so a delegated coding task\n * spawns a real harness on a real git worktree instead of provisioning a\n * sibling sandbox.\n *\n * All harness invocations:\n * - run with `cwd` set to the worktree\n * - inherit env from the parent (the MCP server inside the sandbox has\n * the harness's auth already)\n * - capture stdout/stderr\n * - support cancellation via AbortSignal\n * - enforce a wall-clock timeout\n *\n * @experimental\n */\n\nimport { type ChildProcess, spawn } from 'node:child_process'\nimport { createHash, randomUUID } from 'node:crypto'\nimport { constants, createReadStream } from 'node:fs'\nimport {\n access,\n chmod,\n copyFile,\n mkdir,\n mkdtemp,\n open,\n readFile,\n realpath,\n rm,\n symlink,\n writeFile,\n} from 'node:fs/promises'\nimport { homedir, tmpdir } from 'node:os'\nimport { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n codexSensitiveEnvironmentName,\n collectCodexDiagnosticRedactionValues,\n createCodexExecutionDiagnosticError,\n readCodexAuthRedactionText,\n redactCodexHome,\n} from './codex-diagnostics'\n\nexport type { CodexExecutionFailureDiagnostic } from './codex-diagnostics'\nexport { CodexExecutionDiagnosticError } from './codex-diagnostics'\n\n/** Local coding harness available inside the sandbox. */\nexport type LocalHarness = 'claude' | 'codex' | 'opencode'\n\ntype ReasoningEffort = NonNullable<NonNullable<AgentProfile['model']>['reasoningEffort']>\n\nconst codexReasoningEffort: Record<ReasoningEffort, string> = {\n none: 'none',\n minimal: 'minimal',\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n ultracode: 'xhigh',\n}\n\nfunction codexReasoningArgs(reasoningEffort: ReasoningEffort): string[] {\n const mapped = codexReasoningEffort[reasoningEffort]\n if (mapped === undefined) {\n throw new Error(\n `harnessInvocation: unsupported Codex reasoning effort ${String(reasoningEffort)}`,\n )\n }\n return ['-c', `model_reasoning_effort=\"${mapped}\"`]\n}\n\n/**\n * Default per-harness command + arg shape. `buildArgs` takes ONLY the task prompt and\n * emits the prompt-only invocation (no model, no system prompt) — the safe default shape\n * the in-process executor's `streamPrompt` drives. `modelArgs` maps a resolved model to\n * the harness's selector flag (every supported harness takes `-m <model>`). The §1.5\n * profile-aware mapper `harnessInvocation` composes these to thread the full\n * supervisor-authored profile (systemPrompt + model) into argv.\n */\nconst HARNESS_INVOCATIONS: Record<\n LocalHarness,\n {\n command: string\n buildArgs: (taskPrompt: string) => string[]\n /** Map a resolved model to the harness's model-selector flag. */\n modelArgs: (model: string) => string[]\n /** Map portable reasoning effort when the harness exposes a native control. */\n reasoningArgs?: (reasoningEffort: ReasoningEffort) => string[]\n }\n> = {\n claude: {\n command: 'claude',\n // `-p` IS headless/print mode; the old `--headless` flag was removed from the CLI.\n // Permission bypass is an explicit per-run opt-in below, never the public default.\n buildArgs: (taskPrompt) => ['-p', taskPrompt],\n modelArgs: (model) => ['-m', model],\n },\n codex: {\n command: 'codex',\n buildArgs: (taskPrompt) => ['exec', taskPrompt],\n modelArgs: (model) => ['-m', model],\n reasoningArgs: codexReasoningArgs,\n },\n opencode: {\n command: 'opencode',\n buildArgs: (taskPrompt) => ['run', taskPrompt],\n modelArgs: (model) => ['-m', model],\n },\n}\n\n/** Result of mapping an `AgentProfile` + task prompt onto a harness invocation. */\nexport interface HarnessInvocation {\n command: string\n args: string[]\n}\n\nexport interface HarnessInvocationOptions {\n /** Allow an unattended Claude process to edit its isolated candidate worktree.\n * Ignored by harnesses that do not use Claude's permission prompt. */\n dangerouslySkipPermissions?: boolean\n /** Run Codex with benchmark-safe process controls and JSONL usage output.\n * Valid only for the Codex harness. */\n codexReproducible?: boolean\n}\n\nconst CODEX_REPRODUCIBLE_ARGS = [\n '--ephemeral',\n '--ignore-rules',\n '--json',\n '-c',\n 'approval_policy=\"never\"',\n '-c',\n 'web_search=\"disabled\"',\n '-c',\n 'project_doc_max_bytes=0',\n '-c',\n 'skills.include_instructions=false',\n '-c',\n 'include_apps_instructions=false',\n '--disable',\n 'tool_suggest',\n '-c',\n 'features.multi_agent_v2.root_agent_usage_hint_text=\"\"',\n '-c',\n 'features.multi_agent_v2.subagent_usage_hint_text=\"\"',\n '-c',\n 'features.multi_agent_v2.multi_agent_mode_hint_text=\"\"',\n '--strict-config',\n] as const\n\nfunction buildHarnessArgs(\n harness: LocalHarness,\n taskPrompt: string,\n options: HarnessInvocationOptions = {},\n): string[] {\n const args = HARNESS_INVOCATIONS[harness].buildArgs(taskPrompt)\n if (harness === 'claude' && options.dangerouslySkipPermissions) {\n args.push('--dangerously-skip-permissions')\n }\n if (options.codexReproducible) {\n if (harness !== 'codex') {\n throw new Error('harnessInvocation: codexReproducible requires the Codex harness')\n }\n args.push(...CODEX_REPRODUCIBLE_ARGS)\n }\n return args\n}\n\n/**\n * Map a supervisor-authored `AgentProfile` + the per-task prompt onto a concrete harness\n * `command` + `args` (the §1.5 fix). UNLIKE the prompt-only `HARNESS_INVOCATIONS.buildArgs`\n * — which drops both the authored model and the system prompt — this threads the FULL\n * profile payload into argv:\n *\n * - `profile.prompt.systemPrompt` → the PROMPT channel: a portable, harness-agnostic\n * default that prepends the system prompt above the task prompt (`<system>\\n\\n<task>`),\n * so the authored standing instructions reach EVERY harness (none of the three CLIs\n * expose a portable replace-system-prompt flag for a one-shot non-interactive run).\n * - `profile.prompt.instructions[]` → appended prompt sections in authored order.\n * - `profile.model.default` → the harness's `-m <model>` selector.\n *\n * The task prompt alone is the floor; an empty/absent profile yields exactly the legacy\n * `buildArgs(taskPrompt)` shape so existing callers are byte-identical.\n */\nexport function harnessInvocation(\n harness: LocalHarness,\n profile: AgentProfile,\n taskPrompt: string,\n options: HarnessInvocationOptions = {},\n): HarnessInvocation {\n const invocation = HARNESS_INVOCATIONS[harness]\n if (!invocation) {\n throw new Error(`harnessInvocation: unknown harness ${String(harness)}`)\n }\n\n if (options.codexReproducible) {\n const model = profile.model?.default\n if (typeof model !== 'string' || model.trim().length === 0) {\n throw new Error('harnessInvocation: codexReproducible requires profile.model.default')\n }\n if (profile.model?.reasoningEffort === undefined) {\n throw new Error('harnessInvocation: codexReproducible requires profile.model.reasoningEffort')\n }\n }\n\n const systemPrompt = profile.prompt?.systemPrompt\n const instructions = profile.prompt?.instructions\n if (\n instructions !== undefined &&\n (!Array.isArray(instructions) ||\n instructions.some((instruction) => typeof instruction !== 'string'))\n ) {\n throw new Error('harnessInvocation: profile.prompt.instructions must be an array of strings')\n }\n const promptSections = [\n ...(typeof systemPrompt === 'string' && systemPrompt.trim().length > 0 ? [systemPrompt] : []),\n ...(instructions?.filter((instruction) => instruction.trim().length > 0) ?? []),\n taskPrompt,\n ]\n const composedPrompt = promptSections.join('\\n\\n')\n\n const args = buildHarnessArgs(harness, composedPrompt, options)\n\n const model = profile.model?.default\n if (typeof model === 'string' && model.length > 0) {\n args.push(...invocation.modelArgs(model))\n }\n\n const reasoningEffort = profile.model?.reasoningEffort\n if (reasoningEffort !== undefined && invocation.reasoningArgs) {\n args.push(...invocation.reasoningArgs(reasoningEffort))\n }\n\n return { command: invocation.command, args }\n}\n\n/** @experimental */\nexport interface RunLocalHarnessOptions {\n harness: LocalHarness\n /** Working directory for the subprocess (typically a worktree path). */\n cwd: string\n /** Prompt forwarded as the harness CLI's task argument. */\n taskPrompt: string\n /**\n * Pre-built command + args (e.g. from `harnessInvocation` so the full authored\n * `AgentProfile` — systemPrompt + model — reaches the harness). When set it OVERRIDES the\n * default prompt-only `buildArgs(taskPrompt)` path; `command` defaults to the harness's\n * default binary when only `args` is supplied. When absent the legacy prompt-only shape\n * is used unchanged.\n */\n invocation?: { command?: string; args: ReadonlyArray<string> }\n /** Allow autonomous Claude edits without an interactive permission prompt.\n * Use only when `cwd` is an isolated candidate worktree. */\n dangerouslySkipPermissions?: boolean\n /** Isolate Codex from ambient configuration/instructions and require JSONL token usage.\n * The invocation should come from `harnessInvocation(..., { codexReproducible: true })`. */\n codexReproducible?: boolean\n /** Absolute host paths that reproducible Codex must not read. The normalized set is compiled\n * into the controlled permission profile and its digest is returned in execution evidence. */\n codexReadDeniedPaths?: ReadonlyArray<string>\n /** Wall-clock kill deadline (ms). Default 5 min. Subprocess SIGTERMed on expiry. */\n timeoutMs?: number\n /** Caller cancellation. SIGTERM is sent on abort. */\n signal?: AbortSignal\n /** Override env (defaults to inheriting from the parent). */\n env?: NodeJS.ProcessEnv\n /**\n * Test seam — inject a custom spawner so unit tests can mock the\n * subprocess without touching the OS. Defaults to node's `child_process.spawn`.\n */\n spawn?: (\n command: string,\n args: ReadonlyArray<string>,\n opts: {\n cwd: string\n env: NodeJS.ProcessEnv\n stdio: 'pipe'\n detached: boolean\n },\n ) => ChildProcess\n /** Test seam for locating the native Codex executable before it is staged in the worktree. */\n resolveCodexExecutable?: (command: string, env: NodeJS.ProcessEnv) => Promise<string>\n}\n\n/** Exact aggregate usage emitted by Codex's terminal `turn.completed` JSONL event. */\nexport interface CodexTokenUsage {\n inputTokens: number\n cachedInputTokens: number\n outputTokens: number\n reasoningOutputTokens: number\n}\n\n/** Isolation settings asserted before a reproducible Codex run is allowed to start. */\nexport interface CodexExecutionPolicy {\n sessionPersistence: 'ephemeral'\n userConfig: false\n rules: false\n projectInstructions: false\n skillInstructions: false\n appInstructions: false\n toolSuggestions: false\n multiAgentInstructions: false\n sandbox: 'workspace-write'\n permissionProfile: 'agent_runtime_reproducible'\n approvalPolicy: 'never'\n shellNetwork: false\n webSearch: false\n serviceTier: 'default'\n shellEnvironment: 'core-filtered'\n loginShell: false\n credentialsReadable: false\n hostHomeReadable: false\n procEnvironment: 'private-sanitized'\n sensitiveEnvironmentNamesVisible: false\n parentRepoRead: false\n gitMetadata: false\n temporaryDirectory: 'workspace-private'\n stagedExecutable: 'static-elf-read-only'\n callerReadDeniedPaths: 'enforced'\n containerSockets: false\n}\n\n/** Zero-model-call evidence for the exact Codex process about to run. */\nexport interface CodexExecutionEvidence {\n cliVersion: string\n executableSha256: string\n /** SHA-256 of the exact composed prompt argument proved present in the rendered prompt. */\n requestedPromptSha256: string\n effectivePromptSha256: string\n nonPromptArgsSha256: string\n controlledConfigSha256: string\n /** Sorted normalized paths compiled into the permission profile. */\n readDeniedPaths: string[]\n readDeniedPathsSha256: string\n readDeniedPathCount: number\n policy: CodexExecutionPolicy\n}\n\n/** @experimental */\nexport interface LocalHarnessResult {\n /** OS exit code. `null` when killed before exit. */\n exitCode: number | null\n /** Concatenated stdout. */\n stdout: string\n /** Concatenated stderr. */\n stderr: string\n /** Set when the process exited via signal (timeout / abort). */\n killedBySignal: NodeJS.Signals | null\n /** Wall-clock duration ms (spawn → exit). */\n durationMs: number\n /** Set when timeoutMs elapsed before exit. */\n timedOut: boolean\n /** Present for a reproducible Codex run; parsed from the real terminal JSONL event. */\n usage?: CodexTokenUsage\n /** Present for reproducible Codex runs; generated and checked before model execution. */\n evidence?: CodexExecutionEvidence\n}\n\nconst DEFAULT_TIMEOUT_MS = 5 * 60 * 1000\nconst processKillGraceMs = 250\n\n/**\n * Spawn a local coding harness CLI as a subprocess + collect its output.\n *\n * NOT responsible for parsing the harness's output or extracting a diff —\n * the in-process executor's `streamPrompt` orchestrates `git diff` against\n * the worktree after this resolves. This function is intentionally narrow:\n * spawn, wait, capture, return.\n *\n * Fails loud — throws when:\n * - `cwd` doesn't exist (subprocess emits ENOENT; surfaced as Error)\n * - the harness binary is not on PATH (ENOENT)\n *\n * Does NOT throw when:\n * - the subprocess exits non-zero (`result.exitCode` carries the code)\n * - the subprocess is aborted / timed out (`result.killedBySignal` /\n * `result.timedOut` carries the reason)\n *\n * @experimental\n */\nexport async function runLocalHarness(\n options: RunLocalHarnessOptions,\n): Promise<LocalHarnessResult> {\n const { harness, cwd, taskPrompt } = options\n if (options.codexReproducible && harness !== 'codex') {\n throw new Error('runLocalHarness: codexReproducible requires the Codex harness')\n }\n if (options.codexReproducible && process.platform !== 'linux') {\n throw new Error('runLocalHarness: codexReproducible currently requires Linux')\n }\n if (options.codexReadDeniedPaths !== undefined && !options.codexReproducible) {\n throw new Error('runLocalHarness: codexReadDeniedPaths requires codexReproducible')\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const spawnImpl = options.spawn ?? spawn\n\n const invocation = HARNESS_INVOCATIONS[harness]\n if (!invocation) {\n throw new Error(`runLocalHarness: unknown harness ${String(harness)}`)\n }\n\n const startedAt = Date.now()\n const requestedCommand = options.invocation?.command ?? invocation.command\n const args = options.invocation\n ? [...options.invocation.args]\n : buildHarnessArgs(harness, taskPrompt, options)\n if (options.codexReproducible) assertCodexReproducibleInvocation(requestedCommand, args)\n\n const baseEnv = options.env ?? process.env\n const isolated = options.codexReproducible\n ? await isolateCodexHome({\n baseEnv,\n cwd,\n command: requestedCommand,\n readDeniedPaths: options.codexReadDeniedPaths ?? [],\n resolveExecutable: options.resolveCodexExecutable ?? resolveCodexNativeExecutable,\n })\n : {\n env: baseEnv,\n command: requestedCommand,\n cleanup: async () => undefined,\n controlledConfigSha256: '',\n executableSha256: '',\n readDeniedPathsSha256: '',\n readDeniedPathCount: 0,\n readDeniedPaths: [] as string[],\n diagnosticRedactionValues: [] as string[],\n ambientAuth: '',\n isolatedAuth: '',\n writeProbe: '',\n stagedWriteProbe: '',\n deniedProbePaths: [] as string[],\n }\n const env = isolated.env\n const command = isolated.command\n if (options.codexReproducible) assertCodexReproducibleInvocation(command, args)\n\n try {\n const evidence = options.codexReproducible\n ? await collectCodexExecutionEvidence({\n command,\n args,\n cwd,\n env,\n spawn: spawnImpl,\n controlledConfigSha256: isolated.controlledConfigSha256,\n executableSha256: isolated.executableSha256,\n readDeniedPathsSha256: isolated.readDeniedPathsSha256,\n readDeniedPathCount: isolated.readDeniedPathCount,\n readDeniedPaths: isolated.readDeniedPaths,\n ambientAuth: isolated.ambientAuth,\n isolatedAuth: isolated.isolatedAuth,\n writeProbe: isolated.writeProbe,\n stagedWriteProbe: isolated.stagedWriteProbe,\n deniedProbePaths: isolated.deniedProbePaths,\n ...(options.signal ? { signal: options.signal } : {}),\n })\n : undefined\n return await new Promise<LocalHarnessResult>((resolve, reject) => {\n let child: ChildProcess\n try {\n child = spawnImpl(command, args, {\n cwd,\n env,\n stdio: 'pipe',\n detached: process.platform !== 'win32',\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n // The harness takes its task as an argv arg, not on stdin. Leaving stdin\n // OPEN makes a non-TTY `opencode run` (and likely the other harnesses)\n // BLOCK forever waiting on input — zero output, SIGTERM at the wall cap,\n // empty patch -> \"no candidate passed validation\". Close stdin so the\n // subprocess sees EOF and proceeds (the `cliExecutor` leaf does the same).\n child.stdin?.end()\n\n let stdout = ''\n let stderr = ''\n let timedOut = false\n let settled = false\n let forceKillTimer: ReturnType<typeof setTimeout> | null = null\n let terminationStarted = false\n\n const terminate = () => {\n if (terminationStarted) return\n terminationStarted = true\n signalProcessTree(child, 'SIGTERM')\n forceKillTimer = setTimeout(() => signalProcessTree(child, 'SIGKILL'), processKillGraceMs)\n forceKillTimer.unref?.()\n }\n\n const timer =\n timeoutMs > 0\n ? setTimeout(() => {\n timedOut = true\n terminate()\n }, timeoutMs)\n : null\n if (timer && typeof (timer as { unref?: () => void }).unref === 'function') {\n ;(timer as { unref: () => void }).unref()\n }\n\n const onAbort = () => {\n terminate()\n }\n if (options.signal) {\n if (options.signal.aborted) onAbort()\n else options.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n child.stdout?.on('data', (chunk) => {\n stdout += String(chunk)\n })\n child.stderr?.on('data', (chunk) => {\n stderr += String(chunk)\n })\n\n const finalize = (result: LocalHarnessResult) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (forceKillTimer) clearTimeout(forceKillTimer)\n options.signal?.removeEventListener('abort', onAbort)\n resolve(result)\n }\n\n child.on('error', (err) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (forceKillTimer) clearTimeout(forceKillTimer)\n options.signal?.removeEventListener('abort', onAbort)\n reject(err)\n })\n\n child.on('close', (code, signal) => {\n const durationMs = Date.now() - startedAt\n try {\n const usage = options.codexReproducible ? parseCodexTokenUsage(stdout) : undefined\n finalize({\n exitCode: code,\n stdout,\n stderr: redactCodexHome(stderr, env.CODEX_HOME),\n killedBySignal: signal,\n durationMs,\n timedOut,\n ...(usage ? { usage } : {}),\n ...(evidence ? { evidence } : {}),\n })\n } catch (err) {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (forceKillTimer) clearTimeout(forceKillTimer)\n options.signal?.removeEventListener('abort', onAbort)\n const reason = err instanceof Error ? err.message : String(err)\n reject(\n options.codexReproducible\n ? createCodexExecutionDiagnosticError({\n reason,\n exitCode: code,\n killedBySignal: signal,\n timedOut,\n durationMs,\n stdout,\n stderr,\n codexHome: env.CODEX_HOME,\n redactionValues: isolated.diagnosticRedactionValues,\n cause: err,\n })\n : err instanceof Error\n ? err\n : new Error(reason),\n )\n }\n })\n })\n } finally {\n await isolated.cleanup()\n }\n}\n\nconst CODEX_EXECUTION_POLICY: CodexExecutionPolicy = {\n sessionPersistence: 'ephemeral',\n userConfig: false,\n rules: false,\n projectInstructions: false,\n skillInstructions: false,\n appInstructions: false,\n toolSuggestions: false,\n multiAgentInstructions: false,\n sandbox: 'workspace-write',\n permissionProfile: 'agent_runtime_reproducible',\n approvalPolicy: 'never',\n shellNetwork: false,\n webSearch: false,\n serviceTier: 'default',\n shellEnvironment: 'core-filtered',\n loginShell: false,\n credentialsReadable: false,\n hostHomeReadable: false,\n procEnvironment: 'private-sanitized',\n sensitiveEnvironmentNamesVisible: false,\n parentRepoRead: false,\n gitMetadata: false,\n temporaryDirectory: 'workspace-private',\n stagedExecutable: 'static-elf-read-only',\n callerReadDeniedPaths: 'enforced',\n containerSockets: false,\n}\n\nconst FORBIDDEN_CODEX_PROMPT_MARKERS = [\n '<skills_instructions>',\n '# AGENTS.md instructions',\n '<apps_instructions>',\n '<recommended_plugins>',\n '<multi_agent_mode>',\n 'You are `/root`, the primary agent',\n] as const\n\nasync function collectCodexExecutionEvidence(opts: {\n command: string\n args: string[]\n cwd: string\n env: NodeJS.ProcessEnv\n spawn: NonNullable<RunLocalHarnessOptions['spawn']>\n controlledConfigSha256: string\n readDeniedPaths: string[]\n executableSha256: string\n readDeniedPathsSha256: string\n readDeniedPathCount: number\n ambientAuth: string\n isolatedAuth: string\n writeProbe: string\n stagedWriteProbe: string\n deniedProbePaths: string[]\n signal?: AbortSignal\n}): Promise<CodexExecutionEvidence> {\n assertCodexReproducibleInvocation(opts.command, opts.args)\n const prompt = opts.args[1]\n if (opts.args[0] !== 'exec' || typeof prompt !== 'string' || prompt.length === 0) {\n throw new Error('runLocalHarness: reproducible Codex invocation must be codex exec <prompt>')\n }\n const cliVersion = (await runCodexProbe(opts, ['--version'])).stdout.trim()\n if (!/^codex-cli \\d+\\.\\d+\\.\\d+(?:[-+].+)?$/.test(cliVersion)) {\n throw new Error(\n `runLocalHarness: unexpected Codex CLI version output ${JSON.stringify(cliVersion)}`,\n )\n }\n\n const hiddenEnvironmentChecks = [\n 'CODEX_HOME',\n 'CODEX_ACCESS_TOKEN',\n 'CODEX_API_KEY',\n 'OPENAI_API_KEY',\n ]\n .map((name) => `test -z \"\\${${name}:-}\"`)\n .join(' && ')\n const sandboxProof = [\n hiddenEnvironmentChecks,\n 'test -r .',\n '! test -r .git',\n 'touch \"$1\"',\n 'rm \"$1\"',\n 'staged_dir=$(dirname \"$2\")',\n 'test -x \"$staged_dir/codex\"',\n '! chmod 700 \"$staged_dir\" 2>/dev/null',\n '! rm \"$staged_dir/codex\" 2>/dev/null',\n '! touch \"$2\" 2>/dev/null',\n 'shift 2',\n 'for path in \"$@\"; do ! test -r \"$path\" || exit 1; done',\n 'touch \"$TMPDIR/.agent-runtime-tmp-proof\"',\n 'rm \"$TMPDIR/.agent-runtime-tmp-proof\"',\n ].join(' && ')\n await runCodexProbe(opts, [\n 'sandbox',\n '-P',\n CODEX_PERMISSION_PROFILE,\n '-C',\n opts.cwd,\n 'sh',\n '-c',\n sandboxProof,\n 'sh',\n opts.writeProbe,\n opts.stagedWriteProbe,\n ...opts.deniedProbePaths,\n ])\n await runCodexProbe(opts, [\n 'sandbox',\n '-P',\n CODEX_PERMISSION_PROFILE,\n '-C',\n opts.cwd,\n 'python3',\n '-c',\n `import os,re\npattern=re.compile(br'(TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|AUTH|COOKIE|CODEX_HOME)', re.I)\npaths=('/proc/1/environ', '/proc/self/environ', f'/proc/{os.getppid()}/environ')\nfor path in dict.fromkeys(paths):\n data=open(path,'rb').read().split(b'\\\\0')\n names=(item.split(b'=',1)[0] for item in data if b'=' in item)\n assert not any(pattern.search(name) for name in names), path`,\n ])\n await runCodexProbe(opts, [\n 'sandbox',\n '-P',\n CODEX_PERMISSION_PROFILE,\n '-C',\n opts.cwd,\n 'python3',\n '-c',\n 'import socket,sys\\nfor path in sys.argv[1:]:\\n s=socket.socket(socket.AF_UNIX)\\n try: s.connect(path)\\n except OSError: continue\\n raise SystemExit(1)',\n '/var/run/docker.sock',\n '/run/docker.sock',\n '/var/run/containerd/containerd.sock',\n '/run/containerd/containerd.sock',\n ])\n\n const debugArgs = codexPromptDebugArgs(opts.args, prompt)\n const renderedPrompt = (await runCodexProbe(opts, debugArgs)).stdout\n let parsedPrompt: unknown\n try {\n parsedPrompt = JSON.parse(renderedPrompt)\n } catch {\n throw new Error('runLocalHarness: codex debug prompt-input returned invalid JSON')\n }\n const promptEvidenceText = normalizeCodexDebugPromptNewlines(prompt)\n if (!Array.isArray(parsedPrompt) || !jsonTextContains(parsedPrompt, promptEvidenceText)) {\n throw new Error('runLocalHarness: Codex prompt evidence did not contain the exact task prompt')\n }\n const promptContextWithoutTask = JSON.stringify(redactJsonText(parsedPrompt, promptEvidenceText))\n for (const marker of FORBIDDEN_CODEX_PROMPT_MARKERS) {\n if (promptContextWithoutTask.includes(marker)) {\n throw new Error(`runLocalHarness: Codex prompt evidence contains forbidden marker ${marker}`)\n }\n }\n for (const marker of ['<permissions instructions>', '<environment_context>']) {\n if (!renderedPrompt.includes(marker)) {\n throw new Error(`runLocalHarness: Codex prompt evidence is missing required marker ${marker}`)\n }\n }\n\n const nonPromptArgs = [\n 'codex',\n ...opts.args.map((arg, index) => (index === 1 ? '<PROMPT>' : arg)),\n ]\n return {\n cliVersion,\n executableSha256: opts.executableSha256,\n requestedPromptSha256: sha256(prompt),\n effectivePromptSha256: sha256(renderedPrompt),\n nonPromptArgsSha256: sha256(JSON.stringify(nonPromptArgs)),\n controlledConfigSha256: opts.controlledConfigSha256,\n readDeniedPathsSha256: opts.readDeniedPathsSha256,\n readDeniedPathCount: opts.readDeniedPathCount,\n readDeniedPaths: [...opts.readDeniedPaths],\n policy: { ...CODEX_EXECUTION_POLICY },\n }\n}\n\nfunction assertCodexReproducibleInvocation(command: string, args: string[]): void {\n const executable = basename(command)\n if (executable !== 'codex' && executable !== 'codex.exe') {\n throw new Error('runLocalHarness: reproducible Codex invocation must use the Codex executable')\n }\n const prompt = args[1]\n const expectedPrefix = ['exec', prompt, ...CODEX_REPRODUCIBLE_ARGS]\n const hasExactPrefix = expectedPrefix.every((arg, index) => args[index] === arg)\n const tail = args.slice(expectedPrefix.length)\n const validModel =\n tail[0] === '-m' &&\n typeof tail[1] === 'string' &&\n tail[1].length > 0 &&\n !tail[1].startsWith('-')\n const validReasoning =\n tail[2] === '-c' &&\n typeof tail[3] === 'string' &&\n /^model_reasoning_effort=\"(?:none|minimal|low|medium|high|xhigh)\"$/.test(tail[3])\n if (!hasExactPrefix || tail.length !== 4 || !validModel || !validReasoning) {\n throw new Error(\n 'runLocalHarness: reproducible Codex invocation does not match the required isolated argv',\n )\n }\n}\n\nfunction codexPromptDebugArgs(execArgs: string[], prompt: string): string[] {\n const debugArgs = ['debug', 'prompt-input']\n for (let index = 2; index < execArgs.length; index += 1) {\n const arg = execArgs[index]\n const value = execArgs[index + 1]\n if (arg === '-c' && value !== undefined) {\n debugArgs.push('-c', value)\n index += 1\n } else if (arg === '--disable' && value !== undefined) {\n debugArgs.push('--disable', value)\n index += 1\n } else if (arg === '-m' && value !== undefined) {\n debugArgs.push('-c', `model=${JSON.stringify(value)}`)\n index += 1\n } else if (arg === '-s' && value !== undefined) {\n debugArgs.push('-c', `sandbox_mode=${JSON.stringify(value)}`)\n index += 1\n }\n }\n debugArgs.push(prompt)\n return debugArgs\n}\n\nfunction runCodexProbe(\n opts: {\n command: string\n cwd: string\n env: NodeJS.ProcessEnv\n spawn: NonNullable<RunLocalHarnessOptions['spawn']>\n signal?: AbortSignal\n },\n args: string[],\n): Promise<{ stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n let child: ChildProcess\n try {\n child = opts.spawn(opts.command, args, {\n cwd: opts.cwd,\n env: opts.env,\n stdio: 'pipe',\n detached: process.platform !== 'win32',\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n child.stdin?.end()\n let stdout = ''\n let stderr = ''\n let settled = false\n let forceKillTimer: ReturnType<typeof setTimeout> | null = null\n const timer = setTimeout(() => {\n signalProcessTree(child, 'SIGTERM')\n forceKillTimer = setTimeout(() => signalProcessTree(child, 'SIGKILL'), processKillGraceMs)\n forceKillTimer.unref?.()\n }, 10_000)\n timer.unref?.()\n const onAbort = () => {\n signalProcessTree(child, 'SIGTERM')\n if (!forceKillTimer) {\n forceKillTimer = setTimeout(() => signalProcessTree(child, 'SIGKILL'), processKillGraceMs)\n forceKillTimer.unref?.()\n }\n }\n if (opts.signal) {\n if (opts.signal.aborted) onAbort()\n else opts.signal.addEventListener('abort', onAbort, { once: true })\n }\n child.stdout?.on('data', (chunk) => {\n stdout += String(chunk)\n })\n child.stderr?.on('data', (chunk) => {\n stderr += String(chunk)\n })\n child.on('error', (err) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n if (forceKillTimer) clearTimeout(forceKillTimer)\n opts.signal?.removeEventListener('abort', onAbort)\n reject(err)\n })\n child.on('close', (code, signal) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n if (forceKillTimer) clearTimeout(forceKillTimer)\n opts.signal?.removeEventListener('abort', onAbort)\n if (code !== 0) {\n const safeStderr = redactCodexHome(stderr, opts.env.CODEX_HOME)\n reject(\n new Error(\n `runLocalHarness: Codex evidence probe failed (exit ${String(code)}, signal ${String(signal)}): ${safeStderr.trim()}`,\n ),\n )\n return\n }\n resolve({ stdout, stderr })\n })\n })\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex')\n}\n\n/** Codex's debug renderer converts CRLF pairs to LF. No other whitespace is equivalent. */\nfunction normalizeCodexDebugPromptNewlines(value: string): string {\n return value.replaceAll('\\r\\n', '\\n')\n}\n\nfunction jsonTextContains(value: unknown, needle: string): boolean {\n if (typeof value === 'string') return value.includes(needle)\n if (Array.isArray(value)) return value.some((item) => jsonTextContains(item, needle))\n if (isRecord(value)) return Object.values(value).some((item) => jsonTextContains(item, needle))\n return false\n}\n\nfunction redactJsonText(value: unknown, text: string): unknown {\n if (typeof value === 'string') return value.replaceAll(text, '')\n if (Array.isArray(value)) return value.map((item) => redactJsonText(item, text))\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [key, redactJsonText(item, text)]),\n )\n }\n return value\n}\n\nconst CODEX_AUTH_ENV = ['CODEX_ACCESS_TOKEN', 'CODEX_API_KEY', 'OPENAI_API_KEY'] as const\n\nconst CODEX_PERMISSION_PROFILE = 'agent_runtime_reproducible'\n\nasync function isolateCodexHome(opts: {\n baseEnv: NodeJS.ProcessEnv\n cwd: string\n command: string\n readDeniedPaths: ReadonlyArray<string>\n resolveExecutable: (command: string, env: NodeJS.ProcessEnv) => Promise<string>\n}): Promise<{\n env: NodeJS.ProcessEnv\n command: string\n cleanup: () => Promise<void>\n controlledConfigSha256: string\n executableSha256: string\n readDeniedPaths: string[]\n readDeniedPathsSha256: string\n readDeniedPathCount: number\n diagnosticRedactionValues: string[]\n ambientAuth: string\n isolatedAuth: string\n writeProbe: string\n stagedWriteProbe: string\n deniedProbePaths: string[]\n}> {\n const isolatedHome = await mkdtemp(join(tmpdir(), 'agent-runtime-codex-'))\n await chmod(isolatedHome, 0o700)\n let workspaceTemp = ''\n let stagedExecutableDir = ''\n let ownsStagedExecutableDir = false\n let writeProbe = ''\n const cleanup = async () => {\n if (ownsStagedExecutableDir) {\n await chmod(stagedExecutableDir, 0o700).catch(() => undefined)\n }\n await Promise.all([\n ...(writeProbe ? [rm(writeProbe, { force: true })] : []),\n ...(workspaceTemp ? [rm(workspaceTemp, { recursive: true, force: true })] : []),\n ...(ownsStagedExecutableDir\n ? [rm(stagedExecutableDir, { recursive: true, force: true })]\n : []),\n rm(isolatedHome, { recursive: true, force: true }),\n ])\n }\n try {\n const readDeniedPaths = await normalizeReadDeniedPaths(opts.readDeniedPaths)\n const candidateRoot = await realpath(opts.cwd)\n writeProbe = join(candidateRoot, `.agent-runtime-write-proof-${randomUUID()}`)\n const stagedPath = join(candidateRoot, '.agent-runtime-bin')\n if (\n readDeniedPaths.some(\n (path) =>\n isSameOrDescendant(candidateRoot, path) ||\n isSameOrDescendant(stagedPath, path) ||\n isSameOrDescendant(path, stagedPath),\n )\n ) {\n throw new Error(\n 'runLocalHarness: codexReadDeniedPaths cannot contain the candidate root or staged executable',\n )\n }\n const nativeExecutable = await opts.resolveExecutable(opts.command, opts.baseEnv)\n if (!(await isStaticElfExecutable(nativeExecutable))) {\n throw new Error(\n 'runLocalHarness: reproducible Codex mode requires a statically linked Linux Codex ELF',\n )\n }\n const sourceExecutableSha256 = await sha256File(nativeExecutable)\n\n stagedExecutableDir = stagedPath\n try {\n await mkdir(stagedExecutableDir, { mode: 0o700 })\n ownsStagedExecutableDir = true\n } catch (err) {\n throw new Error(\n `runLocalHarness: candidate-private .agent-runtime-bin must not already exist: ${String((err as NodeJS.ErrnoException).code ?? err)}`,\n )\n }\n const stagedExecutable = join(stagedExecutableDir, 'codex')\n await copyFile(nativeExecutable, stagedExecutable, constants.COPYFILE_FICLONE)\n await chmod(stagedExecutable, 0o500)\n const executableSha256 = await sha256File(stagedExecutable)\n if (\n executableSha256 !== sourceExecutableSha256 ||\n !(await isStaticElfExecutable(stagedExecutable))\n ) {\n throw new Error('runLocalHarness: staged Codex executable digest mismatch')\n }\n await chmod(stagedExecutableDir, 0o500)\n\n workspaceTemp = await mkdtemp(join(candidateRoot, '.agent-runtime-tmp-'))\n await chmod(workspaceTemp, 0o700)\n const ambientHome = resolve(opts.baseEnv.CODEX_HOME?.trim() || join(homedir(), '.codex'))\n const ambientAuth = join(ambientHome, 'auth.json')\n const isolatedAuth = join(isolatedHome, 'auth.json')\n let authText = ''\n try {\n await access(ambientAuth, constants.R_OK)\n authText = await readCodexAuthRedactionText(ambientAuth)\n await symlink(ambientAuth, isolatedAuth)\n } catch (err) {\n throw new Error(\n `runLocalHarness: reproducible Codex mode requires readable auth.json: ${String((err as NodeJS.ErrnoException).code ?? err)}`,\n )\n }\n const deniedHostRoots = [homedir(), opts.baseEnv.HOME?.trim(), ambientHome]\n .filter((path): path is string => Boolean(path))\n .map((path) => resolve(path))\n .filter((path, index, paths) => paths.indexOf(path) === index)\n const controlledConfig = codexControlledConfig({\n ambientTmp: opts.baseEnv.TMPDIR?.trim() || tmpdir(),\n deniedHostRoots,\n workspaceTemp,\n stagedExecutableDir,\n readDeniedPaths,\n })\n await writeFile(join(isolatedHome, 'config.toml'), controlledConfig, { mode: 0o600 })\n const env = { ...opts.baseEnv }\n for (const name of Object.keys(env)) {\n if (\n codexSensitiveEnvironmentName.test(name) ||\n CODEX_AUTH_ENV.some((authName) => authName === name)\n ) {\n delete env[name]\n }\n }\n env.CODEX_HOME = isolatedHome\n const home = homedir()\n const deniedProbePaths = [\n ...deniedHostRoots,\n ambientAuth,\n isolatedAuth,\n join(home, '.claude', '.credentials.json'),\n join(home, '.claude.json'),\n join(home, '.local', 'share', 'opencode', 'auth.json'),\n join(home, '.agents'),\n join(home, 'Documents'),\n join(home, 'Downloads'),\n join(home, '.npm'),\n join(home, 'code'),\n ...readDeniedPaths,\n ].filter((path, index, paths) => paths.indexOf(path) === index)\n return {\n env,\n command: stagedExecutable,\n cleanup,\n controlledConfigSha256: sha256(controlledConfig),\n executableSha256,\n readDeniedPaths,\n readDeniedPathsSha256: sha256(JSON.stringify(readDeniedPaths)),\n readDeniedPathCount: readDeniedPaths.length,\n diagnosticRedactionValues: collectCodexDiagnosticRedactionValues(opts.baseEnv, authText),\n ambientAuth,\n isolatedAuth,\n writeProbe,\n stagedWriteProbe: join(stagedExecutableDir, 'write-proof'),\n deniedProbePaths,\n }\n } catch (err) {\n await cleanup()\n throw err\n }\n}\n\nfunction codexControlledConfig(opts: {\n ambientTmp: string\n deniedHostRoots: string[]\n workspaceTemp: string\n stagedExecutableDir: string\n readDeniedPaths: string[]\n}): string {\n const rules = new Map<string, 'deny' | 'read' | 'write'>()\n const broadDeniedPaths = minimalPathRoots([\n ...opts.deniedHostRoots.map((path) => resolve(path)),\n tmpdir(),\n opts.ambientTmp,\n '/proc',\n '/run/docker',\n '/run/containerd',\n ])\n for (const path of broadDeniedPaths) {\n rules.set(path, 'deny')\n }\n const workspaceRoot = dirname(opts.workspaceTemp)\n for (const path of opts.readDeniedPaths) {\n const alreadyDenied = broadDeniedPaths.some((root) => isSameOrDescendant(path, root))\n if (!alreadyDenied || isSameOrDescendant(path, workspaceRoot)) rules.set(path, 'deny')\n }\n if (!rules.has(opts.workspaceTemp)) rules.set(opts.workspaceTemp, 'write')\n if (!rules.has(opts.stagedExecutableDir)) rules.set(opts.stagedExecutableDir, 'read')\n const filesystemRules = [...rules]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([path, access]) => `${JSON.stringify(path)} = ${JSON.stringify(access)}`)\n .join('\\n')\n return `default_permissions = \"${CODEX_PERMISSION_PROFILE}\"\napproval_policy = \"never\"\nallow_login_shell = false\nservice_tier = \"default\"\n\n[shell_environment_policy]\ninherit = \"core\"\nignore_default_excludes = false\nexclude = [\"^CODEX_HOME$\", \"(?i).*TOKEN.*\", \"(?i).*KEY.*\", \"(?i).*SECRET.*\", \"(?i).*PASSWORD.*\", \"(?i).*CREDENTIAL.*\", \"(?i).*AUTH.*\", \"(?i).*COOKIE.*\"]\nset = { TMPDIR = ${JSON.stringify(opts.workspaceTemp)} }\n\n[permissions.${CODEX_PERMISSION_PROFILE}.filesystem]\n\":minimal\" = \"read\"\n${filesystemRules}\n\":slash_tmp\" = \"deny\"\n\n[permissions.${CODEX_PERMISSION_PROFILE}.filesystem.\":workspace_roots\"]\n\".\" = \"write\"\n\".git\" = \"deny\"\n\n[permissions.${CODEX_PERMISSION_PROFILE}.network]\nenabled = false\n\n[permissions.${CODEX_PERMISSION_PROFILE}.network.unix_sockets]\n\"/var/run/docker.sock\" = \"deny\"\n\"/run/docker.sock\" = \"deny\"\n\"/var/run/containerd/containerd.sock\" = \"deny\"\n\"/run/containerd/containerd.sock\" = \"deny\"\n`\n}\n\nfunction isSameOrDescendant(path: string, root: string): boolean {\n const normalizedPath = resolve(path)\n const normalizedRoot = resolve(root)\n return normalizedPath === normalizedRoot || normalizedPath.startsWith(`${normalizedRoot}${sep}`)\n}\n\nfunction minimalPathRoots(paths: ReadonlyArray<string>): string[] {\n const ordered = [...new Set(paths.map((path) => resolve(path)))].sort(\n (a, b) => a.length - b.length || a.localeCompare(b),\n )\n return ordered.filter(\n (path, index) => !ordered.slice(0, index).some((root) => isSameOrDescendant(path, root)),\n )\n}\n\nasync function normalizeReadDeniedPaths(paths: ReadonlyArray<string>): Promise<string[]> {\n if (!Array.isArray(paths)) {\n throw new Error('runLocalHarness: codexReadDeniedPaths must be an array of absolute paths')\n }\n const normalized = new Set<string>()\n for (const path of paths) {\n if (typeof path !== 'string' || path.length === 0 || path.includes('\\0') || !isAbsolute(path)) {\n throw new Error('runLocalHarness: codexReadDeniedPaths must contain absolute paths')\n }\n const absolute = resolve(path)\n normalized.add(absolute)\n try {\n normalized.add(await realpath(absolute))\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err\n }\n }\n return [...normalized].sort()\n}\n\nasync function resolveCodexNativeExecutable(\n command: string,\n env: NodeJS.ProcessEnv,\n): Promise<string> {\n const candidates =\n command.includes(sep) || isAbsolute(command)\n ? [resolve(command)]\n : (env.PATH ?? '')\n .split(delimiter)\n .filter(Boolean)\n .map((entry) => join(entry, command))\n const seen = new Set<string>()\n for (const candidate of candidates) {\n let resolved: string\n try {\n await access(candidate, constants.X_OK)\n resolved = await realpath(candidate)\n } catch {\n continue\n }\n if (seen.has(resolved)) continue\n seen.add(resolved)\n if (await isStaticElfExecutable(resolved)) return resolved\n const packageRoot = await findCodexPackageRoot(resolved)\n if (!packageRoot) continue\n const bundled = await findBundledCodexExecutable(packageRoot)\n if (bundled) return bundled\n }\n throw new Error(\n 'runLocalHarness: could not resolve the native Codex executable from the requested command',\n )\n}\n\nasync function findCodexPackageRoot(file: string): Promise<string | undefined> {\n let cursor = dirname(file)\n while (true) {\n try {\n const parsed = JSON.parse(await readFile(join(cursor, 'package.json'), 'utf8')) as {\n name?: unknown\n }\n if (parsed.name === '@openai/codex') return cursor\n } catch {\n // Keep walking; PATH wrappers commonly live outside the package directory.\n }\n const parent = dirname(cursor)\n if (parent === cursor) return undefined\n cursor = parent\n }\n}\n\nasync function findBundledCodexExecutable(packageRoot: string): Promise<string | undefined> {\n const target = linuxCodexTarget()\n const candidates = [\n join(\n packageRoot,\n 'node_modules',\n '@openai',\n target.packageName,\n 'vendor',\n target.triple,\n 'bin',\n 'codex',\n ),\n join(packageRoot, 'vendor', target.triple, 'bin', 'codex'),\n ]\n for (const executable of candidates) {\n if (await isStaticElfExecutable(executable)) return executable\n }\n return undefined\n}\n\nfunction linuxCodexTarget(): { packageName: string; triple: string } {\n if (process.platform !== 'linux') {\n throw new Error('runLocalHarness: reproducible Codex mode requires Linux')\n }\n if (process.arch === 'x64') {\n return { packageName: 'codex-linux-x64', triple: 'x86_64-unknown-linux-musl' }\n }\n if (process.arch === 'arm64') {\n return { packageName: 'codex-linux-arm64', triple: 'aarch64-unknown-linux-musl' }\n }\n throw new Error(`runLocalHarness: unsupported Linux architecture ${process.arch}`)\n}\n\nasync function isStaticElfExecutable(path: string): Promise<boolean> {\n let handle: Awaited<ReturnType<typeof open>> | undefined\n try {\n await access(path, constants.X_OK)\n handle = await open(path, 'r')\n const header = Buffer.alloc(64)\n const { bytesRead } = await handle.read(header, 0, header.length, 0)\n if (\n bytesRead !== header.length ||\n !header.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) ||\n header[4] !== 2 ||\n header[5] !== 1\n ) {\n return false\n }\n const programHeaderOffset = Number(header.readBigUInt64LE(32))\n const programHeaderSize = header.readUInt16LE(54)\n const programHeaderCount = header.readUInt16LE(56)\n const expectedMachine = process.arch === 'x64' ? 62 : process.arch === 'arm64' ? 183 : -1\n if (\n ![2, 3].includes(header.readUInt16LE(16)) ||\n header.readUInt16LE(18) !== expectedMachine ||\n !Number.isSafeInteger(programHeaderOffset) ||\n programHeaderOffset < 64 ||\n programHeaderSize < 56 ||\n programHeaderSize > 1024 ||\n programHeaderCount === 0 ||\n programHeaderCount > 1024\n ) {\n return false\n }\n const tableSize = programHeaderSize * programHeaderCount\n const table = Buffer.alloc(tableSize)\n const tableRead = await handle.read(table, 0, tableSize, programHeaderOffset)\n if (tableRead.bytesRead !== tableSize) return false\n for (let index = 0; index < programHeaderCount; index += 1) {\n const type = table.readUInt32LE(index * programHeaderSize)\n if (type === 3) return false\n }\n return true\n } catch {\n return false\n } finally {\n await handle?.close()\n }\n}\n\nfunction sha256File(path: string): Promise<string> {\n return new Promise((resolveDigest, reject) => {\n const hash = createHash('sha256')\n const stream = createReadStream(path)\n stream.on('error', reject)\n stream.on('data', (chunk) => hash.update(chunk))\n stream.on('end', () => resolveDigest(hash.digest('hex')))\n })\n}\n\nfunction signalProcessTree(child: ChildProcess, signal: NodeJS.Signals): void {\n if (process.platform !== 'win32' && typeof child.pid === 'number') {\n try {\n process.kill(-child.pid, signal)\n return\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ESRCH') return\n }\n }\n try {\n child.kill(signal)\n } catch {\n // The process may have exited between the timer and signal delivery.\n }\n}\n\n/** Parse and validate the one terminal usage event emitted by `codex exec --json`. */\nexport function parseCodexTokenUsage(stdout: string): CodexTokenUsage {\n const completed: unknown[] = []\n for (const [index, line] of stdout.split(/\\r?\\n/).entries()) {\n if (line.trim().length === 0) continue\n let event: unknown\n try {\n event = JSON.parse(line)\n } catch {\n throw new Error(`runLocalHarness: Codex JSONL line ${index + 1} is not valid JSON`)\n }\n if (isRecord(event) && event.type === 'turn.completed') completed.push(event)\n }\n if (completed.length !== 1) {\n throw new Error(\n `runLocalHarness: expected exactly one Codex turn.completed usage event, received ${completed.length}`,\n )\n }\n const event = completed[0]\n if (!isRecord(event) || !isRecord(event.usage)) {\n throw new Error('runLocalHarness: Codex turn.completed event is missing usage')\n }\n const usage = event.usage\n const inputTokens = naturalNumber(usage.input_tokens, 'input_tokens')\n const cachedInputTokens = naturalNumber(usage.cached_input_tokens, 'cached_input_tokens')\n const outputTokens = naturalNumber(usage.output_tokens, 'output_tokens')\n const reasoningOutputTokens = naturalNumber(\n usage.reasoning_output_tokens,\n 'reasoning_output_tokens',\n )\n if (cachedInputTokens > inputTokens) {\n throw new Error('runLocalHarness: Codex cached_input_tokens exceeds input_tokens')\n }\n if (reasoningOutputTokens > outputTokens) {\n throw new Error('runLocalHarness: Codex reasoning_output_tokens exceeds output_tokens')\n }\n return { inputTokens, cachedInputTokens, outputTokens, reasoningOutputTokens }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction naturalNumber(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(`runLocalHarness: Codex usage.${field} must be a non-negative safe integer`)\n }\n return value\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,YAAY;AACrB,SAAS,gCAAgC;AAgBlC,IAAM,gCAAN,cAA4C,MAAM;AAAA,EAGvD,YACW,QACA,YACT,OACA;AACA;AAAA,MACE,yDAAyD,MAAM,gBAAgB,KAAK,UAAU,UAAU,CAAC;AAAA,MACzG,EAA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AAM,gCAAgC,KAAK,sCAAsC;AAAA,EAC7F;AACA,SAAO;AACT;","names":["constants","open","model","resolve","constants","access","open","event"]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|