@tangle-network/agent-runtime 0.44.0 → 0.46.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 (88) hide show
  1. package/README.md +95 -203
  2. package/dist/agent.d.ts +3 -2
  3. package/dist/agent.js +5 -7
  4. package/dist/agent.js.map +1 -1
  5. package/dist/analyst-loop.d.ts +28 -2
  6. package/dist/analyst-loop.js +4 -1
  7. package/dist/audit.d.ts +93 -0
  8. package/dist/audit.js +312 -0
  9. package/dist/audit.js.map +1 -0
  10. package/dist/chunk-4B6U4CVQ.js +15 -0
  11. package/dist/chunk-4B6U4CVQ.js.map +1 -0
  12. package/dist/chunk-65FQLI4V.js +4089 -0
  13. package/dist/chunk-65FQLI4V.js.map +1 -0
  14. package/dist/{chunk-GFKVVRQ7.js → chunk-GN75RGM6.js} +13 -12
  15. package/dist/chunk-GN75RGM6.js.map +1 -0
  16. package/dist/chunk-GSUO5QS6.js +146 -0
  17. package/dist/chunk-GSUO5QS6.js.map +1 -0
  18. package/dist/chunk-HNUXAZIJ.js +580 -0
  19. package/dist/chunk-HNUXAZIJ.js.map +1 -0
  20. package/dist/{chunk-SKUZZCHE.js → chunk-I42NHLKX.js} +5 -5
  21. package/dist/chunk-I42NHLKX.js.map +1 -0
  22. package/dist/{chunk-HVYOHJHK.js → chunk-JNPK46YH.js} +2 -2
  23. package/dist/chunk-JNPK46YH.js.map +1 -0
  24. package/dist/{chunk-3HMHSN22.js → chunk-KADIJAD4.js} +38 -24
  25. package/dist/chunk-KADIJAD4.js.map +1 -0
  26. package/dist/{chunk-KDMRUD2P.js → chunk-KPN7OQ64.js} +296 -8
  27. package/dist/chunk-KPN7OQ64.js.map +1 -0
  28. package/dist/{chunk-NRZOXCJK.js → chunk-VR4JIC5H.js} +2 -2
  29. package/dist/chunk-WIR4HOOJ.js +27 -0
  30. package/dist/chunk-WIR4HOOJ.js.map +1 -0
  31. package/dist/coder-DCWFQpmJ.d.ts +114 -0
  32. package/dist/driver-C-mtBo7h.d.ts +221 -0
  33. package/dist/improvement.d.ts +0 -1
  34. package/dist/improvement.js +0 -5
  35. package/dist/improvement.js.map +1 -1
  36. package/dist/index.d.ts +122 -9
  37. package/dist/index.js +398 -10
  38. package/dist/index.js.map +1 -1
  39. package/dist/{kb-gate-D0ZIhFOU.d.ts → kb-gate-2Gwpz_27.d.ts} +86 -9
  40. package/dist/{loop-runner-bin-BLMa8He3.d.ts → loop-runner-bin-D-K6bRp3.d.ts} +17 -13
  41. package/dist/loop-runner-bin.d.ts +8 -6
  42. package/dist/loop-runner-bin.js +6 -8
  43. package/dist/loops.d.ts +7 -393
  44. package/dist/loops.js +96 -27
  45. package/dist/mcp/bin.js +7 -7
  46. package/dist/mcp/bin.js.map +1 -1
  47. package/dist/mcp/index.d.ts +286 -13
  48. package/dist/mcp/index.js +341 -9
  49. package/dist/mcp/index.js.map +1 -1
  50. package/dist/{otel-export-wFDmmurL.d.ts → otel-export-nurzFwuJ.d.ts} +1 -1
  51. package/dist/profiles.d.ts +385 -86
  52. package/dist/profiles.js +549 -4
  53. package/dist/profiles.js.map +1 -1
  54. package/dist/{run-loop-C4L1Sted.d.ts → run-loop-CU2Y00Si.d.ts} +36 -13
  55. package/dist/runtime-hooks-C7JwKb9E.d.ts +70 -0
  56. package/dist/runtime.d.ts +1964 -0
  57. package/dist/runtime.js +114 -0
  58. package/dist/runtime.js.map +1 -0
  59. package/dist/substrate-CUgk7F7s.d.ts +77 -0
  60. package/dist/topology.d.ts +73 -0
  61. package/dist/topology.js +111 -0
  62. package/dist/topology.js.map +1 -0
  63. package/dist/types-BfoeiQRZ.d.ts +438 -0
  64. package/dist/{types-DbJzz2uf.d.ts → types-DnYoHvvZ.d.ts} +110 -4
  65. package/dist/workflow.d.ts +4 -3
  66. package/dist/workflow.js +4 -5
  67. package/dist/workflow.js.map +1 -1
  68. package/package.json +37 -28
  69. package/skills/agent-runtime-adoption/SKILL.md +32 -29
  70. package/skills/generate-eval/SKILL.md +60 -0
  71. package/dist/chunk-3HMHSN22.js.map +0 -1
  72. package/dist/chunk-GFKVVRQ7.js.map +0 -1
  73. package/dist/chunk-HVYOHJHK.js.map +0 -1
  74. package/dist/chunk-KDMRUD2P.js.map +0 -1
  75. package/dist/chunk-PY6NMZYX.js +0 -52
  76. package/dist/chunk-PY6NMZYX.js.map +0 -1
  77. package/dist/chunk-S7JXV32P.js +0 -947
  78. package/dist/chunk-S7JXV32P.js.map +0 -1
  79. package/dist/chunk-SKUZZCHE.js.map +0 -1
  80. package/dist/chunk-SQSCRJ7U.js +0 -65
  81. package/dist/chunk-SQSCRJ7U.js.map +0 -1
  82. package/dist/chunk-VOX6Z3II.js +0 -90
  83. package/dist/chunk-VOX6Z3II.js.map +0 -1
  84. package/dist/chunk-XBUG326M.js +0 -261
  85. package/dist/chunk-XBUG326M.js.map +0 -1
  86. package/dist/dynamic-wUgp6UKs.d.ts +0 -108
  87. package/dist/optimize-prompt-D-urF2wW.d.ts +0 -129
  88. /package/dist/{chunk-NRZOXCJK.js.map → chunk-VR4JIC5H.js.map} +0 -0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-runtime",
3
- "version": "0.44.0",
4
- "description": "Runs domain agents and automates improving them from their own traces — chat turns and loop topologies, with an analyst→prompt/knowledge→eval-gated-ship self-improvement loop.",
3
+ "version": "0.46.0",
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": {
7
7
  "type": "git",
@@ -39,11 +39,21 @@
39
39
  "import": "./dist/agent.js",
40
40
  "default": "./dist/agent.js"
41
41
  },
42
+ "./runtime": {
43
+ "types": "./dist/runtime.d.ts",
44
+ "import": "./dist/runtime.js",
45
+ "default": "./dist/runtime.js"
46
+ },
42
47
  "./loops": {
43
48
  "types": "./dist/loops.d.ts",
44
49
  "import": "./dist/loops.js",
45
50
  "default": "./dist/loops.js"
46
51
  },
52
+ "./topology": {
53
+ "types": "./dist/topology.d.ts",
54
+ "import": "./dist/topology.js",
55
+ "default": "./dist/topology.js"
56
+ },
47
57
  "./workflow": {
48
58
  "types": "./dist/workflow.d.ts",
49
59
  "import": "./dist/workflow.js",
@@ -54,6 +64,11 @@
54
64
  "import": "./dist/profiles.js",
55
65
  "default": "./dist/profiles.js"
56
66
  },
67
+ "./audit": {
68
+ "types": "./dist/audit.d.ts",
69
+ "import": "./dist/audit.js",
70
+ "default": "./dist/audit.js"
71
+ },
57
72
  "./mcp": {
58
73
  "types": "./dist/mcp/index.d.ts",
59
74
  "import": "./dist/mcp/index.js",
@@ -72,45 +87,25 @@
72
87
  "publishConfig": {
73
88
  "access": "public"
74
89
  },
75
- "scripts": {
76
- "build": "tsup",
77
- "dev": "tsup --watch",
78
- "prepare": "tsup",
79
- "test": "vitest run",
80
- "test:watch": "vitest",
81
- "lint": "biome check src tests examples",
82
- "lint:fix": "biome check --write src tests examples",
83
- "typecheck": "tsc --noEmit",
84
- "verify:package": "node scripts/verify-package-exports.mjs"
85
- },
86
- "dependencies": {},
87
90
  "devDependencies": {
88
91
  "@biomejs/biome": "^2.4.0",
89
- "@tangle-network/agent-eval": "^0.61.0",
92
+ "@tangle-network/agent-eval": "^0.83.0",
90
93
  "@tangle-network/sandbox": "^0.4.0",
91
94
  "@types/node": "^25.6.0",
95
+ "playwright": "^1.40.0",
92
96
  "tsup": "^8.0.0",
93
97
  "typescript": "^5.7.0",
94
98
  "vitest": "^3.0.0"
95
99
  },
96
- "pnpm": {
97
- "minimumReleaseAge": 4320,
98
- "minimumReleaseAgeExclude": [
99
- "@tangle-network/agent-eval"
100
- ],
101
- "onlyBuiltDependencies": [
102
- "esbuild"
103
- ]
104
- },
105
100
  "engines": {
106
101
  "node": ">=20"
107
102
  },
108
103
  "license": "MIT",
109
- "packageManager": "pnpm@10.28.0",
110
104
  "peerDependencies": {
111
- "@tangle-network/agent-eval": ">=0.61.0 <1.0.0",
105
+ "@tangle-network/agent-eval": ">=0.83.0 <1.0.0",
112
106
  "@tangle-network/agent-knowledge": ">=1.3.0 <2.0.0",
113
- "@tangle-network/sandbox": ">=0.1.2 <0.5.0"
107
+ "@tangle-network/sandbox": ">=0.1.2 <0.5.0",
108
+ "playwright": "^1.40.0"
114
109
  },
115
110
  "peerDependenciesMeta": {
116
111
  "@tangle-network/agent-knowledge": {
@@ -118,6 +113,20 @@
118
113
  },
119
114
  "@tangle-network/sandbox": {
120
115
  "optional": true
116
+ },
117
+ "playwright": {
118
+ "optional": true
121
119
  }
120
+ },
121
+ "scripts": {
122
+ "build": "tsup",
123
+ "dev": "tsup --watch",
124
+ "test": "vitest run",
125
+ "test:watch": "vitest",
126
+ "lint": "biome check src tests examples",
127
+ "lint:fix": "biome check --write src tests examples",
128
+ "typecheck": "tsc --noEmit",
129
+ "typecheck:examples": "tsc --noEmit -p tsconfig.examples.json",
130
+ "verify:package": "node scripts/verify-package-exports.mjs"
122
131
  }
123
- }
132
+ }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: agent-runtime-adoption
3
- description: Adopt @tangle-network/agent-runtime in a product — the driven-loop kernel (runLoop), topology drivers (refine / fanout-vote / dynamic agent-authored), the loopDispatch campaign bridge, MCP delegation, and identity-gated prompt-surface optimization (optimizePrompt). Self-contained; needs only the published package + @tangle-network/agent-eval. Use when wiring runLoop, choosing a topology driver, optimizing a system/planner prompt, or exposing delegation tools.
3
+ description: Adopt @tangle-network/agent-runtime in a product — the driven-loop kernel (runLoop), topology drivers (refine / fanout-vote / dynamic agent-authored), the loopDispatch campaign bridge, MCP delegation, and the code-surface improvementDriver for agent-eval's selfImprove (the optimization entry point). Self-contained; needs only the published package + @tangle-network/agent-eval. Use when wiring runLoop, choosing a topology driver, optimizing a system/planner prompt or code surface, or exposing delegation tools.
4
4
  ---
5
5
 
6
6
  # agent-runtime adoption — driven loops, topology drivers, prompt optimization
@@ -43,7 +43,7 @@ Topology is data; the kernel is topology-agnostic.
43
43
  - **`createFanoutVoteDriver({ n, selector? })`** — N parallel attempts in
44
44
  iteration 0, score once, pick the winner (default: highest valid score). Use
45
45
  for multi-harness coder fanout, redundant research with disagreement detection.
46
- - **`createDynamicDriver({ planner, maxIterations?, maxFanout? })`** — **the
46
+ - **`createDriver({ planner, maxIterations?, maxFanout? })`** — **the
47
47
  agent authors the topology.** `plan`/`decide` are backed by an injected
48
48
  `TopologyPlanner` that emits one `TopologyMove` per round
49
49
  (`{kind:'refine',task}` | `{kind:'fanout',tasks}` | `{kind:'stop'}`). The
@@ -59,7 +59,7 @@ fanning a single round across several.
59
59
  ### Wiring an LLM planner — `createSandboxPlanner`
60
60
 
61
61
  ```ts
62
- import { createDynamicDriver, createSandboxPlanner, runLoop } from '@tangle-network/agent-runtime/loops'
62
+ import { createDriver, createSandboxPlanner, runLoop } from '@tangle-network/agent-runtime/loops'
63
63
 
64
64
  const planner = createSandboxPlanner<Task, Out>({
65
65
  client, profile: plannerProfile, // any harness; cheap model is fine
@@ -67,7 +67,7 @@ const planner = createSandboxPlanner<Task, Out>({
67
67
  // buildPrompt? — defaults to a history-summary prompt; override to customize
68
68
  })
69
69
  const result = await runLoop({
70
- driver: createDynamicDriver({ planner, maxIterations: 8 }),
70
+ driver: createDriver({ planner, maxIterations: 8 }),
71
71
  agentRuns: workerSpecs, output, validator, task, ctx: { sandboxClient: client },
72
72
  })
73
73
  ```
@@ -106,30 +106,34 @@ const dispatch = loopCampaignDispatch({
106
106
 
107
107
  `loopDispatch` is the `runProfileMatrix` variant (profile is an axis).
108
108
 
109
- ## Identity-gated prompt optimization — `optimizePrompt`
109
+ ## Identity-gated optimization — agent-eval's `selfImprove`
110
110
 
111
- `@tangle-network/agent-runtime/improvement`. The text-surface entry point onto
112
- agent-eval's `runImprovementLoop` sibling to `improvementDriver` (the
113
- code/worktree path). Optimizes any prompt surface (system / planner / judge
114
- rubric) and is **identity-gated by construction**: it runs evals, proposes
115
- candidates (default driver `gepaDriver`), and the held-out gate compares
116
- candidate vs baseline. `result.prompt` is the **baseline unless the gate decided
117
- `'ship'`** so registering a prompt for optimization can never regress it; it
118
- only improves when held-out data earns it.
111
+ The optimization entry point is **`selfImprove`** (`@tangle-network/agent-eval/contract`),
112
+ NOT agent-runtimeagent-runtime contributes the code-surface `improvementDriver`
113
+ (`/improvement`, the git-worktree path) you pass to it as `driver` to optimize CODE
114
+ instead of a string. `selfImprove` optimizes any text/config surface (system /
115
+ planner / judge rubric) and is **identity-gated by construction**: it runs evals,
116
+ proposes candidates (default driver `gepaDriver`), and a held-out gate ships a winner
117
+ only if it beats the baseline. `result.winner.surface` is the **baseline unless
118
+ `result.gateDecision === 'ship'`** so registering a surface for optimization can
119
+ never regress it; it only improves when held-out data earns it.
119
120
 
120
121
  ```ts
121
- import { optimizePrompt } from '@tangle-network/agent-runtime/improvement'
122
- const { prompt, improved, decision, delta } = await optimizePrompt({
123
- baselinePrompt: CURRENT_SYSTEM_PROMPT,
124
- runWithPrompt: (prompt, scenario, ctx) => runYourThing(prompt, scenario), // sandbox / runLoop / direct call
125
- scenarios, holdoutScenarios, judges, runDir,
126
- reflection: { llm, model: REFLECTION_MODEL }, // builds the default gepaDriver
127
- // gate? defaults to heldOutGate; pass defaultProductionGate for red-team hardening
122
+ import { selfImprove } from '@tangle-network/agent-eval/contract'
123
+ const result = await selfImprove({
124
+ baselineSurface: CURRENT_SYSTEM_PROMPT,
125
+ agent: (surface, scenario, ctx) => runYourThing(surface, scenario), // sandbox / runLoop / direct call
126
+ scenarios,
127
+ judge,
128
+ budget: { holdoutScenarios, generations: 3, populationSize: 2 },
129
+ llm: { baseUrl, apiKey, model: REFLECTION_MODEL }, // drives the default gepaDriver
130
+ // driver? — pass agent-runtime's improvementDriver to optimize CODE (worktree) instead of a string
131
+ // gate? — defaults to a held-out gate; pass defaultProductionGate for red-team hardening
128
132
  })
129
- // use `prompt` unconditionally: it's the baseline until a candidate genuinely wins
133
+ // use result.winner.surface unconditionally: it's the baseline until a candidate genuinely wins
130
134
  ```
131
135
 
132
- ### optimizePrompt gotchas — read before wiring
136
+ ### selfImprove gotchas — read before wiring
133
137
 
134
138
  - **`gepaDriver` mutates TEXT only**, and its only structural guard is `##` H2
135
139
  headings (`preserveSections`) + `maxSentenceEdits`. Make load-bearing sections
@@ -137,12 +141,11 @@ const { prompt, improved, decision, delta } = await optimizePrompt({
137
141
  GEPA optimizes the prose, never the envelope/contract.
138
142
  - **Scenarios must be domain-real.** Derive them from the surface's own traces /
139
143
  ground truth, not from unrelated corpora. Cross-domain examples are noise.
140
- - **Extend, don't fork.** If the product already wires `runImprovementLoop`
141
- (e.g. for a main-agent prompt), add the new surface as another target in that
142
- harness rather than bolting on a second optimizer.
143
- - `runWithPrompt` is the only domain seam — the optimizer never assumes how a
144
- prompt runs. Report cost via `ctx.cost` inside it so the integrity guard sees
145
- real activity.
144
+ - **Extend, don't fork.** If the product already wires `selfImprove` /
145
+ `runImprovementLoop` (e.g. for a main-agent prompt), add the new surface as
146
+ another target in that harness rather than bolting on a second optimizer.
147
+ - `agent` is the only domain seam — the optimizer never assumes how a surface
148
+ runs. Report cost via `ctx.cost` inside it so the integrity guard sees real activity.
146
149
  - A live run needs a real backend (`TANGLE_API_KEY` / router, or local
147
150
  cli-bridge) and real spend; it is not free.
148
151
 
@@ -161,7 +164,7 @@ Mount it on a production `AgentProfile.mcp`; do not re-implement delegation.
161
164
  `loops/types.ts:Driver` only when none fit — never fork the kernel.
162
165
  - [ ] `runLoop` is bridged to campaigns via `loopDispatch` / `loopCampaignDispatch`
163
166
  (usage + trace auto-forwarded), not a hand-rolled ExecCtx.
164
- - [ ] Every optimizable prompt is registered through `optimizePrompt` (or the
167
+ - [ ] Every optimizable prompt is registered through `selfImprove` (or the
165
168
  product's existing `runImprovementLoop`), identity-gated on a held-out set.
166
169
  - [ ] Boundaries fail loud: no `null` sandbox client, no silent adapter return,
167
170
  no unguarded planner envelope.
@@ -0,0 +1,60 @@
1
+ ---
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.
4
+ ---
5
+
6
+ # generate-eval — author a certifiable eval task
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).
17
+
18
+ ## Inputs
19
+
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.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/profiles/coder.ts"],"sourcesContent":["/**\n * @experimental\n *\n * `coderProfile` — opinionated preset for code-modification tasks.\n *\n * The agent is told to:\n * - work on a fresh branch inside the sandbox workspace\n * - keep the patch minimal (under `maxDiffLines`)\n * - avoid `forbiddenPaths`\n * - run `testCmd` and `typecheckCmd`\n * - emit a final JSON result the output adapter parses\n *\n * The profile is stateless and agent-agnostic — `harness` selects the\n * sandbox-SDK backend (`claude-code`, `codex`, `opencode/*`). For\n * heterogeneous fanout, use `multiHarnessCoderFanout`.\n */\n\nimport type { AgentProfile, SandboxEvent } from '@tangle-network/sandbox'\nimport { createFanoutVoteDriver } from '../loops/drivers/fanout-vote'\nimport type { AgentRunSpec, DefaultVerdict, Driver, OutputAdapter, Validator } from '../loops/types'\n\nconst DEFAULT_MAX_DIFF_LINES = 400\n\n/** @experimental */\nexport interface CoderTask {\n /** What the agent must accomplish. Free-form prose. */\n goal: string\n /** Absolute path inside the sandbox where the repo lives. */\n repoRoot: string\n /** Default `main`. The branch the agent diffs against. */\n baseBranch?: string\n /** Default `pnpm test --run`. */\n testCmd?: string\n /** Default `pnpm typecheck`. */\n typecheckCmd?: string\n /** Files the agent may inspect for context. Surfaced verbatim in the prompt. */\n contextFiles?: string[]\n /**\n * Paths the agent must not touch. Validator hard-fails on any match.\n * Use glob-free literal path prefixes for unambiguous enforcement.\n */\n forbiddenPaths?: string[]\n /** Default 400. Hard cap; validator hard-fails when exceeded. */\n maxDiffLines?: number\n}\n\n/** @experimental */\nexport interface CoderOutput {\n /** Branch the agent wrote the patch on. */\n branch: string\n /** Unified diff (`git diff <base>..HEAD`). */\n patch: string\n testResult: { passed: boolean; output: string }\n typecheckResult: { passed: boolean; output: string }\n diffStats: { filesChanged: number; insertions: number; deletions: number }\n /** Optional reviewer commentary surfaced by the agent. */\n reviewerNotes?: string\n}\n\n/** @experimental */\nexport interface CoderProfileOptions {\n /** Sandbox-SDK backend.type. Default `'claude-code'`. */\n harness?: string\n /** Default model id passed in `AgentProfile.model.default`. */\n model?: string\n /** Custom system prompt replacement. Default = built-in coder preset. */\n systemPrompt?: string\n /** Stable name for `AgentRunSpec.name`. Default = `coder-${harness}`. */\n name?: string\n}\n\n/**\n * Build a coder preset.\n *\n * `validator` enforces test + typecheck + a 400-line default diff cap. For\n * per-task `forbiddenPaths` / `maxDiffLines` enforcement, pass `task` here\n * — the returned validator closes over its constraints. Without a task\n * the validator falls back to the default cap and skips path enforcement.\n *\n * @experimental\n */\nexport function coderProfile(options: CoderProfileOptions & { task?: CoderTask } = {}): {\n profile: AgentProfile\n taskToPrompt: (task: CoderTask) => string\n output: OutputAdapter<CoderOutput>\n validator: Validator<CoderOutput>\n agentRunSpec: AgentRunSpec<CoderTask>\n} {\n const harness = options.harness ?? 'claude-code'\n const name = options.name ?? `coder-${harness}`\n const systemPrompt = options.systemPrompt ?? DEFAULT_CODER_SYSTEM_PROMPT\n const profile: AgentProfile = {\n name,\n description: 'Code-modification agent. Minimal-diff worktree-based coder.',\n prompt: { systemPrompt },\n model: options.model ? { default: options.model } : undefined,\n tools: { git: true, fs: true, shell: true, test_runner: true },\n metadata: { backendType: harness, role: 'coder' },\n }\n const output: OutputAdapter<CoderOutput> = { parse: parseCoderEvents }\n const validator: Validator<CoderOutput> = options.task\n ? createCoderValidator(options.task)\n : createCoderValidator({\n goal: '',\n repoRoot: '',\n forbiddenPaths: [],\n maxDiffLines: DEFAULT_MAX_DIFF_LINES,\n })\n const agentRunSpec: AgentRunSpec<CoderTask> = {\n name,\n profile,\n taskToPrompt: formatCoderPrompt,\n }\n return { profile, taskToPrompt: formatCoderPrompt, output, validator, agentRunSpec }\n}\n\n/** @experimental */\nexport interface MultiHarnessCoderFanoutOptions {\n /**\n * Sandbox-SDK backend.type identifiers, one per parallel agent. Default:\n * `['claude-code', 'codex', 'opencode/zai-coding-plan/glm-5.1']`.\n */\n harnesses?: string[]\n /** Optional per-harness model override. Indexed parallel to `harnesses`. */\n models?: (string | undefined)[]\n}\n\n/** @experimental */\nexport function multiHarnessCoderFanout(options: MultiHarnessCoderFanoutOptions = {}): {\n agentRuns: AgentRunSpec<CoderTask>[]\n output: OutputAdapter<CoderOutput>\n validator: Validator<CoderOutput>\n driver: Driver<CoderTask, CoderOutput, 'pick-winner' | 'fail'>\n} {\n const harnesses =\n options.harnesses && options.harnesses.length > 0\n ? options.harnesses\n : ['claude-code', 'codex', 'opencode/zai-coding-plan/glm-5.1']\n const models = options.models ?? []\n const agentRuns = harnesses.map((harness, i) => {\n const { agentRunSpec } = coderProfile({ harness, model: models[i] })\n return agentRunSpec\n })\n const { output, validator } = coderProfile()\n const driver = createFanoutVoteDriver<CoderTask, CoderOutput>({ n: harnesses.length })\n return { agentRuns, output, validator, driver }\n}\n\nconst DEFAULT_CODER_SYSTEM_PROMPT = [\n 'You are a coder agent operating inside an isolated sandbox workspace.',\n 'Your job is to deliver a minimal, correct patch for the user-supplied goal.',\n '',\n 'Hard rules:',\n ' 1. Work on a fresh branch off the supplied base. Do not mutate the base branch.',\n ' 2. Never touch a forbidden path. The user will list them explicitly.',\n ' 3. Keep the diff under the max-diff cap. Prefer the smallest change that ships.',\n ' 4. Run the supplied test and typecheck commands before declaring done.',\n ' 5. If either command fails, fix the cause — do not weaken the test or hide the error.',\n '',\n 'When you finish, emit a single final structured message of the shape:',\n ' ```json',\n ' { \"branch\": \"<branch-name>\",',\n ' \"patch\": \"<unified-diff>\",',\n ' \"testResult\": { \"passed\": <bool>, \"output\": \"<stdout/stderr>\" },',\n ' \"typecheckResult\": { \"passed\": <bool>, \"output\": \"<stdout/stderr>\" },',\n ' \"diffStats\": { \"filesChanged\": <int>, \"insertions\": <int>, \"deletions\": <int> },',\n ' \"reviewerNotes\": \"<optional commentary>\" }',\n ' ```',\n].join('\\n')\n\nfunction formatCoderPrompt(task: CoderTask): string {\n const base = task.baseBranch ?? 'main'\n const testCmd = task.testCmd ?? 'pnpm test --run'\n const typecheckCmd = task.typecheckCmd ?? 'pnpm typecheck'\n const maxDiff = task.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES\n const forbidden = task.forbiddenPaths?.length ? task.forbiddenPaths.join(', ') : '(none)'\n const context = task.contextFiles?.length\n ? task.contextFiles.map((f) => ` - ${f}`).join('\\n')\n : ' (none)'\n return [\n `Goal: ${task.goal}`,\n `Repo: ${task.repoRoot}`,\n `Base branch: ${base}`,\n `Run tests with: ${testCmd}`,\n `Run typecheck with: ${typecheckCmd}`,\n `Forbidden paths: ${forbidden}`,\n `Max diff lines: ${maxDiff}`,\n 'Context files:',\n context,\n '',\n 'Produce a minimal patch on a fresh branch. Run tests and typecheck before',\n 'returning. Emit the final JSON result block exactly as instructed.',\n ].join('\\n')\n}\n\n/**\n * Walk the event stream and return the last structured `coder.result` payload.\n *\n * The agent is instructed to emit a JSON block; in practice the sandbox SDK\n * lifts the structured payload onto `data.result` of a `result` / `final`\n * event. When the event stream does not contain a structured result, the\n * adapter scans text deltas for a fenced JSON block matching the expected\n * keys. Both shapes converge on `CoderOutput`.\n */\nfunction parseCoderEvents(events: SandboxEvent[]): CoderOutput {\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const type = String(event.type ?? '')\n const data = isRecord(event.data) ? event.data : {}\n if (type === 'result' || type === 'final' || type === 'coder.result') {\n const direct = coerceCoderOutput(data.result ?? data.output ?? data)\n if (direct) return direct\n }\n }\n // Fallback: scan text deltas in reverse for a fenced JSON block.\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const data = isRecord(event.data) ? event.data : {}\n const text = pickString(data.text) ?? pickString(data.delta)\n if (!text) continue\n const fenced = extractFencedJson(text)\n if (!fenced) continue\n const coerced = coerceCoderOutput(fenced)\n if (coerced) return coerced\n }\n return {\n branch: '',\n patch: '',\n testResult: { passed: false, output: '' },\n typecheckResult: { passed: false, output: '' },\n diffStats: { filesChanged: 0, insertions: 0, deletions: 0 },\n }\n}\n\n/**\n * Build a validator that closes over a specific `CoderTask`'s constraints.\n *\n * Checks in order:\n * 1. Forbidden-path: any `+++` / `---` header in the patch matching a\n * path prefix in `task.forbiddenPaths` fails hard.\n * 2. Diff size: line count above `task.maxDiffLines` (default 400) fails\n * hard; below cap, the score shrinks linearly.\n * 3. Tests: `output.testResult.passed` must be `true`.\n * 4. Typecheck: `output.typecheckResult.passed` must be `true`.\n *\n * Aggregate score: `0.5 * tests + 0.3 * typecheck + 0.2 * (1 - diffLines/maxDiff)`.\n * `valid` is the conjunction of all four.\n *\n * @experimental\n */\n/**\n * Default-on safety floor (folded from the ai-trading-blueprint delegation\n * MCP): a coder patch that touches a credential-shaped path is rejected\n * regardless of `forbiddenPaths` config. Catches `.env`, private keys,\n * keystores, wallets, and the common secret/credential JSON files.\n */\nconst SECRET_PATH_RE =\n /(^|\\/)(\\.env(\\.|$)|.*\\.(pem|key|p12|pfx|keystore|wallet)|id_rsa|id_ed25519|secrets?\\.json|credentials?\\.json)$/i\n\nexport function createCoderValidator(task: CoderTask): Validator<CoderOutput> {\n const maxDiff = task.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES\n const forbidden = task.forbiddenPaths ?? []\n return {\n async validate(output) {\n const scores: Record<string, number> = {}\n const notes: string[] = []\n let pass = true\n\n const touched = touchedPathsFromPatch(output.patch)\n\n // No-op rejection: an empty patch can trivially \"pass\" tests/typecheck\n // (nothing changed) yet does no work — never a valid coder result.\n if (touched.length === 0 || output.patch.trim().length === 0) {\n pass = false\n scores.nonEmpty = 0\n notes.push('empty patch — no files changed')\n } else {\n scores.nonEmpty = 1\n }\n\n // Secret-path floor: always-on, independent of `forbiddenPaths`.\n const touchedSecrets = touched.filter((p) => SECRET_PATH_RE.test(p))\n if (touchedSecrets.length > 0) {\n pass = false\n scores.noSecrets = 0\n notes.push(`touched secret-shaped paths: ${touchedSecrets.join(', ')}`)\n } else {\n scores.noSecrets = 1\n }\n\n const touchedForbidden = forbidden.filter((path) => {\n const prefix = path.endsWith('/') ? path : `${path}/`\n const exact = prefix.slice(0, -1)\n return touched.some((p) => p === exact || p.startsWith(prefix))\n })\n if (touchedForbidden.length > 0) {\n pass = false\n scores.forbiddenPath = 0\n notes.push(`touched forbidden paths: ${touchedForbidden.join(', ')}`)\n } else {\n scores.forbiddenPath = 1\n }\n\n const diffLines = countDiffLines(output.patch)\n if (diffLines > maxDiff) {\n pass = false\n scores.diffSize = 0\n notes.push(`diff ${diffLines} lines exceeds cap ${maxDiff}`)\n } else {\n scores.diffSize = maxDiff === 0 ? 0 : Math.max(0, 1 - diffLines / maxDiff)\n }\n\n scores.tests = output.testResult.passed ? 1 : 0\n scores.typecheck = output.typecheckResult.passed ? 1 : 0\n if (!output.testResult.passed) {\n pass = false\n notes.push('tests failed')\n }\n if (!output.typecheckResult.passed) {\n pass = false\n notes.push('typecheck failed')\n }\n\n const score = 0.5 * scores.tests + 0.3 * scores.typecheck + 0.2 * scores.diffSize\n const verdict: DefaultVerdict = {\n valid: pass,\n score: Number.isFinite(score) ? score : 0,\n scores,\n }\n if (notes.length > 0) verdict.notes = notes.join('; ')\n return verdict\n },\n }\n}\n\nfunction touchedPathsFromPatch(patch: string): string[] {\n const out = new Set<string>()\n for (const line of patch.split(/\\r?\\n/)) {\n if (line.startsWith('+++ ') || line.startsWith('--- ')) {\n const rest = line.slice(4).trim()\n if (rest === '/dev/null') continue\n const stripped = rest.startsWith('a/') || rest.startsWith('b/') ? rest.slice(2) : rest\n out.add(stripped)\n }\n }\n return [...out]\n}\n\nfunction countDiffLines(patch: string): number {\n let count = 0\n for (const line of patch.split(/\\r?\\n/)) {\n if (\n (line.startsWith('+') || line.startsWith('-')) &&\n !line.startsWith('+++') &&\n !line.startsWith('---')\n ) {\n count += 1\n }\n }\n return count\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction pickString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction extractFencedJson(text: string): unknown | undefined {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/i)\n if (!match) return undefined\n const body = (match[1] ?? '').trim()\n if (!body) return undefined\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n\nfunction coerceCoderOutput(value: unknown): CoderOutput | undefined {\n if (!isRecord(value)) return undefined\n const branch = pickString(value.branch)\n const patch = pickString(value.patch) ?? ''\n if (branch === undefined) return undefined\n const testResult = coerceCmdResult(value.testResult)\n const typecheckResult = coerceCmdResult(value.typecheckResult)\n const diffStats = coerceDiffStats(value.diffStats)\n return {\n branch,\n patch,\n testResult,\n typecheckResult,\n diffStats,\n reviewerNotes: pickString(value.reviewerNotes),\n }\n}\n\nfunction coerceCmdResult(value: unknown): { passed: boolean; output: string } {\n if (!isRecord(value)) return { passed: false, output: '' }\n return {\n passed: value.passed === true,\n output: pickString(value.output) ?? '',\n }\n}\n\nfunction coerceDiffStats(value: unknown): {\n filesChanged: number\n insertions: number\n deletions: number\n} {\n if (!isRecord(value)) return { filesChanged: 0, insertions: 0, deletions: 0 }\n return {\n filesChanged: toFiniteInt(value.filesChanged),\n insertions: toFiniteInt(value.insertions),\n deletions: toFiniteInt(value.deletions),\n }\n}\n\nfunction toFiniteInt(value: unknown): number {\n if (typeof value !== 'number') return 0\n if (!Number.isFinite(value)) return 0\n return Math.max(0, Math.trunc(value))\n}\n"],"mappings":";;;;;AAqBA,IAAM,yBAAyB;AA4DxB,SAAS,aAAa,UAAsD,CAAC,GAMlF;AACA,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,OAAO,QAAQ,QAAQ,SAAS,OAAO;AAC7C,QAAM,eAAe,QAAQ,gBAAgB;AAC7C,QAAM,UAAwB;AAAA,IAC5B;AAAA,IACA,aAAa;AAAA,IACb,QAAQ,EAAE,aAAa;AAAA,IACvB,OAAO,QAAQ,QAAQ,EAAE,SAAS,QAAQ,MAAM,IAAI;AAAA,IACpD,OAAO,EAAE,KAAK,MAAM,IAAI,MAAM,OAAO,MAAM,aAAa,KAAK;AAAA,IAC7D,UAAU,EAAE,aAAa,SAAS,MAAM,QAAQ;AAAA,EAClD;AACA,QAAM,SAAqC,EAAE,OAAO,iBAAiB;AACrE,QAAM,YAAoC,QAAQ,OAC9C,qBAAqB,QAAQ,IAAI,IACjC,qBAAqB;AAAA,IACnB,MAAM;AAAA,IACN,UAAU;AAAA,IACV,gBAAgB,CAAC;AAAA,IACjB,cAAc;AAAA,EAChB,CAAC;AACL,QAAM,eAAwC;AAAA,IAC5C;AAAA,IACA;AAAA,IACA,cAAc;AAAA,EAChB;AACA,SAAO,EAAE,SAAS,cAAc,mBAAmB,QAAQ,WAAW,aAAa;AACrF;AAcO,SAAS,wBAAwB,UAA0C,CAAC,GAKjF;AACA,QAAM,YACJ,QAAQ,aAAa,QAAQ,UAAU,SAAS,IAC5C,QAAQ,YACR,CAAC,eAAe,SAAS,kCAAkC;AACjE,QAAM,SAAS,QAAQ,UAAU,CAAC;AAClC,QAAM,YAAY,UAAU,IAAI,CAAC,SAAS,MAAM;AAC9C,UAAM,EAAE,aAAa,IAAI,aAAa,EAAE,SAAS,OAAO,OAAO,CAA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{"version":3,"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n * @experimental\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop via the coder delegate (no-op + secret floor,\n * optional reviewer gate, winner-selection)\n * review → code mode with a REQUIRED reviewer (the gate is the point)\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → identity-gated prompt optimization (optimizePrompt, caller-wired)\n * dynamic → agent-authored topology (runLoop + createDynamicDriver)\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n */\n\nimport type { Scenario } from '@tangle-network/agent-eval/campaign'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport {\n type OptimizePromptOptions,\n type OptimizePromptResult,\n optimizePrompt,\n} from './improvement/optimize-prompt'\nimport {\n type AgentRunSpec,\n createDynamicDriver,\n type DynamicDecision,\n type LoopResult,\n type LoopSandboxClient,\n type OutputAdapter,\n runLoop,\n type TopologyPlanner,\n type Validator,\n} from './loops'\nimport {\n type CoderReviewer,\n type CoderWinnerSelection,\n createDefaultCoderDelegate,\n type DelegateRunCtx,\n} from './mcp/delegates'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport type { DelegateCodeArgs } from './mcp/types'\nimport type { CoderOutput } from './profiles/coder'\n\n/** @experimental Every delegated-loop mode, for validation + CLI surfaces. */\nexport const DELEGATED_LOOP_MODES = [\n 'code',\n 'review',\n 'research',\n 'audit',\n 'self-improve',\n 'dynamic',\n] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** @experimental Type guard for an untrusted mode string (CLI / config input). */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n * @experimental\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the default `code`/`review` runner. */\nexport interface CoderLoopRunnerOptions {\n sandboxClient: LoopSandboxClient\n /** What to build — the delegate args (goal, repoRoot, variants, config, …). */\n args: DelegateCodeArgs\n /** Adversarial reviewer. REQUIRED for `review` mode (see `reviewLoopRunner`). */\n reviewer?: CoderReviewer\n /** Winner-selection strategy. Default `highest-score`. */\n winnerSelection?: CoderWinnerSelection\n /** Harnesses for `variants > 1` fanout. */\n fanoutHarnesses?: string[]\n}\n\n/** @experimental Build a `code`-mode runner over the hardened coder delegate. */\nexport function coderLoopRunner(options: CoderLoopRunnerOptions): DelegatedLoopRunner<CoderOutput> {\n const delegate = createDefaultCoderDelegate({\n sandboxClient: options.sandboxClient,\n ...(options.reviewer ? { reviewer: options.reviewer } : {}),\n ...(options.winnerSelection ? { winnerSelection: options.winnerSelection } : {}),\n ...(options.fanoutHarnesses ? { fanoutHarnesses: options.fanoutHarnesses } : {}),\n })\n return async (signal) => {\n const ctx: DelegateRunCtx = { signal, report: () => {} }\n return delegate(options.args, ctx)\n }\n}\n\n/**\n * @experimental\n *\n * `review` mode = `code` with a REQUIRED reviewer. The gate is the whole point,\n * so the type forces a reviewer (a \"review loop\" with no reviewer is a code loop).\n */\nexport function reviewLoopRunner(\n options: CoderLoopRunnerOptions & { reviewer: CoderReviewer },\n): DelegatedLoopRunner<CoderOutput> {\n return coderLoopRunner(options)\n}\n\n/** @experimental Options for the default `dynamic` runner. */\nexport interface DynamicLoopRunnerOptions<Task, Output> {\n sandboxClient: LoopSandboxClient\n /** The agent-authored topology planner (e.g. `createSandboxPlanner(...)`). */\n planner: TopologyPlanner<Task, Output>\n task: Task\n output: OutputAdapter<Output>\n validator?: Validator<Output>\n /** Exactly one of `agentRun` / `agentRuns` (runLoop validates). */\n agentRun?: AgentRunSpec<Task>\n agentRuns?: AgentRunSpec<Task>[]\n maxIterations?: number\n maxFanout?: number\n}\n\n/** @experimental `dynamic` mode — agent-authored topology over `runLoop`. */\nexport function dynamicLoopRunner<Task, Output>(\n o: DynamicLoopRunnerOptions<Task, Output>,\n): DelegatedLoopRunner<LoopResult<Task, Output, DynamicDecision>> {\n return async (signal) =>\n runLoop<Task, Output, DynamicDecision>({\n driver: createDynamicDriver<Task, Output>({\n planner: o.planner,\n ...(o.maxIterations !== undefined ? { maxIterations: o.maxIterations } : {}),\n ...(o.maxFanout !== undefined ? { maxFanout: o.maxFanout } : {}),\n }),\n ...(o.agentRun ? { agentRun: o.agentRun } : {}),\n ...(o.agentRuns ? { agentRuns: o.agentRuns } : {}),\n output: o.output,\n ...(o.validator ? { validator: o.validator } : {}),\n task: o.task,\n ctx: { sandboxClient: o.sandboxClient, signal },\n ...(o.maxIterations !== undefined ? { maxIterations: o.maxIterations } : {}),\n })\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * @experimental `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/** @experimental `self-improve` mode — identity-gated prompt optimization. */\nexport function selfImproveLoopRunner<TScenario extends Scenario, TArtifact>(\n options: OptimizePromptOptions<TScenario, TArtifact>,\n): DelegatedLoopRunner<OptimizePromptResult<TArtifact, TScenario>> {\n return async () => optimizePrompt<TScenario, TArtifact>(options)\n}\n\n/** @experimental `audit` mode — analyst loop over captured trace/run data. */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n * @experimental\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n * @experimental\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsDO,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,E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