@tangle-network/agent-runtime 0.102.2 → 0.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +73 -10
  2. package/dist/agent.d.ts +1 -1
  3. package/dist/agent.js +5 -5
  4. package/dist/analyst-loop.d.ts +1 -1
  5. package/dist/candidate-execution/index.d.ts +5 -41
  6. package/dist/candidate-execution/index.js +8 -6
  7. package/dist/{chunk-QCXD7NHM.js → chunk-3LJF5XSE.js} +79 -334
  8. package/dist/chunk-3LJF5XSE.js.map +1 -0
  9. package/dist/{chunk-3DW5DEKQ.js → chunk-5AITUUHO.js} +3 -3
  10. package/dist/{chunk-SQ3ZJH3Y.js → chunk-6WZZXQV5.js} +467 -23
  11. package/dist/chunk-6WZZXQV5.js.map +1 -0
  12. package/dist/{chunk-SCOHHMKU.js → chunk-AAN2MB2X.js} +3 -3
  13. package/dist/{chunk-KSM6GFHP.js → chunk-B7K7V22Y.js} +2 -2
  14. package/dist/{chunk-ZUCUAFVF.js → chunk-EAQ5YRRY.js} +1382 -62
  15. package/dist/chunk-EAQ5YRRY.js.map +1 -0
  16. package/dist/chunk-ISPWRSEC.js +408 -0
  17. package/dist/chunk-ISPWRSEC.js.map +1 -0
  18. package/dist/{chunk-7FJJUC73.js → chunk-LFM4JBRW.js} +29 -6
  19. package/dist/{chunk-7FJJUC73.js.map → chunk-LFM4JBRW.js.map} +1 -1
  20. package/dist/{chunk-ROILMKDL.js → chunk-QYCKIV6C.js} +3 -3
  21. package/dist/{chunk-LJLG734E.js → chunk-SBTWKPVR.js} +10 -11
  22. package/dist/{chunk-LJLG734E.js.map → chunk-SBTWKPVR.js.map} +1 -1
  23. package/dist/{chunk-CK76OZPM.js → chunk-SNSMRT6H.js} +56 -386
  24. package/dist/chunk-SNSMRT6H.js.map +1 -0
  25. package/dist/{chunk-EKUMRQNR.js → chunk-TUSOOIDV.js} +2 -2
  26. package/dist/{chunk-J6V6DWWS.js → chunk-ZOYN3JR5.js} +5 -5
  27. package/dist/{chunk-377GOJHJ.js → chunk-ZXICDSAK.js} +333 -4
  28. package/dist/chunk-ZXICDSAK.js.map +1 -0
  29. package/dist/{completion-gate-C6dhVN-N.d.ts → completion-gate-DLINnrkM.d.ts} +1 -1
  30. package/dist/{coordination-D9l_YmwW.d.ts → coordination-DTehA977.d.ts} +250 -8
  31. package/dist/environment-provider.d.ts +2 -2
  32. package/dist/index.d.ts +12 -12
  33. package/dist/index.js +17 -15
  34. package/dist/index.js.map +1 -1
  35. package/dist/intelligence.d.ts +26 -8
  36. package/dist/intelligence.js +24 -7
  37. package/dist/intelligence.js.map +1 -1
  38. package/dist/knowledge.d.ts +6 -6
  39. package/dist/knowledge.js +9 -9
  40. package/dist/{loop-runner-bin-PnWslIw4.d.ts → loop-runner-bin-DhIXsLAd.d.ts} +2 -2
  41. package/dist/loop-runner-bin.d.ts +5 -5
  42. package/dist/loop-runner-bin.js +6 -6
  43. package/dist/loops.d.ts +305 -148
  44. package/dist/loops.js +82 -14
  45. package/dist/mcp/bin.js +3 -3
  46. package/dist/mcp/index.d.ts +6 -6
  47. package/dist/mcp/index.js +6 -6
  48. package/dist/profiles.d.ts +1 -1
  49. package/dist/{profile-DbfaMTdk.d.ts → protected-model-port-DzkUY3HQ.d.ts} +41 -3
  50. package/dist/{structural-rollout-D7xik9XR.d.ts → structural-rollout-BFPIy3iw.d.ts} +3 -3
  51. package/dist/supervise-Cp8bNcJi.d.ts +379 -0
  52. package/dist/testing.js +10 -10
  53. package/dist/testing.js.map +1 -1
  54. package/dist/{types-CWqfCO8s.d.ts → types-Cbp72qyu.d.ts} +1 -1
  55. package/dist/{types-CLat4bT9.d.ts → types-DK11_O4L.d.ts} +1 -1
  56. package/dist/types-lZTE_LBd.d.ts +957 -0
  57. package/dist/{worktree-fanout-DsIR4d6w.d.ts → worktree-fanout-DiiJWjJO.d.ts} +17 -5
  58. package/package.json +3 -2
  59. package/skills/build-with-agent-runtime/SKILL.md +7 -5
  60. package/skills/generate-eval/SKILL.md +45 -52
  61. package/skills/loop-writer/SKILL.md +79 -147
  62. package/skills/supervise/SKILL.md +33 -14
  63. package/dist/chunk-377GOJHJ.js.map +0 -1
  64. package/dist/chunk-CK76OZPM.js.map +0 -1
  65. package/dist/chunk-IMSNJSXH.js +0 -73
  66. package/dist/chunk-IMSNJSXH.js.map +0 -1
  67. package/dist/chunk-QCXD7NHM.js.map +0 -1
  68. package/dist/chunk-SQ3ZJH3Y.js.map +0 -1
  69. package/dist/chunk-ZUCUAFVF.js.map +0 -1
  70. package/dist/supervise-BQdNAXtK.d.ts +0 -131
  71. package/dist/types-D870JlH0.d.ts +0 -500
  72. /package/dist/{chunk-3DW5DEKQ.js.map → chunk-5AITUUHO.js.map} +0 -0
  73. /package/dist/{chunk-SCOHHMKU.js.map → chunk-AAN2MB2X.js.map} +0 -0
  74. /package/dist/{chunk-KSM6GFHP.js.map → chunk-B7K7V22Y.js.map} +0 -0
  75. /package/dist/{chunk-ROILMKDL.js.map → chunk-QYCKIV6C.js.map} +0 -0
  76. /package/dist/{chunk-EKUMRQNR.js.map → chunk-TUSOOIDV.js.map} +0 -0
  77. /package/dist/{chunk-J6V6DWWS.js.map → chunk-ZOYN3JR5.js.map} +0 -0
@@ -1,9 +1,9 @@
1
1
  import { AgentProfile } from '@tangle-network/agent-interface';
2
2
  import { AnalystFinding, DefaultVerdict } from '@tangle-network/agent-eval';
3
- import { N as NodeId, d as Settled, e as Spend, f as AgentSpec, S as Scope, g as SpawnJournal, a as ResultBlobStore, h as ExecutorRegistry, B as Budget, A as Agent, i as RootHandle, b as SupervisedResult, c as Executor } from './types-D870JlH0.js';
4
- import { I as Iteration, R as RuntimeHooks } from './types-CLat4bT9.js';
3
+ import { N as NodeId, a as Settled, g as Spend, h as AgentSpec, S as Scope, c as SpawnJournal, b as ResultBlobStore, i as ExecutorRegistry, B as Budget, A as Agent, j as RootHandle, e as SupervisedResult, f as Executor } from './types-lZTE_LBd.js';
4
+ import { I as Iteration, R as RuntimeHooks } from './types-DK11_O4L.js';
5
5
  import { BackendType } from '@tangle-network/sandbox';
6
- import { W as WorktreeHarnessResult, G as GitRunner, a as WorktreeCheckRunner, D as DeliverableSpec } from './completion-gate-C6dhVN-N.js';
6
+ import { W as WorktreeHarnessResult, G as GitRunner, a as WorktreeCheckRunner, D as DeliverableSpec } from './completion-gate-DLINnrkM.js';
7
7
  import { L as LocalHarness, r as runLocalHarness } from './local-harness-CtK9dSny.js';
8
8
 
9
9
  /**
@@ -114,6 +114,17 @@ interface FanoutOptions<Item, D> {
114
114
  * synthesis child IS the selection); supplying both is a config error.
115
115
  */
116
116
  selectWinner?: FanoutWinnerSelector<D>;
117
+ /**
118
+ * Cap on how many item children run AT ONCE. When set, the fanout dispatches through
119
+ * `rollingDispatch`: it fills `width` slots and admits the next item the moment one settles,
120
+ * instead of opening every item in a single round. Same items, same selection, same conserved
121
+ * pool — only the simultaneity changes.
122
+ *
123
+ * Unset (the default) keeps the single-round batch behavior every existing caller has. Set it
124
+ * when the items outnumber the live capacity a host can actually afford, so the pool is not
125
+ * spent opening children that then queue behind a real fence.
126
+ */
127
+ width?: number;
117
128
  }
118
129
  /** A winner-selection strategy: argmax/sort over the gathered child iterations (each output is the
119
130
  * child's `Outcome<D>`), returning the chosen iteration or `undefined` when none qualifies. */
@@ -451,8 +462,9 @@ interface TrajectoryNode {
451
462
  readonly children: ReadonlyArray<NodeId>;
452
463
  readonly label: string;
453
464
  readonly runtime: string;
454
- /** Terminal status the journal recorded for this node. */
455
- readonly status: 'done' | 'failed' | 'cancelled' | 'pending';
465
+ /** Terminal status the journal recorded for this node. `'waiting'` is a wait-state node that was
466
+ * armed and never woken the journal's record of a run that died mid-wait. */
467
+ readonly status: 'done' | 'failed' | 'cancelled' | 'pending' | 'waiting';
456
468
  /** This node's OWN conserved spend (from its `settled` event). */
457
469
  readonly ownSpend: Spend;
458
470
  /** This node's spend PLUS every descendant's — the rolled-up subtree cost. The cost a parent
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-runtime",
3
- "version": "0.102.2",
3
+ "version": "0.103.0",
4
4
  "description": "Shared task-lifecycle skeleton for agents: a recursive loop kernel for chat turns, one-shot tasks, and multi-attempt loops, with trace capture and eval-gated self-improvement. Domain behavior lives in adapters; scoring and ship-gates in @tangle-network/agent-eval.",
5
5
  "homepage": "https://github.com/tangle-network/agent-runtime#readme",
6
6
  "repository": {
@@ -110,9 +110,10 @@
110
110
  "typecheck:examples": "tsc --noEmit -p tsconfig.examples.json",
111
111
  "generate:testing-fixture": "tsx scripts/generate-agent-improvement-proposal-fixture.ts",
112
112
  "check:testing-fixture": "tsx scripts/generate-agent-improvement-proposal-fixture.ts --check",
113
+ "check:skills": "node scripts/check-skills.mjs",
113
114
  "verify:bench": "pnpm build && pnpm --filter @tangle-network/agent-bench run typecheck:public && pnpm --filter @tangle-network/agent-bench test && pnpm --filter @tangle-network/agent-bench run verify:package:local-runtime",
114
115
  "verify:bench:published": "pnpm build && pnpm --filter @tangle-network/agent-bench run typecheck:public && pnpm --filter @tangle-network/agent-bench test && pnpm --filter @tangle-network/agent-bench run verify:package",
115
- "verify:package": "pnpm run check:testing-fixture && node scripts/verify-package-exports.mjs",
116
+ "verify:package": "pnpm run check:testing-fixture && pnpm run check:skills && node scripts/verify-package-exports.mjs",
116
117
  "verify:primeintellect": "pnpm build && node scripts/verify-primeintellect-v1.mjs",
117
118
  "verify:primeintellect:live": "pnpm build && node scripts/verify-primeintellect-live.mjs",
118
119
  "docs:api": "pnpm run build && typedoc && node scripts/gen-primitive-catalog.mjs",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: build-with-agent-runtime
3
- description: Use before adding an agent loop, benchmark, optimizer, trace wrapper, or candidate activation path. Find and compose the existing Runtime, Eval, Knowledge, and Interface primitives.
3
+ description: Choose and compose current runtime, eval, knowledge, and interface APIs before adding wrappers.
4
4
  ---
5
5
 
6
6
  # Build with agent-runtime
@@ -62,10 +62,11 @@ It performs these steps in order:
62
62
 
63
63
  1. Analyze completed traces.
64
64
  2. Search for a candidate on development tasks.
65
- 3. Freeze the baseline and winner into one exact experiment.
66
- 4. Reject the experiment if its candidate differs from the search winner.
67
- 5. Run baseline and candidate on the same held-back tasks.
68
- 6. Produce findings, confidence intervals, quality, cost, latency, and a decision.
65
+ 3. Build the frozen baseline, candidate, and held-back work.
66
+ 4. Return only baseline, candidate, held-back tasks, and policy; Runtime adds the optimizer ancestry and seals the final experiment.
67
+ 5. Reject the experiment if its candidate differs from the search winner.
68
+ 6. Run baseline and candidate on the same held-back tasks.
69
+ 7. Produce findings, confidence intervals, quality, cost, latency, and a decision.
69
70
 
70
71
  After a person or tenant policy approves the proposal, call `createAgentImprovementActivation(...)` with target identities, funding owner, authority, intent, and expiry.
71
72
  Runtime derives the expected current digests from the measured experiment.
@@ -122,5 +123,6 @@ The product must not recreate candidate hashing, paired comparison, confidence i
122
123
 
123
124
  ## Then consider
124
125
 
126
+ - Use `build-with-agent-knowledge` when agents should improve retrieval, memory, or a knowledge base.
125
127
  - Use `critical-audit` when the change introduces or alters a public contract.
126
128
  - Use `verify` before publishing or adopting the package in a product.
@@ -1,60 +1,53 @@
1
1
  ---
2
2
  name: generate-eval
3
- description: Author ONE execution-certifiable, search-discriminating eval task for a given target (library@version, repo, or release-notes URL). The runtime certifies — your job is to produce a candidate that survives both gates.
3
+ description: Create one pinned fresh-API coding case that passes execution and defeats a no-search baseline.
4
4
  ---
5
5
 
6
- # generate-eval — author a certifiable eval task
6
+ # Generate Eval
7
7
 
8
- You are authoring a benchmark task that measures whether web search helps a
9
- coding agent get a **current API detail exactly right**. Your candidate is
10
- admitted only if an independent certifier confirms BOTH gates:
11
-
12
- 1. **Grounding** — your reference solution executes and passes in a clean
13
- workspace against the real pinned target (the library is the oracle, not
14
- your memory).
15
- 2. **Discrimination** — a strong model WITHOUT search fails your oracle (a
16
- task models already know measures nothing).
8
+ Use this for one benchmark case that measures whether current official documentation helps a coding agent use an exact API correctly.
9
+ Do not use it for general coding quality or subjective output.
17
10
 
18
11
  ## Inputs
19
12
 
20
- - `TARGET` a library + version (`hono@4.6`), a repo, or a release-notes URL.
21
- - `OUT` the file path where you write exactly one candidate JSON object.
22
-
23
- ## Procedure
24
-
25
- 1. **Find the discriminating detail.** Use web search on the target's release
26
- notes / changelog / current docs. Pick ONE precise, recent-or-niche detail:
27
- an exact method name, option key, config field, or flag — ideally one where
28
- the *plausible wrong guess* is specific (e.g. models guess `maxRetries`
29
- where the real key is `limit`). Record the primary-doc URL.
30
- 2. **Author the task** as JSON with `schemaVersion: 1` and fields:
31
- - `id` (kebab-case), `domain`, `prompt` ask for the exact identifiers and
32
- a minimal runnable usage; the answer must be gradable from its TEXT.
33
- - `needsFreshDocs` the specific fact + the wrong guess models make.
34
- - `oracle` `containsAll`: distinctive exact identifiers a correct answer
35
- must contain (specific enough that a wrong answer can't contain them by
36
- accident); `notContains`: the plausible wrong/deprecated forms; optional
37
- `regex` for structure. No generic words.
38
- - `searchQuery`, `expectedUrlIncludes`, `sourceUrl` — retrieval provenance.
39
- - `setup` — commands that provision a CLEAN workspace and PIN the target
40
- (`npm init -y`, `npm i hono@4.6.3` / `pip install pkg==x.y`). The
41
- certifier replays these from scratch.
42
- - `reference` — `files` (minimal code exercising the detail against the
43
- real installed target) + `cmd` (exits 0 only when the API is used
44
- correctly) + `stdoutContains` (print a value derived from the real API
45
- call, so an empty no-op can't pass).
46
- 3. **Self-check before emitting** (you have a shell use it):
47
- - Run `setup` + `reference.cmd` yourself; fix until they pass.
48
- - Write the correct answer to your own prompt; confirm every
49
- `containsAll` string appears in it and none of `notContains` does.
50
- - Write the *plausible wrong* answer; confirm the oracle FAILS it.
51
- 4. **Emit** exactly one JSON object to `OUT`. No prose around it.
52
-
53
- ## Hard rules
54
-
55
- - **Never mock or stub the target.** The reference must import and exercise
56
- the real installed library. A mocked reference is a void candidate.
57
- - Expect repair feedback: the certifier returns gate diagnostics (compile
58
- errors, oracle misses). Iterating is normal fix and re-emit.
59
- - One candidate per invocation. Quality over quantity: a rejected candidate
60
- costs a full certification cycle.
13
+ - `TARGET`: a pinned package version, repository commit, or release.
14
+ - `OUT`: the path for one candidate JSON object.
15
+
16
+ Read `bench/src/generate-eval/schema.ts` and `bench/src/generate-eval/certify.ts` before authoring the candidate.
17
+ Those files define the current format and checks.
18
+
19
+ ## Build One Case
20
+
21
+ 1. Read the target's official documentation, release notes, types, and installed implementation.
22
+ 2. Find one recent or niche identifier, option, behavior, or migration that a capable model could plausibly get wrong without search.
23
+ 3. Pin the target exactly and record the primary source URL.
24
+ 4. Write a realistic prompt that requires the detail but does not reveal it.
25
+ 5. Add a minimal reference workspace that imports and exercises the real target.
26
+ 6. Make the reference command fail on a no-op, deprecated form, or plausible wrong guess.
27
+ 7. Add exact positive and negative answer checks only where text matching cannot be satisfied accidentally.
28
+
29
+ Never mock the target or use the candidate answer as the source of truth.
30
+ Prefer executable behavior over identifier matching.
31
+
32
+ ## Calibrate
33
+
34
+ Run all of these before writing `OUT`:
35
+
36
+ 1. Fresh setup plus the reference command passes in a clean workspace.
37
+ 2. The correct answer passes the answer checks.
38
+ 3. A plausible wrong answer fails.
39
+ 4. A strong no-search baseline fails for the intended API mistake rather than setup, network, or scoring failure.
40
+ 5. A search-enabled pilot can find the official source and solve the case.
41
+
42
+ Reject a case that both baselines solve, neither baseline can solve, depends on an unavailable package, leaks the answer through setup, or grades generic words.
43
+
44
+ ## Output
45
+
46
+ Write exactly one schema-valid candidate to `OUT`.
47
+ Include the pinned target, source, clean setup, reference files and command, expected output, answer checks, and the observed calibration results required by the current schema.
48
+
49
+ ## Then consider
50
+
51
+ - `calibrate-before-measure` before running a larger search comparison.
52
+ - `eval-engineering` when the target is a production agent capability rather than fresh API recall.
53
+ - `verify` before publishing a generated task set.
@@ -1,171 +1,103 @@
1
1
  ---
2
2
  name: loop-writer
3
- description: Author clean recursive agent loops on @tangle-network/agent-runtime. Use for Scope/supervisor orchestration, runLoop, Pi/sandbox drivers, fanout, trace analysts, verifiers/judges, question escalation, live messages, and self-improving loop recipes.
3
+ description: Write a custom control policy only when current runtime composition APIs cannot express it.
4
4
  ---
5
5
 
6
- # loop-writer
6
+ # Loop Writer
7
7
 
8
- Design the smallest loop that can honestly solve the objective. The blessed
9
- surface is the substrate: `fanout`/`pipeline` for fixed shapes, `runLoop` for
10
- round-synchronous sandbox loops, and `Scope`/Supervisor for recursive
11
- driver/worker trees. Do not create a second loop grammar.
8
+ Use this only for a control policy that the shipped high-level APIs cannot express.
9
+ Read `docs/canonical-api.md`, current exports, the implementation, and the nearest test before writing code.
10
+ Do not copy signatures from this skill.
12
11
 
13
- ## Mental Model
12
+ ## Choose The Existing Path First
14
13
 
15
- ```txt
16
- user -> Pi/root driver -> supervisor -> sandbox driver -> worker -> leaf harness
17
- ```
14
+ | Need | Existing path |
15
+ |---|---|
16
+ | One product chat turn | `handleChatTurn(...)` |
17
+ | One task or bounded multi-turn task | `runAgentTask(...)` or `runAgentTaskStream(...)` |
18
+ | Two or more actors taking turns | `defineConversation(...)` and `runConversation(...)` |
19
+ | A driver coordinating workers | `supervise(...)` or `superviseSurface(...)` |
20
+ | Parallel or fixed composition | `fanout(...)`, `pipeline(...)`, `panel(...)`, `verify(...)`, or `loopUntil(...)` |
21
+ | Parallel repository workers with isolated branches | `worktreeFanout(...)` |
22
+ | Repeated work in a graded tool environment | `runAgentic(...)` |
23
+ | Equal-budget comparison over that environment | `runBenchmark(...)` |
24
+ | Low-level round policy with custom planning and stopping | `runLoop(...)` |
18
25
 
19
- Each level may spawn below, wait below, analyze below, steer below, and escalate
20
- questions upward. The substrate owns budget, trace, abort, journal, and replay.
21
- The driver owns strategy.
26
+ If an existing row fits, use it and stop.
27
+ Do not create another wrapper solely to rename inputs or results.
22
28
 
23
- ## Pick The Primitive
29
+ ## Custom Loop Contract
24
30
 
25
- | Objective | Use |
26
- |---|---|
27
- | Try N attempts, pick best | `fanout` (or the `sample` strategy) |
28
- | Ordered stages | `pipeline` |
29
- | Improve until executable check passes | `loopUntil` + verifier |
30
- | Review from several lenses | `panel` |
31
- | Simulated user/product eval | `defineConversation` + `runConversation` |
32
- | Dynamic topology / drivers of drivers | `Scope` or sandbox driver + `createCoordinationTools` |
33
- | Run N coding workers on isolated worktrees, gate each, pick best patch | `worktreeFanout` |
34
- | Mutate a shared repo | git branch/clone loop with typed merge outcomes (`gitWorkspace` seam) |
35
-
36
- If a fixed combinator solves it, do not use a dynamic driver.
37
-
38
- ## Minimal Sandbox Loop
39
-
40
- ```ts
41
- // runLoop takes a caller-supplied Driver directly (plan() → Task[]; decide() → terminal).
42
- // `[task]` → refine, N copies → fanout, `[]` → stop. Keep it this small or use a Strategy.
43
- const refineDriver: Driver<Task, Out, 'done' | 'fail'> = {
44
- name: 'refine',
45
- plan: async (task, history) => (history.at(-1)?.verdict?.valid ? [] : [task]),
46
- decide: (history) => (history.at(-1)?.verdict?.valid ? 'done' : 'fail'),
47
- }
48
-
49
- const trace: unknown[] = []
50
- const result = await runLoop({
51
- driver: refineDriver,
52
- agentRun: agentRunSpec,
53
- output,
54
- validator: executableGate,
55
- task,
56
- ctx: {
57
- sandboxClient,
58
- traceEmitter: { emit: async (event) => trace.push(event) },
59
- },
60
- })
61
-
62
- const observation = await observe(
63
- {
64
- task: String(task),
65
- output: JSON.stringify(result.winner?.output ?? result.decision),
66
- trace,
67
- outcome: result.winner ? 'passed' : 'failed',
68
- runId,
69
- },
70
- { chat, model, corpus },
71
- )
72
- ```
31
+ A custom loop has five explicit parts:
73
32
 
74
- ## Minimal Recursive Driver
75
-
76
- ```ts
77
- const driver: Agent<Task, Output> = {
78
- name: 'secure-build-driver',
79
- async act(task, scope) {
80
- const spawned = scope.spawn(workerAgent, task, { budget: perWorker, label: 'worker-a' })
81
- if (!spawned.ok) throw new Error(spawned.reason)
82
-
83
- const settled = await scope.next()
84
- const observation = await observe(
85
- {
86
- task: String(task),
87
- output: JSON.stringify(settled),
88
- trace: [settled, scope.view],
89
- outcome: settled?.kind === 'done' ? 'passed' : 'failed',
90
- runId,
91
- },
92
- { chat, model, corpus },
93
- )
94
-
95
- const steer = observation.findings[0]?.recommended_action
96
- if (!steer) return synthesize(settled, observation)
97
-
98
- const correction = scope.spawn(workerAgent, { task, prior: settled }, {
99
- budget: perWorker,
100
- label: 'worker-corrected',
101
- })
102
- if (!correction.ok) throw new Error(correction.reason)
103
- if (!scope.send(correction.handle.id, { steer })) throw new Error('steer delivery failed')
104
-
105
- const fixed = await scope.next()
106
- return synthesize(fixed, observation)
107
- },
108
- }
109
-
110
- const result = await createSupervisor<Task, Output>().run(driver, task, supervisorOpts)
33
+ ```text
34
+ task -> plan work -> execute attempts -> check outcomes -> continue or stop
111
35
  ```
112
36
 
113
- When the driver lives in a sandbox, expose the same verbs through
114
- `createCoordinationTools`: `spawn_agent`, `await_event`, `observe_agent`,
115
- `steer_agent`, `list_questions`, `answer_question`, `ask_parent`, `stop`, and
116
- optional analyst tools (`list_analysts`, `run_analyst`).
37
+ Keep ownership separate:
117
38
 
118
- ## Role Boundaries
39
+ - The driver chooses work and termination from task plus prior outcomes.
40
+ - Executors run attempts and return observed artifacts.
41
+ - Objective checks determine whether an artifact is usable.
42
+ - Trace emission records plans, attempts, tool effects, checks, spend, and decisions.
43
+ - The caller owns policy, budgets, credentials, persistence, and side-effect authority.
119
44
 
120
- - **Verifier**: executable shippability gate; controls accept/reject.
121
- - **Judge**: held-out score only; never steers the current run.
122
- - **Analyst**: trace-derived diagnosis over worker, pairwise, subtree, or full
123
- loop traces; may emit findings, questions, messages, or blockers.
124
- - **Driver/reviewer**: consumes evidence and chooses continue, steer, spawn,
125
- answer, escalate, or stop.
45
+ The driver must not mutate product state while planning.
46
+ An LLM score must not override failed builds, tests, missing evidence, denied permissions, or service errors.
126
47
 
127
- ## Questions And Steering
48
+ ## Required States
128
49
 
129
- Questions are blockers, not prose hidden in output. A child asks its parent; the
130
- parent answers when it has evidence, defers when safe, or escalates to Pi/user
131
- when answering would invent requirements. `failClosed` loops must not stop clean
132
- with unresolved `blocks-run` questions.
50
+ Model every terminal and resumable state explicitly:
133
51
 
134
- Steer sparingly: only when an analyst finds a concrete mistake, a loop is
135
- duplicating work, a parent/Pi answers a blocker, or a verifier reveals a specific
136
- fix a running worker can still use. Delivery is through `Scope.send` or
137
- `steer_agent`; failed delivery means spawn a fresh corrected attempt.
52
+ - succeeded with the accepted artifact;
53
+ - exhausted by rounds, tokens, money, time, or concurrency;
54
+ - cancelled by the caller;
55
+ - blocked on a question or permission;
56
+ - failed before an attempt;
57
+ - failed during execution or checking;
58
+ - interrupted with enough durable state to resume safely.
138
59
 
139
- ## Workspace Loops
60
+ Use stable run, attempt, task, and parent IDs.
61
+ Persist the accepted artifact, every attempted artifact identity, spend, and final reason.
62
+ Resume from durable facts, not an in-memory counter or summary alone.
140
63
 
141
- Git is the durable workspace seam:
64
+ ## Steering And Questions
142
65
 
143
- - one branch/clone per worker
144
- - `gitWorkspace({ ref })` when host and sandbox need the same clone/commit/push contract
145
- - explicit commit per worker
146
- - typed merge result: `merged | conflict | stale-base | rejected | verifier-failed`
147
- - resume derives completion from git state, not only a side journal
148
- - conflicts become blockers/questions, not silent overwrite
66
+ Steering is a typed input to a running or replacement attempt.
67
+ Record who sent it, why, which evidence motivated it, whether delivery succeeded, and which attempt consumed it.
149
68
 
150
- Proof command (real sandbox, real observe→steer join):
69
+ Questions are explicit events.
70
+ Route them to the responsible parent or user, preserve unanswered blockers, and fail closed when a required answer is unavailable.
71
+ Do not bury a permission request in free-form worker output.
151
72
 
152
- ```bash
153
- TANGLE_API_KEY=... pnpm exec tsx bench/src/cloud-loop.mts
154
- ```
73
+ ## Parallel And Recursive Work
74
+
75
+ Give parallel workers isolated state unless shared mutation is the point of the task.
76
+ For repository changes, use one worktree per worker and explicit merge outcomes.
77
+ For external writes, use idempotency keys and product-owned transactions.
78
+
79
+ Recursive supervisors use the same budget, cancellation, trace, question, and completion contracts at every depth.
80
+ Do not grant a child more authority than its parent.
81
+
82
+ ## Tests
83
+
84
+ Cover:
85
+
86
+ - success on the first and later rounds;
87
+ - invalid output followed by a corrected attempt;
88
+ - every budget limit;
89
+ - abort propagation to in-flight work;
90
+ - service and check failures remaining distinct from agent failure;
91
+ - unresolved blocking questions;
92
+ - interrupted run recovery without duplicate side effects;
93
+ - deterministic replay of decisions from saved outcomes where supported.
94
+
95
+ ## Completion
96
+
97
+ The change is complete when the public entrypoint is smaller than the policy it replaces, all states above are observable, a real task exercises the custom behavior, and package typecheck, tests, build, docs, and package verification pass.
98
+
99
+ ## Then consider
155
100
 
156
- It proves `openSandboxRun -> observe -> steer -> corrective worker` over a live
157
- sandbox. The old `observe-steer-workspace-loop.mts` used mock executors and is
158
- deleted the live proof is the only valid one.
159
-
160
- ## Final Check
161
-
162
- - Does every meaningful product land in result blobs, journals, commits,
163
- conversation journals, or trace events?
164
- - Are verifier, judge, analyst, and driver roles separated?
165
- - Can blocking questions move up the chain?
166
- - Can Pi/parent steer without bypassing verification?
167
- - Is workspace mutation transactional if workers edit shared code?
168
- - Can existing trace/journal views isolate agents, pairs, subtrees, and the full
169
- run?
170
- - Is the loop small enough that an agent can author it without inventing hidden
171
- runtime behavior?
101
+ - `critical-audit` when the loop changes a public contract or authority boundary.
102
+ - `eval-engineering` when the loop's stopping condition needs a new evaluation case.
103
+ - `verify` before publishing the package.
@@ -1,24 +1,43 @@
1
1
  ---
2
2
  name: supervise
3
- description: Decompose a task into sub-tasks, author a worker AgentProfile for each, drive and verify the workers, and settle only when a deployable check passes. Carrying this skill is what makes an agent a supervisor.
3
+ description: Drive worker agents with explicit profiles, corrections, budgets, and checked delivery.
4
4
  ---
5
5
 
6
6
  # Supervise
7
7
 
8
- You are a supervisor. You do NOT do the work yourself you design and drive specialist worker agents.
8
+ Use this policy only when the running agent has the coordination tools, including `spawn_agent` and `await_event`.
9
+ The supervisor plans and checks work; workers produce the artifacts.
9
10
 
10
- ## Loop
11
+ ## Run The Work
11
12
 
12
- 1. **Decompose** the task into the smallest set of sub-tasks a single focused worker can each deliver.
13
- 2. **Author** a worker per sub-task by calling `spawn_agent` with a complete `profile`:
14
- - `name` a short id.
15
- - `skills` the skill files the worker should carry (by name), OR `systemPrompt` — rich, specific instructions for this sub-task.
16
- - `model` the model best suited to this sub-task (optional).
17
- Write the instructions a power user would write — never a one-liner. **Never spawn a worker with an empty profile.** The quality of the worker is the quality of the profile you author.
18
- 3. **Await** each worker with `await_event`. Its result reports `valid: true` only if the worker's deployable check passed.
19
- 4. **On failure**, author a *new* worker whose profile names the specific failure and how to fix it — never blindly retry the same profile.
20
- 5. **Stop** (reply with no tool call) once the work is delivered. Only a delivered (`valid: true`) worker counts; you cannot declare done yourself.
13
+ 1. Split the job into independent deliverables with observable completion checks.
14
+ 2. Call `spawn_agent` with a focused task and a complete worker profile.
15
+ 3. Assign each worker only the tools, context, authority, and budget it needs.
16
+ 4. Use `await_event` to collect questions, findings, progress, and settlements.
17
+ 5. Answer blocking questions or steer the responsible worker with specific evidence.
18
+ 6. When work fails, change the task, profile, evidence, or approach before spawning a replacement.
19
+ 7. Accept only a settlement whose declared check passed and whose artifact can be inspected.
20
+ 8. Stop when every required deliverable is accepted or a named limit or blocker is reached.
21
21
 
22
- ## Authoring sub-supervisors
22
+ A worker profile names its role, task, relevant skills or system instructions, model constraints, tools, budget, expected artifact, and completion check.
23
+ Do not spawn empty profiles or blind retries.
23
24
 
24
- If a sub-task is itself too large for one worker, author it as a **sub-supervisor**: give its profile a `skills` list that includes `supervise`. It will decompose and drive its own workers one level deeper. This is not a special call — it is the same `spawn_agent`, just a profile that carries this skill.
25
+ ## Parallel And Recursive Work
26
+
27
+ Run independent workers concurrently when their state and side effects are isolated.
28
+ Use one worktree per repository-writing worker.
29
+ Give external writes stable idempotency keys.
30
+
31
+ A worker may itself supervise only when its profile includes this policy and the runtime grants coordination tools.
32
+ Child workers inherit stricter authority and budget limits than their parent.
33
+
34
+ ## Completion
35
+
36
+ Report worker IDs, assignments, accepted artifacts, failed or cancelled work, spend, unresolved questions, and the exact checks run.
37
+ The supervisor cannot turn an unchecked worker claim into completion.
38
+
39
+ ## Then consider
40
+
41
+ - `build-with-agent-runtime` when this policy should become a reusable product integration.
42
+ - `eval-engineering` when worker acceptance needs a new executable case.
43
+ - `verify` after the accepted artifacts are assembled.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/candidate-execution/exact-process-executor.ts"],"sourcesContent":["import { posix } from 'node:path'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { TraceStore } from '@tangle-network/agent-eval'\nimport type { AgentCandidateTermination, Sha256Digest } from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentCapabilities,\n AgentEnvironmentProvider,\n AgentExactProcess,\n AgentExactProcessEnvironment,\n AgentExactProcessLaunch,\n AgentExactProcessResources,\n AgentExactProcessStatus,\n} from '@tangle-network/agent-interface/environment-provider'\n\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n immutableCandidateValue,\n sha256Bytes,\n} from './digest'\nimport {\n CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV,\n CANDIDATE_KNOWLEDGE_ROOT_ENV,\n candidateKnowledgeExecutionPaths,\n} from './knowledge'\nimport type {\n AgentCandidateExecutorPort,\n AgentCandidateExecutorRequest,\n AgentCandidateExecutorStopRequest,\n} from './types'\n\nconst DEFAULT_PROVISION_TIMEOUT_MS = 120_000\nconst DEFAULT_RECOVERY_RETENTION_MS = 15 * 60_000\n\ninterface ExactProcessRunState {\n environment: AgentExactProcessEnvironment\n output?: Uint8Array\n termination?: AgentCandidateTermination\n runtimeTermination?: AgentCandidateTermination\n trace?: {\n runId: string\n scenarioId: string\n startedAt: number\n deadlineAtMs: number\n timeoutMs: number\n tags: Record<string, string>\n written: boolean\n }\n}\n\nexport interface ExactProcessCandidateExecutorOptions {\n provider: AgentEnvironmentProvider\n resources: AgentExactProcessResources\n provisionTimeoutMs?: number\n recoveryRetentionMs?: number\n providerOptions?: Record<string, unknown>\n}\n\n/** Adapt one neutral exact-process provider to Runtime's trusted candidate boundary. */\nexport function exactProcessProviderAsCandidateExecutor(\n options: ExactProcessCandidateExecutorOptions,\n): AgentCandidateExecutorPort {\n return new ExactProcessAgentCandidateExecutor(options)\n}\n\nclass ExactProcessAgentCandidateExecutor implements AgentCandidateExecutorPort {\n private readonly states = new Map<string, ExactProcessRunState>()\n private readonly exactProcess\n private readonly resources: AgentExactProcessResources\n private readonly provisionTimeoutMs: number\n private readonly recoveryRetentionMs: number\n private readonly providerOptions?: Record<string, unknown>\n private capabilitiesPromise?: Promise<AgentEnvironmentCapabilities>\n\n constructor(private readonly options: ExactProcessCandidateExecutorOptions) {\n if (!options.provider.exactProcess) {\n throw new Error(\n `agent environment provider \"${options.provider.name}\" does not implement exact processes`,\n )\n }\n this.exactProcess = options.provider.exactProcess\n this.resources = exactResources(options.resources)\n this.provisionTimeoutMs = positiveInteger(\n options.provisionTimeoutMs ?? DEFAULT_PROVISION_TIMEOUT_MS,\n 'exact process provision timeout',\n )\n this.recoveryRetentionMs = positiveInteger(\n options.recoveryRetentionMs ?? DEFAULT_RECOVERY_RETENTION_MS,\n 'exact process recovery retention',\n )\n this.providerOptions = options.providerOptions\n ? immutableCandidateValue(options.providerOptions)\n : undefined\n }\n\n async execute(\n request: AgentCandidateExecutorRequest,\n context: Parameters<AgentCandidateExecutorPort['execute']>[1],\n ) {\n assertSupportedRequest(request)\n const outcome = request.benchmark.task.outcome\n if (outcome.kind !== 'output') throw new Error('exact process executor requires an output task')\n const network = request.executionPlan.value.material.model.access.network\n const egress =\n network.mode === 'disabled'\n ? ({ mode: 'blocked' } as const)\n : ({ mode: 'strict', allowDomains: [...network.domains] } as const)\n await this.assertCapability(egress.mode)\n context.signal.throwIfAborted()\n\n const key = executionKey(request.executionId, request.executionPlan.value.digest)\n if (this.states.has(key)) throw new Error('candidate execution environment is already active')\n const image = exactImage(\n request.executionPlan.value.material.container.image,\n request.executionPlan.value.material.container.manifestDigest,\n )\n const maxLifetimeMs = environmentLifetimeMs(\n request.hardLimits.timeoutMs,\n this.recoveryRetentionMs,\n )\n const createMaterial = immutableCandidateValue({\n kind: 'agent-candidate-exact-process-create',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n image,\n egress,\n maxLifetimeMs,\n provisionTimeoutMs: this.provisionTimeoutMs,\n resources: this.resources,\n output: { mediaType: outcome.mediaType, maxBytes: outcome.maxBytes },\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n const createInputDigest = canonicalCandidateDigest(createMaterial)\n const metadata = immutableCandidateValue({\n kind: 'agent-candidate-execution',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n createInputDigest,\n outputMediaType: outcome.mediaType,\n outputMaxBytes: outcome.maxBytes,\n })\n const environment = await this.exactProcess.create({\n image,\n egress,\n maxLifetimeMs,\n provisionTimeoutMs: this.provisionTimeoutMs,\n resources: this.resources,\n metadata,\n idempotencyKey: executionIdempotencyKey(\n request.executionId,\n request.executionPlan.value.digest,\n ),\n signal: context.signal,\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n try {\n assertExecutionEnvironment(environment, metadata, this.options.provider.name)\n } catch (error) {\n try {\n await environment.destroy()\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n 'exact process validation and cleanup both failed',\n )\n }\n throw error\n }\n const state: ExactProcessRunState = { environment }\n this.states.set(key, state)\n\n const existing = await environment.process.list()\n if (existing.length !== 0) {\n throw new Error('fresh candidate environment already contains a process')\n }\n await materializeRequest(environment, request, context.signal)\n const launch = exactLaunch(request)\n const startedAt = Date.now()\n state.trace = {\n runId: request.trace.runId,\n scenarioId: request.benchmark.task.scenario.id,\n startedAt,\n deadlineAtMs: context.deadlineAtMs,\n timeoutMs: request.hardLimits.timeoutMs,\n tags: {\n ...request.trace.tags,\n environmentId: environment.id,\n environmentProvider: environment.provider,\n },\n written: false,\n }\n const process = await environment.process.spawn(launch, { signal: context.signal })\n const outputPromise = collectOutput(process, outcome.maxBytes)\n void outputPromise.catch(() => undefined)\n let cancellation: Promise<void> | undefined\n let processExited = false\n const cancel = () => {\n if (!processExited) cancellation ??= stopProcess(process)\n }\n context.signal.addEventListener('abort', cancel, { once: true })\n if (context.signal.aborted) cancel()\n try {\n const termination = await process.wait()\n processExited = true\n context.signal.removeEventListener('abort', cancel)\n if (cancellation) await cancellation\n const status = await process.status()\n assertTerminalStatus(status, termination)\n state.output = await awaitOutput(outputPromise, context.signal, context.deadlineAtMs)\n state.termination = termination\n await appendExactProcessTrace(state, context.traceStore, status)\n return { executionId: request.executionId, termination }\n } finally {\n context.signal.removeEventListener('abort', cancel)\n }\n }\n\n async stop(\n request: AgentCandidateExecutorStopRequest,\n context: Parameters<AgentCandidateExecutorPort['stop']>[1],\n ): Promise<{ readonly stopped: true }> {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, true)\n if (!environment) return { stopped: true }\n let statuses = await environment.process.list()\n if (statuses.length > 1) {\n throw new Error('candidate exact process environment contains more than one process')\n }\n const status = statuses[0]\n if (status?.running) {\n const process = await environment.process.get(status.pid)\n if (!process) throw new Error('candidate environment lost its running process handle')\n await stopProcess(process)\n }\n context.signal.throwIfAborted()\n statuses = await environment.process.list()\n if (statuses.some((entry) => entry.running)) {\n throw new Error('candidate exact process termination is not proven')\n }\n const finalStatus = statuses[0]\n if (finalStatus) assertTerminalStatus(finalStatus)\n const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest))\n if (state) {\n state.termination = finalStatus?.termination ?? state.termination\n if (context.reason === 'timeout' && state.trace) {\n state.runtimeTermination = {\n kind: 'timeout',\n timeoutMs: state.trace.timeoutMs,\n }\n }\n await appendExactProcessTrace(state, context.traceStore, finalStatus)\n }\n return { stopped: true }\n }\n\n async capture(\n request: AgentCandidateExecutorStopRequest,\n context: Parameters<AgentCandidateExecutorPort['capture']>[1],\n ) {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, false)\n const statuses = await environment.process.list()\n const status = statuses[0]\n if (statuses.length !== 1 || !status || status.running) {\n throw new Error('candidate environment must contain one stopped process before capture')\n }\n assertTerminalStatus(status)\n const process = await environment.process.get(status.pid)\n if (!process) throw new Error('candidate environment lost its captured process handle')\n const currentStatus = await process.status()\n assertTerminalStatus(currentStatus, status.termination)\n const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest))\n const output =\n state?.output ??\n (await awaitOutput(\n collectOutput(process, outputSpec(environment).maxBytes),\n context.signal,\n Date.now() + this.provisionTimeoutMs,\n ))\n context.signal.throwIfAborted()\n const evidence = canonicalCandidateBytes({\n kind: 'agent-candidate-exact-process-capture',\n provider: environment.provider,\n environmentId: environment.id,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlanDigest,\n createInputDigest: environment.metadata?.createInputDigest,\n process: {\n pid: status.pid,\n exitCode: status.exitCode,\n ...(status.exitSignal ? { exitSignal: status.exitSignal } : {}),\n termination: status.termination,\n },\n ...(state?.runtimeTermination ? { runtimeTermination: state.runtimeTermination } : {}),\n output: { sha256: sha256Bytes(output), byteLength: output.byteLength },\n })\n return {\n taskOutcome: { kind: 'output' as const, bytes: output },\n evidence,\n }\n }\n\n async dispose(\n request: AgentCandidateExecutorStopRequest,\n context: { signal: AbortSignal },\n ): Promise<{ readonly disposed: true }> {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, true)\n if (!environment) return { disposed: true }\n let destroyError: unknown\n try {\n await environment.destroy()\n } catch (error) {\n destroyError = error\n }\n const remaining = await this.exactProcess.get(environment.id)\n if (remaining) {\n throw new Error('exact process environment disposal is not proven', { cause: destroyError })\n }\n context.signal.throwIfAborted()\n this.states.delete(executionKey(request.executionId, request.executionPlanDigest))\n return { disposed: true }\n }\n\n private async assertCapability(mode?: 'blocked' | 'strict'): Promise<void> {\n const pending =\n this.capabilitiesPromise ?? Promise.resolve(this.options.provider.capabilities())\n this.capabilitiesPromise = pending\n let capabilities: AgentEnvironmentCapabilities\n try {\n capabilities = await pending\n } catch (error) {\n if (this.capabilitiesPromise === pending) this.capabilitiesPromise = undefined\n throw error\n }\n const exact = capabilities.exactProcess\n if (!exact) {\n throw new Error(\n `agent environment provider \"${this.options.provider.name}\" does not declare exact process support`,\n )\n }\n if (mode && !exact.egress.includes(mode)) {\n throw new Error(\n `agent environment provider \"${this.options.provider.name}\" does not declare ${mode} exact egress`,\n )\n }\n }\n\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: false,\n ): Promise<AgentExactProcessEnvironment>\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: true,\n ): Promise<AgentExactProcessEnvironment | undefined>\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: boolean,\n ): Promise<AgentExactProcessEnvironment | undefined> {\n const key = executionKey(request.executionId, request.executionPlanDigest)\n const active = this.states.get(key)?.environment\n if (active) return active\n const metadata = {\n kind: 'agent-candidate-execution',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlanDigest,\n }\n const listed = await this.exactProcess.list({\n metadata,\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n const matches = listed.filter(\n (environment) =>\n environment.provider === this.options.provider.name &&\n Object.entries(metadata).every(([name, value]) =>\n isDeepStrictEqual(environment.metadata?.[name], value),\n ),\n )\n if (matches.length > 1) {\n throw new Error('multiple exact process environments match one candidate execution')\n }\n const environment = matches[0]\n if (!environment) {\n if (missingIsDeleted) return undefined\n throw new Error('candidate exact process evidence is unavailable')\n }\n if (!isSha256Digest(environment.metadata?.createInputDigest)) {\n throw new Error('candidate exact process create-input digest is unavailable')\n }\n this.states.set(key, { environment })\n return environment\n }\n}\n\nasync function appendExactProcessTrace(\n state: ExactProcessRunState,\n traceStore: TraceStore,\n status?: AgentExactProcessStatus,\n): Promise<void> {\n const trace = state.trace\n if (!trace || trace.written) return\n const endedAt = Math.max(trace.startedAt, Math.min(Date.now(), trace.deadlineAtMs))\n const termination = state.runtimeTermination ?? state.termination ?? status?.termination\n await traceStore.appendRun({\n runId: trace.runId,\n scenarioId: trace.scenarioId,\n startedAt: trace.startedAt,\n endedAt,\n status: termination?.kind === 'exit' && termination.exitCode === 0 ? 'completed' : 'failed',\n tags: trace.tags,\n })\n trace.written = true\n}\n\nfunction assertSupportedRequest(request: AgentCandidateExecutorRequest): void {\n if (request.benchmark.task.outcome.kind !== 'output') {\n throw new Error(\n 'exact process candidate executor does not support workspace outcomes; use Pier',\n )\n }\n if (request.executionPlan.value.material.codeKind !== 'disabled' || request.inputs.candidate) {\n throw new Error('exact process candidate executor does not support code workspaces; use Pier')\n }\n if (request.memory.mode !== 'disabled') {\n throw new Error('exact process candidate executor does not support isolated memory')\n }\n const mediaType = request.benchmark.task.outcome.mediaType.toLowerCase()\n if (\n !(\n mediaType.startsWith('text/') ||\n mediaType === 'application/json' ||\n mediaType.endsWith('+json')\n )\n ) {\n throw new Error('exact process candidate executor supports only UTF-8 text and JSON outputs')\n }\n if (!posix.isAbsolute(request.launch.executable) && !request.launch.env.PATH?.trim()) {\n throw new Error('exact process candidate executable must be absolute or declare a signed PATH')\n }\n}\n\nasync function materializeRequest(\n environment: AgentExactProcessEnvironment,\n request: AgentCandidateExecutorRequest,\n signal: AbortSignal,\n): Promise<void> {\n const knowledgePaths = assertKnowledgeExecutionBinding(request)\n for (const file of request.inputs.task.files) {\n await environment.writeFile(beneath(request.roots.taskRoot, file.path), file.bytes, {\n mode: file.mode,\n signal,\n })\n }\n const profileRoot =\n request.executionPlan.value.material.profile.targetWorkspace === 'task'\n ? request.roots.taskRoot\n : request.roots.candidateRoot\n if (!profileRoot) throw new Error('candidate profile targets a missing workspace')\n for (const file of request.profileActivation.files) {\n await environment.writeFile(\n beneath(profileRoot, file.path),\n Buffer.from(file.content, 'utf8'),\n { mode: file.mode, signal },\n )\n }\n if (request.knowledge && knowledgePaths) {\n for (const file of request.knowledge.files) {\n await environment.writeFile(beneath(knowledgePaths.root, file.path), file.bytes, {\n mode: file.mode,\n signal,\n })\n }\n if (request.knowledge.retrievalConfig && knowledgePaths.retrievalConfig) {\n await environment.writeFile(\n knowledgePaths.retrievalConfig,\n request.knowledge.retrievalConfig,\n { mode: 0o644, signal },\n )\n }\n }\n if (request.instruction.delivery.kind === 'utf8-file') {\n await environment.writeFile(request.instruction.delivery.path, request.instruction.bytes, {\n mode: 0o644,\n signal,\n })\n }\n}\n\nfunction assertKnowledgeExecutionBinding(\n request: AgentCandidateExecutorRequest,\n): ReturnType<typeof candidateKnowledgeExecutionPaths> | undefined {\n const knowledge = request.knowledge\n if (!knowledge) {\n if (\n request.launch.env[CANDIDATE_KNOWLEDGE_ROOT_ENV] !== undefined ||\n request.launch.env[CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV] !== undefined\n ) {\n throw new Error('candidate launch declares knowledge paths without verified knowledge')\n }\n return undefined\n }\n const paths = candidateKnowledgeExecutionPaths(\n request.roots.taskRoot,\n knowledge.retrievalConfig !== undefined,\n )\n if (\n request.launch.env[CANDIDATE_KNOWLEDGE_ROOT_ENV] !== paths.root ||\n request.launch.env[CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV] !== paths.retrievalConfig\n ) {\n throw new Error('candidate knowledge paths do not match the signed launch environment')\n }\n const reserved = [paths.root, paths.retrievalConfig].filter(\n (value): value is string => value !== undefined,\n )\n const profileRoot =\n request.executionPlan.value.material.profile.targetWorkspace === 'task'\n ? request.roots.taskRoot\n : request.roots.candidateRoot\n const otherFiles = [\n ...request.inputs.task.files.map((file) => beneath(request.roots.taskRoot, file.path)),\n ...(profileRoot\n ? request.profileActivation.files.map((file) => beneath(profileRoot, file.path))\n : []),\n ...(request.instruction.delivery.kind === 'utf8-file'\n ? [request.instruction.delivery.path]\n : []),\n ]\n if (\n otherFiles.some((path) =>\n reserved.some(\n (reservedPath) =>\n path === reservedPath ||\n path.startsWith(`${reservedPath}/`) ||\n reservedPath.startsWith(`${path}/`),\n ),\n )\n ) {\n throw new Error('candidate knowledge paths overlap other execution inputs')\n }\n return paths\n}\n\nfunction exactLaunch(request: AgentCandidateExecutorRequest): AgentExactProcessLaunch {\n const instruction = new TextDecoder('utf-8', { fatal: true }).decode(request.instruction.bytes)\n const base = {\n executable: request.launch.executable,\n args: request.launch.args,\n cwd: request.launch.cwd,\n env: request.launch.env,\n timeoutMs: 0,\n }\n switch (request.instruction.delivery.kind) {\n case 'argv-append':\n return { ...base, args: [...base.args, instruction] }\n case 'stdin-utf8':\n return { ...base, stdin: instruction }\n case 'utf8-file':\n return base\n }\n}\n\nasync function collectOutput(process: AgentExactProcess, maxBytes: number): Promise<Uint8Array> {\n const chunks: Buffer[] = []\n let byteLength = 0\n for await (const chunk of process.stdout()) {\n const bytes = Buffer.from(chunk, 'utf8')\n byteLength += bytes.byteLength\n if (byteLength > maxBytes) {\n let stopError: unknown\n try {\n await stopProcess(process)\n } catch (error) {\n stopError = error\n }\n throw new Error(`candidate output exceeds its ${maxBytes}-byte maximum`, {\n cause: stopError,\n })\n }\n chunks.push(bytes)\n }\n return Uint8Array.from(Buffer.concat(chunks, byteLength))\n}\n\nasync function awaitOutput(\n output: Promise<Uint8Array>,\n signal: AbortSignal,\n deadlineAtMs: number,\n): Promise<Uint8Array> {\n signal.throwIfAborted()\n const remainingMs = deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw new Error('candidate output deadline expired')\n let timer: ReturnType<typeof setTimeout> | undefined\n let onAbort: (() => void) | undefined\n try {\n return await Promise.race([\n output,\n new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(signal.reason ?? new Error('candidate output cancelled'))\n signal.addEventListener('abort', onAbort, { once: true })\n timer = setTimeout(\n () => reject(new Error('candidate output deadline expired')),\n remainingMs,\n )\n }),\n ])\n } finally {\n if (onAbort) signal.removeEventListener('abort', onAbort)\n if (timer) clearTimeout(timer)\n }\n}\n\nasync function stopProcess(process: AgentExactProcess): Promise<void> {\n const before = await process.status()\n if (!before.running) return\n try {\n await process.kill()\n } catch (error) {\n if ((await process.status()).running) throw error\n }\n const termination = await process.wait()\n assertTerminalStatus(await process.status(), termination)\n}\n\nfunction assertTerminalStatus(\n status: AgentExactProcessStatus,\n expected?: AgentCandidateTermination,\n): asserts status is AgentExactProcessStatus & { termination: AgentCandidateTermination } {\n if (status.running || !status.termination) {\n throw new Error('exact process returned no terminal reason after exit')\n }\n if (expected && !isDeepStrictEqual(status.termination, expected)) {\n throw new Error('exact process wait and status returned different terminal reasons')\n }\n}\n\nfunction assertExecutionEnvironment(\n environment: AgentExactProcessEnvironment,\n metadata: Record<string, unknown>,\n providerName: string,\n): void {\n if (!environment.id || environment.provider !== providerName) {\n throw new Error('exact process provider returned the wrong environment identity')\n }\n if (\n !Object.entries(metadata).every(([name, value]) =>\n isDeepStrictEqual(environment.metadata?.[name], value),\n )\n ) {\n throw new Error('exact process provider did not persist candidate execution metadata')\n }\n}\n\nfunction outputSpec(environment: AgentExactProcessEnvironment): { maxBytes: number } {\n const maxBytes = environment.metadata?.outputMaxBytes\n if (!Number.isSafeInteger(maxBytes) || Number(maxBytes) < 1) {\n throw new Error('candidate exact process output bound is unavailable')\n }\n return { maxBytes: Number(maxBytes) }\n}\n\nfunction executionKey(executionId: string, executionPlanDigest: Sha256Digest): string {\n return `${executionId}\\0${executionPlanDigest}`\n}\n\nfunction executionIdempotencyKey(executionId: string, executionPlanDigest: Sha256Digest): string {\n return `candidate-${canonicalCandidateDigest({\n kind: 'agent-candidate-execution-identity',\n executionId,\n executionPlanDigest,\n }).slice('sha256:'.length)}`\n}\n\nfunction exactImage(image: string, manifestDigest: Sha256Digest): string {\n if (isSha256Digest(image)) {\n if (image !== manifestDigest) {\n throw new Error('candidate container image conflicts with its resolved manifest')\n }\n return image\n }\n const marker = image.lastIndexOf('@')\n if (marker < 0) return `${image}@${manifestDigest}`\n if (image.slice(marker + 1) !== manifestDigest) {\n throw new Error('candidate container image conflicts with its resolved manifest')\n }\n return image\n}\n\nfunction environmentLifetimeMs(timeoutMs: number, retentionMs: number): number {\n const total = positiveInteger(timeoutMs, 'candidate execution timeout') + retentionMs\n if (!Number.isSafeInteger(total)) throw new Error('candidate environment lifetime is too large')\n return Math.ceil(total / 1_000) * 1_000\n}\n\nfunction exactResources(resources: AgentExactProcessResources): AgentExactProcessResources {\n if (!Number.isFinite(resources.cpu) || resources.cpu <= 0) {\n throw new Error('exact process CPU must be positive and finite')\n }\n return Object.freeze({\n cpu: resources.cpu,\n memoryMb: positiveInteger(resources.memoryMb, 'exact process memory'),\n diskMb: positiveInteger(resources.diskMb, 'exact process disk'),\n })\n}\n\nfunction positiveInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1)\n throw new Error(`${label} must be a positive integer`)\n return value\n}\n\nfunction beneath(root: string, relativePath: string): string {\n if (posix.isAbsolute(relativePath)) throw new Error('candidate input path must be relative')\n const path = posix.normalize(relativePath)\n if (path === '..' || path.startsWith('../')) {\n throw new Error('candidate input path escapes its execution root')\n }\n return posix.join(root, path)\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value)\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,yBAAyB;AA+BlC,IAAM,+BAA+B;AACrC,IAAM,gCAAgC,KAAK;AA2BpC,SAAS,wCACd,SAC4B;AAC5B,SAAO,IAAI,mCAAmC,OAAO;AACvD;AAEA,IAAM,qCAAN,MAA+E;AAAA,EAS7E,YAA6B,SAA+C;AAA/C;AAC3B,QAAI,CAAC,QAAQ,SAAS,cAAc;AAClC,YAAM,IAAI;AAAA,QACR,+BAA+B,QAAQ,SAAS,IAAI;AAAA,MACtD;AAAA,IACF;AACA,SAAK,eAAe,QAAQ,SAAS;AACrC,SAAK,YAAY,eAAe,QAAQ,SAAS;AACjD,SAAK,qBAAqB;AAAA,MACxB,QAAQ,sBAAsB;AAAA,MAC9B;AAAA,IACF;A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