@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.
Files changed (71) hide show
  1. package/README.md +27 -16
  2. package/dist/agent.d.ts +1 -1
  3. package/dist/agent.js +5 -3
  4. package/dist/agent.js.map +1 -1
  5. package/dist/analyst-loop.d.ts +1 -1
  6. package/dist/analyst-loop.js +2 -2
  7. package/dist/{chunk-K5M3SHEU.js → chunk-2BDXWZUC.js} +5 -34
  8. package/dist/chunk-2BDXWZUC.js.map +1 -0
  9. package/dist/chunk-A73RADPB.js +281 -0
  10. package/dist/chunk-A73RADPB.js.map +1 -0
  11. package/dist/chunk-FRBWCJLP.js +396 -0
  12. package/dist/chunk-FRBWCJLP.js.map +1 -0
  13. package/dist/chunk-GRAGM4MC.js +72 -0
  14. package/dist/chunk-GRAGM4MC.js.map +1 -0
  15. package/dist/{chunk-K6WP7PYW.js → chunk-JTH2FPCK.js} +3231 -424
  16. package/dist/chunk-JTH2FPCK.js.map +1 -0
  17. package/dist/{chunk-P4QNEXFC.js → chunk-KJH62YEK.js} +2 -2
  18. package/dist/{chunk-HNUXAZIJ.js → chunk-P5OKDSLB.js} +2 -2
  19. package/dist/{chunk-GSUO5QS6.js → chunk-VLF5RHEQ.js} +2 -5
  20. package/dist/{chunk-GSUO5QS6.js.map → chunk-VLF5RHEQ.js.map} +1 -1
  21. package/dist/{chunk-JFIYKDXF.js → chunk-XRYEZPR6.js} +2 -1
  22. package/dist/chunk-XRYEZPR6.js.map +1 -0
  23. package/dist/{coder-LKm3Mczw.d.ts → coder-CEkUFv8h.d.ts} +1 -1
  24. package/dist/{types-CNDJCL_0.d.ts → coordination-BMzskrUR.d.ts} +268 -2
  25. package/dist/{kb-gate-CKfykcYQ.d.ts → delegates-BPLIl8EC.d.ts} +491 -566
  26. package/dist/index.d.ts +7 -7
  27. package/dist/index.js +23 -80
  28. package/dist/index.js.map +1 -1
  29. package/dist/intelligence.d.ts +2 -2
  30. package/dist/kb-gate-CuzMYGYM.d.ts +76 -0
  31. package/dist/{loop-runner-bin-D4Ir7b00.d.ts → loop-runner-bin-BGpVVyXp.d.ts} +6 -27
  32. package/dist/loop-runner-bin.d.ts +5 -5
  33. package/dist/loop-runner-bin.js +6 -5
  34. package/dist/loops.d.ts +8 -6
  35. package/dist/loops.js +32 -8
  36. package/dist/mcp/bin.js +94 -30
  37. package/dist/mcp/bin.js.map +1 -1
  38. package/dist/mcp/index.d.ts +9 -272
  39. package/dist/mcp/index.js +45 -365
  40. package/dist/mcp/index.js.map +1 -1
  41. package/dist/{openai-tools-CKfR3EMh.d.ts → openai-tools-CoeLQ7Uo.d.ts} +1 -1
  42. package/dist/profiles.d.ts +2 -2
  43. package/dist/profiles.js +4 -4
  44. package/dist/{router-client-B0Qi1NiN.d.ts → router-client-30Y_pca8.d.ts} +1 -1
  45. package/dist/{run-loop-DgVhucoR.d.ts → run-loop-DluzfJ2h.d.ts} +1 -1
  46. package/dist/runtime.d.ts +424 -23
  47. package/dist/runtime.js +32 -8
  48. package/dist/topology.d.ts +54 -1
  49. package/dist/topology.js +222 -0
  50. package/dist/topology.js.map +1 -1
  51. package/dist/{types-CklkW4Eh.d.ts → types-C8rNlxfV.d.ts} +4 -4
  52. package/dist/workflow.d.ts +2 -2
  53. package/dist/workflow.js +4 -2
  54. package/dist/workflow.js.map +1 -1
  55. package/package.json +5 -5
  56. package/skills/agent-runtime-adoption/SKILL.md +54 -46
  57. package/skills/build-with-agent-runtime/SKILL.md +12 -8
  58. package/skills/loop-writer/SKILL.md +9 -1
  59. package/skills/supervise/SKILL.md +24 -0
  60. package/dist/chunk-5M2WDWBI.js +0 -908
  61. package/dist/chunk-5M2WDWBI.js.map +0 -1
  62. package/dist/chunk-AYRQZRDV.js +0 -623
  63. package/dist/chunk-AYRQZRDV.js.map +0 -1
  64. package/dist/chunk-FO4DCM7R.js +0 -1356
  65. package/dist/chunk-FO4DCM7R.js.map +0 -1
  66. package/dist/chunk-JFIYKDXF.js.map +0 -1
  67. package/dist/chunk-K5M3SHEU.js.map +0 -1
  68. package/dist/chunk-K6WP7PYW.js.map +0 -1
  69. package/dist/driver-B2RKkVJW.d.ts +0 -221
  70. /package/dist/{chunk-P4QNEXFC.js.map → chunk-KJH62YEK.js.map} +0 -0
  71. /package/dist/{chunk-HNUXAZIJ.js.map → chunk-P5OKDSLB.js.map} +0 -0
@@ -1,623 +0,0 @@
1
- import {
2
- coderProfile,
3
- multiHarnessCoderFanout
4
- } from "./chunk-KADIJAD4.js";
5
- import {
6
- buildLoopSpanNodes
7
- } from "./chunk-G3RGMA7C.js";
8
- import {
9
- createSandboxForSpec,
10
- deleteBoxSafe,
11
- runLoop,
12
- sleep,
13
- throwAbort,
14
- throwIfAborted
15
- } from "./chunk-K6WP7PYW.js";
16
- import {
17
- ValidationError
18
- } from "./chunk-GSUO5QS6.js";
19
-
20
- // src/mcp/delegation-trace.ts
21
- var DELEGATION_TRACE_MAX_SPANS = 512;
22
- var DELEGATION_TRACE_MAX_BYTES = 256 * 1024;
23
- function buildDelegationTraceSpans(events) {
24
- return buildLoopSpanNodes(events).map((node) => ({
25
- spanId: node.spanId,
26
- ...node.parentSpanId !== void 0 ? { parentSpanId: node.parentSpanId } : {},
27
- name: node.name,
28
- kind: node.kind,
29
- startMs: node.startMs,
30
- endMs: node.endMs,
31
- ...Object.keys(node.attrs).length > 0 ? { meta: node.attrs } : {}
32
- }));
33
- }
34
- function capDelegationTrace(spans, caps) {
35
- const maxSpans = caps?.maxSpans ?? DELEGATION_TRACE_MAX_SPANS;
36
- const maxBytes = caps?.maxBytes ?? DELEGATION_TRACE_MAX_BYTES;
37
- let start = Math.max(0, spans.length - maxSpans);
38
- const sizes = spans.map((span) => JSON.stringify(span).length + 1);
39
- let total = 0;
40
- for (let i = start; i < sizes.length; i += 1) total += sizes[i];
41
- while (start < spans.length - 1 && total > maxBytes) {
42
- total -= sizes[start];
43
- start += 1;
44
- }
45
- return { trace: spans.slice(start), truncated: start > 0 };
46
- }
47
- function createDelegationTraceCollector(onSpans) {
48
- const buffers = /* @__PURE__ */ new Map();
49
- const flush = (events) => {
50
- const spans = buildDelegationTraceSpans(events);
51
- if (spans.length > 0) onSpans(spans);
52
- };
53
- return {
54
- emitter: {
55
- emit(event) {
56
- const buf = buffers.get(event.runId);
57
- if (buf) buf.push(event);
58
- else buffers.set(event.runId, [event]);
59
- if (event.kind === "loop.ended") {
60
- const events = buffers.get(event.runId) ?? [event];
61
- buffers.delete(event.runId);
62
- flush(events);
63
- }
64
- }
65
- },
66
- settle() {
67
- for (const events of buffers.values()) flush(events);
68
- buffers.clear();
69
- }
70
- };
71
- }
72
- function generateDelegationSpanId() {
73
- const bytes = new Uint8Array(8);
74
- if (typeof globalThis.crypto?.getRandomValues === "function") {
75
- globalThis.crypto.getRandomValues(bytes);
76
- } else {
77
- for (let i = 0; i < 8; i += 1) bytes[i] = Math.floor(Math.random() * 256);
78
- }
79
- return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
80
- }
81
- function composeLoopTraceEmitters(...emitters) {
82
- const live = emitters.filter((e) => e !== void 0);
83
- if (live.length === 0) return void 0;
84
- if (live.length === 1) return live[0];
85
- return {
86
- emit(event) {
87
- const pending = [];
88
- for (const emitter of live) {
89
- const result = emitter.emit(event);
90
- if (result) pending.push(result);
91
- }
92
- if (pending.length > 0) return Promise.all(pending).then(() => void 0);
93
- }
94
- };
95
- }
96
-
97
- // src/mcp/detached-turn.ts
98
- var DEFAULT_TICK_INTERVAL_MS = 5e3;
99
- function formatDetachedSessionRef(parts) {
100
- assertRefComponent("sessionId", parts.sessionId);
101
- if (parts.sandboxId === void 0) return `session=${parts.sessionId}`;
102
- assertRefComponent("sandboxId", parts.sandboxId);
103
- return `sandbox=${parts.sandboxId};session=${parts.sessionId}`;
104
- }
105
- function parseDetachedSessionRef(raw) {
106
- const fields = /* @__PURE__ */ new Map();
107
- for (const pair of raw.split(";")) {
108
- const eq = pair.indexOf("=");
109
- const key = eq === -1 ? "" : pair.slice(0, eq);
110
- const value = eq === -1 ? "" : pair.slice(eq + 1);
111
- if (key !== "session" && key !== "sandbox" || value.length === 0 || fields.has(key)) {
112
- throw new ValidationError(
113
- `parseDetachedSessionRef: malformed detachedSessionRef ${JSON.stringify(raw)} \u2014 expected "session=<id>" or "sandbox=<id>;session=<id>"`
114
- );
115
- }
116
- fields.set(key, value);
117
- }
118
- const sessionId = fields.get("session");
119
- if (!sessionId) {
120
- throw new ValidationError(
121
- `parseDetachedSessionRef: detachedSessionRef ${JSON.stringify(raw)} carries no session id`
122
- );
123
- }
124
- const sandboxId = fields.get("sandbox");
125
- return { sessionId, ...sandboxId !== void 0 ? { sandboxId } : {} };
126
- }
127
- function assertRefComponent(name, value) {
128
- if (value.length === 0 || value.includes(";") || value.includes("=")) {
129
- throw new ValidationError(
130
- `formatDetachedSessionRef: ${name} ${JSON.stringify(value)} must be non-empty and free of ";" / "="`
131
- );
132
- }
133
- }
134
- function detachedTurnEvents(sessionId, turn) {
135
- return [
136
- {
137
- type: "result",
138
- id: sessionId,
139
- data: {
140
- text: turn.text,
141
- finalText: turn.text,
142
- success: true,
143
- result: turn.result
144
- }
145
- }
146
- ];
147
- }
148
- async function runDetachedTurn(options) {
149
- const intervalMs = options.tickIntervalMs ?? DEFAULT_TICK_INTERVAL_MS;
150
- const trace = createDetachedTurnTrace(options);
151
- trace.started();
152
- const box = await createSandboxForSpec(options.client, options.spec, options.signal).catch(
153
- (err) => {
154
- trace.ended(err instanceof Error ? err.message : String(err));
155
- throw err;
156
- }
157
- );
158
- const drive = box;
159
- const onAbort = () => {
160
- void drive._sessionCancel?.(options.sessionId).catch(() => {
161
- });
162
- };
163
- try {
164
- if (typeof drive.driveTurn !== "function") {
165
- throw new ValidationError(
166
- "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."
167
- );
168
- }
169
- const sandboxId = box.id;
170
- if (typeof sandboxId !== "string" || sandboxId.length === 0) {
171
- throw new ValidationError(
172
- "runDetachedTurn: the acquired sandbox carries no id \u2014 without it the detached run cannot be resumed after a restart, so refusing to dispatch detached."
173
- );
174
- }
175
- options.bindSandbox(sandboxId);
176
- trace.dispatched(sandboxId);
177
- options.signal.addEventListener("abort", onAbort, { once: true });
178
- for (; ; ) {
179
- throwIfAborted(options.signal);
180
- const tick = await drive.driveTurn(options.prompt, {
181
- sessionId: options.sessionId,
182
- turnId: options.sessionId,
183
- ...options.wallCapMs !== void 0 ? { wallCapMs: options.wallCapMs } : {}
184
- });
185
- throwIfAborted(options.signal);
186
- if (tick.state === "completed") {
187
- trace.ended();
188
- return { text: tick.text, result: tick.result };
189
- }
190
- if (tick.state === "failed") {
191
- throw new Error(`detached turn ${options.sessionId} failed: ${tick.error}`);
192
- }
193
- options.report({ iteration: 0, phase: detachedRunningPhase(tick.elapsedMs) });
194
- await sleep(intervalMs, options.signal);
195
- }
196
- } catch (err) {
197
- trace.ended(err instanceof Error ? err.message : String(err));
198
- throw err;
199
- } finally {
200
- options.signal.removeEventListener("abort", onAbort);
201
- if (options.signal.aborted) onAbort();
202
- await deleteBoxSafe(box);
203
- }
204
- }
205
- function createDetachedTurnTrace(options) {
206
- const emitter = options.traceEmitter;
207
- if (!emitter) {
208
- return { started() {
209
- }, dispatched() {
210
- }, ended() {
211
- } };
212
- }
213
- const runId = options.sessionId;
214
- const agentRunName = options.spec.name ?? options.spec.profile.name ?? "detached-turn";
215
- const startMs = Date.now();
216
- let done = false;
217
- const emit = (event) => {
218
- void emitter.emit(event);
219
- };
220
- return {
221
- started() {
222
- emit({
223
- kind: "loop.started",
224
- runId,
225
- timestamp: startMs,
226
- payload: {
227
- driver: "detached-turn",
228
- agentRunNames: [agentRunName],
229
- maxIterations: 1,
230
- maxConcurrency: 1
231
- }
232
- });
233
- emit({
234
- kind: "loop.iteration.started",
235
- runId,
236
- timestamp: startMs,
237
- payload: { iterationIndex: 0, agentRunName, taskHash: options.sessionId }
238
- });
239
- },
240
- dispatched(sandboxId) {
241
- emit({
242
- kind: "loop.iteration.dispatch",
243
- runId,
244
- timestamp: Date.now(),
245
- payload: {
246
- iterationIndex: 0,
247
- agentRunName,
248
- placement: options.placement ?? "sibling",
249
- sandboxId
250
- }
251
- });
252
- },
253
- ended(error) {
254
- if (done) return;
255
- done = true;
256
- const endMs = Date.now();
257
- emit({
258
- kind: "loop.iteration.ended",
259
- runId,
260
- timestamp: endMs,
261
- payload: {
262
- iterationIndex: 0,
263
- agentRunName,
264
- costUsd: 0,
265
- durationMs: endMs - startMs,
266
- ...error !== void 0 ? { error } : {}
267
- }
268
- });
269
- emit({
270
- kind: "loop.ended",
271
- runId,
272
- timestamp: endMs,
273
- payload: {
274
- ...error === void 0 ? { winnerIterationIndex: 0 } : {},
275
- totalCostUsd: 0,
276
- durationMs: endMs - startMs,
277
- iterations: 1
278
- }
279
- });
280
- }
281
- };
282
- }
283
- function detachedRunningPhase(elapsedMs) {
284
- return elapsedMs === void 0 ? "detached-running" : `detached-running ${Math.round(elapsedMs / 1e3)}s`;
285
- }
286
- function createDriveTurnResumeDriver(options) {
287
- const cancelHooked = /* @__PURE__ */ new Set();
288
- return {
289
- intervalMs: options.intervalMs ?? DEFAULT_TICK_INTERVAL_MS,
290
- async tick({ record, detachedSessionRef }, ctx) {
291
- const ref = parseDetachedSessionRef(detachedSessionRef);
292
- if (ref.sandboxId === void 0) {
293
- return {
294
- state: "failed",
295
- error: {
296
- 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`,
297
- kind: "DetachedSessionUnboundError"
298
- }
299
- };
300
- }
301
- const box = await options.resolveSandbox(ref.sandboxId);
302
- if (!cancelHooked.has(record.taskId)) {
303
- cancelHooked.add(record.taskId);
304
- ctx.signal.addEventListener(
305
- "abort",
306
- () => {
307
- void box._sessionCancel?.(ref.sessionId).catch(() => {
308
- });
309
- },
310
- { once: true }
311
- );
312
- }
313
- if (ctx.signal.aborted) throwAbort();
314
- const tick = await box.driveTurn(options.buildMessage(record), {
315
- sessionId: ref.sessionId,
316
- turnId: ref.sessionId,
317
- ...options.wallCapMs !== void 0 ? { wallCapMs: options.wallCapMs } : {}
318
- });
319
- if (tick.state === "completed") {
320
- const output = await options.settleOutput(
321
- { text: tick.text, result: tick.result },
322
- record,
323
- {
324
- signal: ctx.signal
325
- }
326
- );
327
- return { state: "completed", output };
328
- }
329
- if (tick.state === "failed") {
330
- return {
331
- state: "failed",
332
- error: {
333
- message: `detached turn ${ref.sessionId} failed: ${tick.error}`,
334
- kind: "DetachedTurnFailedError"
335
- }
336
- };
337
- }
338
- ctx.report({ iteration: 0, phase: detachedRunningPhase(tick.elapsedMs) });
339
- return { state: "running" };
340
- }
341
- };
342
- }
343
-
344
- // src/mcp/executor.ts
345
- function createSiblingSandboxExecutor(options) {
346
- const underlying = options.client;
347
- const client = {
348
- create(opts) {
349
- return underlying.create(opts);
350
- },
351
- describePlacement(box) {
352
- return { kind: "sibling", sandboxId: readId(box) };
353
- }
354
- };
355
- return {
356
- client,
357
- placement: "sibling",
358
- describe() {
359
- return "sibling-sandbox (each delegation = fresh sandbox via client.create)";
360
- }
361
- };
362
- }
363
- function createFleetWorkspaceExecutor(options) {
364
- const fleet = options.fleet;
365
- const exclude = new Set(options.excludeMachineIds ?? []);
366
- let callIndex = 0;
367
- const placementBySandboxId = /* @__PURE__ */ new Map();
368
- const client = {
369
- async create() {
370
- const ids = fleet.ids.filter((id) => !exclude.has(id));
371
- if (ids.length === 0) {
372
- throw new Error(
373
- `agent-runtime: fleet ${fleet.fleetId} has no eligible worker machines (ids=[${fleet.ids.join(",")}], excluded=[${[...exclude].join(",")}])`
374
- );
375
- }
376
- const selector = options.selectMachine;
377
- const machineId = selector ? selector({ callIndex, ids }) : ids[callIndex % ids.length];
378
- callIndex += 1;
379
- if (typeof machineId !== "string" || machineId.length === 0) {
380
- throw new Error("agent-runtime: fleet executor selectMachine returned an empty machine id");
381
- }
382
- const box = await fleet.sandbox(machineId);
383
- const sandboxId = readId(box);
384
- if (sandboxId) placementBySandboxId.set(sandboxId, { machineId });
385
- return box;
386
- },
387
- describePlacement(box) {
388
- const sandboxId = readId(box);
389
- const recorded = sandboxId ? placementBySandboxId.get(sandboxId) : void 0;
390
- return {
391
- kind: "fleet",
392
- sandboxId,
393
- fleetId: fleet.fleetId,
394
- machineId: recorded?.machineId
395
- };
396
- }
397
- };
398
- return {
399
- client,
400
- placement: "fleet",
401
- describe() {
402
- const excluded = exclude.size > 0 ? ` (excluded=[${[...exclude].join(",")}])` : "";
403
- return `fleet-workspace (fleetId=${fleet.fleetId}, machines=[${fleet.ids.join(",")}]${excluded})`;
404
- }
405
- };
406
- }
407
- function readId(box) {
408
- const raw = box.id;
409
- return typeof raw === "string" && raw.length > 0 ? raw : void 0;
410
- }
411
-
412
- // src/mcp/delegates.ts
413
- function createDefaultCoderDelegate(options) {
414
- const executor = resolveExecutor(options);
415
- const sandboxClient = executor.client;
416
- const fanoutHarnesses = options.fanoutHarnesses;
417
- const maxConcurrency = options.maxConcurrency ?? 4;
418
- const traceEmitter = options.traceEmitter;
419
- return async (args, ctx) => {
420
- const task = coderTaskFromArgs(args);
421
- const variants = Math.max(1, Math.trunc(args.variants ?? 1));
422
- const loopEmitter = composeLoopTraceEmitters(traceEmitter, ctx.traceEmitter);
423
- ctx.report({ iteration: 0, phase: "starting" });
424
- if (variants <= 1) {
425
- const { agentRunSpec, output, validator } = coderProfile({
426
- task,
427
- ...options.harness ? { harness: options.harness } : {},
428
- ...options.model ? { model: options.model } : {}
429
- });
430
- if (ctx.detachedSessionRef !== void 0 && ctx.updateDetachedSessionRef) {
431
- const { sessionId } = parseDetachedSessionRef(ctx.detachedSessionRef);
432
- const rebind = ctx.updateDetachedSessionRef;
433
- const turn = await runDetachedTurn({
434
- client: sandboxClient,
435
- spec: agentRunSpec,
436
- prompt: agentRunSpec.taskToPrompt(task),
437
- sessionId,
438
- bindSandbox: (sandboxId) => rebind(formatDetachedSessionRef({ sandboxId, sessionId })),
439
- signal: ctx.signal,
440
- report: ctx.report,
441
- ...loopEmitter ? { traceEmitter: loopEmitter } : {},
442
- ...executor.placement === "fleet" ? { placement: "fleet" } : {},
443
- ...options.detachedTickIntervalMs !== void 0 ? { tickIntervalMs: options.detachedTickIntervalMs } : {},
444
- ...options.detachedWallCapMs !== void 0 ? { wallCapMs: options.detachedWallCapMs } : {}
445
- });
446
- const chosen3 = await settleDetachedCoderTurn(turn, {
447
- task,
448
- sessionId,
449
- signal: ctx.signal,
450
- ...options.harness ? { harness: options.harness } : {},
451
- ...options.model ? { model: options.model } : {},
452
- ...options.reviewer ? { reviewer: options.reviewer } : {}
453
- });
454
- ctx.report({ iteration: 1, phase: "completed" });
455
- return chosen3;
456
- }
457
- const result2 = await runLoop({
458
- driver: singleShotDriver,
459
- agentRun: agentRunSpec,
460
- output,
461
- validator,
462
- task,
463
- ctx: {
464
- sandboxClient,
465
- signal: ctx.signal,
466
- ...loopEmitter ? { traceEmitter: loopEmitter } : {}
467
- },
468
- maxIterations: 1,
469
- maxConcurrency
470
- });
471
- const chosen2 = await pickCoderWinner({
472
- iterations: result2.iterations,
473
- reviewer: options.reviewer,
474
- selection: options.winnerSelection ?? "highest-score",
475
- task,
476
- signal: ctx.signal
477
- });
478
- if (!chosen2) throw new Error(noWinnerMessage(options.reviewer));
479
- ctx.report({ iteration: 1, phase: "completed" });
480
- return chosen2;
481
- }
482
- const fanout = multiHarnessCoderFanout({
483
- ...fanoutHarnesses && fanoutHarnesses.length > 0 ? { harnesses: fanoutHarnesses.slice(0, variants) } : {},
484
- ...options.fanoutModels ? { models: options.fanoutModels.slice(0, variants) } : {}
485
- });
486
- const agentRuns = fanout.agentRuns.slice(0, variants);
487
- const result = await runLoop({
488
- driver: fanout.driver,
489
- agentRuns,
490
- output: fanout.output,
491
- validator: fanout.validator,
492
- task,
493
- ctx: {
494
- sandboxClient,
495
- signal: ctx.signal,
496
- ...loopEmitter ? { traceEmitter: loopEmitter } : {}
497
- },
498
- maxIterations: variants,
499
- maxConcurrency: Math.min(maxConcurrency, variants)
500
- });
501
- const chosen = await pickCoderWinner({
502
- iterations: result.iterations,
503
- reviewer: options.reviewer,
504
- selection: options.winnerSelection ?? "highest-score",
505
- task,
506
- signal: ctx.signal
507
- });
508
- if (!chosen) throw new Error(noWinnerMessage(options.reviewer));
509
- ctx.report({ iteration: agentRuns.length, phase: "completed" });
510
- return chosen;
511
- };
512
- }
513
- async function pickCoderWinner(args) {
514
- const valid = [];
515
- for (const iter of args.iterations) {
516
- if (iter.output === void 0 || iter.error || iter.verdict?.valid !== true) continue;
517
- valid.push({
518
- index: iter.index,
519
- output: iter.output,
520
- score: iter.verdict.score ?? 0,
521
- readiness: iter.verdict.score ?? 0
522
- });
523
- }
524
- if (valid.length === 0) return void 0;
525
- let eligible = valid;
526
- if (args.reviewer) {
527
- eligible = [];
528
- for (const c of valid) {
529
- const review = await args.reviewer(c.output, args.task, { signal: args.signal });
530
- if (review.approved) eligible.push({ ...c, readiness: review.readiness });
531
- }
532
- if (eligible.length === 0) return void 0;
533
- }
534
- return selectCoderCandidate(eligible, args.selection).output;
535
- }
536
- function selectCoderCandidate(candidates, selection) {
537
- const diffLines = (c) => c.output.diffStats.insertions + c.output.diffStats.deletions;
538
- const sorted = [...candidates].sort((a, b) => {
539
- switch (selection) {
540
- case "smallest-diff":
541
- return diffLines(a) - diffLines(b) || a.index - b.index;
542
- case "highest-readiness":
543
- return b.readiness - a.readiness || a.index - b.index;
544
- case "first-approved":
545
- return a.index - b.index;
546
- default:
547
- return b.score - a.score || a.index - b.index;
548
- }
549
- });
550
- return sorted[0];
551
- }
552
- function noWinnerMessage(reviewer) {
553
- return reviewer ? "coder delegate: no candidate passed validation + review" : "coder delegate: no candidate passed validation";
554
- }
555
- function coderTaskFromArgs(args) {
556
- return {
557
- goal: buildCoderGoal(args),
558
- repoRoot: args.repoRoot,
559
- testCmd: args.config?.testCmd,
560
- typecheckCmd: args.config?.typecheckCmd,
561
- forbiddenPaths: args.config?.forbiddenPaths,
562
- maxDiffLines: args.config?.maxDiffLines
563
- };
564
- }
565
- async function settleDetachedCoderTurn(turn, options) {
566
- const { output, validator } = coderProfile({
567
- task: options.task,
568
- ...options.harness ? { harness: options.harness } : {},
569
- ...options.model ? { model: options.model } : {}
570
- });
571
- const parsed = output.parse(detachedTurnEvents(options.sessionId, turn));
572
- const verdict = await validator.validate(parsed, { iteration: 0, signal: options.signal });
573
- if (verdict.valid !== true) throw new Error(noWinnerMessage(options.reviewer));
574
- if (options.reviewer) {
575
- const review = await options.reviewer(parsed, options.task, { signal: options.signal });
576
- if (!review.approved) throw new Error(noWinnerMessage(options.reviewer));
577
- }
578
- return parsed;
579
- }
580
- function buildCoderGoal(args) {
581
- if (!args.contextHint) return args.goal;
582
- return [args.goal, "", "## Context", args.contextHint].join("\n");
583
- }
584
- function resolveExecutor(options) {
585
- if (options.executor && options.sandboxClient) {
586
- throw new Error("createDefaultCoderDelegate: pass exactly one of `executor` or `sandboxClient`");
587
- }
588
- if (options.executor) return options.executor;
589
- if (options.sandboxClient) {
590
- return createSiblingSandboxExecutor({ client: options.sandboxClient });
591
- }
592
- throw new Error("createDefaultCoderDelegate: `executor` or `sandboxClient` is required");
593
- }
594
- var singleShotDriver = {
595
- name: "mcp-single-shot",
596
- async plan(task, history) {
597
- return history.length === 0 ? [task] : [];
598
- },
599
- decide(history) {
600
- return history.length > 0 ? "pick-winner" : "fail";
601
- }
602
- };
603
-
604
- export {
605
- DELEGATION_TRACE_MAX_SPANS,
606
- DELEGATION_TRACE_MAX_BYTES,
607
- buildDelegationTraceSpans,
608
- capDelegationTrace,
609
- createDelegationTraceCollector,
610
- generateDelegationSpanId,
611
- composeLoopTraceEmitters,
612
- formatDetachedSessionRef,
613
- parseDetachedSessionRef,
614
- detachedTurnEvents,
615
- runDetachedTurn,
616
- createDriveTurnResumeDriver,
617
- createSiblingSandboxExecutor,
618
- createFleetWorkspaceExecutor,
619
- createDefaultCoderDelegate,
620
- coderTaskFromArgs,
621
- settleDetachedCoderTurn
622
- };
623
- //# sourceMappingURL=chunk-AYRQZRDV.js.map