@tangle-network/agent-runtime 0.59.0 → 0.61.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/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -2
- package/dist/agent.js.map +1 -1
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/{chunk-IN7WHMGZ.js → chunk-5V343QPB.js} +47 -7
- package/dist/chunk-5V343QPB.js.map +1 -0
- package/dist/chunk-7IXF3VUJ.js +59 -0
- package/dist/chunk-7IXF3VUJ.js.map +1 -0
- package/dist/{chunk-ZWGEA722.js → chunk-AU5MCNHO.js} +2 -2
- package/dist/chunk-IBRJTG7O.js +475 -0
- package/dist/chunk-IBRJTG7O.js.map +1 -0
- package/dist/{chunk-MMDIORZY.js → chunk-Q5R33I7Y.js} +4 -23
- package/dist/chunk-Q5R33I7Y.js.map +1 -0
- package/dist/{chunk-45D64J7B.js → chunk-VCOT7XEQ.js} +190 -99
- package/dist/chunk-VCOT7XEQ.js.map +1 -0
- package/dist/coder-DD5J5Onk.d.ts +52 -0
- package/dist/coordination-k29badiX.d.ts +381 -0
- package/dist/{delegates-C94qchkz.d.ts → delegates-CWMv_rKL.d.ts} +649 -21
- package/dist/index.d.ts +9 -6
- package/dist/index.js +9 -9
- package/dist/intelligence.d.ts +1 -1
- package/dist/{loop-runner-bin-Noz7P-mS.d.ts → loop-runner-bin-Bqt0hiNY.d.ts} +46 -12
- package/dist/loop-runner-bin.d.ts +7 -4
- package/dist/loop-runner-bin.js +4 -4
- package/dist/loops.d.ts +7 -6
- package/dist/loops.js +17 -6
- package/dist/mcp/bin.js +10 -10
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +12 -12
- package/dist/mcp/index.js +7 -7
- package/dist/{openai-tools-d4GKwgya.d.ts → openai-tools-CA2N3-Ak.d.ts} +1 -1
- package/dist/profiles.d.ts +7 -9
- package/dist/profiles.js +5 -7
- package/dist/profiles.js.map +1 -1
- package/dist/{run-loop-CcqfR_gy.d.ts → run-loop-D3PwlG7J.d.ts} +1 -1
- package/dist/runtime.d.ts +30 -1046
- package/dist/runtime.js +17 -6
- package/dist/{types-CUzjRFZ3.d.ts → types-Crxftafi.d.ts} +2 -2
- package/dist/workflow.d.ts +2 -2
- package/dist/workflow.js +1 -2
- package/dist/workflow.js.map +1 -1
- package/dist/worktree-fanout-CBULEoVe.d.ts +1098 -0
- package/package.json +2 -2
- package/dist/chunk-45D64J7B.js.map +0 -1
- package/dist/chunk-4FEUFYOY.js +0 -282
- package/dist/chunk-4FEUFYOY.js.map +0 -1
- package/dist/chunk-7QYOXFCD.js +0 -293
- package/dist/chunk-7QYOXFCD.js.map +0 -1
- package/dist/chunk-IN7WHMGZ.js.map +0 -1
- package/dist/chunk-MMDIORZY.js.map +0 -1
- package/dist/coder-CybltHEm.d.ts +0 -163
- package/dist/coordination-Biw19JzN.d.ts +0 -944
- /package/dist/{chunk-ZWGEA722.js.map → chunk-AU5MCNHO.js.map} +0 -0
package/dist/chunk-4FEUFYOY.js
DELETED
|
@@ -1,282 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
composeLoopTraceEmitters,
|
|
3
|
-
detachedTurnEvents,
|
|
4
|
-
formatDetachedSessionRef,
|
|
5
|
-
parseDetachedSessionRef,
|
|
6
|
-
runDetachedTurn,
|
|
7
|
-
runLoop
|
|
8
|
-
} from "./chunk-45D64J7B.js";
|
|
9
|
-
import {
|
|
10
|
-
coderProfile,
|
|
11
|
-
multiHarnessCoderFanout
|
|
12
|
-
} from "./chunk-7QYOXFCD.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
|
-
...options.systemPrompt ? { systemPrompt: options.systemPrompt } : {}
|
|
100
|
-
});
|
|
101
|
-
if (ctx.detachedSessionRef !== void 0 && ctx.updateDetachedSessionRef) {
|
|
102
|
-
const { sessionId } = parseDetachedSessionRef(ctx.detachedSessionRef);
|
|
103
|
-
const rebind = ctx.updateDetachedSessionRef;
|
|
104
|
-
const turn = await runDetachedTurn({
|
|
105
|
-
client: sandboxClient,
|
|
106
|
-
spec: agentRunSpec,
|
|
107
|
-
prompt: agentRunSpec.taskToPrompt(task),
|
|
108
|
-
sessionId,
|
|
109
|
-
bindSandbox: (sandboxId) => rebind(formatDetachedSessionRef({ sandboxId, sessionId })),
|
|
110
|
-
signal: ctx.signal,
|
|
111
|
-
report: ctx.report,
|
|
112
|
-
...loopEmitter ? { traceEmitter: loopEmitter } : {},
|
|
113
|
-
...executor.placement === "fleet" ? { placement: "fleet" } : {},
|
|
114
|
-
...options.detachedTickIntervalMs !== void 0 ? { tickIntervalMs: options.detachedTickIntervalMs } : {},
|
|
115
|
-
...options.detachedWallCapMs !== void 0 ? { wallCapMs: options.detachedWallCapMs } : {}
|
|
116
|
-
});
|
|
117
|
-
const chosen3 = await settleDetachedCoderTurn(turn, {
|
|
118
|
-
task,
|
|
119
|
-
sessionId,
|
|
120
|
-
signal: ctx.signal,
|
|
121
|
-
...options.harness ? { harness: options.harness } : {},
|
|
122
|
-
...options.model ? { model: options.model } : {},
|
|
123
|
-
...options.reviewer ? { reviewer: options.reviewer } : {}
|
|
124
|
-
});
|
|
125
|
-
ctx.report({ iteration: 1, phase: "completed" });
|
|
126
|
-
return chosen3;
|
|
127
|
-
}
|
|
128
|
-
const result2 = await runLoop({
|
|
129
|
-
driver: singleShotDriver,
|
|
130
|
-
agentRun: agentRunSpec,
|
|
131
|
-
output,
|
|
132
|
-
validator,
|
|
133
|
-
task,
|
|
134
|
-
ctx: {
|
|
135
|
-
sandboxClient,
|
|
136
|
-
signal: ctx.signal,
|
|
137
|
-
...loopEmitter ? { traceEmitter: loopEmitter } : {}
|
|
138
|
-
},
|
|
139
|
-
maxIterations: 1,
|
|
140
|
-
maxConcurrency
|
|
141
|
-
});
|
|
142
|
-
const chosen2 = await pickCoderWinner({
|
|
143
|
-
iterations: result2.iterations,
|
|
144
|
-
reviewer: options.reviewer,
|
|
145
|
-
selection: options.winnerSelection ?? "highest-score",
|
|
146
|
-
task,
|
|
147
|
-
signal: ctx.signal
|
|
148
|
-
});
|
|
149
|
-
if (!chosen2) throw new Error(noWinnerMessage(options.reviewer));
|
|
150
|
-
ctx.report({ iteration: 1, phase: "completed" });
|
|
151
|
-
return chosen2;
|
|
152
|
-
}
|
|
153
|
-
const fanout = multiHarnessCoderFanout({
|
|
154
|
-
...fanoutHarnesses && fanoutHarnesses.length > 0 ? { harnesses: fanoutHarnesses.slice(0, variants) } : {},
|
|
155
|
-
...options.fanoutModels ? { models: options.fanoutModels.slice(0, variants) } : {}
|
|
156
|
-
});
|
|
157
|
-
const agentRuns = fanout.agentRuns.slice(0, variants);
|
|
158
|
-
const result = await runLoop({
|
|
159
|
-
driver: fanout.driver,
|
|
160
|
-
agentRuns,
|
|
161
|
-
output: fanout.output,
|
|
162
|
-
validator: fanout.validator,
|
|
163
|
-
task,
|
|
164
|
-
ctx: {
|
|
165
|
-
sandboxClient,
|
|
166
|
-
signal: ctx.signal,
|
|
167
|
-
...loopEmitter ? { traceEmitter: loopEmitter } : {}
|
|
168
|
-
},
|
|
169
|
-
maxIterations: variants,
|
|
170
|
-
maxConcurrency: Math.min(maxConcurrency, variants)
|
|
171
|
-
});
|
|
172
|
-
const chosen = await pickCoderWinner({
|
|
173
|
-
iterations: result.iterations,
|
|
174
|
-
reviewer: options.reviewer,
|
|
175
|
-
selection: options.winnerSelection ?? "highest-score",
|
|
176
|
-
task,
|
|
177
|
-
signal: ctx.signal
|
|
178
|
-
});
|
|
179
|
-
if (!chosen) throw new Error(noWinnerMessage(options.reviewer));
|
|
180
|
-
ctx.report({ iteration: agentRuns.length, phase: "completed" });
|
|
181
|
-
return chosen;
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
async function pickCoderWinner(args) {
|
|
185
|
-
const valid = [];
|
|
186
|
-
for (const iter of args.iterations) {
|
|
187
|
-
if (iter.output === void 0 || iter.error || iter.verdict?.valid !== true) continue;
|
|
188
|
-
valid.push({
|
|
189
|
-
index: iter.index,
|
|
190
|
-
output: iter.output,
|
|
191
|
-
score: iter.verdict.score ?? 0,
|
|
192
|
-
readiness: iter.verdict.score ?? 0
|
|
193
|
-
});
|
|
194
|
-
}
|
|
195
|
-
if (valid.length === 0) return void 0;
|
|
196
|
-
let eligible = valid;
|
|
197
|
-
if (args.reviewer) {
|
|
198
|
-
eligible = [];
|
|
199
|
-
for (const c of valid) {
|
|
200
|
-
const review = await args.reviewer(c.output, args.task, { signal: args.signal });
|
|
201
|
-
if (review.approved) eligible.push({ ...c, readiness: review.readiness });
|
|
202
|
-
}
|
|
203
|
-
if (eligible.length === 0) return void 0;
|
|
204
|
-
}
|
|
205
|
-
return selectCoderCandidate(eligible, args.selection).output;
|
|
206
|
-
}
|
|
207
|
-
function selectCoderCandidate(candidates, selection) {
|
|
208
|
-
const diffLines = (c) => c.output.diffStats.insertions + c.output.diffStats.deletions;
|
|
209
|
-
const sorted = [...candidates].sort((a, b) => {
|
|
210
|
-
switch (selection) {
|
|
211
|
-
case "smallest-diff":
|
|
212
|
-
return diffLines(a) - diffLines(b) || a.index - b.index;
|
|
213
|
-
case "highest-readiness":
|
|
214
|
-
return b.readiness - a.readiness || a.index - b.index;
|
|
215
|
-
case "first-approved":
|
|
216
|
-
return a.index - b.index;
|
|
217
|
-
default:
|
|
218
|
-
return b.score - a.score || a.index - b.index;
|
|
219
|
-
}
|
|
220
|
-
});
|
|
221
|
-
return sorted[0];
|
|
222
|
-
}
|
|
223
|
-
function noWinnerMessage(reviewer) {
|
|
224
|
-
return reviewer ? "coder delegate: no candidate passed validation + review" : "coder delegate: no candidate passed validation";
|
|
225
|
-
}
|
|
226
|
-
function coderTaskFromArgs(args) {
|
|
227
|
-
return {
|
|
228
|
-
goal: buildCoderGoal(args),
|
|
229
|
-
repoRoot: args.repoRoot,
|
|
230
|
-
testCmd: args.config?.testCmd,
|
|
231
|
-
typecheckCmd: args.config?.typecheckCmd,
|
|
232
|
-
forbiddenPaths: args.config?.forbiddenPaths,
|
|
233
|
-
maxDiffLines: args.config?.maxDiffLines
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
async function settleDetachedCoderTurn(turn, options) {
|
|
237
|
-
const { output, validator } = coderProfile({
|
|
238
|
-
task: options.task,
|
|
239
|
-
...options.harness ? { harness: options.harness } : {},
|
|
240
|
-
...options.model ? { model: options.model } : {}
|
|
241
|
-
});
|
|
242
|
-
const parsed = output.parse(detachedTurnEvents(options.sessionId, turn));
|
|
243
|
-
const verdict = await validator.validate(parsed, { iteration: 0, signal: options.signal });
|
|
244
|
-
if (verdict.valid !== true) throw new Error(noWinnerMessage(options.reviewer));
|
|
245
|
-
if (options.reviewer) {
|
|
246
|
-
const review = await options.reviewer(parsed, options.task, { signal: options.signal });
|
|
247
|
-
if (!review.approved) throw new Error(noWinnerMessage(options.reviewer));
|
|
248
|
-
}
|
|
249
|
-
return parsed;
|
|
250
|
-
}
|
|
251
|
-
function buildCoderGoal(args) {
|
|
252
|
-
if (!args.contextHint) return args.goal;
|
|
253
|
-
return [args.goal, "", "## Context", args.contextHint].join("\n");
|
|
254
|
-
}
|
|
255
|
-
function resolveExecutor(options) {
|
|
256
|
-
if (options.executor && options.sandboxClient) {
|
|
257
|
-
throw new Error("createDefaultCoderDelegate: pass exactly one of `executor` or `sandboxClient`");
|
|
258
|
-
}
|
|
259
|
-
if (options.executor) return options.executor;
|
|
260
|
-
if (options.sandboxClient) {
|
|
261
|
-
return createSiblingSandboxExecutor({ client: options.sandboxClient });
|
|
262
|
-
}
|
|
263
|
-
throw new Error("createDefaultCoderDelegate: `executor` or `sandboxClient` is required");
|
|
264
|
-
}
|
|
265
|
-
var singleShotDriver = {
|
|
266
|
-
name: "mcp-single-shot",
|
|
267
|
-
async plan(task, history) {
|
|
268
|
-
return history.length === 0 ? [task] : [];
|
|
269
|
-
},
|
|
270
|
-
decide(history) {
|
|
271
|
-
return history.length > 0 ? "pick-winner" : "fail";
|
|
272
|
-
}
|
|
273
|
-
};
|
|
274
|
-
|
|
275
|
-
export {
|
|
276
|
-
createSiblingSandboxExecutor,
|
|
277
|
-
createFleetWorkspaceExecutor,
|
|
278
|
-
createDefaultCoderDelegate,
|
|
279
|
-
coderTaskFromArgs,
|
|
280
|
-
settleDetachedCoderTurn
|
|
281
|
-
};
|
|
282
|
-
//# sourceMappingURL=chunk-4FEUFYOY.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/executor.ts","../src/mcp/delegates.ts"],"sourcesContent":["/**\n * @experimental\n *\n * Delegation executors — the layer between MCP delegates and the sandbox\n * substrate. Each executor exposes a {@link 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 /**\n * The worker's authored system prompt (§1.5). Flows onto `coderProfile`'s\n * `profile.prompt.systemPrompt` → through `runLoop` → the executor's `harnessInvocation`, so the\n * harness runs under this stance, not just the default coder prompt. Omit to keep the default.\n */\n systemPrompt?: 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 * This is the SANDBOX-SESSION coder path: workers run the in-box harness via the\n * `SandboxClient`'s `streamPrompt`, and single-variant turns can dispatch DETACHED\n * (driveTurn ticks) so a durable queue resumes them across an MCP restart — a substrate\n * the recursive worktree-CLI leaf does not yet have a journal-replay equivalent for.\n *\n * For NEW local-repo coding, `worktreeCoderFanout` is a generic alternative (author an\n * `AgentProfile` per harness → `createWorktreeCliExecutor` leaves → `gateOnDeliverable`). This\n * factory remains first-class: it owns the sandbox-session + detached-resume substrate that the\n * worktree-CLI leaf does not yet replicate.\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 ...(options.systemPrompt ? { systemPrompt: options.systemPrompt } : {}),\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 * SCOPE NOTE (detached/resume): the detached `driveTurn`-tick + cross-restart resume path is\n * bound to the `runLoop` + sandbox-session substrate. The recursive `Scope`/worktree-CLI leaf has\n * journal→replay but no driveTurn-over-a-detached-sandbox-session equivalent yet, so resume is NOT\n * advertised on the generic `worktreeCoderFanout` path. This helper (with `coderTaskFromArgs` and\n * `createDriveTurnResumeDriver`) stays as the resume seam `bin.ts` wires for in-flight records.\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;A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uEAAuE;AACzF;AAQA,IAAM,mBAAmB;AAAA,EACvB,MAAM;AAAA,EACN,MAAM,KAAW,MAAY,SAAkD;AAC7E,WAAO,QAAQ,WAAW,IAAI,CAAC,IAAI,IAAI,CAAC;AAAA,EAC1C;AAAA,EACA,OAAO,SAAyD;AAC9D,WAAO,QAAQ,SAAS,IAAI,gBAAgB;AAAA,EAC9C;AACF;","names":["chosen","result"]}
|
package/dist/chunk-7QYOXFCD.js
DELETED
|
@@ -1,293 +0,0 @@
|
|
|
1
|
-
// src/profiles/coder.ts
|
|
2
|
-
var DEFAULT_MAX_DIFF_LINES = 400;
|
|
3
|
-
function coderProfile(options = {}) {
|
|
4
|
-
const harness = options.harness ?? "claude-code";
|
|
5
|
-
const name = options.name ?? `coder-${harness}`;
|
|
6
|
-
const systemPrompt = options.systemPrompt ?? DEFAULT_CODER_SYSTEM_PROMPT;
|
|
7
|
-
const profile = {
|
|
8
|
-
name,
|
|
9
|
-
description: "Code-modification agent. Minimal-diff worktree-based coder.",
|
|
10
|
-
prompt: { systemPrompt },
|
|
11
|
-
model: options.model ? { default: options.model } : void 0,
|
|
12
|
-
tools: { git: true, fs: true, shell: true, test_runner: true },
|
|
13
|
-
metadata: { backendType: harness, role: "coder" }
|
|
14
|
-
};
|
|
15
|
-
const output = { parse: parseCoderEvents };
|
|
16
|
-
const validator = options.task ? createCoderValidator(options.task) : createCoderValidator({
|
|
17
|
-
goal: "",
|
|
18
|
-
repoRoot: "",
|
|
19
|
-
forbiddenPaths: [],
|
|
20
|
-
maxDiffLines: DEFAULT_MAX_DIFF_LINES
|
|
21
|
-
});
|
|
22
|
-
const agentRunSpec = {
|
|
23
|
-
name,
|
|
24
|
-
profile,
|
|
25
|
-
taskToPrompt: formatCoderPrompt
|
|
26
|
-
};
|
|
27
|
-
return { profile, taskToPrompt: formatCoderPrompt, output, validator, agentRunSpec };
|
|
28
|
-
}
|
|
29
|
-
function multiHarnessCoderFanout(options = {}) {
|
|
30
|
-
const harnesses = options.harnesses && options.harnesses.length > 0 ? options.harnesses : ["claude-code", "codex", "opencode/zai-coding-plan/glm-5.1"];
|
|
31
|
-
const models = options.models ?? [];
|
|
32
|
-
const agentRuns = harnesses.map((harness, i) => {
|
|
33
|
-
const { agentRunSpec } = coderProfile({ harness, model: models[i] });
|
|
34
|
-
return agentRunSpec;
|
|
35
|
-
});
|
|
36
|
-
const { output, validator } = coderProfile();
|
|
37
|
-
const driver = {
|
|
38
|
-
name: "fanout",
|
|
39
|
-
plan: async (task, history) => history.length === 0 ? agentRuns.map(() => task) : [],
|
|
40
|
-
decide: (history) => history.some((i) => i.verdict?.valid === true) ? "pick-winner" : "fail"
|
|
41
|
-
};
|
|
42
|
-
return { agentRuns, output, validator, driver };
|
|
43
|
-
}
|
|
44
|
-
var DEFAULT_CODER_SYSTEM_PROMPT = [
|
|
45
|
-
"You are a coder agent operating inside an isolated sandbox workspace.",
|
|
46
|
-
"Your job is to deliver a minimal, correct patch for the user-supplied goal.",
|
|
47
|
-
"",
|
|
48
|
-
"Hard rules:",
|
|
49
|
-
" 1. Work on a fresh branch off the supplied base. Do not mutate the base branch.",
|
|
50
|
-
" 2. Never touch a forbidden path. The user will list them explicitly.",
|
|
51
|
-
" 3. Keep the diff under the max-diff cap. Prefer the smallest change that ships.",
|
|
52
|
-
" 4. Run the supplied test and typecheck commands before declaring done.",
|
|
53
|
-
" 5. If either command fails, fix the cause \u2014 do not weaken the test or hide the error.",
|
|
54
|
-
"",
|
|
55
|
-
"When you finish, emit a single final structured message of the shape:",
|
|
56
|
-
" ```json",
|
|
57
|
-
' { "branch": "<branch-name>",',
|
|
58
|
-
' "patch": "<unified-diff>",',
|
|
59
|
-
' "testResult": { "passed": <bool>, "output": "<stdout/stderr>" },',
|
|
60
|
-
' "typecheckResult": { "passed": <bool>, "output": "<stdout/stderr>" },',
|
|
61
|
-
' "diffStats": { "filesChanged": <int>, "insertions": <int>, "deletions": <int> },',
|
|
62
|
-
' "reviewerNotes": "<optional commentary>" }',
|
|
63
|
-
" ```"
|
|
64
|
-
].join("\n");
|
|
65
|
-
function formatCoderPrompt(task) {
|
|
66
|
-
const base = task.baseBranch ?? "main";
|
|
67
|
-
const testCmd = task.testCmd ?? "pnpm test --run";
|
|
68
|
-
const typecheckCmd = task.typecheckCmd ?? "pnpm typecheck";
|
|
69
|
-
const maxDiff = task.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES;
|
|
70
|
-
const forbidden = task.forbiddenPaths?.length ? task.forbiddenPaths.join(", ") : "(none)";
|
|
71
|
-
const context = task.contextFiles?.length ? task.contextFiles.map((f) => ` - ${f}`).join("\n") : " (none)";
|
|
72
|
-
return [
|
|
73
|
-
`Goal: ${task.goal}`,
|
|
74
|
-
`Repo: ${task.repoRoot}`,
|
|
75
|
-
`Base branch: ${base}`,
|
|
76
|
-
`Run tests with: ${testCmd}`,
|
|
77
|
-
`Run typecheck with: ${typecheckCmd}`,
|
|
78
|
-
`Forbidden paths: ${forbidden}`,
|
|
79
|
-
`Max diff lines: ${maxDiff}`,
|
|
80
|
-
"Context files:",
|
|
81
|
-
context,
|
|
82
|
-
"",
|
|
83
|
-
"Produce a minimal patch on a fresh branch. Run tests and typecheck before",
|
|
84
|
-
"returning. Emit the final JSON result block exactly as instructed."
|
|
85
|
-
].join("\n");
|
|
86
|
-
}
|
|
87
|
-
function parseCoderEvents(events) {
|
|
88
|
-
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
89
|
-
const event = events[i];
|
|
90
|
-
if (!event) continue;
|
|
91
|
-
const type = String(event.type ?? "");
|
|
92
|
-
const data = isRecord(event.data) ? event.data : {};
|
|
93
|
-
if (type === "result" || type === "final" || type === "coder.result") {
|
|
94
|
-
const direct = coerceCoderOutput(data.result ?? data.output ?? data);
|
|
95
|
-
if (direct) return direct;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
const transcript = collectAssistantText(events);
|
|
99
|
-
for (const candidate of fencedJsonBlocks(transcript)) {
|
|
100
|
-
const coerced = coerceCoderOutput(candidate);
|
|
101
|
-
if (coerced) return coerced;
|
|
102
|
-
}
|
|
103
|
-
return {
|
|
104
|
-
branch: "",
|
|
105
|
-
patch: "",
|
|
106
|
-
testResult: { passed: false, output: "" },
|
|
107
|
-
typecheckResult: { passed: false, output: "" },
|
|
108
|
-
diffStats: { filesChanged: 0, insertions: 0, deletions: 0 }
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
var SECRET_PATH_RE = /(^|\/)(\.env(\.|$)|.*\.(pem|key|p12|pfx|keystore|wallet)|id_rsa|id_ed25519|secrets?\.json|credentials?\.json)$/i;
|
|
112
|
-
function runCoderChecks(input, constraints = {}) {
|
|
113
|
-
const maxDiff = constraints.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES;
|
|
114
|
-
const forbidden = constraints.forbiddenPaths ?? [];
|
|
115
|
-
const scores = {};
|
|
116
|
-
const notes = [];
|
|
117
|
-
let pass = true;
|
|
118
|
-
const touched = touchedPathsFromPatch(input.patch);
|
|
119
|
-
if (touched.length === 0 || input.patch.trim().length === 0) {
|
|
120
|
-
pass = false;
|
|
121
|
-
scores.nonEmpty = 0;
|
|
122
|
-
notes.push("empty patch \u2014 no files changed");
|
|
123
|
-
} else {
|
|
124
|
-
scores.nonEmpty = 1;
|
|
125
|
-
}
|
|
126
|
-
const touchedSecrets = touched.filter((p) => SECRET_PATH_RE.test(p));
|
|
127
|
-
if (touchedSecrets.length > 0) {
|
|
128
|
-
pass = false;
|
|
129
|
-
scores.noSecrets = 0;
|
|
130
|
-
notes.push(`touched secret-shaped paths: ${touchedSecrets.join(", ")}`);
|
|
131
|
-
} else {
|
|
132
|
-
scores.noSecrets = 1;
|
|
133
|
-
}
|
|
134
|
-
const touchedForbidden = forbidden.filter((path) => {
|
|
135
|
-
const prefix = path.endsWith("/") ? path : `${path}/`;
|
|
136
|
-
const exact = prefix.slice(0, -1);
|
|
137
|
-
return touched.some((p) => p === exact || p.startsWith(prefix));
|
|
138
|
-
});
|
|
139
|
-
if (touchedForbidden.length > 0) {
|
|
140
|
-
pass = false;
|
|
141
|
-
scores.forbiddenPath = 0;
|
|
142
|
-
notes.push(`touched forbidden paths: ${touchedForbidden.join(", ")}`);
|
|
143
|
-
} else {
|
|
144
|
-
scores.forbiddenPath = 1;
|
|
145
|
-
}
|
|
146
|
-
const diffLines = countDiffLines(input.patch);
|
|
147
|
-
if (diffLines > maxDiff) {
|
|
148
|
-
pass = false;
|
|
149
|
-
scores.diffSize = 0;
|
|
150
|
-
notes.push(`diff ${diffLines} lines exceeds cap ${maxDiff}`);
|
|
151
|
-
} else {
|
|
152
|
-
scores.diffSize = maxDiff === 0 ? 0 : Math.max(0, 1 - diffLines / maxDiff);
|
|
153
|
-
}
|
|
154
|
-
scores.tests = input.testsPassed ? 1 : 0;
|
|
155
|
-
scores.typecheck = input.typecheckPassed ? 1 : 0;
|
|
156
|
-
if (!input.testsPassed) {
|
|
157
|
-
pass = false;
|
|
158
|
-
notes.push("tests failed");
|
|
159
|
-
}
|
|
160
|
-
if (!input.typecheckPassed) {
|
|
161
|
-
pass = false;
|
|
162
|
-
notes.push("typecheck failed");
|
|
163
|
-
}
|
|
164
|
-
const score = 0.5 * scores.tests + 0.3 * scores.typecheck + 0.2 * scores.diffSize;
|
|
165
|
-
const verdict = {
|
|
166
|
-
valid: pass,
|
|
167
|
-
score: Number.isFinite(score) ? score : 0,
|
|
168
|
-
scores
|
|
169
|
-
};
|
|
170
|
-
if (notes.length > 0) verdict.notes = notes.join("; ");
|
|
171
|
-
return verdict;
|
|
172
|
-
}
|
|
173
|
-
function createCoderValidator(task) {
|
|
174
|
-
const constraints = {
|
|
175
|
-
maxDiffLines: task.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES,
|
|
176
|
-
forbiddenPaths: task.forbiddenPaths ?? []
|
|
177
|
-
};
|
|
178
|
-
return {
|
|
179
|
-
async validate(output) {
|
|
180
|
-
return runCoderChecks(
|
|
181
|
-
{
|
|
182
|
-
patch: output.patch,
|
|
183
|
-
testsPassed: output.testResult.passed,
|
|
184
|
-
typecheckPassed: output.typecheckResult.passed
|
|
185
|
-
},
|
|
186
|
-
constraints
|
|
187
|
-
);
|
|
188
|
-
}
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
function touchedPathsFromPatch(patch) {
|
|
192
|
-
const out = /* @__PURE__ */ new Set();
|
|
193
|
-
for (const line of patch.split(/\r?\n/)) {
|
|
194
|
-
if (line.startsWith("+++ ") || line.startsWith("--- ")) {
|
|
195
|
-
const rest = line.slice(4).trim();
|
|
196
|
-
if (rest === "/dev/null") continue;
|
|
197
|
-
const stripped = rest.startsWith("a/") || rest.startsWith("b/") ? rest.slice(2) : rest;
|
|
198
|
-
out.add(stripped);
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
return [...out];
|
|
202
|
-
}
|
|
203
|
-
function countDiffLines(patch) {
|
|
204
|
-
let count = 0;
|
|
205
|
-
for (const line of patch.split(/\r?\n/)) {
|
|
206
|
-
if ((line.startsWith("+") || line.startsWith("-")) && !line.startsWith("+++") && !line.startsWith("---")) {
|
|
207
|
-
count += 1;
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
return count;
|
|
211
|
-
}
|
|
212
|
-
function isRecord(value) {
|
|
213
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
214
|
-
}
|
|
215
|
-
function pickString(value) {
|
|
216
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
217
|
-
}
|
|
218
|
-
function collectAssistantText(events) {
|
|
219
|
-
const chunks = [];
|
|
220
|
-
for (const event of events) {
|
|
221
|
-
if (!event) continue;
|
|
222
|
-
const data = isRecord(event.data) ? event.data : {};
|
|
223
|
-
if (String(event.type ?? "") === "message.part.updated") {
|
|
224
|
-
const part = isRecord(data.part) ? data.part : {};
|
|
225
|
-
const partType = String(part.type ?? "");
|
|
226
|
-
if (partType !== "text" && partType !== "") continue;
|
|
227
|
-
const text2 = pickString(data.delta) ?? pickString(part.text);
|
|
228
|
-
if (text2) chunks.push(text2);
|
|
229
|
-
continue;
|
|
230
|
-
}
|
|
231
|
-
const text = pickString(data.text) ?? pickString(data.delta);
|
|
232
|
-
if (text) chunks.push(text);
|
|
233
|
-
}
|
|
234
|
-
return chunks.join("");
|
|
235
|
-
}
|
|
236
|
-
function fencedJsonBlocks(text) {
|
|
237
|
-
const out = [];
|
|
238
|
-
const matches = [...text.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];
|
|
239
|
-
for (let i = matches.length - 1; i >= 0; i -= 1) {
|
|
240
|
-
const body = (matches[i]?.[1] ?? "").trim();
|
|
241
|
-
if (!body) continue;
|
|
242
|
-
try {
|
|
243
|
-
out.push(JSON.parse(body));
|
|
244
|
-
} catch {
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
return out;
|
|
248
|
-
}
|
|
249
|
-
function coerceCoderOutput(value) {
|
|
250
|
-
if (!isRecord(value)) return void 0;
|
|
251
|
-
const branch = pickString(value.branch);
|
|
252
|
-
const patch = pickString(value.patch) ?? "";
|
|
253
|
-
if (branch === void 0) return void 0;
|
|
254
|
-
const testResult = coerceCmdResult(value.testResult);
|
|
255
|
-
const typecheckResult = coerceCmdResult(value.typecheckResult);
|
|
256
|
-
const diffStats = coerceDiffStats(value.diffStats);
|
|
257
|
-
return {
|
|
258
|
-
branch,
|
|
259
|
-
patch,
|
|
260
|
-
testResult,
|
|
261
|
-
typecheckResult,
|
|
262
|
-
diffStats,
|
|
263
|
-
reviewerNotes: pickString(value.reviewerNotes)
|
|
264
|
-
};
|
|
265
|
-
}
|
|
266
|
-
function coerceCmdResult(value) {
|
|
267
|
-
if (!isRecord(value)) return { passed: false, output: "" };
|
|
268
|
-
return {
|
|
269
|
-
passed: value.passed === true,
|
|
270
|
-
output: pickString(value.output) ?? ""
|
|
271
|
-
};
|
|
272
|
-
}
|
|
273
|
-
function coerceDiffStats(value) {
|
|
274
|
-
if (!isRecord(value)) return { filesChanged: 0, insertions: 0, deletions: 0 };
|
|
275
|
-
return {
|
|
276
|
-
filesChanged: toFiniteInt(value.filesChanged),
|
|
277
|
-
insertions: toFiniteInt(value.insertions),
|
|
278
|
-
deletions: toFiniteInt(value.deletions)
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
function toFiniteInt(value) {
|
|
282
|
-
if (typeof value !== "number") return 0;
|
|
283
|
-
if (!Number.isFinite(value)) return 0;
|
|
284
|
-
return Math.max(0, Math.trunc(value));
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
export {
|
|
288
|
-
coderProfile,
|
|
289
|
-
multiHarnessCoderFanout,
|
|
290
|
-
runCoderChecks,
|
|
291
|
-
createCoderValidator
|
|
292
|
-
};
|
|
293
|
-
//# sourceMappingURL=chunk-7QYOXFCD.js.map
|