@tangle-network/agent-runtime 0.49.0 → 0.50.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 (46) hide show
  1. package/dist/agent.d.ts +1 -1
  2. package/dist/agent.js +1 -1
  3. package/dist/analyst-loop.d.ts +1 -1
  4. package/dist/{chunk-U2VEWKKK.js → chunk-BKAIVNFA.js} +3 -3
  5. package/dist/{chunk-PXUTIMGJ.js → chunk-CM2IK7VS.js} +148 -25
  6. package/dist/chunk-CM2IK7VS.js.map +1 -0
  7. package/dist/{chunk-XTEZ3YJ4.js → chunk-ML4IXGTV.js} +2 -2
  8. package/dist/{chunk-IQS4HI3F.js → chunk-NDM5VXZW.js} +8 -6
  9. package/dist/{chunk-IQS4HI3F.js.map → chunk-NDM5VXZW.js.map} +1 -1
  10. package/dist/chunk-OM3YNZIW.js +978 -0
  11. package/dist/chunk-OM3YNZIW.js.map +1 -0
  12. package/dist/{chunk-VIEDXELL.js → chunk-RHW75JW5.js} +94 -348
  13. package/dist/chunk-RHW75JW5.js.map +1 -0
  14. package/dist/{coder-CVZNGbyg.d.ts → coder-_YCf3BAK.d.ts} +2 -2
  15. package/dist/{driver-DYU2sgHr.d.ts → driver-DLI1io57.d.ts} +1 -1
  16. package/dist/index.d.ts +7 -7
  17. package/dist/index.js +13 -11
  18. package/dist/index.js.map +1 -1
  19. package/dist/{kb-gate-CsXpNRk7.d.ts → kb-gate-CHAyt4aI.d.ts} +436 -10
  20. package/dist/{loop-runner-bin-Cgn0A-NW.d.ts → loop-runner-bin-DFUNgpeK.d.ts} +4 -4
  21. package/dist/loop-runner-bin.d.ts +5 -5
  22. package/dist/loop-runner-bin.js +3 -3
  23. package/dist/loops.d.ts +5 -5
  24. package/dist/loops.js +7 -1
  25. package/dist/mcp/bin.js +28 -14
  26. package/dist/mcp/bin.js.map +1 -1
  27. package/dist/mcp/index.d.ts +17 -56
  28. package/dist/mcp/index.js +17 -5
  29. package/dist/mcp/index.js.map +1 -1
  30. package/dist/openai-tools-D4HLDWgw.d.ts +45 -0
  31. package/dist/profiles.d.ts +2 -2
  32. package/dist/{run-loop-DvD4aGiE.d.ts → run-loop-BIineL1T.d.ts} +1 -1
  33. package/dist/runtime.d.ts +119 -17
  34. package/dist/runtime.js +7 -1
  35. package/dist/{types-BpDfCPUp.d.ts → types-5MGt5KTY.d.ts} +1 -1
  36. package/dist/{types-nBMuollC.d.ts → types-BEQsBhOE.d.ts} +1 -1
  37. package/dist/workflow.d.ts +2 -2
  38. package/dist/workflow.js +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-GHX7XOJ2.js +0 -433
  41. package/dist/chunk-GHX7XOJ2.js.map +0 -1
  42. package/dist/chunk-PXUTIMGJ.js.map +0 -1
  43. package/dist/chunk-VIEDXELL.js.map +0 -1
  44. package/dist/otel-export-EzfsVUhh.d.ts +0 -191
  45. /package/dist/{chunk-U2VEWKKK.js.map → chunk-BKAIVNFA.js.map} +0 -0
  46. /package/dist/{chunk-XTEZ3YJ4.js.map → chunk-ML4IXGTV.js.map} +0 -0
@@ -1,433 +0,0 @@
1
- import {
2
- coderProfile,
3
- multiHarnessCoderFanout
4
- } from "./chunk-KADIJAD4.js";
5
- import {
6
- createSandboxForSpec,
7
- deleteBoxSafe,
8
- runLoop,
9
- sleep,
10
- throwAbort,
11
- throwIfAborted
12
- } from "./chunk-PXUTIMGJ.js";
13
- import {
14
- ValidationError
15
- } from "./chunk-GSUO5QS6.js";
16
-
17
- // src/mcp/detached-turn.ts
18
- var DEFAULT_TICK_INTERVAL_MS = 5e3;
19
- function formatDetachedSessionRef(parts) {
20
- assertRefComponent("sessionId", parts.sessionId);
21
- if (parts.sandboxId === void 0) return `session=${parts.sessionId}`;
22
- assertRefComponent("sandboxId", parts.sandboxId);
23
- return `sandbox=${parts.sandboxId};session=${parts.sessionId}`;
24
- }
25
- function parseDetachedSessionRef(raw) {
26
- const fields = /* @__PURE__ */ new Map();
27
- for (const pair of raw.split(";")) {
28
- const eq = pair.indexOf("=");
29
- const key = eq === -1 ? "" : pair.slice(0, eq);
30
- const value = eq === -1 ? "" : pair.slice(eq + 1);
31
- if (key !== "session" && key !== "sandbox" || value.length === 0 || fields.has(key)) {
32
- throw new ValidationError(
33
- `parseDetachedSessionRef: malformed detachedSessionRef ${JSON.stringify(raw)} \u2014 expected "session=<id>" or "sandbox=<id>;session=<id>"`
34
- );
35
- }
36
- fields.set(key, value);
37
- }
38
- const sessionId = fields.get("session");
39
- if (!sessionId) {
40
- throw new ValidationError(
41
- `parseDetachedSessionRef: detachedSessionRef ${JSON.stringify(raw)} carries no session id`
42
- );
43
- }
44
- const sandboxId = fields.get("sandbox");
45
- return { sessionId, ...sandboxId !== void 0 ? { sandboxId } : {} };
46
- }
47
- function assertRefComponent(name, value) {
48
- if (value.length === 0 || value.includes(";") || value.includes("=")) {
49
- throw new ValidationError(
50
- `formatDetachedSessionRef: ${name} ${JSON.stringify(value)} must be non-empty and free of ";" / "="`
51
- );
52
- }
53
- }
54
- function detachedTurnEvents(sessionId, turn) {
55
- return [
56
- {
57
- type: "result",
58
- id: sessionId,
59
- data: {
60
- text: turn.text,
61
- finalText: turn.text,
62
- success: true,
63
- result: turn.result
64
- }
65
- }
66
- ];
67
- }
68
- async function runDetachedTurn(options) {
69
- const intervalMs = options.tickIntervalMs ?? DEFAULT_TICK_INTERVAL_MS;
70
- const box = await createSandboxForSpec(options.client, options.spec, options.signal);
71
- const drive = box;
72
- const onAbort = () => {
73
- void drive._sessionCancel?.(options.sessionId).catch(() => {
74
- });
75
- };
76
- try {
77
- if (typeof drive.driveTurn !== "function") {
78
- throw new ValidationError(
79
- "runDetachedTurn: the acquired sandbox exposes no driveTurn(message, { sessionId }) \u2014 detached dispatch requires @tangle-network/sandbox >= 0.6 and a session-backed placement (sibling/fleet); disable detached dispatch for this executor."
80
- );
81
- }
82
- const sandboxId = box.id;
83
- if (typeof sandboxId !== "string" || sandboxId.length === 0) {
84
- throw new ValidationError(
85
- "runDetachedTurn: the acquired sandbox carries no id \u2014 without it the detached run cannot be resumed after a restart, so refusing to dispatch detached."
86
- );
87
- }
88
- options.bindSandbox(sandboxId);
89
- options.signal.addEventListener("abort", onAbort, { once: true });
90
- for (; ; ) {
91
- throwIfAborted(options.signal);
92
- const tick = await drive.driveTurn(options.prompt, {
93
- sessionId: options.sessionId,
94
- turnId: options.sessionId,
95
- ...options.wallCapMs !== void 0 ? { wallCapMs: options.wallCapMs } : {}
96
- });
97
- throwIfAborted(options.signal);
98
- if (tick.state === "completed") return { text: tick.text, result: tick.result };
99
- if (tick.state === "failed") {
100
- throw new Error(`detached turn ${options.sessionId} failed: ${tick.error}`);
101
- }
102
- options.report({ iteration: 0, phase: detachedRunningPhase(tick.elapsedMs) });
103
- await sleep(intervalMs, options.signal);
104
- }
105
- } finally {
106
- options.signal.removeEventListener("abort", onAbort);
107
- if (options.signal.aborted) onAbort();
108
- await deleteBoxSafe(box);
109
- }
110
- }
111
- function detachedRunningPhase(elapsedMs) {
112
- return elapsedMs === void 0 ? "detached-running" : `detached-running ${Math.round(elapsedMs / 1e3)}s`;
113
- }
114
- function createDriveTurnResumeDriver(options) {
115
- const cancelHooked = /* @__PURE__ */ new Set();
116
- return {
117
- intervalMs: options.intervalMs ?? DEFAULT_TICK_INTERVAL_MS,
118
- async tick({ record, detachedSessionRef }, ctx) {
119
- const ref = parseDetachedSessionRef(detachedSessionRef);
120
- if (ref.sandboxId === void 0) {
121
- return {
122
- state: "failed",
123
- error: {
124
- message: `detached session "${ref.sessionId}" was never bound to a sandbox \u2014 the previous process died before the box was acquired, so the turn was never dispatched and cannot be resumed`,
125
- kind: "DetachedSessionUnboundError"
126
- }
127
- };
128
- }
129
- const box = await options.resolveSandbox(ref.sandboxId);
130
- if (!cancelHooked.has(record.taskId)) {
131
- cancelHooked.add(record.taskId);
132
- ctx.signal.addEventListener(
133
- "abort",
134
- () => {
135
- void box._sessionCancel?.(ref.sessionId).catch(() => {
136
- });
137
- },
138
- { once: true }
139
- );
140
- }
141
- if (ctx.signal.aborted) throwAbort();
142
- const tick = await box.driveTurn(options.buildMessage(record), {
143
- sessionId: ref.sessionId,
144
- turnId: ref.sessionId,
145
- ...options.wallCapMs !== void 0 ? { wallCapMs: options.wallCapMs } : {}
146
- });
147
- if (tick.state === "completed") {
148
- const output = await options.settleOutput(
149
- { text: tick.text, result: tick.result },
150
- record,
151
- {
152
- signal: ctx.signal
153
- }
154
- );
155
- return { state: "completed", output };
156
- }
157
- if (tick.state === "failed") {
158
- return {
159
- state: "failed",
160
- error: {
161
- message: `detached turn ${ref.sessionId} failed: ${tick.error}`,
162
- kind: "DetachedTurnFailedError"
163
- }
164
- };
165
- }
166
- ctx.report({ iteration: 0, phase: detachedRunningPhase(tick.elapsedMs) });
167
- return { state: "running" };
168
- }
169
- };
170
- }
171
-
172
- // src/mcp/executor.ts
173
- function createSiblingSandboxExecutor(options) {
174
- const underlying = options.client;
175
- const client = {
176
- create(opts) {
177
- return underlying.create(opts);
178
- },
179
- describePlacement(box) {
180
- return { kind: "sibling", sandboxId: readId(box) };
181
- }
182
- };
183
- return {
184
- client,
185
- placement: "sibling",
186
- describe() {
187
- return "sibling-sandbox (each delegation = fresh sandbox via client.create)";
188
- }
189
- };
190
- }
191
- function createFleetWorkspaceExecutor(options) {
192
- const fleet = options.fleet;
193
- const exclude = new Set(options.excludeMachineIds ?? []);
194
- let callIndex = 0;
195
- const placementBySandboxId = /* @__PURE__ */ new Map();
196
- const client = {
197
- async create() {
198
- const ids = fleet.ids.filter((id) => !exclude.has(id));
199
- if (ids.length === 0) {
200
- throw new Error(
201
- `agent-runtime: fleet ${fleet.fleetId} has no eligible worker machines (ids=[${fleet.ids.join(",")}], excluded=[${[...exclude].join(",")}])`
202
- );
203
- }
204
- const selector = options.selectMachine;
205
- const machineId = selector ? selector({ callIndex, ids }) : ids[callIndex % ids.length];
206
- callIndex += 1;
207
- if (typeof machineId !== "string" || machineId.length === 0) {
208
- throw new Error("agent-runtime: fleet executor selectMachine returned an empty machine id");
209
- }
210
- const box = await fleet.sandbox(machineId);
211
- const sandboxId = readId(box);
212
- if (sandboxId) placementBySandboxId.set(sandboxId, { machineId });
213
- return box;
214
- },
215
- describePlacement(box) {
216
- const sandboxId = readId(box);
217
- const recorded = sandboxId ? placementBySandboxId.get(sandboxId) : void 0;
218
- return {
219
- kind: "fleet",
220
- sandboxId,
221
- fleetId: fleet.fleetId,
222
- machineId: recorded?.machineId
223
- };
224
- }
225
- };
226
- return {
227
- client,
228
- placement: "fleet",
229
- describe() {
230
- const excluded = exclude.size > 0 ? ` (excluded=[${[...exclude].join(",")}])` : "";
231
- return `fleet-workspace (fleetId=${fleet.fleetId}, machines=[${fleet.ids.join(",")}]${excluded})`;
232
- }
233
- };
234
- }
235
- function readId(box) {
236
- const raw = box.id;
237
- return typeof raw === "string" && raw.length > 0 ? raw : void 0;
238
- }
239
-
240
- // src/mcp/delegates.ts
241
- function createDefaultCoderDelegate(options) {
242
- const executor = resolveExecutor(options);
243
- const sandboxClient = executor.client;
244
- const fanoutHarnesses = options.fanoutHarnesses;
245
- const maxConcurrency = options.maxConcurrency ?? 4;
246
- const traceEmitter = options.traceEmitter;
247
- return async (args, ctx) => {
248
- const task = coderTaskFromArgs(args);
249
- const variants = Math.max(1, Math.trunc(args.variants ?? 1));
250
- ctx.report({ iteration: 0, phase: "starting" });
251
- if (variants <= 1) {
252
- const { agentRunSpec, output, validator } = coderProfile({
253
- task,
254
- ...options.harness ? { harness: options.harness } : {},
255
- ...options.model ? { model: options.model } : {}
256
- });
257
- if (ctx.detachedSessionRef !== void 0 && ctx.updateDetachedSessionRef) {
258
- const { sessionId } = parseDetachedSessionRef(ctx.detachedSessionRef);
259
- const rebind = ctx.updateDetachedSessionRef;
260
- const turn = await runDetachedTurn({
261
- client: sandboxClient,
262
- spec: agentRunSpec,
263
- prompt: agentRunSpec.taskToPrompt(task),
264
- sessionId,
265
- bindSandbox: (sandboxId) => rebind(formatDetachedSessionRef({ sandboxId, sessionId })),
266
- signal: ctx.signal,
267
- report: ctx.report,
268
- ...options.detachedTickIntervalMs !== void 0 ? { tickIntervalMs: options.detachedTickIntervalMs } : {},
269
- ...options.detachedWallCapMs !== void 0 ? { wallCapMs: options.detachedWallCapMs } : {}
270
- });
271
- const chosen3 = await settleDetachedCoderTurn(turn, {
272
- task,
273
- sessionId,
274
- signal: ctx.signal,
275
- ...options.harness ? { harness: options.harness } : {},
276
- ...options.model ? { model: options.model } : {},
277
- ...options.reviewer ? { reviewer: options.reviewer } : {}
278
- });
279
- ctx.report({ iteration: 1, phase: "completed" });
280
- return chosen3;
281
- }
282
- const result2 = await runLoop({
283
- driver: singleShotDriver,
284
- agentRun: agentRunSpec,
285
- output,
286
- validator,
287
- task,
288
- ctx: { sandboxClient, signal: ctx.signal, ...traceEmitter ? { traceEmitter } : {} },
289
- maxIterations: 1,
290
- maxConcurrency
291
- });
292
- const chosen2 = await pickCoderWinner({
293
- iterations: result2.iterations,
294
- reviewer: options.reviewer,
295
- selection: options.winnerSelection ?? "highest-score",
296
- task,
297
- signal: ctx.signal
298
- });
299
- if (!chosen2) throw new Error(noWinnerMessage(options.reviewer));
300
- ctx.report({ iteration: 1, phase: "completed" });
301
- return chosen2;
302
- }
303
- const fanout = multiHarnessCoderFanout({
304
- ...fanoutHarnesses && fanoutHarnesses.length > 0 ? { harnesses: fanoutHarnesses.slice(0, variants) } : {},
305
- ...options.fanoutModels ? { models: options.fanoutModels.slice(0, variants) } : {}
306
- });
307
- const agentRuns = fanout.agentRuns.slice(0, variants);
308
- const result = await runLoop({
309
- driver: fanout.driver,
310
- agentRuns,
311
- output: fanout.output,
312
- validator: fanout.validator,
313
- task,
314
- ctx: { sandboxClient, signal: ctx.signal, ...traceEmitter ? { traceEmitter } : {} },
315
- maxIterations: variants,
316
- maxConcurrency: Math.min(maxConcurrency, variants)
317
- });
318
- const chosen = await pickCoderWinner({
319
- iterations: result.iterations,
320
- reviewer: options.reviewer,
321
- selection: options.winnerSelection ?? "highest-score",
322
- task,
323
- signal: ctx.signal
324
- });
325
- if (!chosen) throw new Error(noWinnerMessage(options.reviewer));
326
- ctx.report({ iteration: agentRuns.length, phase: "completed" });
327
- return chosen;
328
- };
329
- }
330
- async function pickCoderWinner(args) {
331
- const valid = [];
332
- for (const iter of args.iterations) {
333
- if (iter.output === void 0 || iter.error || iter.verdict?.valid !== true) continue;
334
- valid.push({
335
- index: iter.index,
336
- output: iter.output,
337
- score: iter.verdict.score ?? 0,
338
- readiness: iter.verdict.score ?? 0
339
- });
340
- }
341
- if (valid.length === 0) return void 0;
342
- let eligible = valid;
343
- if (args.reviewer) {
344
- eligible = [];
345
- for (const c of valid) {
346
- const review = await args.reviewer(c.output, args.task, { signal: args.signal });
347
- if (review.approved) eligible.push({ ...c, readiness: review.readiness });
348
- }
349
- if (eligible.length === 0) return void 0;
350
- }
351
- return selectCoderCandidate(eligible, args.selection).output;
352
- }
353
- function selectCoderCandidate(candidates, selection) {
354
- const diffLines = (c) => c.output.diffStats.insertions + c.output.diffStats.deletions;
355
- const sorted = [...candidates].sort((a, b) => {
356
- switch (selection) {
357
- case "smallest-diff":
358
- return diffLines(a) - diffLines(b) || a.index - b.index;
359
- case "highest-readiness":
360
- return b.readiness - a.readiness || a.index - b.index;
361
- case "first-approved":
362
- return a.index - b.index;
363
- default:
364
- return b.score - a.score || a.index - b.index;
365
- }
366
- });
367
- return sorted[0];
368
- }
369
- function noWinnerMessage(reviewer) {
370
- return reviewer ? "coder delegate: no candidate passed validation + review" : "coder delegate: no candidate passed validation";
371
- }
372
- function coderTaskFromArgs(args) {
373
- return {
374
- goal: buildCoderGoal(args),
375
- repoRoot: args.repoRoot,
376
- testCmd: args.config?.testCmd,
377
- typecheckCmd: args.config?.typecheckCmd,
378
- forbiddenPaths: args.config?.forbiddenPaths,
379
- maxDiffLines: args.config?.maxDiffLines
380
- };
381
- }
382
- async function settleDetachedCoderTurn(turn, options) {
383
- const { output, validator } = coderProfile({
384
- task: options.task,
385
- ...options.harness ? { harness: options.harness } : {},
386
- ...options.model ? { model: options.model } : {}
387
- });
388
- const parsed = output.parse(detachedTurnEvents(options.sessionId, turn));
389
- const verdict = await validator.validate(parsed, { iteration: 0, signal: options.signal });
390
- if (verdict.valid !== true) throw new Error(noWinnerMessage(options.reviewer));
391
- if (options.reviewer) {
392
- const review = await options.reviewer(parsed, options.task, { signal: options.signal });
393
- if (!review.approved) throw new Error(noWinnerMessage(options.reviewer));
394
- }
395
- return parsed;
396
- }
397
- function buildCoderGoal(args) {
398
- if (!args.contextHint) return args.goal;
399
- return [args.goal, "", "## Context", args.contextHint].join("\n");
400
- }
401
- function resolveExecutor(options) {
402
- if (options.executor && options.sandboxClient) {
403
- throw new Error("createDefaultCoderDelegate: pass exactly one of `executor` or `sandboxClient`");
404
- }
405
- if (options.executor) return options.executor;
406
- if (options.sandboxClient) {
407
- return createSiblingSandboxExecutor({ client: options.sandboxClient });
408
- }
409
- throw new Error("createDefaultCoderDelegate: `executor` or `sandboxClient` is required");
410
- }
411
- var singleShotDriver = {
412
- name: "mcp-single-shot",
413
- async plan(task, history) {
414
- return history.length === 0 ? [task] : [];
415
- },
416
- decide(history) {
417
- return history.length > 0 ? "pick-winner" : "fail";
418
- }
419
- };
420
-
421
- export {
422
- formatDetachedSessionRef,
423
- parseDetachedSessionRef,
424
- detachedTurnEvents,
425
- runDetachedTurn,
426
- createDriveTurnResumeDriver,
427
- createSiblingSandboxExecutor,
428
- createFleetWorkspaceExecutor,
429
- createDefaultCoderDelegate,
430
- coderTaskFromArgs,
431
- settleDetachedCoderTurn
432
- };
433
- //# sourceMappingURL=chunk-GHX7XOJ2.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mcp/detached-turn.ts","../src/mcp/executor.ts","../src/mcp/delegates.ts"],"sourcesContent":["/**\n * @experimental\n *\n * Detached delegation turns over the sandbox SDK's `driveTurn` primitive.\n *\n * Two halves of one story:\n *\n * - {@link runDetachedTurn} — the dispatch side. A single-session delegate\n * (single-variant coder / researcher) acquires a box, binds the sandbox id\n * into the record's `detachedSessionRef`, then advances the turn with\n * repeated `driveTurn` ticks instead of holding a live SSE stream. The\n * session id is deterministic and supplied at submit time, so a process\n * crash between ticks loses nothing — the turn keeps running in the box.\n *\n * - {@link createDriveTurnResumeDriver} — the resume side. A\n * `DelegationResumeDriver` that re-attaches restored in-flight records to\n * their detached runs: parse the record's ref, resolve the box, advance the\n * turn one `driveTurn` pass per `tick()`, and map the SDK's three states\n * (`completed | running | failed`) onto `DelegationResumeTick`.\n *\n * Both sides type the box structurally ({@link DriveTurnCapableBox}) so tests\n * inject fakes and the module never requires the sandbox SDK at runtime — the\n * SDK stays an optional peer, exactly like the executors' `SandboxClient` seam.\n *\n * Tradeoffs of detached mode (why it is opt-in, not the default): a detached\n * turn yields one terminal payload instead of a live event stream, so per-token\n * loop trace events and kernel token/cost aggregation are not produced for that\n * turn. Multi-variant fanout stays on the streaming `runLoop` path — N\n * concurrent sessions cannot be expressed as one resume key, and winner\n * selection needs every candidate.\n */\n\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport type { AgentRunSpec, SandboxClient } from '../runtime'\nimport { createSandboxForSpec } from '../runtime'\nimport { deleteBoxSafe, sleep, throwAbort, throwIfAborted } from '../runtime/util'\nimport type { DelegationRecord, DelegationResumeDriver, DelegationResumeTick } from './task-queue'\nimport type { DelegationProgress, DelegationResultPayload } from './types'\n\nconst DEFAULT_TICK_INTERVAL_MS = 5000\n\n/**\n * Structural mirror of the sandbox SDK's `TurnDriveResult` (>= 0.6).\n * Discriminated on `state`; `failed` is terminal and deterministic per the\n * SDK contract — re-invoking with the same ids returns the same outcome.\n *\n * @experimental\n */\nexport type DriveTurnTick =\n | { state: 'completed'; text: string; result: Record<string, unknown> }\n | { state: 'running'; startedAt?: Date; elapsedMs?: number }\n | { state: 'failed'; error: string }\n\n/**\n * The box surface detached turns need. `SandboxInstance`\n * (`@tangle-network/sandbox` >= 0.6) satisfies it structurally; tests pass\n * in-memory fakes. `_sessionCancel` is the SDK's remote-cancellation surface —\n * optional here because older SDKs / fakes may not expose it; when present it\n * is invoked on abort so the remote run actually stops.\n *\n * @experimental\n */\nexport interface DriveTurnCapableBox {\n driveTurn(\n message: string,\n opts: { sessionId: string; turnId?: string; wallCapMs?: number },\n ): Promise<DriveTurnTick>\n _sessionCancel?(id: string): Promise<void>\n}\n\n/**\n * Decoded `DelegationRecord.detachedSessionRef`. `sandboxId` is absent between\n * submit and box acquisition — a record restored in that window is not\n * resumable (there is no box to resume on) and the resume driver fails it\n * loud rather than dispatching onto a guessed box.\n *\n * @experimental\n */\nexport interface DetachedSessionRefParts {\n sessionId: string\n sandboxId?: string\n}\n\n/**\n * Encode ref parts into the JSON-safe string stored on the record:\n * `session=<id>` before the box exists, `sandbox=<id>;session=<id>` once\n * bound. Ids must not contain the `;`/`=` delimiters.\n *\n * @experimental\n */\nexport function formatDetachedSessionRef(parts: DetachedSessionRefParts): string {\n assertRefComponent('sessionId', parts.sessionId)\n if (parts.sandboxId === undefined) return `session=${parts.sessionId}`\n assertRefComponent('sandboxId', parts.sandboxId)\n return `sandbox=${parts.sandboxId};session=${parts.sessionId}`\n}\n\n/** @experimental Inverse of {@link formatDetachedSessionRef}; throws `ValidationError` on malformed input. */\nexport function parseDetachedSessionRef(raw: string): DetachedSessionRefParts {\n const fields = new Map<string, string>()\n for (const pair of raw.split(';')) {\n const eq = pair.indexOf('=')\n const key = eq === -1 ? '' : pair.slice(0, eq)\n const value = eq === -1 ? '' : pair.slice(eq + 1)\n if ((key !== 'session' && key !== 'sandbox') || value.length === 0 || fields.has(key)) {\n throw new ValidationError(\n `parseDetachedSessionRef: malformed detachedSessionRef ${JSON.stringify(raw)} — expected \"session=<id>\" or \"sandbox=<id>;session=<id>\"`,\n )\n }\n fields.set(key, value)\n }\n const sessionId = fields.get('session')\n if (!sessionId) {\n throw new ValidationError(\n `parseDetachedSessionRef: detachedSessionRef ${JSON.stringify(raw)} carries no session id`,\n )\n }\n const sandboxId = fields.get('sandbox')\n return { sessionId, ...(sandboxId !== undefined ? { sandboxId } : {}) }\n}\n\nfunction assertRefComponent(name: string, value: string): void {\n if (value.length === 0 || value.includes(';') || value.includes('=')) {\n throw new ValidationError(\n `formatDetachedSessionRef: ${name} ${JSON.stringify(value)} must be non-empty and free of \";\" / \"=\"`,\n )\n }\n}\n\n/** @experimental The terminal payload of a finished detached turn. */\nexport interface DetachedTurn {\n /** Final assistant text. */\n text: string\n /** The SDK's cached AgentExecutionResult-shape record for the turn. */\n result: Record<string, unknown>\n}\n\n/**\n * Synthesize the terminal event array a detached turn settles through. Shaped\n * so the existing event-stream output adapters (coder, researcher) parse it:\n * `data.result` for adapters that read a structured terminal record, `data.text`\n * for adapters that scan assistant text for the fenced result block.\n *\n * @experimental\n */\nexport function detachedTurnEvents(sessionId: string, turn: DetachedTurn): SandboxEvent[] {\n return [\n {\n type: 'result',\n id: sessionId,\n data: {\n text: turn.text,\n finalText: turn.text,\n success: true,\n result: turn.result,\n },\n } as SandboxEvent,\n ]\n}\n\n/** @experimental */\nexport interface RunDetachedTurnOptions {\n /** Sandbox client used to acquire the box (the delegate's executor client). */\n client: SandboxClient\n /** Profile + overrides for box acquisition — same spec the streaming path uses. */\n spec: AgentRunSpec<unknown>\n /** The full turn prompt; consumed by `driveTurn`'s dispatch leg. */\n prompt: string\n /** Deterministic resume key, minted at submit time (`parseDetachedSessionRef(ref).sessionId`). */\n sessionId: string\n /**\n * Called once the box exists, with its sandbox id. Callers persist\n * `formatDetachedSessionRef({ sandboxId, sessionId })` onto the record here so\n * a restart can resolve the box again.\n */\n bindSandbox(sandboxId: string): void\n signal: AbortSignal\n report(progress: DelegationProgress): void\n /** Delay between `running` ticks (ms). Default 5000. */\n tickIntervalMs?: number\n /** Wall-clock cap forwarded to `driveTurn` — the SDK cancels and fails a session past it. */\n wallCapMs?: number\n}\n\n/**\n * Dispatch one detached turn and advance it to a terminal state with\n * `driveTurn` ticks. The first tick dispatches (idempotent on `sessionId`);\n * subsequent ticks poll. On abort the remote session is cancelled via\n * `_sessionCancel` when the box exposes it. The box is torn down on every\n * in-process exit path (success, failure, abort) — only a process death skips\n * teardown, which is exactly the case the resume driver re-attaches to.\n *\n * @experimental\n */\nexport async function runDetachedTurn(options: RunDetachedTurnOptions): Promise<DetachedTurn> {\n const intervalMs = options.tickIntervalMs ?? DEFAULT_TICK_INTERVAL_MS\n const box = await createSandboxForSpec(options.client, options.spec, options.signal)\n const drive = box as Partial<DriveTurnCapableBox>\n const onAbort = () => {\n void drive._sessionCancel?.(options.sessionId).catch(() => {})\n }\n try {\n if (typeof drive.driveTurn !== 'function') {\n throw new ValidationError(\n 'runDetachedTurn: the acquired sandbox exposes no driveTurn(message, { sessionId }) — ' +\n 'detached dispatch requires @tangle-network/sandbox >= 0.6 and a session-backed ' +\n 'placement (sibling/fleet); disable detached dispatch for this executor.',\n )\n }\n const sandboxId = (box as { id?: unknown }).id\n if (typeof sandboxId !== 'string' || sandboxId.length === 0) {\n throw new ValidationError(\n 'runDetachedTurn: the acquired sandbox carries no id — without it the detached run ' +\n 'cannot be resumed after a restart, so refusing to dispatch detached.',\n )\n }\n options.bindSandbox(sandboxId)\n options.signal.addEventListener('abort', onAbort, { once: true })\n for (;;) {\n throwIfAborted(options.signal)\n const tick = await drive.driveTurn(options.prompt, {\n sessionId: options.sessionId,\n turnId: options.sessionId,\n ...(options.wallCapMs !== undefined ? { wallCapMs: options.wallCapMs } : {}),\n })\n throwIfAborted(options.signal)\n if (tick.state === 'completed') return { text: tick.text, result: tick.result }\n if (tick.state === 'failed') {\n throw new Error(`detached turn ${options.sessionId} failed: ${tick.error}`)\n }\n options.report({ iteration: 0, phase: detachedRunningPhase(tick.elapsedMs) })\n await sleep(intervalMs, options.signal)\n }\n } finally {\n options.signal.removeEventListener('abort', onAbort)\n if (options.signal.aborted) onAbort()\n await deleteBoxSafe(box)\n }\n}\n\nfunction detachedRunningPhase(elapsedMs: number | undefined): string {\n return elapsedMs === undefined\n ? 'detached-running'\n : `detached-running ${Math.round(elapsedMs / 1000)}s`\n}\n\n/** @experimental */\nexport interface DriveTurnResumeDriverOptions {\n /**\n * Resolve the live box owning a detached session. The bin wires this to the\n * sandbox client's `get(sandboxId)`; throw when the box no longer exists —\n * a thrown tick settles the record as failed, which is the truth.\n */\n resolveSandbox(sandboxId: string): Promise<DriveTurnCapableBox>\n /**\n * Rebuild the turn prompt from the persisted record. Only consumed by\n * `driveTurn`'s dispatch leg — i.e. when the previous process died after\n * binding the box but before the session was dispatched. Must reproduce the\n * prompt the delegate would have sent.\n */\n buildMessage(record: DelegationRecord): string\n /**\n * Map a completed turn onto the delegation's typed output payload (parse +\n * validate per profile). Throw when the resumed result does not pass the\n * profile's gate — the queue settles the record as failed with that error.\n */\n settleOutput(\n turn: DetachedTurn,\n record: DelegationRecord,\n ctx: { signal: AbortSignal },\n ): Promise<DelegationResultPayload['output']> | DelegationResultPayload['output']\n /** Delay between `running` ticks (ms). Default 5000. */\n intervalMs?: number\n /** Wall-clock cap forwarded to `driveTurn` on every tick. */\n wallCapMs?: number\n}\n\n/**\n * Build the `driveTurn`-backed {@link DelegationResumeDriver}. Each `tick()`\n * is one settle/poll/dispatch pass:\n *\n * - ref without a sandbox binding → `failed` (`DetachedSessionUnboundError`):\n * the previous process died before a box existed; there is nothing to resume.\n * - `driveTurn` `completed` → `settleOutput` → `completed` tick.\n * - `running` → progress via `ctx.report`, `running` tick (queue re-ticks\n * after `intervalMs`).\n * - `failed` → `failed` tick (`DetachedTurnFailedError`) — terminal per the\n * SDK's deterministic-failure contract.\n *\n * Abort: the queue stops ticking once `cancel()` flips the record, so remote\n * cancellation is hooked onto `ctx.signal` (once per task) and fires\n * `_sessionCancel` when the SDK surface exposes it. The driver never deletes\n * boxes — it cannot know whether `sandboxId` is a disposable sibling or a\n * fleet machine, and destroying a fleet machine would be unrecoverable.\n *\n * @experimental\n */\nexport function createDriveTurnResumeDriver(\n options: DriveTurnResumeDriverOptions,\n): DelegationResumeDriver {\n const cancelHooked = new Set<string>()\n return {\n intervalMs: options.intervalMs ?? DEFAULT_TICK_INTERVAL_MS,\n async tick({ record, detachedSessionRef }, ctx): Promise<DelegationResumeTick> {\n const ref = parseDetachedSessionRef(detachedSessionRef)\n if (ref.sandboxId === undefined) {\n return {\n state: 'failed',\n error: {\n message:\n `detached session \"${ref.sessionId}\" was never bound to a sandbox — the previous ` +\n 'process died before the box was acquired, so the turn was never dispatched and ' +\n 'cannot be resumed',\n kind: 'DetachedSessionUnboundError',\n },\n }\n }\n const box = await options.resolveSandbox(ref.sandboxId)\n if (!cancelHooked.has(record.taskId)) {\n cancelHooked.add(record.taskId)\n ctx.signal.addEventListener(\n 'abort',\n () => {\n void box._sessionCancel?.(ref.sessionId).catch(() => {})\n },\n { once: true },\n )\n }\n if (ctx.signal.aborted) throwAbort()\n const tick = await box.driveTurn(options.buildMessage(record), {\n sessionId: ref.sessionId,\n turnId: ref.sessionId,\n ...(options.wallCapMs !== undefined ? { wallCapMs: options.wallCapMs } : {}),\n })\n if (tick.state === 'completed') {\n const output = await options.settleOutput(\n { text: tick.text, result: tick.result },\n record,\n {\n signal: ctx.signal,\n },\n )\n return { state: 'completed', output }\n }\n if (tick.state === 'failed') {\n return {\n state: 'failed',\n error: {\n message: `detached turn ${ref.sessionId} failed: ${tick.error}`,\n kind: 'DetachedTurnFailedError',\n },\n }\n }\n ctx.report({ iteration: 0, phase: detachedRunningPhase(tick.elapsedMs) })\n return { state: 'running' }\n },\n }\n}\n","/**\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 {\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\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` and therefore emit no loop trace events for that turn.\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 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 ...(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: { 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 : {}),\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: { 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\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":";;;;;;;;;;;;;;;;;AAwCA,IAAM,2BAA2B;AAmD1B,SAAS,yBAAyB,OAAwC;AAC/E,qBAAmB,aAAa,MAAM,SAAS;AAC/C,MAAI,MAAM,cAAc,OAAW,QAAO,WAAW,MAAM,SAAS;AACpE,qBAAmB,aAAa,MAAM,SAAS;AAC/C,SAAO,WAAW,MAAM,SAAS,YAAY,MAAM,SAAS;AAC9D;AAGO,SAAS,wBAAwB,KAAsC;AAC5E,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,QAAQ,IAAI,MAAM,GAAG,GAAG;AACjC,UAAM,KAAK,KAAK,QAAQ,GAAG;AAC3B,UAAM,MAAM,OAAO,KAAK,KAAK,KAAK,MAAM,GAAG,EAAE;AAC7C,UAAM,QAAQ,OAAO,KAAK,KAAK,KAAK,MAAM,KAAK,CAAC;AAChD,QAAK,QAAQ,aAAa,QAAQ,aAAc,MAAM,WAAW,KAAK,OAAO,IAAI,GAAG,GAAG;AACrF,YAAM,IAAI;AAAA,QACR,yDAAyD,KAAK,UAAU,GAAG,CAAC;AAAA,MAC9E;AAAA,IACF;AACA,WAAO,IAAI,KAAK,KAAK;AAAA,EACvB;AACA,QAAM,YAAY,OAAO,IAAI,SAAS;AACtC,MAAI,CAAC,WAAW;AACd,UAAM,IAAI;AAAA,MACR,+CAA+C,KAAK,UAAU,GAAG,CAAC;AAAA,IACpE;AAAA,EACF;AACA,QAAM,YAAY,OA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