@tangle-network/agent-runtime 0.45.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 (63) hide show
  1. package/README.md +3 -3
  2. package/dist/agent.d.ts +5 -5
  3. package/dist/agent.js +2 -2
  4. package/dist/agent.js.map +1 -1
  5. package/dist/analyst-loop.d.ts +5 -40
  6. package/dist/analyst-loop.js +2 -4
  7. package/dist/{chunk-KEWO4KI6.js → chunk-65FQLI4V.js} +628 -138
  8. package/dist/chunk-65FQLI4V.js.map +1 -0
  9. package/dist/{chunk-NYN5RTLP.js → chunk-GN75RGM6.js} +7 -7
  10. package/dist/chunk-GN75RGM6.js.map +1 -0
  11. package/dist/{chunk-PRX45WE2.js → chunk-GSUO5QS6.js} +1 -119
  12. package/dist/chunk-GSUO5QS6.js.map +1 -0
  13. package/dist/{chunk-FK53TXOP.js → chunk-HNUXAZIJ.js} +4 -27
  14. package/dist/chunk-HNUXAZIJ.js.map +1 -0
  15. package/dist/{chunk-IJ6FGOPO.js → chunk-I42NHLKX.js} +3 -3
  16. package/dist/chunk-I42NHLKX.js.map +1 -0
  17. package/dist/{chunk-IJGS6J7X.js → chunk-JNPK46YH.js} +2 -2
  18. package/dist/{chunk-QR4UUC5P.js → chunk-KADIJAD4.js} +33 -19
  19. package/dist/chunk-KADIJAD4.js.map +1 -0
  20. package/dist/{chunk-Z2QXVBA6.js → chunk-KPN7OQ64.js} +4 -4
  21. package/dist/chunk-KPN7OQ64.js.map +1 -0
  22. package/dist/{chunk-KSMX62JF.js → chunk-VR4JIC5H.js} +2 -2
  23. package/dist/{coder-CczgMqFx.d.ts → coder-DCWFQpmJ.d.ts} +1 -1
  24. package/dist/{dynamic-BvllHV6M.d.ts → driver-C-mtBo7h.d.ts} +6 -6
  25. package/dist/{improvement-adapter-CWegd3vw.d.ts → improvement-adapter-BC4HhuAR.d.ts} +1 -1
  26. package/dist/improvement.d.ts +2 -2
  27. package/dist/index.d.ts +8 -8
  28. package/dist/index.js +8 -8
  29. package/dist/{kb-gate-D9GBocLN.d.ts → kb-gate-2Gwpz_27.d.ts} +7 -7
  30. package/dist/{loop-runner-bin-CPrCoKqC.d.ts → loop-runner-bin-D-K6bRp3.d.ts} +11 -11
  31. package/dist/loop-runner-bin.d.ts +6 -6
  32. package/dist/loop-runner-bin.js +6 -6
  33. package/dist/loops.d.ts +5 -5
  34. package/dist/loops.js +10 -10
  35. package/dist/mcp/bin.js +6 -6
  36. package/dist/mcp/bin.js.map +1 -1
  37. package/dist/mcp/index.d.ts +11 -11
  38. package/dist/mcp/index.js +7 -7
  39. package/dist/{otel-export-Dy2DyUCU.d.ts → otel-export-nurzFwuJ.d.ts} +1 -1
  40. package/dist/profiles.d.ts +8 -8
  41. package/dist/profiles.js +1 -1
  42. package/dist/profiles.js.map +1 -1
  43. package/dist/{run-loop--hSoIknW.d.ts → run-loop-CU2Y00Si.d.ts} +2 -2
  44. package/dist/runtime.d.ts +156 -52
  45. package/dist/runtime.js +10 -10
  46. package/dist/{types-1HbsFa7H.d.ts → types-BfoeiQRZ.d.ts} +20 -20
  47. package/dist/{types-DdzkffAm.d.ts → types-DnYoHvvZ.d.ts} +17 -5
  48. package/dist/{types-BtRLF2U3.d.ts → types-p8dWBIXL.d.ts} +1 -1
  49. package/dist/workflow.d.ts +3 -3
  50. package/dist/workflow.js +2 -2
  51. package/dist/workflow.js.map +1 -1
  52. package/package.json +13 -24
  53. package/skills/agent-runtime-adoption/SKILL.md +3 -3
  54. package/skills/generate-eval/SKILL.md +60 -0
  55. package/dist/chunk-FK53TXOP.js.map +0 -1
  56. package/dist/chunk-IJ6FGOPO.js.map +0 -1
  57. package/dist/chunk-KEWO4KI6.js.map +0 -1
  58. package/dist/chunk-NYN5RTLP.js.map +0 -1
  59. package/dist/chunk-PRX45WE2.js.map +0 -1
  60. package/dist/chunk-QR4UUC5P.js.map +0 -1
  61. package/dist/chunk-Z2QXVBA6.js.map +0 -1
  62. /package/dist/{chunk-IJGS6J7X.js.map → chunk-JNPK46YH.js.map} +0 -0
  63. /package/dist/{chunk-KSMX62JF.js.map → chunk-VR4JIC5H.js.map} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-runtime",
3
- "version": "0.45.0",
3
+ "version": "0.46.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": {
@@ -87,18 +87,6 @@
87
87
  "publishConfig": {
88
88
  "access": "public"
89
89
  },
90
- "scripts": {
91
- "build": "tsup",
92
- "dev": "tsup --watch",
93
- "prepare": "tsup",
94
- "test": "vitest run",
95
- "test:watch": "vitest",
96
- "lint": "biome check src tests examples",
97
- "lint:fix": "biome check --write src tests examples",
98
- "typecheck": "tsc --noEmit",
99
- "typecheck:examples": "tsc --noEmit -p tsconfig.examples.json",
100
- "verify:package": "node scripts/verify-package-exports.mjs"
101
- },
102
90
  "devDependencies": {
103
91
  "@biomejs/biome": "^2.4.0",
104
92
  "@tangle-network/agent-eval": "^0.83.0",
@@ -109,20 +97,10 @@
109
97
  "typescript": "^5.7.0",
110
98
  "vitest": "^3.0.0"
111
99
  },
112
- "pnpm": {
113
- "minimumReleaseAge": 4320,
114
- "minimumReleaseAgeExclude": [
115
- "@tangle-network/agent-eval"
116
- ],
117
- "onlyBuiltDependencies": [
118
- "esbuild"
119
- ]
120
- },
121
100
  "engines": {
122
101
  "node": ">=20"
123
102
  },
124
103
  "license": "MIT",
125
- "packageManager": "pnpm@10.28.0",
126
104
  "peerDependencies": {
127
105
  "@tangle-network/agent-eval": ">=0.83.0 <1.0.0",
128
106
  "@tangle-network/agent-knowledge": ">=1.3.0 <2.0.0",
@@ -139,5 +117,16 @@
139
117
  "playwright": {
140
118
  "optional": true
141
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"
142
131
  }
143
- }
132
+ }
@@ -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
  ```
@@ -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/analyst-loop/iterations-to-trace-store.ts","../src/analyst-loop/run-analyst-loop.ts","../src/analyst-loop/analyst-driver-hook.ts"],"sourcesContent":["/**\n * @experimental\n *\n * The read seam that closes the autonomous loop: project a round's `Iteration[]`\n * (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the\n * read interface the trace analysts query. `runAnalystLoop` has had zero consumers\n * because nothing turned a loop's iterations into a store — this is that bridge.\n *\n * One iteration → one trace. The iteration is the root AGENT span; each `SandboxEvent`\n * becomes a child span (LLM for llm_call events, TOOL for tool events, else SPAN), so an\n * analyst can walk a shot's trace, cluster its errors, and emit findings the driver\n * steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event\n * lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration\n * surfaces a real ERROR span carrying the real message.\n */\n\nimport {\n type DatasetOverview,\n DEFAULT_TRACE_ANALYST_BUDGETS,\n type QueryTracesPage,\n type SearchSpanResult,\n type SearchTraceResult,\n type SpanMatchRecord,\n TRACE_ANALYST_TRUNCATION_MARKER_PREFIX,\n type TraceAnalysisStore,\n type TraceAnalystByteBudgets,\n type TraceAnalystFilters,\n type TraceAnalystSpan,\n type TraceAnalystSpanKind,\n type TraceAnalystTraceSummary,\n type ViewSpansResult,\n type ViewTraceResult,\n} from '@tangle-network/agent-eval'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { AnalystError } from '../errors'\nimport { extractLlmCallEvent } from '../runtime/sandbox-events'\nimport type { Iteration } from '../runtime/types'\n\n/** ErrorCluster isn't re-exported from the agent-eval root; derive it from the overview. */\ntype ErrorCluster = DatasetOverview['error_clusters'][number]\n\ninterface ProjectedTrace {\n summary: TraceAnalystTraceSummary\n spans: TraceAnalystSpan[]\n /** raw JSONL bytes of this trace's spans — the byte-budget accounting unit. */\n rawBytes: number\n}\n\nconst bytesOf = (v: unknown): number => Buffer.byteLength(JSON.stringify(v) ?? '', 'utf8')\nconst iso = (ms: number): string => new Date(ms).toISOString()\n\n/** Normalize volatile tokens out of a status message so semantically identical failures\n * collapse to one signature (digits, hex/uuids, paths, durations → placeholders). */\nfunction normalizeSignature(message: string): string {\n return message\n .replace(/0x[0-9a-fA-F]+/g, 'HEX')\n .replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g, 'UUID')\n .replace(/(\\/[\\w.-]+){2,}/g, 'PATH')\n .replace(/\\b\\d+(\\.\\d+)?(ms|s|m|h)\\b/g, 'DUR')\n .replace(/\\b\\d+\\b/g, '#')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 200)\n}\n\nfunction spanKindFor(\n event: SandboxEvent,\n agentRunName: string,\n): {\n kind: TraceAnalystSpanKind\n model: string | null\n tool: string | null\n} {\n const llm = extractLlmCallEvent(event, agentRunName)\n if (llm) return { kind: 'LLM', model: llm.model ?? null, tool: null }\n const type = String(event?.type ?? '')\n if (/tool/i.test(type)) {\n const d = event?.data as { name?: unknown; tool?: unknown } | undefined\n const tool = typeof d?.name === 'string' ? d.name : typeof d?.tool === 'string' ? d.tool : type\n return { kind: 'TOOL', model: null, tool }\n }\n return { kind: 'SPAN', model: null, tool: null }\n}\n\nfunction errorMessageOf(event: SandboxEvent): string | undefined {\n const type = String(event?.type ?? '')\n const d = event?.data as { error?: unknown; message?: unknown } | undefined\n if (/error|fail/i.test(type) || d?.error) {\n const m = d?.error ?? d?.message\n return typeof m === 'string' ? m : `${type} error`\n }\n return undefined\n}\n\n/** Project one iteration → one trace: root AGENT span + a child span per event. */\nfunction projectIteration<Task, Output>(iter: Iteration<Task, Output>): ProjectedTrace {\n const traceId =\n (\n iter.events.find((e) => (e?.data as { sandboxId?: string } | undefined)?.sandboxId)?.data as\n | { sandboxId?: string }\n | undefined\n )?.sandboxId ?? `iter-${iter.index}`\n const start = iso(iter.startedAt)\n const end = iso(iter.endedAt || iter.startedAt)\n const durationMs = Math.max(0, (iter.endedAt || iter.startedAt) - iter.startedAt)\n const rootId = `${traceId}:root`\n const iterErrored = Boolean(iter.error) || iter.verdict?.valid === false\n const spans: TraceAnalystSpan[] = [\n {\n trace_id: traceId,\n span_id: rootId,\n parent_span_id: null,\n name: iter.agentRunName,\n kind: 'AGENT',\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n status: iter.error ? 'ERROR' : 'OK',\n status_message: iter.error?.message,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: null,\n tool_name: null,\n attributes: {\n 'iteration.index': iter.index,\n 'verdict.valid': iter.verdict?.valid,\n 'verdict.score': iter.verdict?.score,\n 'output.preview':\n iter.output === undefined ? undefined : String(iter.output).slice(0, 2000),\n },\n },\n ]\n const models = new Set<string>()\n const tools = new Set<string>()\n iter.events.forEach((event, i) => {\n const { kind, model, tool } = spanKindFor(event, iter.agentRunName)\n if (model) models.add(model)\n if (tool) tools.add(tool)\n const errMsg = errorMessageOf(event)\n spans.push({\n trace_id: traceId,\n span_id: `${traceId}:e${i}`,\n parent_span_id: rootId,\n name: String(event?.type ?? 'event'),\n kind,\n start_time: start,\n end_time: end,\n duration_ms: 0,\n status: errMsg ? 'ERROR' : 'OK',\n status_message: errMsg,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: model,\n tool_name: tool,\n attributes: (event?.data as Record<string, unknown> | undefined) ?? {},\n })\n })\n const hasErrors = spans.some((s) => s.status === 'ERROR') || iterErrored\n const summary: TraceAnalystTraceSummary = {\n trace_id: traceId,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n span_count: spans.length,\n has_errors: hasErrors,\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n raw_jsonl_bytes: bytesOf(spans),\n models: [...models],\n tools: [...tools],\n }\n return { summary, spans, rawBytes: summary.raw_jsonl_bytes }\n}\n\nfunction matchesFilters(t: ProjectedTrace, f?: TraceAnalystFilters): boolean {\n if (!f) return true\n if (f.has_errors !== undefined && t.summary.has_errors !== f.has_errors) return false\n if (f.service_names?.length && !f.service_names.includes(t.summary.service_name ?? ''))\n return false\n if (f.agent_names?.length && !f.agent_names.includes(t.summary.agent_name ?? '')) return false\n if (f.model_names?.length && !f.model_names.some((m) => t.summary.models.includes(m)))\n return false\n if (f.tool_names?.length && !f.tool_names.some((tn) => t.summary.tools.includes(tn))) return false\n if (f.start_time_after && t.summary.start_time < f.start_time_after) return false\n if (f.start_time_before && t.summary.start_time > f.start_time_before) return false\n if (f.regex_pattern && !new RegExp(f.regex_pattern).test(JSON.stringify(t.spans))) return false\n return true\n}\n\nfunction capAttributes(\n attributes: Record<string, unknown>,\n perAttrCap: number,\n): { capped: Record<string, unknown>; truncated: number } {\n let truncated = 0\n const capped: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attributes)) {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof s === 'string' && s.length > perAttrCap) {\n truncated += 1\n capped[k] = `${TRACE_ANALYST_TRUNCATION_MARKER_PREFIX} ${s.length}b]${s.slice(0, perAttrCap)}`\n } else {\n capped[k] = v\n }\n }\n return { capped, truncated }\n}\n\n/**\n * Build an in-memory `TraceAnalysisStore` over a loop round's iterations. Fail-loud on an\n * empty round — there is nothing for an analyst to read, and a silent empty store would\n * mask a broken capture path.\n */\nexport function iterationsToTraceStore<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n budgets: TraceAnalystByteBudgets = DEFAULT_TRACE_ANALYST_BUDGETS,\n): TraceAnalysisStore {\n if (iterations.length === 0) {\n throw new AnalystError('iterationsToTraceStore: no iterations to analyze (empty round)')\n }\n const traces = iterations.map((it) => projectIteration(it))\n const byId = new Map(traces.map((t) => [t.summary.trace_id, t]))\n\n const buildClusters = (set: ProjectedTrace[]): ErrorCluster[] => {\n const map = new Map<string, ErrorCluster>()\n for (const t of set) {\n for (const s of t.spans) {\n if (s.status !== 'ERROR' || !s.status_message) continue\n const sig = normalizeSignature(s.status_message)\n const c = map.get(sig) ?? {\n signature: sig,\n status_message_sample: s.status_message,\n span_name: s.name,\n tool_name: s.tool_name,\n trace_count: 0,\n span_count: 0,\n prevalence: 0,\n exemplar_trace_ids: [],\n exemplar_span_ids: [],\n }\n c.span_count += 1\n if (\n !c.exemplar_trace_ids.includes(t.summary.trace_id) &&\n c.exemplar_trace_ids.length < 10\n ) {\n c.exemplar_trace_ids.push(t.summary.trace_id)\n c.trace_count += 1\n }\n if (c.exemplar_span_ids.length < 10) c.exemplar_span_ids.push(s.span_id)\n map.set(sig, c)\n }\n }\n const errorTraces = set.filter((t) => t.summary.has_errors).length || 1\n const clusters = [...map.values()].map((c) => ({\n ...c,\n prevalence: c.trace_count / errorTraces,\n }))\n return clusters.sort((a, b) => b.trace_count - a.trace_count)\n }\n\n return {\n async getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview> {\n const set = traces.filter((t) => matchesFilters(t, filters))\n const services = new Set<string>()\n const agents = new Set<string>()\n const models = new Set<string>()\n const tools = new Set<string>()\n let errorSpans = 0\n for (const t of set) {\n if (t.summary.service_name) services.add(t.summary.service_name)\n if (t.summary.agent_name) agents.add(t.summary.agent_name)\n for (const m of t.summary.models) models.add(m)\n for (const tn of t.summary.tools) tools.add(tn)\n errorSpans += t.spans.filter((s) => s.status === 'ERROR').length\n }\n const times = set.map((t) => t.summary.start_time).sort()\n return {\n total_traces: set.length,\n raw_jsonl_bytes: set.reduce((n, t) => n + t.rawBytes, 0),\n services: [...services],\n agents: [...agents],\n models: [...models],\n tool_names: [...tools],\n sample_trace_ids: set.slice(0, 20).map((t) => t.summary.trace_id),\n errors: {\n trace_count: set.filter((t) => t.summary.has_errors).length,\n span_count: errorSpans,\n },\n error_clusters: buildClusters(set),\n time_range: times.length ? { earliest: times[0]!, latest: times[times.length - 1]! } : null,\n }\n },\n\n async queryTraces(opts): Promise<QueryTracesPage> {\n const set = traces.filter((t) => matchesFilters(t, opts.filters))\n const offset = opts.offset ?? 0\n const page = set.slice(offset, offset + opts.limit)\n return {\n traces: page.map((t) => t.summary),\n total: set.length,\n has_more: offset + opts.limit < set.length,\n }\n },\n\n async countTraces(filters?: TraceAnalystFilters): Promise<number> {\n return traces.filter((t) => matchesFilters(t, filters)).length\n },\n\n async viewTrace(opts): Promise<ViewTraceResult> {\n const t = byId.get(opts.trace_id)\n if (!t) return { trace_id: opts.trace_id, spans: [] }\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeViewBudget\n const projected = t.spans.map((s) => ({\n ...s,\n attributes: capAttributes(s.attributes, cap).capped,\n }))\n if (bytesOf(projected) > budgets.perCallByteCeiling) {\n const names = new Map<string, number>()\n for (const s of t.spans) names.set(s.name, (names.get(s.name) ?? 0) + 1)\n return {\n trace_id: opts.trace_id,\n oversized: {\n span_count: t.spans.length,\n top_span_names: [...names.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20),\n span_response_bytes_max: Math.max(...t.spans.map((s) => bytesOf(s))),\n error_span_count: t.spans.filter((s) => s.status === 'ERROR').length,\n },\n }\n }\n return { trace_id: opts.trace_id, spans: projected }\n },\n\n async viewSpans(opts): Promise<ViewSpansResult> {\n const t = byId.get(opts.trace_id)\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeSpanBudget\n const want = new Set(opts.span_ids)\n const found = (t?.spans ?? []).filter((s) => want.has(s.span_id))\n let truncated = 0\n const spans = found.map((s) => {\n const { capped, truncated: n } = capAttributes(s.attributes, cap)\n truncated += n\n return { ...s, attributes: capped }\n })\n const foundIds = new Set(found.map((s) => s.span_id))\n return {\n trace_id: opts.trace_id,\n spans,\n missing_span_ids: opts.span_ids.filter((id) => !foundIds.has(id)),\n truncated_attribute_count: truncated,\n }\n },\n\n async searchTrace(opts): Promise<SearchTraceResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const hits: SpanMatchRecord[] = []\n for (const s of t?.spans ?? []) {\n for (const hit of searchSpanAttrs(s, opts.regex_pattern, budgets.perMatchTextBudget)) {\n if (hits.length >= max) break\n hits.push(hit)\n }\n }\n return {\n trace_id: opts.trace_id,\n hits,\n total_matches: hits.length,\n has_more: hits.length >= max,\n }\n },\n\n async searchSpan(opts): Promise<SearchSpanResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const span = (t?.spans ?? []).find((s) => s.span_id === opts.span_id)\n const hits = span\n ? searchSpanAttrs(span, opts.regex_pattern, budgets.perMatchTextBudget).slice(0, max)\n : []\n return {\n trace_id: opts.trace_id,\n span_id: opts.span_id,\n hits,\n total_matches: hits.length,\n has_more: false,\n }\n },\n }\n}\n\nfunction searchSpanAttrs(\n span: TraceAnalystSpan,\n pattern: string,\n textCap: number,\n): SpanMatchRecord[] {\n const re = new RegExp(pattern, 'g')\n const hits: SpanMatchRecord[] = []\n for (const [k, v] of Object.entries(span.attributes)) {\n const text = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof text !== 'string') continue\n re.lastIndex = 0\n const m = re.exec(text)\n if (!m) continue\n const at = m.index\n hits.push({\n trace_id: span.trace_id,\n span_id: span.span_id,\n span_name: span.name,\n span_kind: span.kind,\n attribute_path: `attributes.${k}`,\n matched_text: m[0].slice(0, textCap),\n context_before: text.slice(Math.max(0, at - textCap / 2), at),\n context_after: text.slice(at + m[0].length, at + m[0].length + textCap / 2),\n match_offset: at,\n })\n }\n return hits\n}\n","/**\n * `runAnalystLoop` — the one call agent apps reach for to close the\n * recursive-self-improvement loop.\n *\n * 1. Load baseline findings (last run, or the slice the caller specifies)\n * 2. Run the analyst registry with priorFindings injected\n * 3. Persist the new run's findings to the ledger\n * 4. Diff the new run against the baseline\n * 5. Hand the findings to the knowledge adapter → proposals (and\n * optionally apply them) → wiki edits\n * 6. Hand the findings to the improvement adapter → prompt / tool /\n * scaffolding edits (review-only by default)\n * 7. Return a single report the consumer renders / persists / acts on.\n *\n * Adapters are optional: the loop works as a \"run + diff + report\"\n * primitive when no adapters are wired; it closes end-to-end when\n * both adapters are wired.\n */\n\nimport type { AnalystFinding, AnalystRunResult, FindingsDiff } from '@tangle-network/agent-eval'\nimport { diffFindings } from '@tangle-network/agent-eval'\n\nimport type {\n AnalystLoopEvent,\n AnalystRegistryStreamingLike,\n ImprovementReport,\n KnowledgeReport,\n RunAnalystLoopOpts,\n RunAnalystLoopResult,\n} from './types'\n\nexport async function runAnalystLoop<TProposal = unknown, TEdit = unknown>(\n opts: RunAnalystLoopOpts,\n): Promise<RunAnalystLoopResult<TProposal, TEdit>> {\n const log = opts.log ?? defaultLog\n const strategy = opts.priorFindingsStrategy ?? 'per-kind'\n const emit = makeEmitter(opts.onEvent)\n const startedAt = Date.now()\n\n // 1. Resolve baseline + load prior findings.\n const baselineRunId = resolveBaselineRunId(opts)\n const priorAll: ReadonlyArray<AnalystFinding & { run_id: string }> = baselineRunId\n ? (opts.findingsStore?.loadRun(baselineRunId) ?? [])\n : []\n log('baseline resolved', { baselineRunId, prior_findings: priorAll.length })\n await emit({\n type: 'baseline-resolved',\n runId: opts.runId,\n baselineRunId,\n priorFindingCount: priorAll.length,\n })\n\n // 2. Run the registry. Strategy controls how analysts see priors.\n // When the registry exposes runStream, forward each event verbatim\n // so subscribers see per-analyst progress in real time.\n const priorFindings = buildPriorFindingsInput(priorAll, strategy, opts.registry.list())\n const analystResult = await runRegistry(opts, priorFindings, emit)\n log('analyst run complete', {\n findings: analystResult.findings.length,\n cost_usd: analystResult.total_cost_usd,\n per_analyst: analystResult.per_analyst.map((s) => ({\n id: s.analyst_id,\n status: s.status,\n n: s.findings_count,\n })),\n })\n\n // 3. Persist the new run before any side-effecting adapter runs so\n // the ledger is the source of truth even if an adapter throws.\n if (opts.findingsStore && analystResult.findings.length > 0) {\n await opts.findingsStore.append(opts.runId, analystResult.findings)\n await emit({\n type: 'findings-persisted',\n runId: opts.runId,\n count: analystResult.findings.length,\n })\n }\n\n // 4. Diff vs baseline.\n let diff: FindingsDiff | null = null\n if (baselineRunId && analystResult.findings.length > 0) {\n diff = diffFindings(\n priorAll.map((f) => ({ ...f })),\n analystResult.findings.map((f) => ({ ...f, run_id: opts.runId })),\n )\n log('diff vs baseline', {\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n await emit({\n type: 'diff-computed',\n runId: opts.runId,\n baselineRunId,\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n }\n\n // 5. Knowledge adapter — proposals + optional auto-apply.\n let knowledge: KnowledgeReport<TProposal> | null = null\n if (opts.knowledgeAdapter) {\n knowledge = await runKnowledgeAdapter(opts, analystResult.findings, log, emit)\n }\n\n // 6. Improvement adapter — prompt / tool / scaffolding edits.\n let improvement: ImprovementReport<TEdit> | null = null\n if (opts.improvementAdapter) {\n improvement = await runImprovementAdapter(opts, analystResult.findings, log, emit)\n }\n\n await emit({\n type: 'loop-completed',\n runId: opts.runId,\n durationMs: Date.now() - startedAt,\n })\n\n return {\n runId: opts.runId,\n baselineRunId,\n analystResult,\n diff,\n knowledge,\n improvement,\n }\n}\n\ntype Emitter = (event: AnalystLoopEvent) => Promise<void>\n\nfunction makeEmitter(onEvent: RunAnalystLoopOpts['onEvent']): Emitter {\n if (!onEvent) return async () => {}\n return async (event) => {\n await onEvent(event)\n }\n}\n\nasync function runRegistry(\n opts: RunAnalystLoopOpts,\n priorFindings: ReturnType<typeof buildPriorFindingsInput>,\n emit: Emitter,\n): Promise<AnalystRunResult> {\n const reg = opts.registry as AnalystRegistryStreamingLike\n if (typeof reg.runStream === 'function' && opts.onEvent) {\n let final: AnalystRunResult | null = null\n for await (const ev of reg.runStream(opts.runId, opts.inputs, { priorFindings })) {\n await emit({ type: 'analyst', runId: opts.runId, event: ev })\n if (ev.type === 'run-completed') final = ev.result\n }\n if (!final) {\n throw new Error('runAnalystLoop: registry.runStream ended without run-completed event')\n }\n return final\n }\n return opts.registry.run(opts.runId, opts.inputs, { priorFindings })\n}\n\nfunction resolveBaselineRunId(opts: RunAnalystLoopOpts): string | null {\n if (opts.baselineRunId === null) return null\n if (typeof opts.baselineRunId === 'string') return opts.baselineRunId\n if (!opts.findingsStore) return null\n const all = opts.findingsStore.loadAll()\n let last: string | null = null\n for (const row of all) {\n if (row.run_id === opts.runId) continue\n last = row.run_id\n }\n return last\n}\n\nfunction buildPriorFindingsInput(\n prior: ReadonlyArray<AnalystFinding & { run_id: string }>,\n strategy: 'per-kind' | 'wildcard' | 'none',\n registry: ReadonlyArray<{ id: string }>,\n): ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>> | undefined {\n if (strategy === 'none' || prior.length === 0) return undefined\n const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest as AnalystFinding)\n if (strategy === 'wildcard') {\n return { '*': stripped }\n }\n void registry\n return stripped\n}\n\nasync function runKnowledgeAdapter<TProposal>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<KnowledgeReport<TProposal>> {\n const adapter = opts.knowledgeAdapter!\n const batch = await adapter.proposeFromFindings(findings)\n log('knowledge.proposeFromFindings', {\n proposals: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'knowledge-proposed',\n runId: opts.runId,\n proposalCount: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n const auto = opts.autoApply?.knowledge ?? false\n const threshold = opts.autoApply?.knowledgeConfidenceThreshold ?? 0.85\n\n if (!auto || !adapter.apply) {\n await emit({\n type: 'knowledge-applied',\n runId: opts.runId,\n writtenCount: 0,\n withheldForReview: batch.proposals.length,\n })\n return {\n proposals: batch.proposals as TProposal[],\n applied: [],\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: batch.proposals.length,\n }\n }\n\n const findingsById = new Map(findings.map((f) => [f.finding_id, f]))\n const safe: TProposal[] = []\n let withheld = 0\n for (const p of batch.proposals as Array<TProposal & { sourceFindingId?: string }>) {\n const src = p.sourceFindingId ? findingsById.get(p.sourceFindingId) : undefined\n if (!src) {\n withheld += 1\n continue\n }\n if (src.confidence < threshold) {\n withheld += 1\n continue\n }\n safe.push(p)\n }\n const result = await adapter.apply(safe)\n log('knowledge.apply', {\n applied: result.written.length,\n withheld_for_review: withheld,\n warnings: result.warnings.length,\n })\n await emit({\n type: 'knowledge-applied',\n runId: opts.runId,\n writtenCount: result.written.length,\n withheldForReview: withheld,\n })\n return {\n proposals: batch.proposals as TProposal[],\n applied: result.written,\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: withheld,\n }\n}\n\nasync function runImprovementAdapter<TEdit>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<ImprovementReport<TEdit>> {\n const adapter = opts.improvementAdapter!\n const batch = await adapter.proposeFromFindings(findings)\n log('improvement.proposeFromFindings', {\n edits: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'improvement-proposed',\n runId: opts.runId,\n editCount: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n const auto = opts.autoApply?.improvement ?? false\n const threshold = opts.autoApply?.improvementConfidenceThreshold ?? 0.9\n\n if (!auto || !adapter.apply) {\n await emit({\n type: 'improvement-applied',\n runId: opts.runId,\n appliedCount: 0,\n withheldForReview: batch.edits.length,\n })\n return {\n edits: batch.edits as TEdit[],\n applied: [],\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: batch.edits.length,\n }\n }\n\n const findingsById = new Map(findings.map((f) => [f.finding_id, f]))\n const safe: TEdit[] = []\n let withheld = 0\n for (const e of batch.edits as Array<TEdit & { sourceFindingId?: string }>) {\n const src = e.sourceFindingId ? findingsById.get(e.sourceFindingId) : undefined\n if (!src || src.confidence < threshold) {\n withheld += 1\n continue\n }\n safe.push(e)\n }\n const result = await adapter.apply(safe)\n log('improvement.apply', {\n applied: result.applied.length,\n withheld_for_review: withheld,\n warnings: result.warnings.length,\n })\n await emit({\n type: 'improvement-applied',\n runId: opts.runId,\n appliedCount: result.applied.length,\n withheldForReview: withheld,\n })\n return {\n edits: batch.edits as TEdit[],\n applied: result.applied,\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: withheld,\n }\n}\n\nfunction defaultLog(msg: string, fields?: Record<string, unknown>): void {\n if (fields) console.log(`[analyst-loop] ${msg}`, fields)\n else console.log(`[analyst-loop] ${msg}`)\n}\n","/**\n * @experimental\n *\n * STEP 2 of closing the autonomous loop: `createAnalystDriverHook` returns the exact\n * `analyze` callback `createDynamicDriver` already accepts. Each round it projects the\n * round's iterations into a `TraceAnalysisStore` (STEP 1), runs `runAnalystLoop` over the\n * registry, threads the prior round's findings as the baseline (cross-round memory), and\n * returns the findings — which the driver feeds to the planner via `PlannerContext.analyses`.\n *\n * This is `runAnalystLoop`'s first consumer: the wire that turns \"trace analysts exist\" into\n * \"trace analysts drive the next prompt.\" The driver enforces the steer-firewall\n * (`assertTraceDerivedFindings`) on what this returns, so a kind that leaks judge-derived\n * evidence fails loud here — selector ≠ judge stays intact for free.\n */\n\nimport type { AnalystFinding, AnalystRunInputs } from '@tangle-network/agent-eval'\nimport type { AnalyzeInput } from '../runtime/dynamic'\nimport type { Iteration } from '../runtime/types'\nimport { randomSuffix } from '../runtime/util'\nimport { iterationsToTraceStore } from './iterations-to-trace-store'\nimport { runAnalystLoop } from './run-analyst-loop'\nimport type { AnalystRegistryLike, FindingsStoreLike } from './types'\n\nexport interface AnalystDriverHookOptions {\n /** The analyst registry, pre-populated with the trace-analyst kinds to run each round. */\n registry: AnalystRegistryLike\n /**\n * Durable findings ledger. When set, each round's findings are appended and diffed\n * against the prior round (cross-run memory). `null`/omitted = one-shot, no persistence.\n */\n findingsStore?: FindingsStoreLike | null\n /** How prior-round findings reach the analysts. Default `'per-kind'` (threads memory). */\n priorFindingsStrategy?: 'per-kind' | 'wildcard' | 'none'\n /** Base run id; each round runs as `${runId}-r{round}`. Default = a random base. */\n runId?: string\n}\n\n/**\n * Build the `analyze` hook for `createDynamicDriver({ planner, analyze })`. Fail-loud: an\n * empty round throws inside `iterationsToTraceStore` rather than returning empty findings.\n */\nexport function createAnalystDriverHook<Task, Output>(\n opts: AnalystDriverHookOptions,\n): (input: AnalyzeInput<Task, Output>) => Promise<ReadonlyArray<AnalystFinding>> {\n const baseRunId = opts.runId ?? `analyst-${randomSuffix()}`\n let priorRunId: string | undefined\n return async ({ history }: AnalyzeInput<Task, Output>) => {\n const traceStore = iterationsToTraceStore(history as ReadonlyArray<Iteration<Task, Output>>)\n const runId = `${baseRunId}-r${history.length}`\n const result = await runAnalystLoop({\n runId,\n registry: opts.registry,\n inputs: { traceStore } as AnalystRunInputs,\n findingsStore: opts.findingsStore ?? null,\n // thread the prior round's findings as the baseline → cross-round steering memory.\n baselineRunId: priorRunId,\n priorFindingsStrategy: opts.priorFindingsStrategy ?? 'per-kind',\n })\n priorRunId = runId\n return result.analystResult.findings\n }\n}\n"],"mappings":";;;;;;;AAgBA;AAAA,EAEE;AAAA,EAKA;AAAA,OASK;AAgBP,IAAM,UAAU,CAAC,MAAuB,OAAO,WAAW,KAAK,UAAU,CAAC,KAAK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AAA,EACvB;AACF;AAEA,SAAS,WAAW,KAAa,QAAwC;AACvE,MAAI,OAAQ,SAAQ,IAAI,kBAAkB,GAAG,IAAI,MAAM;AAAA,MAClD,SAAQ,IAAI,kBAAkB,GAAG,EAAE;AAC1C;;;ACxSO,SAAS,wBACd,MAC+E;AAC/E,QAAM,YAAY,KAAK,SAAS,WAAW,aAAa,CAAC;AACzD,MAAI;AACJ,SAAO,OAAO,EAAE,QAAQ,MAAkC;AACxD,UAAM,aAAa,uBAAuB,OAAiD;AAC3F,UAAM,QAAQ,GAAG,SAAS,KAAK,QAAQ,MAAM;AAC7C,UAAM,SAAS,MAAM,eAAe;AAAA,MAClC;AAAA,MACA,UAAU,KAAK;AAAA,MACf,QAAQ,EAAE,WAAW;AAAA,MACrB,eAAe,KAAK,iBAAiB;AAAA;AAAA,MAErC,eAAe;AAAA,MACf,uBAAuB,KAAK,yBAAyB;AAAA,IACvD,CAAC;AACD,iBAAa;AACb,WAAO,OAAO,cAAc;AAAA,EAC9B;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mcp/executor.ts","../src/mcp/delegates.ts"],"sourcesContent":["/**\n * @experimental\n *\n * Delegation executors — the layer between MCP delegates and the sandbox\n * substrate. Each executor exposes a {@link LoopSandboxClient} the kernel\n * consumes plus a placement tag so the trace pipeline can correlate workers\n * with their physical placement.\n *\n * Two implementations ship in-box:\n *\n * - {@link createSiblingSandboxExecutor} — every delegation spawns a fresh\n * sandbox sibling to the caller. Default when the MCP server runs as a\n * standalone CLI mounted outside a fleet.\n *\n * - {@link createFleetWorkspaceExecutor} — delegations dispatch onto machines\n * in the caller's existing fleet so worker diffs land directly on the\n * caller's filesystem (the fleet's shared workspace). Selected when the\n * parent sandbox passes `TANGLE_FLEET_ID` into the MCP server's env.\n */\n\nimport type { CreateSandboxOptions, SandboxInstance } from '@tangle-network/sandbox'\nimport type { LoopSandboxClient, LoopSandboxPlacement } from '../runtime'\n\n/** @experimental */\nexport interface DelegationExecutor {\n /** Sandbox client the kernel calls. Returned with `describePlacement` set. */\n readonly client: LoopSandboxClient\n /** Best-effort one-liner used in stderr boot logs and diagnostics. */\n describe(): string\n}\n\n/** @experimental */\nexport interface SiblingSandboxExecutorOptions {\n client: LoopSandboxClient\n}\n\n/**\n * Wrap a raw sandbox SDK client so the kernel emits\n * `loop.iteration.dispatch` events with `{ placement: 'sibling', sandboxId }`.\n *\n * The returned client `.create()` delegates to the underlying client; the\n * only added behavior is a `describePlacement` tag the kernel reads.\n *\n * @experimental\n */\nexport function createSiblingSandboxExecutor(\n options: SiblingSandboxExecutorOptions,\n): DelegationExecutor {\n const underlying = options.client\n const client: LoopSandboxClient = {\n create(opts?: CreateSandboxOptions): Promise<SandboxInstance> {\n return underlying.create(opts)\n },\n describePlacement(box: SandboxInstance): LoopSandboxPlacement {\n return { kind: 'sibling', sandboxId: readId(box) }\n },\n }\n return {\n client,\n describe(): string {\n return 'sibling-sandbox (each delegation = fresh sandbox via client.create)'\n },\n }\n}\n\n/**\n * Minimal `SandboxFleet` surface the fleet executor calls. Declared\n * structurally so tests can pass an in-memory stub without instantiating the\n * sandbox SDK.\n *\n * @experimental\n */\nexport interface FleetHandle {\n readonly fleetId: string\n /** Machine ids in dispatch-eligible order. The executor round-robins. */\n readonly ids: ReadonlyArray<string>\n /** Resolve a machine id to its `SandboxInstance` — that machine is mounted\n * on the fleet's shared workspace, so any diff the worker writes lands on\n * every other fleet machine's filesystem too. */\n sandbox(machineId: string): Promise<SandboxInstance>\n}\n\n/** @experimental */\nexport interface FleetWorkspaceExecutorOptions {\n fleet: FleetHandle\n /**\n * Override the machine-selection policy. Default = round-robin across\n * `fleet.ids`, skipping the optional `excludeMachineIds` set (typically the\n * coordinator machine the MCP server is running on).\n */\n selectMachine?: (call: { callIndex: number; ids: ReadonlyArray<string> }) => string\n /**\n * Machine ids to skip during default round-robin. Set to the caller's own\n * machineId so workers don't compete with the orchestrator on the same VM.\n */\n excludeMachineIds?: ReadonlyArray<string>\n}\n\n/**\n * Build an executor that resolves each delegated iteration to an existing\n * machine in `fleet`. The fleet's shared-workspace policy means the worker\n * machine sees the caller's filesystem — diffs land in-place with no\n * cross-sandbox copy step.\n *\n * @experimental\n */\nexport function createFleetWorkspaceExecutor(\n options: FleetWorkspaceExecutorOptions,\n): DelegationExecutor {\n const fleet = options.fleet\n const exclude = new Set(options.excludeMachineIds ?? [])\n let callIndex = 0\n // machineId-by-sandboxId, populated as we resolve machines so\n // `describePlacement` can recover the assignment from the SandboxInstance\n // the kernel hands back.\n const placementBySandboxId = new Map<string, { machineId: string }>()\n\n const client: LoopSandboxClient = {\n async create(): Promise<SandboxInstance> {\n const ids = fleet.ids.filter((id) => !exclude.has(id))\n if (ids.length === 0) {\n throw new Error(\n `agent-runtime: fleet ${fleet.fleetId} has no eligible worker machines (ids=[${fleet.ids.join(',')}], excluded=[${[...exclude].join(',')}])`,\n )\n }\n const selector = options.selectMachine\n const machineId = selector ? selector({ callIndex, ids }) : ids[callIndex % ids.length]\n callIndex += 1\n if (typeof machineId !== 'string' || machineId.length === 0) {\n throw new Error('agent-runtime: fleet executor selectMachine returned an empty machine id')\n }\n const box = await fleet.sandbox(machineId)\n const sandboxId = readId(box)\n if (sandboxId) placementBySandboxId.set(sandboxId, { machineId })\n return box\n },\n describePlacement(box: SandboxInstance): LoopSandboxPlacement {\n const sandboxId = readId(box)\n const recorded = sandboxId ? placementBySandboxId.get(sandboxId) : undefined\n return {\n kind: 'fleet',\n sandboxId,\n fleetId: fleet.fleetId,\n machineId: recorded?.machineId,\n }\n },\n }\n\n return {\n client,\n describe(): string {\n const excluded = exclude.size > 0 ? ` (excluded=[${[...exclude].join(',')}])` : ''\n return `fleet-workspace (fleetId=${fleet.fleetId}, machines=[${fleet.ids.join(',')}]${excluded})`\n },\n }\n}\n\nfunction readId(box: SandboxInstance): string | undefined {\n const raw = (box as unknown as { id?: unknown }).id\n return typeof raw === 'string' && raw.length > 0 ? raw : undefined\n}\n","/**\n * @experimental\n *\n * Delegate factories — the layer between MCP tool handlers and the\n * underlying `runLoop` runners.\n *\n * The MCP server is profile-agnostic: it owns the task queue + feedback\n * store + transport. Each `*Delegate` is the closure that the queue\n * invokes when a task runs. Consumers can override either delegate to\n * inject custom drivers, mocks, fleet-aware dispatchers, etc.\n *\n * The default coder delegate is wired here because we own\n * `coderProfile` / `multiHarnessCoderFanout`. The default researcher\n * delegate is **not** wired in this file — `agent-knowledge` cannot be\n * imported from `agent-runtime` without inducing a cycle. Consumers\n * pass `researcherDelegate` explicitly when constructing the server.\n */\n\nimport { type CoderOutput, coderProfile, multiHarnessCoderFanout } from '../profiles/coder'\nimport type { Iteration, LoopSandboxClient, LoopTraceEmitter } from '../runtime'\nimport { runLoop } from '../runtime'\nimport { createSiblingSandboxExecutor, type DelegationExecutor } from './executor'\nimport type {\n CoderTask,\n DelegateCodeArgs,\n DelegateResearchArgs,\n DelegateUiAuditArgs,\n DelegationProgress,\n ResearchOutputShape,\n UiAuditorDelegationOutput,\n} from './types'\n\n/** @experimental */\nexport interface DelegateRunCtx {\n signal: AbortSignal\n report(progress: DelegationProgress): void\n}\n\n/** @experimental */\nexport type CoderDelegate = (\n args: DelegateCodeArgs,\n ctx: DelegateRunCtx,\n) => Promise<import('../profiles/coder').CoderOutput>\n\n/** @experimental */\nexport type ResearcherDelegate = (\n args: DelegateResearchArgs,\n ctx: DelegateRunCtx,\n) => Promise<ResearchOutputShape>\n\n/**\n * UI-auditor delegate — fully consumer-injected. agent-runtime ships no\n * default factory because the inputs are workspace path + judge function\n * + (optionally) a `LoopSandboxClient`, and the judge is the consumer's\n * model seam. See `createInProcessUiAuditClient` + `uiAuditorProfile` in\n * `@tangle-network/agent-runtime/profiles` for the canonical wiring.\n *\n * @experimental\n */\nexport type UiAuditorDelegate = (\n args: DelegateUiAuditArgs,\n ctx: DelegateRunCtx,\n) => Promise<UiAuditorDelegationOutput>\n\n/** @experimental Structured review verdict over a coder candidate. */\nexport interface CoderReview {\n /** Gate: only approved candidates are eligible to win. */\n approved: boolean\n /** Reviewer's recommendation — surfaced in traces. */\n recommendation: 'ship' | 'approve-with-nits' | 'changes-requested' | 'reject'\n /** Readiness 0..1, used by the `highest-readiness` winner-selection strategy. */\n readiness: number\n notes?: string\n}\n\n/**\n * @experimental\n *\n * Optional adversarial reviewer over a coder candidate that already passed\n * mechanical validation (tests/typecheck/forbidden/diff/no-op/secrets). Folded\n * from the ai-trading-blueprint delegation MCP: a candidate is only eligible to\n * win if the reviewer approves it. The reviewer is the consumer's seam — an LLM\n * judge, a `pnpm review` command, anything returning a `CoderReview`.\n */\nexport type CoderReviewer = (\n output: import('../profiles/coder').CoderOutput,\n task: CoderTask,\n ctx: { signal: AbortSignal },\n) => Promise<CoderReview> | CoderReview\n\n/**\n * @experimental Winner-selection strategy among validated (+ reviewed)\n * candidates. `highest-readiness` requires a `reviewer`. Default `highest-score`\n * (the kernel's behavior — preserves backward compatibility).\n */\nexport type CoderWinnerSelection =\n | 'highest-score'\n | 'smallest-diff'\n | 'highest-readiness'\n | 'first-approved'\n\n/** @experimental */\nexport interface CreateDefaultCoderDelegateOptions {\n /**\n * Execution placement. Pass a {@link DelegationExecutor} (sibling or fleet)\n * to control where worker iterations land. `sandboxClient` is a\n * convenience shorthand that wraps the client in a sibling executor — pass\n * one or the other, not both.\n */\n executor?: DelegationExecutor\n /**\n * Convenience shorthand for sibling placement. Equivalent to\n * `executor: createSiblingSandboxExecutor({ client: sandboxClient })`.\n */\n sandboxClient?: LoopSandboxClient\n /** Default `['claude-code', 'codex', 'opencode/zai-coding-plan/glm-5.1']` when variants > 1. */\n fanoutHarnesses?: string[]\n /** Hard cap on the kernel's per-batch concurrency. Default 4. */\n maxConcurrency?: number\n /**\n * Optional adversarial reviewer. When set, a candidate must pass mechanical\n * validation AND `reviewer.approved` to be eligible to win — empty/secret/\n * test-failing patches are already gone; this catches the \"compiles + passes\n * but wrong/unsafe\" class the deterministic validator can't see.\n */\n reviewer?: CoderReviewer\n /** Winner-selection strategy among eligible candidates. Default `highest-score`. */\n winnerSelection?: CoderWinnerSelection\n /**\n * Loop trace emitter forwarded into every delegated `runLoop`. Wire\n * `createPropagatingTraceEmitter(readTraceContextFromEnv())` here (the bin\n * does) so delegated build-loops export their topology spans to the OTLP /\n * Tangle Intelligence sink when `OTEL_EXPORTER_OTLP_ENDPOINT` is set — and\n * are a cheap no-op when it isn't. Configurable by construction.\n */\n traceEmitter?: LoopTraceEmitter\n}\n\n/**\n * Build a coder delegate that drives `runLoop` against the project's\n * sandbox client + coder profile. When `args.variants > 1` it switches\n * to the multi-harness fanout topology.\n *\n * @experimental\n */\nexport function createDefaultCoderDelegate(\n options: CreateDefaultCoderDelegateOptions,\n): CoderDelegate {\n const executor = resolveExecutor(options)\n const sandboxClient = executor.client\n const fanoutHarnesses = options.fanoutHarnesses\n const maxConcurrency = options.maxConcurrency ?? 4\n const traceEmitter = options.traceEmitter\n return async (args, ctx) => {\n const task: CoderTask = {\n goal: buildCoderGoal(args),\n repoRoot: args.repoRoot,\n testCmd: args.config?.testCmd,\n typecheckCmd: args.config?.typecheckCmd,\n forbiddenPaths: args.config?.forbiddenPaths,\n maxDiffLines: args.config?.maxDiffLines,\n }\n const variants = Math.max(1, Math.trunc(args.variants ?? 1))\n ctx.report({ iteration: 0, phase: 'starting' })\n if (variants <= 1) {\n const { agentRunSpec, output, validator } = coderProfile({ task })\n const result = await runLoop({\n driver: singleShotDriver,\n agentRun: agentRunSpec,\n output,\n validator,\n task,\n ctx: { sandboxClient, signal: ctx.signal, ...(traceEmitter ? { traceEmitter } : {}) },\n maxIterations: 1,\n maxConcurrency,\n })\n const chosen = await pickCoderWinner({\n iterations: result.iterations,\n reviewer: options.reviewer,\n selection: options.winnerSelection ?? 'highest-score',\n task,\n signal: ctx.signal,\n })\n if (!chosen) throw new Error(noWinnerMessage(options.reviewer))\n ctx.report({ iteration: 1, phase: 'completed' })\n return chosen\n }\n const fanout = multiHarnessCoderFanout(\n fanoutHarnesses && fanoutHarnesses.length > 0\n ? { harnesses: fanoutHarnesses.slice(0, variants) }\n : { harnesses: undefined },\n )\n const agentRuns = fanout.agentRuns.slice(0, variants)\n const result = await runLoop({\n driver: fanout.driver,\n agentRuns,\n output: fanout.output,\n validator: fanout.validator,\n task,\n ctx: { sandboxClient, signal: ctx.signal, ...(traceEmitter ? { traceEmitter } : {}) },\n maxIterations: variants,\n maxConcurrency: Math.min(maxConcurrency, variants),\n })\n const chosen = await pickCoderWinner({\n iterations: result.iterations,\n reviewer: options.reviewer,\n selection: options.winnerSelection ?? 'highest-score',\n task,\n signal: ctx.signal,\n })\n if (!chosen) throw new Error(noWinnerMessage(options.reviewer))\n ctx.report({ iteration: agentRuns.length, phase: 'completed' })\n return chosen\n }\n}\n\ninterface PickCoderWinnerArgs {\n iterations: ReadonlyArray<Iteration<CoderTask, CoderOutput>>\n reviewer: CoderReviewer | undefined\n selection: CoderWinnerSelection\n task: CoderTask\n signal: AbortSignal\n}\n\ninterface CoderCandidate {\n index: number\n output: CoderOutput\n score: number\n readiness: number\n}\n\n/**\n * Pick the winning coder candidate from a finished loop's iterations:\n * 1. keep only mechanically-VALID candidates (the validator already gated\n * tests/typecheck/forbidden/diff/no-op/secrets),\n * 2. if a `reviewer` is wired, keep only those it APPROVES,\n * 3. select among survivors by the chosen strategy.\n * Returns `undefined` when nothing survives — the delegate fails loud.\n */\nasync function pickCoderWinner(args: PickCoderWinnerArgs): Promise<CoderOutput | undefined> {\n const valid: CoderCandidate[] = []\n for (const iter of args.iterations) {\n if (iter.output === undefined || iter.error || iter.verdict?.valid !== true) continue\n valid.push({\n index: iter.index,\n output: iter.output,\n score: iter.verdict.score ?? 0,\n readiness: iter.verdict.score ?? 0,\n })\n }\n if (valid.length === 0) return undefined\n\n let eligible = valid\n if (args.reviewer) {\n eligible = []\n for (const c of valid) {\n const review = await args.reviewer(c.output, args.task, { signal: args.signal })\n if (review.approved) eligible.push({ ...c, readiness: review.readiness })\n }\n if (eligible.length === 0) return undefined\n }\n\n return selectCoderCandidate(eligible, args.selection).output\n}\n\n/** Apply the winner-selection strategy; ties broken by earliest iteration. */\nfunction selectCoderCandidate(\n candidates: CoderCandidate[],\n selection: CoderWinnerSelection,\n): CoderCandidate {\n const diffLines = (c: CoderCandidate) =>\n c.output.diffStats.insertions + c.output.diffStats.deletions\n const sorted = [...candidates].sort((a, b) => {\n switch (selection) {\n case 'smallest-diff':\n return diffLines(a) - diffLines(b) || a.index - b.index\n case 'highest-readiness':\n return b.readiness - a.readiness || a.index - b.index\n case 'first-approved':\n return a.index - b.index\n default:\n return b.score - a.score || a.index - b.index\n }\n })\n return sorted[0]!\n}\n\nfunction noWinnerMessage(reviewer: CoderReviewer | undefined): string {\n return reviewer\n ? 'coder delegate: no candidate passed validation + review'\n : 'coder delegate: no candidate passed validation'\n}\n\nfunction buildCoderGoal(args: DelegateCodeArgs): string {\n if (!args.contextHint) return args.goal\n return [args.goal, '', '## Context', args.contextHint].join('\\n')\n}\n\nfunction resolveExecutor(options: CreateDefaultCoderDelegateOptions): DelegationExecutor {\n if (options.executor && options.sandboxClient) {\n throw new Error('createDefaultCoderDelegate: pass exactly one of `executor` or `sandboxClient`')\n }\n if (options.executor) return options.executor\n if (options.sandboxClient) {\n return createSiblingSandboxExecutor({ client: options.sandboxClient })\n }\n throw new Error('createDefaultCoderDelegate: `executor` or `sandboxClient` is required')\n}\n\n/**\n * Single-shot driver — plan one task on iteration 0, stop after one\n * iteration. Used by the coder delegate when `variants <= 1`. Keeps the\n * runLoop kernel-level accounting (timing, cost, trace emission) while\n * skipping fanout/refine topology overhead.\n */\nconst singleShotDriver = {\n name: 'mcp-single-shot',\n async plan<Task>(task: Task, history: ReadonlyArray<unknown>): Promise<Task[]> {\n return history.length === 0 ? [task] : []\n },\n decide(history: ReadonlyArray<unknown>): 'pick-winner' | 'fail' {\n return history.length > 0 ? 'pick-winner' : 'fail'\n },\n}\n"],"mappings":";;;;;;;;;AA6CO,SAAS,6BACd,SACoB;AACpB,QAAM,aAAa,QAAQ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