@tangle-network/agent-runtime 0.53.0 → 0.54.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.
- package/README.md +27 -16
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +5 -3
- package/dist/agent.js.map +1 -1
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/analyst-loop.js +2 -2
- package/dist/{chunk-K5M3SHEU.js → chunk-2BDXWZUC.js} +5 -34
- package/dist/chunk-2BDXWZUC.js.map +1 -0
- package/dist/chunk-A73RADPB.js +281 -0
- package/dist/chunk-A73RADPB.js.map +1 -0
- package/dist/chunk-FRBWCJLP.js +396 -0
- package/dist/chunk-FRBWCJLP.js.map +1 -0
- package/dist/chunk-GRAGM4MC.js +72 -0
- package/dist/chunk-GRAGM4MC.js.map +1 -0
- package/dist/{chunk-K6WP7PYW.js → chunk-JTH2FPCK.js} +3231 -424
- package/dist/chunk-JTH2FPCK.js.map +1 -0
- package/dist/{chunk-P4QNEXFC.js → chunk-KJH62YEK.js} +2 -2
- package/dist/{chunk-HNUXAZIJ.js → chunk-P5OKDSLB.js} +2 -2
- package/dist/{chunk-GSUO5QS6.js → chunk-VLF5RHEQ.js} +2 -5
- package/dist/{chunk-GSUO5QS6.js.map → chunk-VLF5RHEQ.js.map} +1 -1
- package/dist/{chunk-JFIYKDXF.js → chunk-XRYEZPR6.js} +2 -1
- package/dist/chunk-XRYEZPR6.js.map +1 -0
- package/dist/{coder-LKm3Mczw.d.ts → coder-CEkUFv8h.d.ts} +1 -1
- package/dist/{types-CNDJCL_0.d.ts → coordination-BMzskrUR.d.ts} +268 -2
- package/dist/{kb-gate-CKfykcYQ.d.ts → delegates-BPLIl8EC.d.ts} +491 -566
- package/dist/index.d.ts +7 -7
- package/dist/index.js +23 -80
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +2 -2
- package/dist/kb-gate-CuzMYGYM.d.ts +76 -0
- package/dist/{loop-runner-bin-D4Ir7b00.d.ts → loop-runner-bin-BGpVVyXp.d.ts} +6 -27
- package/dist/loop-runner-bin.d.ts +5 -5
- package/dist/loop-runner-bin.js +6 -5
- package/dist/loops.d.ts +8 -6
- package/dist/loops.js +32 -8
- package/dist/mcp/bin.js +94 -30
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +9 -272
- package/dist/mcp/index.js +45 -365
- package/dist/mcp/index.js.map +1 -1
- package/dist/{openai-tools-CKfR3EMh.d.ts → openai-tools-CoeLQ7Uo.d.ts} +1 -1
- package/dist/profiles.d.ts +2 -2
- package/dist/profiles.js +4 -4
- package/dist/{router-client-B0Qi1NiN.d.ts → router-client-30Y_pca8.d.ts} +1 -1
- package/dist/{run-loop-DgVhucoR.d.ts → run-loop-DluzfJ2h.d.ts} +1 -1
- package/dist/runtime.d.ts +424 -23
- package/dist/runtime.js +32 -8
- package/dist/topology.d.ts +54 -1
- package/dist/topology.js +222 -0
- package/dist/topology.js.map +1 -1
- package/dist/{types-CklkW4Eh.d.ts → types-C8rNlxfV.d.ts} +4 -4
- package/dist/workflow.d.ts +2 -2
- package/dist/workflow.js +4 -2
- package/dist/workflow.js.map +1 -1
- package/package.json +5 -5
- package/skills/agent-runtime-adoption/SKILL.md +54 -46
- package/skills/build-with-agent-runtime/SKILL.md +12 -8
- package/skills/loop-writer/SKILL.md +9 -1
- package/skills/supervise/SKILL.md +24 -0
- package/dist/chunk-5M2WDWBI.js +0 -908
- package/dist/chunk-5M2WDWBI.js.map +0 -1
- package/dist/chunk-AYRQZRDV.js +0 -623
- package/dist/chunk-AYRQZRDV.js.map +0 -1
- package/dist/chunk-FO4DCM7R.js +0 -1356
- package/dist/chunk-FO4DCM7R.js.map +0 -1
- package/dist/chunk-JFIYKDXF.js.map +0 -1
- package/dist/chunk-K5M3SHEU.js.map +0 -1
- package/dist/chunk-K6WP7PYW.js.map +0 -1
- package/dist/driver-B2RKkVJW.d.ts +0 -221
- /package/dist/{chunk-P4QNEXFC.js.map → chunk-KJH62YEK.js.map} +0 -0
- /package/dist/{chunk-HNUXAZIJ.js.map → chunk-P5OKDSLB.js.map} +0 -0
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import {
|
|
2
|
+
coderProfile,
|
|
3
|
+
multiHarnessCoderFanout
|
|
4
|
+
} from "./chunk-KADIJAD4.js";
|
|
5
|
+
import {
|
|
6
|
+
composeLoopTraceEmitters,
|
|
7
|
+
detachedTurnEvents,
|
|
8
|
+
formatDetachedSessionRef,
|
|
9
|
+
parseDetachedSessionRef,
|
|
10
|
+
runDetachedTurn,
|
|
11
|
+
runLoop
|
|
12
|
+
} from "./chunk-JTH2FPCK.js";
|
|
13
|
+
|
|
14
|
+
// src/mcp/executor.ts
|
|
15
|
+
function createSiblingSandboxExecutor(options) {
|
|
16
|
+
const underlying = options.client;
|
|
17
|
+
const client = {
|
|
18
|
+
create(opts) {
|
|
19
|
+
return underlying.create(opts);
|
|
20
|
+
},
|
|
21
|
+
describePlacement(box) {
|
|
22
|
+
return { kind: "sibling", sandboxId: readId(box) };
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
return {
|
|
26
|
+
client,
|
|
27
|
+
placement: "sibling",
|
|
28
|
+
describe() {
|
|
29
|
+
return "sibling-sandbox (each delegation = fresh sandbox via client.create)";
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function createFleetWorkspaceExecutor(options) {
|
|
34
|
+
const fleet = options.fleet;
|
|
35
|
+
const exclude = new Set(options.excludeMachineIds ?? []);
|
|
36
|
+
let callIndex = 0;
|
|
37
|
+
const placementBySandboxId = /* @__PURE__ */ new Map();
|
|
38
|
+
const client = {
|
|
39
|
+
async create() {
|
|
40
|
+
const ids = fleet.ids.filter((id) => !exclude.has(id));
|
|
41
|
+
if (ids.length === 0) {
|
|
42
|
+
throw new Error(
|
|
43
|
+
`agent-runtime: fleet ${fleet.fleetId} has no eligible worker machines (ids=[${fleet.ids.join(",")}], excluded=[${[...exclude].join(",")}])`
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
const selector = options.selectMachine;
|
|
47
|
+
const machineId = selector ? selector({ callIndex, ids }) : ids[callIndex % ids.length];
|
|
48
|
+
callIndex += 1;
|
|
49
|
+
if (typeof machineId !== "string" || machineId.length === 0) {
|
|
50
|
+
throw new Error("agent-runtime: fleet executor selectMachine returned an empty machine id");
|
|
51
|
+
}
|
|
52
|
+
const box = await fleet.sandbox(machineId);
|
|
53
|
+
const sandboxId = readId(box);
|
|
54
|
+
if (sandboxId) placementBySandboxId.set(sandboxId, { machineId });
|
|
55
|
+
return box;
|
|
56
|
+
},
|
|
57
|
+
describePlacement(box) {
|
|
58
|
+
const sandboxId = readId(box);
|
|
59
|
+
const recorded = sandboxId ? placementBySandboxId.get(sandboxId) : void 0;
|
|
60
|
+
return {
|
|
61
|
+
kind: "fleet",
|
|
62
|
+
sandboxId,
|
|
63
|
+
fleetId: fleet.fleetId,
|
|
64
|
+
machineId: recorded?.machineId
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
return {
|
|
69
|
+
client,
|
|
70
|
+
placement: "fleet",
|
|
71
|
+
describe() {
|
|
72
|
+
const excluded = exclude.size > 0 ? ` (excluded=[${[...exclude].join(",")}])` : "";
|
|
73
|
+
return `fleet-workspace (fleetId=${fleet.fleetId}, machines=[${fleet.ids.join(",")}]${excluded})`;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function readId(box) {
|
|
78
|
+
const raw = box.id;
|
|
79
|
+
return typeof raw === "string" && raw.length > 0 ? raw : void 0;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// src/mcp/delegates.ts
|
|
83
|
+
function createDefaultCoderDelegate(options) {
|
|
84
|
+
const executor = resolveExecutor(options);
|
|
85
|
+
const sandboxClient = executor.client;
|
|
86
|
+
const fanoutHarnesses = options.fanoutHarnesses;
|
|
87
|
+
const maxConcurrency = options.maxConcurrency ?? 4;
|
|
88
|
+
const traceEmitter = options.traceEmitter;
|
|
89
|
+
return async (args, ctx) => {
|
|
90
|
+
const task = coderTaskFromArgs(args);
|
|
91
|
+
const variants = Math.max(1, Math.trunc(args.variants ?? 1));
|
|
92
|
+
const loopEmitter = composeLoopTraceEmitters(traceEmitter, ctx.traceEmitter);
|
|
93
|
+
ctx.report({ iteration: 0, phase: "starting" });
|
|
94
|
+
if (variants <= 1) {
|
|
95
|
+
const { agentRunSpec, output, validator } = coderProfile({
|
|
96
|
+
task,
|
|
97
|
+
...options.harness ? { harness: options.harness } : {},
|
|
98
|
+
...options.model ? { model: options.model } : {}
|
|
99
|
+
});
|
|
100
|
+
if (ctx.detachedSessionRef !== void 0 && ctx.updateDetachedSessionRef) {
|
|
101
|
+
const { sessionId } = parseDetachedSessionRef(ctx.detachedSessionRef);
|
|
102
|
+
const rebind = ctx.updateDetachedSessionRef;
|
|
103
|
+
const turn = await runDetachedTurn({
|
|
104
|
+
client: sandboxClient,
|
|
105
|
+
spec: agentRunSpec,
|
|
106
|
+
prompt: agentRunSpec.taskToPrompt(task),
|
|
107
|
+
sessionId,
|
|
108
|
+
bindSandbox: (sandboxId) => rebind(formatDetachedSessionRef({ sandboxId, sessionId })),
|
|
109
|
+
signal: ctx.signal,
|
|
110
|
+
report: ctx.report,
|
|
111
|
+
...loopEmitter ? { traceEmitter: loopEmitter } : {},
|
|
112
|
+
...executor.placement === "fleet" ? { placement: "fleet" } : {},
|
|
113
|
+
...options.detachedTickIntervalMs !== void 0 ? { tickIntervalMs: options.detachedTickIntervalMs } : {},
|
|
114
|
+
...options.detachedWallCapMs !== void 0 ? { wallCapMs: options.detachedWallCapMs } : {}
|
|
115
|
+
});
|
|
116
|
+
const chosen3 = await settleDetachedCoderTurn(turn, {
|
|
117
|
+
task,
|
|
118
|
+
sessionId,
|
|
119
|
+
signal: ctx.signal,
|
|
120
|
+
...options.harness ? { harness: options.harness } : {},
|
|
121
|
+
...options.model ? { model: options.model } : {},
|
|
122
|
+
...options.reviewer ? { reviewer: options.reviewer } : {}
|
|
123
|
+
});
|
|
124
|
+
ctx.report({ iteration: 1, phase: "completed" });
|
|
125
|
+
return chosen3;
|
|
126
|
+
}
|
|
127
|
+
const result2 = await runLoop({
|
|
128
|
+
driver: singleShotDriver,
|
|
129
|
+
agentRun: agentRunSpec,
|
|
130
|
+
output,
|
|
131
|
+
validator,
|
|
132
|
+
task,
|
|
133
|
+
ctx: {
|
|
134
|
+
sandboxClient,
|
|
135
|
+
signal: ctx.signal,
|
|
136
|
+
...loopEmitter ? { traceEmitter: loopEmitter } : {}
|
|
137
|
+
},
|
|
138
|
+
maxIterations: 1,
|
|
139
|
+
maxConcurrency
|
|
140
|
+
});
|
|
141
|
+
const chosen2 = await pickCoderWinner({
|
|
142
|
+
iterations: result2.iterations,
|
|
143
|
+
reviewer: options.reviewer,
|
|
144
|
+
selection: options.winnerSelection ?? "highest-score",
|
|
145
|
+
task,
|
|
146
|
+
signal: ctx.signal
|
|
147
|
+
});
|
|
148
|
+
if (!chosen2) throw new Error(noWinnerMessage(options.reviewer));
|
|
149
|
+
ctx.report({ iteration: 1, phase: "completed" });
|
|
150
|
+
return chosen2;
|
|
151
|
+
}
|
|
152
|
+
const fanout = multiHarnessCoderFanout({
|
|
153
|
+
...fanoutHarnesses && fanoutHarnesses.length > 0 ? { harnesses: fanoutHarnesses.slice(0, variants) } : {},
|
|
154
|
+
...options.fanoutModels ? { models: options.fanoutModels.slice(0, variants) } : {}
|
|
155
|
+
});
|
|
156
|
+
const agentRuns = fanout.agentRuns.slice(0, variants);
|
|
157
|
+
const result = await runLoop({
|
|
158
|
+
driver: fanout.driver,
|
|
159
|
+
agentRuns,
|
|
160
|
+
output: fanout.output,
|
|
161
|
+
validator: fanout.validator,
|
|
162
|
+
task,
|
|
163
|
+
ctx: {
|
|
164
|
+
sandboxClient,
|
|
165
|
+
signal: ctx.signal,
|
|
166
|
+
...loopEmitter ? { traceEmitter: loopEmitter } : {}
|
|
167
|
+
},
|
|
168
|
+
maxIterations: variants,
|
|
169
|
+
maxConcurrency: Math.min(maxConcurrency, variants)
|
|
170
|
+
});
|
|
171
|
+
const chosen = await pickCoderWinner({
|
|
172
|
+
iterations: result.iterations,
|
|
173
|
+
reviewer: options.reviewer,
|
|
174
|
+
selection: options.winnerSelection ?? "highest-score",
|
|
175
|
+
task,
|
|
176
|
+
signal: ctx.signal
|
|
177
|
+
});
|
|
178
|
+
if (!chosen) throw new Error(noWinnerMessage(options.reviewer));
|
|
179
|
+
ctx.report({ iteration: agentRuns.length, phase: "completed" });
|
|
180
|
+
return chosen;
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
async function pickCoderWinner(args) {
|
|
184
|
+
const valid = [];
|
|
185
|
+
for (const iter of args.iterations) {
|
|
186
|
+
if (iter.output === void 0 || iter.error || iter.verdict?.valid !== true) continue;
|
|
187
|
+
valid.push({
|
|
188
|
+
index: iter.index,
|
|
189
|
+
output: iter.output,
|
|
190
|
+
score: iter.verdict.score ?? 0,
|
|
191
|
+
readiness: iter.verdict.score ?? 0
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
if (valid.length === 0) return void 0;
|
|
195
|
+
let eligible = valid;
|
|
196
|
+
if (args.reviewer) {
|
|
197
|
+
eligible = [];
|
|
198
|
+
for (const c of valid) {
|
|
199
|
+
const review = await args.reviewer(c.output, args.task, { signal: args.signal });
|
|
200
|
+
if (review.approved) eligible.push({ ...c, readiness: review.readiness });
|
|
201
|
+
}
|
|
202
|
+
if (eligible.length === 0) return void 0;
|
|
203
|
+
}
|
|
204
|
+
return selectCoderCandidate(eligible, args.selection).output;
|
|
205
|
+
}
|
|
206
|
+
function selectCoderCandidate(candidates, selection) {
|
|
207
|
+
const diffLines = (c) => c.output.diffStats.insertions + c.output.diffStats.deletions;
|
|
208
|
+
const sorted = [...candidates].sort((a, b) => {
|
|
209
|
+
switch (selection) {
|
|
210
|
+
case "smallest-diff":
|
|
211
|
+
return diffLines(a) - diffLines(b) || a.index - b.index;
|
|
212
|
+
case "highest-readiness":
|
|
213
|
+
return b.readiness - a.readiness || a.index - b.index;
|
|
214
|
+
case "first-approved":
|
|
215
|
+
return a.index - b.index;
|
|
216
|
+
default:
|
|
217
|
+
return b.score - a.score || a.index - b.index;
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
return sorted[0];
|
|
221
|
+
}
|
|
222
|
+
function noWinnerMessage(reviewer) {
|
|
223
|
+
return reviewer ? "coder delegate: no candidate passed validation + review" : "coder delegate: no candidate passed validation";
|
|
224
|
+
}
|
|
225
|
+
function coderTaskFromArgs(args) {
|
|
226
|
+
return {
|
|
227
|
+
goal: buildCoderGoal(args),
|
|
228
|
+
repoRoot: args.repoRoot,
|
|
229
|
+
testCmd: args.config?.testCmd,
|
|
230
|
+
typecheckCmd: args.config?.typecheckCmd,
|
|
231
|
+
forbiddenPaths: args.config?.forbiddenPaths,
|
|
232
|
+
maxDiffLines: args.config?.maxDiffLines
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
async function settleDetachedCoderTurn(turn, options) {
|
|
236
|
+
const { output, validator } = coderProfile({
|
|
237
|
+
task: options.task,
|
|
238
|
+
...options.harness ? { harness: options.harness } : {},
|
|
239
|
+
...options.model ? { model: options.model } : {}
|
|
240
|
+
});
|
|
241
|
+
const parsed = output.parse(detachedTurnEvents(options.sessionId, turn));
|
|
242
|
+
const verdict = await validator.validate(parsed, { iteration: 0, signal: options.signal });
|
|
243
|
+
if (verdict.valid !== true) throw new Error(noWinnerMessage(options.reviewer));
|
|
244
|
+
if (options.reviewer) {
|
|
245
|
+
const review = await options.reviewer(parsed, options.task, { signal: options.signal });
|
|
246
|
+
if (!review.approved) throw new Error(noWinnerMessage(options.reviewer));
|
|
247
|
+
}
|
|
248
|
+
return parsed;
|
|
249
|
+
}
|
|
250
|
+
function buildCoderGoal(args) {
|
|
251
|
+
if (!args.contextHint) return args.goal;
|
|
252
|
+
return [args.goal, "", "## Context", args.contextHint].join("\n");
|
|
253
|
+
}
|
|
254
|
+
function resolveExecutor(options) {
|
|
255
|
+
if (options.executor && options.sandboxClient) {
|
|
256
|
+
throw new Error("createDefaultCoderDelegate: pass exactly one of `executor` or `sandboxClient`");
|
|
257
|
+
}
|
|
258
|
+
if (options.executor) return options.executor;
|
|
259
|
+
if (options.sandboxClient) {
|
|
260
|
+
return createSiblingSandboxExecutor({ client: options.sandboxClient });
|
|
261
|
+
}
|
|
262
|
+
throw new Error("createDefaultCoderDelegate: `executor` or `sandboxClient` is required");
|
|
263
|
+
}
|
|
264
|
+
var singleShotDriver = {
|
|
265
|
+
name: "mcp-single-shot",
|
|
266
|
+
async plan(task, history) {
|
|
267
|
+
return history.length === 0 ? [task] : [];
|
|
268
|
+
},
|
|
269
|
+
decide(history) {
|
|
270
|
+
return history.length > 0 ? "pick-winner" : "fail";
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
export {
|
|
275
|
+
createSiblingSandboxExecutor,
|
|
276
|
+
createFleetWorkspaceExecutor,
|
|
277
|
+
createDefaultCoderDelegate,
|
|
278
|
+
coderTaskFromArgs,
|
|
279
|
+
settleDetachedCoderTurn
|
|
280
|
+
};
|
|
281
|
+
//# sourceMappingURL=chunk-A73RADPB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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 SandboxClient} 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 { LoopSandboxPlacement, SandboxClient } from '../runtime'\n\n/** @experimental */\nexport interface DelegationExecutor {\n /** Sandbox client the kernel calls. Returned with `describePlacement` set. */\n readonly client: SandboxClient\n /** Best-effort one-liner used in stderr boot logs and diagnostics. */\n describe(): string\n /**\n * Where delegated work physically runs. `sibling` and `fleet` placements are\n * session-backed (boxes expose `driveTurn`, so detached dispatch + resume\n * apply); `in-process` spawns local harness CLIs with no sandbox session to\n * detach. Optional so consumer-implemented executors stay source-compatible;\n * absent means \"unknown\" and detached dispatch is not enabled for it.\n */\n readonly placement?: 'sibling' | 'fleet' | 'in-process'\n}\n\n/** @experimental */\nexport interface SiblingSandboxExecutorOptions {\n client: SandboxClient\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: SandboxClient = {\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 placement: 'sibling',\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: SandboxClient = {\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 placement: 'fleet',\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 { AgentRunSpec, Iteration, LoopTraceEmitter, SandboxClient } from '../runtime'\nimport { runLoop } from '../runtime'\nimport { composeLoopTraceEmitters } from './delegation-trace'\nimport {\n type DetachedTurn,\n detachedTurnEvents,\n formatDetachedSessionRef,\n parseDetachedSessionRef,\n runDetachedTurn,\n} from './detached-turn'\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 * Detached-run resume key recorded on the queue record at submit time\n * (`formatDetachedSessionRef`). Present only when the submit path requested\n * detached dispatch — its presence is what routes a session-backed delegate\n * onto the `driveTurn` tick path instead of holding a stream.\n */\n detachedSessionRef?: string\n /** Rebind the record's resume key (e.g. once the sandbox id is known). */\n updateDetachedSessionRef?(ref: string): void\n /**\n * Per-delegation trace sink supplied by the queue — loop events emitted\n * here land on the delegation record as a compact span tree. Delegates\n * compose it with their configured OTEL emitter so both sinks observe\n * the same stream.\n */\n traceEmitter?: LoopTraceEmitter\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 `SandboxClient`, 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?: SandboxClient\n /** Backend harness for the single-coder path. Default comes from `coderProfile`. */\n harness?: string\n /** Model override for the single-coder path. */\n model?: string\n /** Default `['claude-code', 'codex', 'opencode/zai-coding-plan/glm-5.1']` when variants > 1. */\n fanoutHarnesses?: string[]\n /** Optional per-harness model override for `variants > 1`. */\n fanoutModels?: (string | undefined)[]\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 * Detached single-variant turns (taken when `ctx.detachedSessionRef` is set)\n * bypass `runLoop`; `runDetachedTurn` synthesizes a single-iteration loop\n * event stream for them so this emitter observes detached work too.\n */\n traceEmitter?: LoopTraceEmitter\n /** Tick cadence (ms) for the detached single-variant path. Default 5000. */\n detachedTickIntervalMs?: number\n /** Wall-clock cap (ms) forwarded to `driveTurn` for detached turns. */\n detachedWallCapMs?: number\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 = coderTaskFromArgs(args)\n const variants = Math.max(1, Math.trunc(args.variants ?? 1))\n const loopEmitter = composeLoopTraceEmitters(traceEmitter, ctx.traceEmitter)\n ctx.report({ iteration: 0, phase: 'starting' })\n if (variants <= 1) {\n const { agentRunSpec, output, validator } = coderProfile({\n task,\n ...(options.harness ? { harness: options.harness } : {}),\n ...(options.model ? { model: options.model } : {}),\n })\n // Detached dispatch: one session on one box, driven by `driveTurn` ticks\n // instead of a held stream, so the run survives an MCP-process restart\n // (the resume driver re-attaches via the persisted ref). Only the\n // single-variant path detaches — fanout needs N sessions + winner\n // selection over every candidate, which one resume key cannot express.\n if (ctx.detachedSessionRef !== undefined && ctx.updateDetachedSessionRef) {\n const { sessionId } = parseDetachedSessionRef(ctx.detachedSessionRef)\n const rebind = ctx.updateDetachedSessionRef\n const turn = await runDetachedTurn({\n client: sandboxClient,\n spec: agentRunSpec as AgentRunSpec<unknown>,\n prompt: agentRunSpec.taskToPrompt(task),\n sessionId,\n bindSandbox: (sandboxId) => rebind(formatDetachedSessionRef({ sandboxId, sessionId })),\n signal: ctx.signal,\n report: ctx.report,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n ...(executor.placement === 'fleet' ? { placement: 'fleet' as const } : {}),\n ...(options.detachedTickIntervalMs !== undefined\n ? { tickIntervalMs: options.detachedTickIntervalMs }\n : {}),\n ...(options.detachedWallCapMs !== undefined\n ? { wallCapMs: options.detachedWallCapMs }\n : {}),\n })\n const chosen = await settleDetachedCoderTurn(turn, {\n task,\n sessionId,\n signal: ctx.signal,\n ...(options.harness ? { harness: options.harness } : {}),\n ...(options.model ? { model: options.model } : {}),\n ...(options.reviewer ? { reviewer: options.reviewer } : {}),\n })\n ctx.report({ iteration: 1, phase: 'completed' })\n return chosen\n }\n const result = await runLoop({\n driver: singleShotDriver,\n agentRun: agentRunSpec,\n output,\n validator,\n task,\n ctx: {\n sandboxClient,\n signal: ctx.signal,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n },\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 : {}),\n ...(options.fanoutModels ? { models: options.fanoutModels.slice(0, variants) } : {}),\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: {\n sandboxClient,\n signal: ctx.signal,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n },\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\n/**\n * Canonical `DelegateCodeArgs` → `CoderTask` mapping — the single source for\n * the delegate's live dispatch AND the resume driver's settle/message\n * rebuilding, so a resumed record reproduces exactly the task the original\n * process dispatched.\n *\n * @experimental\n */\nexport function coderTaskFromArgs(args: DelegateCodeArgs): CoderTask {\n return {\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}\n\n/** @experimental */\nexport interface SettleDetachedCoderTurnOptions {\n task: CoderTask\n /** Session id of the detached turn — used as the synthesized event id. */\n sessionId: string\n signal: AbortSignal\n harness?: string\n model?: string\n /** Same gate as the streaming path: an unapproved candidate cannot win. */\n reviewer?: CoderReviewer\n}\n\n/**\n * Settle a completed detached coder turn through the same gate the streaming\n * path applies: parse the terminal payload with the coder output adapter,\n * run the mechanical validator (tests/typecheck/forbidden/diff/no-op/secrets),\n * then the optional reviewer. Throws when nothing survives — a resumed or\n * detached run must not return an unvalidated patch.\n *\n * @experimental\n */\nexport async function settleDetachedCoderTurn(\n turn: DetachedTurn,\n options: SettleDetachedCoderTurnOptions,\n): Promise<CoderOutput> {\n const { output, validator } = coderProfile({\n task: options.task,\n ...(options.harness ? { harness: options.harness } : {}),\n ...(options.model ? { model: options.model } : {}),\n })\n const parsed = output.parse(detachedTurnEvents(options.sessionId, turn))\n const verdict = await validator.validate(parsed, { iteration: 0, signal: options.signal })\n if (verdict.valid !== true) throw new Error(noWinnerMessage(options.reviewer))\n if (options.reviewer) {\n const review = await options.reviewer(parsed, options.task, { signal: options.signal })\n if (!review.approved) throw new Error(noWinnerMessage(options.reviewer))\n }\n return parsed\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":";;;;;;;;;;;;;;AAqDO,SAAS,6BACd,SACoB;AACpB,QAAM,aAAa,QAAQ;AAC3B,QAAM,SAAwB;AAAA,IAC5B,OAAO,MAAuD;AAC5D,aAAO,WAAW,OAAO,IAAI;AAAA,IAC/B;AAAA,IACA,kBAAkB,KAA4C;AAC5D,aAAO,EAAE,MAAM,WAAW,WAAW,OAAO,GAAG,EAAE;AAAA,IACnD;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,IACA,WAAW;AAAA,IACX,WAAmB;AACjB,aAAO;AAAA,IACT;AAAA,EACF;AACF;AA2CO,SAAS,6BACd,SACoB;AACpB,QAAM,QAAQ,QAAQ;AACtB,QAAM,UAAU,IAAI,IAAI,QAAQ,qBAAqB,CAAC,CAAC;AACvD,MAAI,YAAY;AAIhB,QAAM,uBAAuB,oBAAI,IAAmC;AAEpE,QAAM,SAAwB;AAAA,IAC5B,MAAM,SAAmC;AACvC,YAAM,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