@tangle-network/agent-runtime 0.68.0 → 0.70.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -13
- package/dist/agent.d.ts +4 -5
- package/dist/agent.js +3 -6
- package/dist/agent.js.map +1 -1
- package/dist/chunk-BYZCXQHF.js +474 -0
- package/dist/chunk-BYZCXQHF.js.map +1 -0
- package/dist/{chunk-OYU5LR4T.js → chunk-EDCVUZZC.js} +2 -2
- package/dist/{chunk-QNUEFNU7.js → chunk-L5ZFBVT6.js} +6 -6
- package/dist/chunk-L5ZFBVT6.js.map +1 -0
- package/dist/{chunk-VKUHUFX7.js → chunk-QXWGSDAQ.js} +914 -590
- package/dist/chunk-QXWGSDAQ.js.map +1 -0
- package/dist/{chunk-LTEF2LYD.js → chunk-ZNQVMMR5.js} +3 -3
- package/dist/{coordination-Curpzeyc.d.ts → coordination-C7WxwHXq.d.ts} +8 -1
- package/dist/{delegates-CLFNAKyi.d.ts → delegates-DqAgo32T.d.ts} +105 -10
- package/dist/{improvement-adapter-BC4HhuAR.d.ts → improvement-adapter-BVuMragr.d.ts} +1 -1
- package/dist/index.d.ts +439 -100
- package/dist/index.js +583 -125
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +2 -3
- package/dist/{loop-runner-bin-B6dzNZC8.d.ts → loop-runner-bin-B0NeLTRd.d.ts} +4 -4
- package/dist/loop-runner-bin.d.ts +7 -10
- package/dist/loop-runner-bin.js +4 -7
- package/dist/loops.d.ts +3149 -16
- package/dist/loops.js +34 -63
- package/dist/mcp/bin.js +14 -16
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +8 -12
- package/dist/mcp/index.js +16 -19
- package/dist/mcp/index.js.map +1 -1
- package/dist/{openai-tools-CA2N3-Ak.d.ts → openai-tools-DPx9Gzvn.d.ts} +1 -1
- package/dist/profiles.d.ts +94 -6
- package/dist/profiles.js +320 -9
- package/dist/profiles.js.map +1 -1
- package/dist/{router-client-30Y_pca8.d.ts → router-client-C7kp_ECN.d.ts} +37 -1
- package/dist/{substrate-CUgk7F7s.d.ts → substrate-BoRXgvka.d.ts} +52 -1
- package/dist/{types-Crxftafi.d.ts → types-BYa2ZOAx.d.ts} +83 -2
- package/dist/{types-p8dWBIXL.d.ts → types-DJu6TBGp.d.ts} +2 -16
- package/dist/{worktree-fanout-DUiKPApb.d.ts → worktree-fanout-gNfl0Byj.d.ts} +9 -37
- package/package.json +9 -39
- package/dist/analyst-loop.d.ts +0 -52
- package/dist/analyst-loop.js +0 -11
- package/dist/analyst-loop.js.map +0 -1
- package/dist/audit.d.ts +0 -93
- package/dist/audit.js +0 -312
- package/dist/audit.js.map +0 -1
- package/dist/chunk-4B6U4CVQ.js +0 -15
- package/dist/chunk-4B6U4CVQ.js.map +0 -1
- package/dist/chunk-FCIPUALH.js +0 -214
- package/dist/chunk-FCIPUALH.js.map +0 -1
- package/dist/chunk-O2UPHN7X.js +0 -114
- package/dist/chunk-O2UPHN7X.js.map +0 -1
- package/dist/chunk-P5OKDSLB.js +0 -580
- package/dist/chunk-P5OKDSLB.js.map +0 -1
- package/dist/chunk-QNUEFNU7.js.map +0 -1
- package/dist/chunk-VKUHUFX7.js.map +0 -1
- package/dist/chunk-VLF5RHEQ.js +0 -143
- package/dist/chunk-VLF5RHEQ.js.map +0 -1
- package/dist/coder-2leJPOvC.d.ts +0 -52
- package/dist/improvement.d.ts +0 -208
- package/dist/improvement.js +0 -343
- package/dist/improvement.js.map +0 -1
- package/dist/local-harness-BE_h8szs.d.ts +0 -93
- package/dist/platform.d.ts +0 -255
- package/dist/platform.js +0 -229
- package/dist/platform.js.map +0 -1
- package/dist/run-loop-D3PwlG7J.d.ts +0 -112
- package/dist/runtime-hooks-C7JwKb9E.d.ts +0 -70
- package/dist/runtime.d.ts +0 -3108
- package/dist/runtime.js +0 -263
- package/dist/runtime.js.map +0 -1
- package/dist/topology.d.ts +0 -126
- package/dist/topology.js +0 -333
- package/dist/topology.js.map +0 -1
- package/dist/workflow.d.ts +0 -551
- package/dist/workflow.js +0 -1781
- package/dist/workflow.js.map +0 -1
- /package/dist/{chunk-OYU5LR4T.js.map → chunk-EDCVUZZC.js.map} +0 -0
- /package/dist/{chunk-LTEF2LYD.js.map → chunk-ZNQVMMR5.js.map} +0 -0
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createKbGate
|
|
3
|
+
} from "./chunk-FNMGYYSS.js";
|
|
4
|
+
import {
|
|
5
|
+
detachedSessionDelegate
|
|
6
|
+
} from "./chunk-L5ZFBVT6.js";
|
|
7
|
+
import {
|
|
8
|
+
ConfigError,
|
|
9
|
+
createExecutorRegistry,
|
|
10
|
+
definePersona,
|
|
11
|
+
runPersonified,
|
|
12
|
+
worktreeFanout
|
|
13
|
+
} from "./chunk-QXWGSDAQ.js";
|
|
14
|
+
|
|
15
|
+
// src/loop-runner.ts
|
|
16
|
+
import {
|
|
17
|
+
selfImprove
|
|
18
|
+
} from "@tangle-network/agent-eval/contract";
|
|
19
|
+
|
|
20
|
+
// src/analyst-loop/iterations-to-trace-store.ts
|
|
21
|
+
import {
|
|
22
|
+
DEFAULT_TRACE_ANALYST_BUDGETS,
|
|
23
|
+
TRACE_ANALYST_TRUNCATION_MARKER_PREFIX
|
|
24
|
+
} from "@tangle-network/agent-eval";
|
|
25
|
+
|
|
26
|
+
// src/analyst-loop/run-analyst-loop.ts
|
|
27
|
+
import { diffFindings } from "@tangle-network/agent-eval";
|
|
28
|
+
async function runAnalystLoop(opts) {
|
|
29
|
+
const log = opts.log ?? defaultLog;
|
|
30
|
+
const strategy = opts.priorFindingsStrategy ?? "per-kind";
|
|
31
|
+
const emit = makeEmitter(opts.onEvent);
|
|
32
|
+
const startedAt = Date.now();
|
|
33
|
+
const baselineRunId = resolveBaselineRunId(opts);
|
|
34
|
+
const priorAll = baselineRunId ? opts.findingsStore?.loadRun(baselineRunId) ?? [] : [];
|
|
35
|
+
log("baseline resolved", { baselineRunId, prior_findings: priorAll.length });
|
|
36
|
+
await emit({
|
|
37
|
+
type: "baseline-resolved",
|
|
38
|
+
runId: opts.runId,
|
|
39
|
+
baselineRunId,
|
|
40
|
+
priorFindingCount: priorAll.length
|
|
41
|
+
});
|
|
42
|
+
const priorFindings = buildPriorFindingsInput(priorAll, strategy, opts.registry.list());
|
|
43
|
+
const analystResult = await runRegistry(opts, priorFindings, emit);
|
|
44
|
+
log("analyst run complete", {
|
|
45
|
+
findings: analystResult.findings.length,
|
|
46
|
+
cost_usd: analystResult.total_cost_usd,
|
|
47
|
+
per_analyst: analystResult.per_analyst.map((s) => ({
|
|
48
|
+
id: s.analyst_id,
|
|
49
|
+
status: s.status,
|
|
50
|
+
n: s.findings_count
|
|
51
|
+
}))
|
|
52
|
+
});
|
|
53
|
+
if (opts.findingsStore && analystResult.findings.length > 0) {
|
|
54
|
+
await opts.findingsStore.append(opts.runId, analystResult.findings);
|
|
55
|
+
await emit({
|
|
56
|
+
type: "findings-persisted",
|
|
57
|
+
runId: opts.runId,
|
|
58
|
+
count: analystResult.findings.length
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
let diff = null;
|
|
62
|
+
if (baselineRunId && analystResult.findings.length > 0) {
|
|
63
|
+
diff = diffFindings(
|
|
64
|
+
priorAll.map((f) => ({ ...f })),
|
|
65
|
+
analystResult.findings.map((f) => ({ ...f, run_id: opts.runId }))
|
|
66
|
+
);
|
|
67
|
+
log("diff vs baseline", {
|
|
68
|
+
appeared: diff.appeared.length,
|
|
69
|
+
disappeared: diff.disappeared.length,
|
|
70
|
+
persisted: diff.persisted.length,
|
|
71
|
+
changed: diff.changed.length
|
|
72
|
+
});
|
|
73
|
+
await emit({
|
|
74
|
+
type: "diff-computed",
|
|
75
|
+
runId: opts.runId,
|
|
76
|
+
baselineRunId,
|
|
77
|
+
appeared: diff.appeared.length,
|
|
78
|
+
disappeared: diff.disappeared.length,
|
|
79
|
+
persisted: diff.persisted.length,
|
|
80
|
+
changed: diff.changed.length
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
let knowledge = null;
|
|
84
|
+
if (opts.knowledgeAdapter) {
|
|
85
|
+
knowledge = await runKnowledgeAdapter(opts, analystResult.findings, log, emit);
|
|
86
|
+
}
|
|
87
|
+
let improvement = null;
|
|
88
|
+
if (opts.improvementAdapter) {
|
|
89
|
+
improvement = await runImprovementAdapter(opts, analystResult.findings, log, emit);
|
|
90
|
+
}
|
|
91
|
+
await emit({
|
|
92
|
+
type: "loop-completed",
|
|
93
|
+
runId: opts.runId,
|
|
94
|
+
durationMs: Date.now() - startedAt
|
|
95
|
+
});
|
|
96
|
+
return {
|
|
97
|
+
runId: opts.runId,
|
|
98
|
+
baselineRunId,
|
|
99
|
+
analystResult,
|
|
100
|
+
diff,
|
|
101
|
+
knowledge,
|
|
102
|
+
improvement
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function makeEmitter(onEvent) {
|
|
106
|
+
if (!onEvent) return async () => {
|
|
107
|
+
};
|
|
108
|
+
return async (event) => {
|
|
109
|
+
await onEvent(event);
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
async function runRegistry(opts, priorFindings, emit) {
|
|
113
|
+
const reg = opts.registry;
|
|
114
|
+
if (typeof reg.runStream === "function" && opts.onEvent) {
|
|
115
|
+
let final = null;
|
|
116
|
+
for await (const ev of reg.runStream(opts.runId, opts.inputs, { priorFindings })) {
|
|
117
|
+
await emit({ type: "analyst", runId: opts.runId, event: ev });
|
|
118
|
+
if (ev.type === "run-completed") final = ev.result;
|
|
119
|
+
}
|
|
120
|
+
if (!final) {
|
|
121
|
+
throw new Error("runAnalystLoop: registry.runStream ended without run-completed event");
|
|
122
|
+
}
|
|
123
|
+
return final;
|
|
124
|
+
}
|
|
125
|
+
return opts.registry.run(opts.runId, opts.inputs, { priorFindings });
|
|
126
|
+
}
|
|
127
|
+
function resolveBaselineRunId(opts) {
|
|
128
|
+
if (opts.baselineRunId === null) return null;
|
|
129
|
+
if (typeof opts.baselineRunId === "string") return opts.baselineRunId;
|
|
130
|
+
if (!opts.findingsStore) return null;
|
|
131
|
+
const all = opts.findingsStore.loadAll();
|
|
132
|
+
let last = null;
|
|
133
|
+
for (const row of all) {
|
|
134
|
+
if (row.run_id === opts.runId) continue;
|
|
135
|
+
last = row.run_id;
|
|
136
|
+
}
|
|
137
|
+
return last;
|
|
138
|
+
}
|
|
139
|
+
function buildPriorFindingsInput(prior, strategy, registry) {
|
|
140
|
+
if (strategy === "none" || prior.length === 0) return void 0;
|
|
141
|
+
const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest);
|
|
142
|
+
if (strategy === "wildcard") {
|
|
143
|
+
return { "*": stripped };
|
|
144
|
+
}
|
|
145
|
+
void registry;
|
|
146
|
+
return stripped;
|
|
147
|
+
}
|
|
148
|
+
async function runKnowledgeAdapter(opts, findings, log, emit) {
|
|
149
|
+
const adapter = opts.knowledgeAdapter;
|
|
150
|
+
const batch = await adapter.proposeFromFindings(findings);
|
|
151
|
+
log("knowledge.proposeFromFindings", {
|
|
152
|
+
proposals: batch.proposals.length,
|
|
153
|
+
skipped: batch.skipped,
|
|
154
|
+
errors: batch.errors.length
|
|
155
|
+
});
|
|
156
|
+
await emit({
|
|
157
|
+
type: "knowledge-proposed",
|
|
158
|
+
runId: opts.runId,
|
|
159
|
+
proposalCount: batch.proposals.length,
|
|
160
|
+
skipped: batch.skipped,
|
|
161
|
+
errors: batch.errors.length
|
|
162
|
+
});
|
|
163
|
+
const auto = opts.autoApply?.knowledge ?? false;
|
|
164
|
+
const threshold = opts.autoApply?.knowledgeConfidenceThreshold ?? 0.85;
|
|
165
|
+
if (!auto || !adapter.apply) {
|
|
166
|
+
await emit({
|
|
167
|
+
type: "knowledge-applied",
|
|
168
|
+
runId: opts.runId,
|
|
169
|
+
writtenCount: 0,
|
|
170
|
+
withheldForReview: batch.proposals.length
|
|
171
|
+
});
|
|
172
|
+
return {
|
|
173
|
+
proposals: batch.proposals,
|
|
174
|
+
applied: [],
|
|
175
|
+
skipped: batch.skipped,
|
|
176
|
+
errors: batch.errors,
|
|
177
|
+
withheld_for_review: batch.proposals.length
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
const findingsById = new Map(findings.map((f) => [f.finding_id, f]));
|
|
181
|
+
const safe = [];
|
|
182
|
+
let withheld = 0;
|
|
183
|
+
for (const p of batch.proposals) {
|
|
184
|
+
const src = p.sourceFindingId ? findingsById.get(p.sourceFindingId) : void 0;
|
|
185
|
+
if (!src) {
|
|
186
|
+
withheld += 1;
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (src.confidence < threshold) {
|
|
190
|
+
withheld += 1;
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
safe.push(p);
|
|
194
|
+
}
|
|
195
|
+
const result = await adapter.apply(safe);
|
|
196
|
+
log("knowledge.apply", {
|
|
197
|
+
applied: result.written.length,
|
|
198
|
+
withheld_for_review: withheld,
|
|
199
|
+
warnings: result.warnings.length
|
|
200
|
+
});
|
|
201
|
+
await emit({
|
|
202
|
+
type: "knowledge-applied",
|
|
203
|
+
runId: opts.runId,
|
|
204
|
+
writtenCount: result.written.length,
|
|
205
|
+
withheldForReview: withheld
|
|
206
|
+
});
|
|
207
|
+
return {
|
|
208
|
+
proposals: batch.proposals,
|
|
209
|
+
applied: result.written,
|
|
210
|
+
skipped: batch.skipped,
|
|
211
|
+
errors: batch.errors,
|
|
212
|
+
withheld_for_review: withheld
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
async function runImprovementAdapter(opts, findings, log, emit) {
|
|
216
|
+
const adapter = opts.improvementAdapter;
|
|
217
|
+
const batch = await adapter.proposeFromFindings(findings);
|
|
218
|
+
log("improvement.proposeFromFindings", {
|
|
219
|
+
edits: batch.edits.length,
|
|
220
|
+
skipped: batch.skipped,
|
|
221
|
+
errors: batch.errors.length
|
|
222
|
+
});
|
|
223
|
+
await emit({
|
|
224
|
+
type: "improvement-proposed",
|
|
225
|
+
runId: opts.runId,
|
|
226
|
+
editCount: batch.edits.length,
|
|
227
|
+
skipped: batch.skipped,
|
|
228
|
+
errors: batch.errors.length
|
|
229
|
+
});
|
|
230
|
+
const auto = opts.autoApply?.improvement ?? false;
|
|
231
|
+
const threshold = opts.autoApply?.improvementConfidenceThreshold ?? 0.9;
|
|
232
|
+
if (!auto || !adapter.apply) {
|
|
233
|
+
await emit({
|
|
234
|
+
type: "improvement-applied",
|
|
235
|
+
runId: opts.runId,
|
|
236
|
+
appliedCount: 0,
|
|
237
|
+
withheldForReview: batch.edits.length
|
|
238
|
+
});
|
|
239
|
+
return {
|
|
240
|
+
edits: batch.edits,
|
|
241
|
+
applied: [],
|
|
242
|
+
skipped: batch.skipped,
|
|
243
|
+
errors: batch.errors,
|
|
244
|
+
withheld_for_review: batch.edits.length
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
const findingsById = new Map(findings.map((f) => [f.finding_id, f]));
|
|
248
|
+
const safe = [];
|
|
249
|
+
let withheld = 0;
|
|
250
|
+
for (const e of batch.edits) {
|
|
251
|
+
const src = e.sourceFindingId ? findingsById.get(e.sourceFindingId) : void 0;
|
|
252
|
+
if (!src || src.confidence < threshold) {
|
|
253
|
+
withheld += 1;
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
safe.push(e);
|
|
257
|
+
}
|
|
258
|
+
const result = await adapter.apply(safe);
|
|
259
|
+
log("improvement.apply", {
|
|
260
|
+
applied: result.applied.length,
|
|
261
|
+
withheld_for_review: withheld,
|
|
262
|
+
warnings: result.warnings.length
|
|
263
|
+
});
|
|
264
|
+
await emit({
|
|
265
|
+
type: "improvement-applied",
|
|
266
|
+
runId: opts.runId,
|
|
267
|
+
appliedCount: result.applied.length,
|
|
268
|
+
withheldForReview: withheld
|
|
269
|
+
});
|
|
270
|
+
return {
|
|
271
|
+
edits: batch.edits,
|
|
272
|
+
applied: result.applied,
|
|
273
|
+
skipped: batch.skipped,
|
|
274
|
+
errors: batch.errors,
|
|
275
|
+
withheld_for_review: withheld
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
function defaultLog(msg, fields) {
|
|
279
|
+
if (fields) console.log(`[analyst-loop] ${msg}`, fields);
|
|
280
|
+
else console.log(`[analyst-loop] ${msg}`);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// src/loop-runner.ts
|
|
284
|
+
var DELEGATED_LOOP_MODES = ["code", "review", "research", "audit", "self-improve"];
|
|
285
|
+
function isDelegatedLoopMode(value) {
|
|
286
|
+
return typeof value === "string" && DELEGATED_LOOP_MODES.includes(value);
|
|
287
|
+
}
|
|
288
|
+
async function runDelegatedLoop(mode, registry, options = {}) {
|
|
289
|
+
const runner = registry[mode];
|
|
290
|
+
if (!runner) {
|
|
291
|
+
throw new ConfigError(
|
|
292
|
+
`runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${Object.keys(registry).join(", ") || "none"})`
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
const now = options.now ?? Date.now;
|
|
296
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
297
|
+
const start = now();
|
|
298
|
+
try {
|
|
299
|
+
const output = await runner(signal);
|
|
300
|
+
return { mode, ok: true, output, durationMs: now() - start };
|
|
301
|
+
} catch (err) {
|
|
302
|
+
return {
|
|
303
|
+
mode,
|
|
304
|
+
ok: false,
|
|
305
|
+
error: err instanceof Error ? err.message : String(err),
|
|
306
|
+
durationMs: now() - start
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
function coderLoopRunner(options) {
|
|
311
|
+
const delegate = detachedSessionDelegate({
|
|
312
|
+
sandboxClient: options.sandboxClient,
|
|
313
|
+
...options.reviewer ? { reviewer: options.reviewer } : {},
|
|
314
|
+
...options.winnerSelection ? { winnerSelection: options.winnerSelection } : {},
|
|
315
|
+
...options.fanoutHarnesses ? { fanoutHarnesses: options.fanoutHarnesses } : {}
|
|
316
|
+
});
|
|
317
|
+
return async (signal) => {
|
|
318
|
+
const ctx = { signal, report: () => {
|
|
319
|
+
} };
|
|
320
|
+
return delegate(options.args, ctx);
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
function worktreeLoopRunner(options) {
|
|
324
|
+
const shape = worktreeFanout({
|
|
325
|
+
repoRoot: options.repoRoot,
|
|
326
|
+
taskPrompt: options.taskPrompt,
|
|
327
|
+
harnesses: options.harnesses,
|
|
328
|
+
...options.testCmd !== void 0 ? { testCmd: options.testCmd } : {},
|
|
329
|
+
...options.typecheckCmd !== void 0 ? { typecheckCmd: options.typecheckCmd } : {},
|
|
330
|
+
...options.require !== void 0 ? { require: options.require } : {},
|
|
331
|
+
...options.maxDiffLines !== void 0 ? { maxDiffLines: options.maxDiffLines } : {},
|
|
332
|
+
...options.forbiddenPaths !== void 0 ? { forbiddenPaths: options.forbiddenPaths } : {},
|
|
333
|
+
...options.winnerStrategy !== void 0 ? { winnerStrategy: options.winnerStrategy } : {},
|
|
334
|
+
...options.runGit ? { runGit: options.runGit } : {},
|
|
335
|
+
...options.runHarness ? { runHarness: options.runHarness } : {},
|
|
336
|
+
...options.runCommand ? { runCommand: options.runCommand } : {}
|
|
337
|
+
});
|
|
338
|
+
const persona = definePersona({
|
|
339
|
+
name: "worktree-coder",
|
|
340
|
+
root: { profile: { name: "worktree-coder" }, harness: null },
|
|
341
|
+
directive: "deliver a minimal validated patch on a fresh worktree",
|
|
342
|
+
context: { role: "coder" },
|
|
343
|
+
executors: { registry: createExecutorRegistry() }
|
|
344
|
+
});
|
|
345
|
+
return async (signal) => {
|
|
346
|
+
const result = await runPersonified({
|
|
347
|
+
persona,
|
|
348
|
+
shape,
|
|
349
|
+
task: options.taskPrompt,
|
|
350
|
+
budget: options.budget,
|
|
351
|
+
signal
|
|
352
|
+
});
|
|
353
|
+
if (result.kind !== "winner" || result.out.kind !== "done") {
|
|
354
|
+
const blockers = result.kind === "winner" && result.out.kind === "blocked" ? result.out.blockers.join("; ") : `supervisor settled ${result.kind}`;
|
|
355
|
+
throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`);
|
|
356
|
+
}
|
|
357
|
+
return result.out.deliverable;
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
function researchLoopRunner(o) {
|
|
361
|
+
const gate = createKbGate(o.gate);
|
|
362
|
+
const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1));
|
|
363
|
+
return async (signal) => {
|
|
364
|
+
const accepted = [];
|
|
365
|
+
let vetoed = [];
|
|
366
|
+
let rounds = 0;
|
|
367
|
+
for (let round = 0; round < maxRounds; round += 1) {
|
|
368
|
+
if (signal.aborted) break;
|
|
369
|
+
rounds += 1;
|
|
370
|
+
const candidates = await o.research(round, vetoed);
|
|
371
|
+
if (candidates.length === 0) break;
|
|
372
|
+
vetoed = [];
|
|
373
|
+
for (const c of candidates) {
|
|
374
|
+
const v = await gate(c);
|
|
375
|
+
if (v.accepted) accepted.push(c);
|
|
376
|
+
else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason });
|
|
377
|
+
}
|
|
378
|
+
if (vetoed.length === 0) break;
|
|
379
|
+
}
|
|
380
|
+
return { accepted, vetoed, rounds };
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
function selfImproveLoopRunner(options) {
|
|
384
|
+
return async () => selfImprove(options);
|
|
385
|
+
}
|
|
386
|
+
function auditLoopRunner(options) {
|
|
387
|
+
return async () => runAnalystLoop(options);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// src/loop-runner-bin.ts
|
|
391
|
+
async function runLoopRunnerCli(args) {
|
|
392
|
+
if (!isDelegatedLoopMode(args.mode)) {
|
|
393
|
+
return {
|
|
394
|
+
exitCode: 2,
|
|
395
|
+
error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(", ")})`
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
let registry;
|
|
399
|
+
try {
|
|
400
|
+
registry = await args.loadRegistry();
|
|
401
|
+
} catch (err) {
|
|
402
|
+
return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` };
|
|
403
|
+
}
|
|
404
|
+
if (!registry[args.mode]) {
|
|
405
|
+
return {
|
|
406
|
+
exitCode: 2,
|
|
407
|
+
error: `config registers no runner for mode '${args.mode}' (registered: ${Object.keys(registry).join(", ") || "none"})`
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
const result = await runDelegatedLoop(args.mode, registry, {
|
|
411
|
+
...args.now ? { now: args.now } : {}
|
|
412
|
+
});
|
|
413
|
+
return { exitCode: result.ok ? 0 : 1, result };
|
|
414
|
+
}
|
|
415
|
+
function parseLoopRunnerArgv(argv) {
|
|
416
|
+
const out = {};
|
|
417
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
418
|
+
const a = argv[i];
|
|
419
|
+
if (a === "--mode") out.mode = argv[++i];
|
|
420
|
+
else if (a === "--config") out.config = argv[++i];
|
|
421
|
+
else if (a?.startsWith("--mode=")) out.mode = a.slice("--mode=".length);
|
|
422
|
+
else if (a?.startsWith("--config=")) out.config = a.slice("--config=".length);
|
|
423
|
+
}
|
|
424
|
+
return out;
|
|
425
|
+
}
|
|
426
|
+
function resolveRegistry(mod) {
|
|
427
|
+
const def = mod?.default ?? mod;
|
|
428
|
+
const value = typeof def === "function" ? def() : def;
|
|
429
|
+
return value;
|
|
430
|
+
}
|
|
431
|
+
function errMsg(err) {
|
|
432
|
+
return err instanceof Error ? err.message : String(err);
|
|
433
|
+
}
|
|
434
|
+
async function main() {
|
|
435
|
+
const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2));
|
|
436
|
+
if (!mode || !config) {
|
|
437
|
+
process.stderr.write(
|
|
438
|
+
`usage: agent-runtime-loop --mode <mode> --config <module>
|
|
439
|
+
modes: ${DELEGATED_LOOP_MODES.join(" | ")}
|
|
440
|
+
config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)
|
|
441
|
+
`
|
|
442
|
+
);
|
|
443
|
+
process.exit(2);
|
|
444
|
+
}
|
|
445
|
+
const { pathToFileURL } = await import("url");
|
|
446
|
+
const { resolve } = await import("path");
|
|
447
|
+
const cli = await runLoopRunnerCli({
|
|
448
|
+
mode,
|
|
449
|
+
loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href))
|
|
450
|
+
});
|
|
451
|
+
process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}
|
|
452
|
+
`);
|
|
453
|
+
if (cli.error) process.stderr.write(`${cli.error}
|
|
454
|
+
`);
|
|
455
|
+
process.exit(cli.exitCode);
|
|
456
|
+
}
|
|
457
|
+
var invokedScript = typeof process !== "undefined" ? process.argv?.[1] : void 0;
|
|
458
|
+
if (invokedScript && /loop-runner-bin\.(js|ts|mjs)$/.test(invokedScript)) {
|
|
459
|
+
void main();
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
export {
|
|
463
|
+
DELEGATED_LOOP_MODES,
|
|
464
|
+
isDelegatedLoopMode,
|
|
465
|
+
runDelegatedLoop,
|
|
466
|
+
coderLoopRunner,
|
|
467
|
+
worktreeLoopRunner,
|
|
468
|
+
researchLoopRunner,
|
|
469
|
+
selfImproveLoopRunner,
|
|
470
|
+
auditLoopRunner,
|
|
471
|
+
runLoopRunnerCli,
|
|
472
|
+
parseLoopRunnerArgv
|
|
473
|
+
};
|
|
474
|
+
//# sourceMappingURL=chunk-BYZCXQHF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/loop-runner.ts","../src/analyst-loop/iterations-to-trace-store.ts","../src/analyst-loop/run-analyst-loop.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n * @experimental\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop via the coder delegate (no-op + secret floor,\n * optional reviewer gate, winner-selection)\n * review → code mode with a REQUIRED reviewer (the gate is the point)\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → closed-loop text/config optimization (selfImprove, held-out gated)\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n */\n\nimport type { Scenario } from '@tangle-network/agent-eval/campaign'\nimport {\n type SelfImproveOptions,\n type SelfImproveResult,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport {\n type CoderReviewer,\n type DelegateRunCtx,\n type DetachedWinnerSelection,\n detachedSessionDelegate,\n} from './mcp/delegates'\nimport type { CoderOutput } from './mcp/detached-coder'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport type { DelegateCodeArgs } from './mcp/types'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type SandboxClient,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** @experimental Every delegated-loop mode, for validation + CLI surfaces. */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** @experimental Type guard for an untrusted mode string (CLI / config input). */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n * @experimental\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the default `code`/`review` runner. */\nexport interface CoderLoopRunnerOptions {\n sandboxClient: SandboxClient\n /** What to build — the delegate args (goal, repoRoot, variants, config, …). */\n args: DelegateCodeArgs\n /** Adversarial reviewer. Pass one to run `review` mode (an approval gate over the candidate). */\n reviewer?: CoderReviewer\n /** Winner-selection strategy. Default `highest-score`. */\n winnerSelection?: DetachedWinnerSelection\n /** Harnesses for `variants > 1` fanout. */\n fanoutHarnesses?: string[]\n}\n\n/**\n * @experimental Build a `code`/`review`-mode runner over the sandbox-session coder delegate. Pass a\n * `reviewer` to run `review` mode — an approval gate over the validated candidate.\n */\nexport function coderLoopRunner(options: CoderLoopRunnerOptions): DelegatedLoopRunner<CoderOutput> {\n const delegate = detachedSessionDelegate({\n sandboxClient: options.sandboxClient,\n ...(options.reviewer ? { reviewer: options.reviewer } : {}),\n ...(options.winnerSelection ? { winnerSelection: options.winnerSelection } : {}),\n ...(options.fanoutHarnesses ? { fanoutHarnesses: options.fanoutHarnesses } : {}),\n })\n return async (signal) => {\n const ctx: DelegateRunCtx = { signal, report: () => {} }\n return delegate(options.args, ctx)\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n * @experimental\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. This is the local-repo counterpart to\n * {@link coderLoopRunner} (which drives the in-box harness over a `SandboxClient`): no `runLoop`\n * driver, no role-coupled delegate — the harness list is the fanout, the gate is `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: { name: 'worktree-coder' }, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * @experimental `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/** @experimental `self-improve` mode — agent-eval's one-call closed loop (held-out gated). */\nexport function selfImproveLoopRunner<TScenario extends Scenario, TArtifact>(\n options: SelfImproveOptions<TScenario, TArtifact>,\n): DelegatedLoopRunner<SelfImproveResult<TScenario, TArtifact>> {\n return async () => selfImprove<TScenario, TArtifact>(options)\n}\n\n/** @experimental `audit` mode — analyst loop over captured trace/run data. */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","/**\n * @experimental\n *\n * The read seam that closes the autonomous loop: project a round's `Iteration[]`\n * (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the\n * read interface the trace analysts query. `runAnalystLoop` has had zero consumers\n * because nothing turned a loop's iterations into a store — this is that bridge.\n *\n * One iteration → one trace. The iteration is the root AGENT span; each `SandboxEvent`\n * becomes a child span (LLM for llm_call events, TOOL for tool events, else SPAN), so an\n * analyst can walk a shot's trace, cluster its errors, and emit findings the driver\n * steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event\n * lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration\n * surfaces a real ERROR span carrying the real message.\n */\n\nimport {\n type DatasetOverview,\n DEFAULT_TRACE_ANALYST_BUDGETS,\n type QueryTracesPage,\n type SearchSpanResult,\n type SearchTraceResult,\n type SpanMatchRecord,\n TRACE_ANALYST_TRUNCATION_MARKER_PREFIX,\n type TraceAnalysisStore,\n type TraceAnalystByteBudgets,\n type TraceAnalystFilters,\n type TraceAnalystSpan,\n type TraceAnalystSpanKind,\n type TraceAnalystTraceSummary,\n type ViewSpansResult,\n type ViewTraceResult,\n} from '@tangle-network/agent-eval'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { AnalystError } from '../errors'\nimport { extractLlmCallEvent } from '../runtime/sandbox-events'\nimport type { Iteration } from '../runtime/types'\n\n/** ErrorCluster isn't re-exported from the agent-eval root; derive it from the overview. */\ntype ErrorCluster = DatasetOverview['error_clusters'][number]\n\ninterface ProjectedTrace {\n summary: TraceAnalystTraceSummary\n spans: TraceAnalystSpan[]\n /** raw JSONL bytes of this trace's spans — the byte-budget accounting unit. */\n rawBytes: number\n}\n\nconst bytesOf = (v: unknown): number => Buffer.byteLength(JSON.stringify(v) ?? '', 'utf8')\nconst iso = (ms: number): string => new Date(ms).toISOString()\n\n/** Normalize volatile tokens out of a status message so semantically identical failures\n * collapse to one signature (digits, hex/uuids, paths, durations → placeholders). */\nfunction normalizeSignature(message: string): string {\n return message\n .replace(/0x[0-9a-fA-F]+/g, 'HEX')\n .replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g, 'UUID')\n .replace(/(\\/[\\w.-]+){2,}/g, 'PATH')\n .replace(/\\b\\d+(\\.\\d+)?(ms|s|m|h)\\b/g, 'DUR')\n .replace(/\\b\\d+\\b/g, '#')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 200)\n}\n\nfunction spanKindFor(\n event: SandboxEvent,\n agentRunName: string,\n): {\n kind: TraceAnalystSpanKind\n model: string | null\n tool: string | null\n} {\n const llm = extractLlmCallEvent(event, agentRunName)\n if (llm) return { kind: 'LLM', model: llm.model ?? null, tool: null }\n const type = String(event?.type ?? '')\n if (/tool/i.test(type)) {\n const d = event?.data as { name?: unknown; tool?: unknown } | undefined\n const tool = typeof d?.name === 'string' ? d.name : typeof d?.tool === 'string' ? d.tool : type\n return { kind: 'TOOL', model: null, tool }\n }\n return { kind: 'SPAN', model: null, tool: null }\n}\n\nfunction errorMessageOf(event: SandboxEvent): string | undefined {\n const type = String(event?.type ?? '')\n const d = event?.data as { error?: unknown; message?: unknown } | undefined\n if (/error|fail/i.test(type) || d?.error) {\n const m = d?.error ?? d?.message\n return typeof m === 'string' ? m : `${type} error`\n }\n return undefined\n}\n\n/** Project one iteration → one trace: root AGENT span + a child span per event. */\nfunction projectIteration<Task, Output>(iter: Iteration<Task, Output>): ProjectedTrace {\n const traceId =\n (\n iter.events.find((e) => (e?.data as { sandboxId?: string } | undefined)?.sandboxId)?.data as\n | { sandboxId?: string }\n | undefined\n )?.sandboxId ?? `iter-${iter.index}`\n const start = iso(iter.startedAt)\n const end = iso(iter.endedAt || iter.startedAt)\n const durationMs = Math.max(0, (iter.endedAt || iter.startedAt) - iter.startedAt)\n const rootId = `${traceId}:root`\n const iterErrored = Boolean(iter.error) || iter.verdict?.valid === false\n const spans: TraceAnalystSpan[] = [\n {\n trace_id: traceId,\n span_id: rootId,\n parent_span_id: null,\n name: iter.agentRunName,\n kind: 'AGENT',\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n status: iter.error ? 'ERROR' : 'OK',\n status_message: iter.error?.message,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: null,\n tool_name: null,\n attributes: {\n 'iteration.index': iter.index,\n 'verdict.valid': iter.verdict?.valid,\n 'verdict.score': iter.verdict?.score,\n 'output.preview':\n iter.output === undefined ? undefined : String(iter.output).slice(0, 2000),\n },\n },\n ]\n const models = new Set<string>()\n const tools = new Set<string>()\n iter.events.forEach((event, i) => {\n const { kind, model, tool } = spanKindFor(event, iter.agentRunName)\n if (model) models.add(model)\n if (tool) tools.add(tool)\n const errMsg = errorMessageOf(event)\n spans.push({\n trace_id: traceId,\n span_id: `${traceId}:e${i}`,\n parent_span_id: rootId,\n name: String(event?.type ?? 'event'),\n kind,\n start_time: start,\n end_time: end,\n duration_ms: 0,\n status: errMsg ? 'ERROR' : 'OK',\n status_message: errMsg,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: model,\n tool_name: tool,\n attributes: (event?.data as Record<string, unknown> | undefined) ?? {},\n })\n })\n const hasErrors = spans.some((s) => s.status === 'ERROR') || iterErrored\n const summary: TraceAnalystTraceSummary = {\n trace_id: traceId,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n span_count: spans.length,\n has_errors: hasErrors,\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n raw_jsonl_bytes: bytesOf(spans),\n models: [...models],\n tools: [...tools],\n }\n return { summary, spans, rawBytes: summary.raw_jsonl_bytes }\n}\n\nfunction matchesFilters(t: ProjectedTrace, f?: TraceAnalystFilters): boolean {\n if (!f) return true\n if (f.has_errors !== undefined && t.summary.has_errors !== f.has_errors) return false\n if (f.service_names?.length && !f.service_names.includes(t.summary.service_name ?? ''))\n return false\n if (f.agent_names?.length && !f.agent_names.includes(t.summary.agent_name ?? '')) return false\n if (f.model_names?.length && !f.model_names.some((m) => t.summary.models.includes(m)))\n return false\n if (f.tool_names?.length && !f.tool_names.some((tn) => t.summary.tools.includes(tn))) return false\n if (f.start_time_after && t.summary.start_time < f.start_time_after) return false\n if (f.start_time_before && t.summary.start_time > f.start_time_before) return false\n if (f.regex_pattern && !new RegExp(f.regex_pattern).test(JSON.stringify(t.spans))) return false\n return true\n}\n\nfunction capAttributes(\n attributes: Record<string, unknown>,\n perAttrCap: number,\n): { capped: Record<string, unknown>; truncated: number } {\n let truncated = 0\n const capped: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attributes)) {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof s === 'string' && s.length > perAttrCap) {\n truncated += 1\n capped[k] = `${TRACE_ANALYST_TRUNCATION_MARKER_PREFIX} ${s.length}b]${s.slice(0, perAttrCap)}`\n } else {\n capped[k] = v\n }\n }\n return { capped, truncated }\n}\n\n/**\n * Build an in-memory `TraceAnalysisStore` over a loop round's iterations. Fail-loud on an\n * empty round — there is nothing for an analyst to read, and a silent empty store would\n * mask a broken capture path.\n */\nexport function iterationsToTraceStore<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n budgets: TraceAnalystByteBudgets = DEFAULT_TRACE_ANALYST_BUDGETS,\n): TraceAnalysisStore {\n if (iterations.length === 0) {\n throw new AnalystError('iterationsToTraceStore: no iterations to analyze (empty round)')\n }\n const traces = iterations.map((it) => projectIteration(it))\n const byId = new Map(traces.map((t) => [t.summary.trace_id, t]))\n\n const buildClusters = (set: ProjectedTrace[]): ErrorCluster[] => {\n const map = new Map<string, ErrorCluster>()\n for (const t of set) {\n for (const s of t.spans) {\n if (s.status !== 'ERROR' || !s.status_message) continue\n const sig = normalizeSignature(s.status_message)\n const c = map.get(sig) ?? {\n signature: sig,\n status_message_sample: s.status_message,\n span_name: s.name,\n tool_name: s.tool_name,\n trace_count: 0,\n span_count: 0,\n prevalence: 0,\n exemplar_trace_ids: [],\n exemplar_span_ids: [],\n }\n c.span_count += 1\n if (\n !c.exemplar_trace_ids.includes(t.summary.trace_id) &&\n c.exemplar_trace_ids.length < 10\n ) {\n c.exemplar_trace_ids.push(t.summary.trace_id)\n c.trace_count += 1\n }\n if (c.exemplar_span_ids.length < 10) c.exemplar_span_ids.push(s.span_id)\n map.set(sig, c)\n }\n }\n const errorTraces = set.filter((t) => t.summary.has_errors).length || 1\n const clusters = [...map.values()].map((c) => ({\n ...c,\n prevalence: c.trace_count / errorTraces,\n }))\n return clusters.sort((a, b) => b.trace_count - a.trace_count)\n }\n\n return {\n async getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview> {\n const set = traces.filter((t) => matchesFilters(t, filters))\n const services = new Set<string>()\n const agents = new Set<string>()\n const models = new Set<string>()\n const tools = new Set<string>()\n let errorSpans = 0\n for (const t of set) {\n if (t.summary.service_name) services.add(t.summary.service_name)\n if (t.summary.agent_name) agents.add(t.summary.agent_name)\n for (const m of t.summary.models) models.add(m)\n for (const tn of t.summary.tools) tools.add(tn)\n errorSpans += t.spans.filter((s) => s.status === 'ERROR').length\n }\n const times = set.map((t) => t.summary.start_time).sort()\n return {\n total_traces: set.length,\n raw_jsonl_bytes: set.reduce((n, t) => n + t.rawBytes, 0),\n services: [...services],\n agents: [...agents],\n models: [...models],\n tool_names: [...tools],\n sample_trace_ids: set.slice(0, 20).map((t) => t.summary.trace_id),\n errors: {\n trace_count: set.filter((t) => t.summary.has_errors).length,\n span_count: errorSpans,\n },\n error_clusters: buildClusters(set),\n time_range: times.length ? { earliest: times[0]!, latest: times[times.length - 1]! } : null,\n }\n },\n\n async queryTraces(opts): Promise<QueryTracesPage> {\n const set = traces.filter((t) => matchesFilters(t, opts.filters))\n const offset = opts.offset ?? 0\n const page = set.slice(offset, offset + opts.limit)\n return {\n traces: page.map((t) => t.summary),\n total: set.length,\n has_more: offset + opts.limit < set.length,\n }\n },\n\n async countTraces(filters?: TraceAnalystFilters): Promise<number> {\n return traces.filter((t) => matchesFilters(t, filters)).length\n },\n\n async viewTrace(opts): Promise<ViewTraceResult> {\n const t = byId.get(opts.trace_id)\n if (!t) return { trace_id: opts.trace_id, spans: [] }\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeViewBudget\n const projected = t.spans.map((s) => ({\n ...s,\n attributes: capAttributes(s.attributes, cap).capped,\n }))\n if (bytesOf(projected) > budgets.perCallByteCeiling) {\n const names = new Map<string, number>()\n for (const s of t.spans) names.set(s.name, (names.get(s.name) ?? 0) + 1)\n return {\n trace_id: opts.trace_id,\n oversized: {\n span_count: t.spans.length,\n top_span_names: [...names.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20),\n span_response_bytes_max: Math.max(...t.spans.map((s) => bytesOf(s))),\n error_span_count: t.spans.filter((s) => s.status === 'ERROR').length,\n },\n }\n }\n return { trace_id: opts.trace_id, spans: projected }\n },\n\n async viewSpans(opts): Promise<ViewSpansResult> {\n const t = byId.get(opts.trace_id)\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeSpanBudget\n const want = new Set(opts.span_ids)\n const found = (t?.spans ?? []).filter((s) => want.has(s.span_id))\n let truncated = 0\n const spans = found.map((s) => {\n const { capped, truncated: n } = capAttributes(s.attributes, cap)\n truncated += n\n return { ...s, attributes: capped }\n })\n const foundIds = new Set(found.map((s) => s.span_id))\n return {\n trace_id: opts.trace_id,\n spans,\n missing_span_ids: opts.span_ids.filter((id) => !foundIds.has(id)),\n truncated_attribute_count: truncated,\n }\n },\n\n async searchTrace(opts): Promise<SearchTraceResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const hits: SpanMatchRecord[] = []\n for (const s of t?.spans ?? []) {\n for (const hit of searchSpanAttrs(s, opts.regex_pattern, budgets.perMatchTextBudget)) {\n if (hits.length >= max) break\n hits.push(hit)\n }\n }\n return {\n trace_id: opts.trace_id,\n hits,\n total_matches: hits.length,\n has_more: hits.length >= max,\n }\n },\n\n async searchSpan(opts): Promise<SearchSpanResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const span = (t?.spans ?? []).find((s) => s.span_id === opts.span_id)\n const hits = span\n ? searchSpanAttrs(span, opts.regex_pattern, budgets.perMatchTextBudget).slice(0, max)\n : []\n return {\n trace_id: opts.trace_id,\n span_id: opts.span_id,\n hits,\n total_matches: hits.length,\n has_more: false,\n }\n },\n }\n}\n\nfunction searchSpanAttrs(\n span: TraceAnalystSpan,\n pattern: string,\n textCap: number,\n): SpanMatchRecord[] {\n const re = new RegExp(pattern, 'g')\n const hits: SpanMatchRecord[] = []\n for (const [k, v] of Object.entries(span.attributes)) {\n const text = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof text !== 'string') continue\n re.lastIndex = 0\n const m = re.exec(text)\n if (!m) continue\n const at = m.index\n hits.push({\n trace_id: span.trace_id,\n span_id: span.span_id,\n span_name: span.name,\n span_kind: span.kind,\n attribute_path: `attributes.${k}`,\n matched_text: m[0].slice(0, textCap),\n context_before: text.slice(Math.max(0, at - textCap / 2), at),\n context_after: text.slice(at + m[0].length, at + m[0].length + textCap / 2),\n match_offset: at,\n })\n }\n return hits\n}\n","/**\n * `runAnalystLoop` — the one call agent apps reach for to close the\n * recursive-self-improvement loop.\n *\n * 1. Load baseline findings (last run, or the slice the caller specifies)\n * 2. Run the analyst registry with priorFindings injected\n * 3. Persist the new run's findings to the ledger\n * 4. Diff the new run against the baseline\n * 5. Hand the findings to the knowledge adapter → proposals (and\n * optionally apply them) → wiki edits\n * 6. Hand the findings to the improvement adapter → prompt / tool /\n * scaffolding edits (review-only by default)\n * 7. Return a single report the consumer renders / persists / acts on.\n *\n * Adapters are optional: the loop works as a \"run + diff + report\"\n * primitive when no adapters are wired; it closes end-to-end when\n * both adapters are wired.\n */\n\nimport type { AnalystFinding, AnalystRunResult, FindingsDiff } from '@tangle-network/agent-eval'\nimport { diffFindings } from '@tangle-network/agent-eval'\n\nimport type {\n AnalystLoopEvent,\n AnalystRegistryStreamingLike,\n ImprovementReport,\n KnowledgeReport,\n RunAnalystLoopOpts,\n RunAnalystLoopResult,\n} from './types'\n\nexport async function runAnalystLoop<TProposal = unknown, TEdit = unknown>(\n opts: RunAnalystLoopOpts,\n): Promise<RunAnalystLoopResult<TProposal, TEdit>> {\n const log = opts.log ?? defaultLog\n const strategy = opts.priorFindingsStrategy ?? 'per-kind'\n const emit = makeEmitter(opts.onEvent)\n const startedAt = Date.now()\n\n // 1. Resolve baseline + load prior findings.\n const baselineRunId = resolveBaselineRunId(opts)\n const priorAll: ReadonlyArray<AnalystFinding & { run_id: string }> = baselineRunId\n ? (opts.findingsStore?.loadRun(baselineRunId) ?? [])\n : []\n log('baseline resolved', { baselineRunId, prior_findings: priorAll.length })\n await emit({\n type: 'baseline-resolved',\n runId: opts.runId,\n baselineRunId,\n priorFindingCount: priorAll.length,\n })\n\n // 2. Run the registry. Strategy controls how analysts see priors.\n // When the registry exposes runStream, forward each event verbatim\n // so subscribers see per-analyst progress in real time.\n const priorFindings = buildPriorFindingsInput(priorAll, strategy, opts.registry.list())\n const analystResult = await runRegistry(opts, priorFindings, emit)\n log('analyst run complete', {\n findings: analystResult.findings.length,\n cost_usd: analystResult.total_cost_usd,\n per_analyst: analystResult.per_analyst.map((s) => ({\n id: s.analyst_id,\n status: s.status,\n n: s.findings_count,\n })),\n })\n\n // 3. Persist the new run before any side-effecting adapter runs so\n // the ledger is the source of truth even if an adapter throws.\n if (opts.findingsStore && analystResult.findings.length > 0) {\n await opts.findingsStore.append(opts.runId, analystResult.findings)\n await emit({\n type: 'findings-persisted',\n runId: opts.runId,\n count: analystResult.findings.length,\n })\n }\n\n // 4. Diff vs baseline.\n let diff: FindingsDiff | null = null\n if (baselineRunId && analystResult.findings.length > 0) {\n diff = diffFindings(\n priorAll.map((f) => ({ ...f })),\n analystResult.findings.map((f) => ({ ...f, run_id: opts.runId })),\n )\n log('diff vs baseline', {\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n await emit({\n type: 'diff-computed',\n runId: opts.runId,\n baselineRunId,\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n }\n\n // 5. Knowledge adapter — proposals + optional auto-apply.\n let knowledge: KnowledgeReport<TProposal> | null = null\n if (opts.knowledgeAdapter) {\n knowledge = await runKnowledgeAdapter(opts, analystResult.findings, log, emit)\n }\n\n // 6. Improvement adapter — prompt / tool / scaffolding edits.\n let improvement: ImprovementReport<TEdit> | null = null\n if (opts.improvementAdapter) {\n improvement = await runImprovementAdapter(opts, analystResult.findings, log, emit)\n }\n\n await emit({\n type: 'loop-completed',\n runId: opts.runId,\n durationMs: Date.now() - startedAt,\n })\n\n return {\n runId: opts.runId,\n baselineRunId,\n analystResult,\n diff,\n knowledge,\n improvement,\n }\n}\n\ntype Emitter = (event: AnalystLoopEvent) => Promise<void>\n\nfunction makeEmitter(onEvent: RunAnalystLoopOpts['onEvent']): Emitter {\n if (!onEvent) return async () => {}\n return async (event) => {\n await onEvent(event)\n }\n}\n\nasync function runRegistry(\n opts: RunAnalystLoopOpts,\n priorFindings: ReturnType<typeof buildPriorFindingsInput>,\n emit: Emitter,\n): Promise<AnalystRunResult> {\n const reg = opts.registry as AnalystRegistryStreamingLike\n if (typeof reg.runStream === 'function' && opts.onEvent) {\n let final: AnalystRunResult | null = null\n for await (const ev of reg.runStream(opts.runId, opts.inputs, { priorFindings })) {\n await emit({ type: 'analyst', runId: opts.runId, event: ev })\n if (ev.type === 'run-completed') final = ev.result\n }\n if (!final) {\n throw new Error('runAnalystLoop: registry.runStream ended without run-completed event')\n }\n return final\n }\n return opts.registry.run(opts.runId, opts.inputs, { priorFindings })\n}\n\nfunction resolveBaselineRunId(opts: RunAnalystLoopOpts): string | null {\n if (opts.baselineRunId === null) return null\n if (typeof opts.baselineRunId === 'string') return opts.baselineRunId\n if (!opts.findingsStore) return null\n const all = opts.findingsStore.loadAll()\n let last: string | null = null\n for (const row of all) {\n if (row.run_id === opts.runId) continue\n last = row.run_id\n }\n return last\n}\n\nfunction buildPriorFindingsInput(\n prior: ReadonlyArray<AnalystFinding & { run_id: string }>,\n strategy: 'per-kind' | 'wildcard' | 'none',\n registry: ReadonlyArray<{ id: string }>,\n): ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>> | undefined {\n if (strategy === 'none' || prior.length === 0) return undefined\n const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest as AnalystFinding)\n if (strategy === 'wildcard') {\n return { '*': stripped }\n }\n void registry\n return stripped\n}\n\nasync function runKnowledgeAdapter<TProposal>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<KnowledgeReport<TProposal>> {\n const adapter = opts.knowledgeAdapter!\n const batch = await adapter.proposeFromFindings(findings)\n log('knowledge.proposeFromFindings', {\n proposals: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'knowledge-proposed',\n runId: opts.runId,\n proposalCount: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n const auto = opts.autoApply?.knowledge ?? false\n const threshold = opts.autoApply?.knowledgeConfidenceThreshold ?? 0.85\n\n if (!auto || !adapter.apply) {\n await emit({\n type: 'knowledge-applied',\n runId: opts.runId,\n writtenCount: 0,\n withheldForReview: batch.proposals.length,\n })\n return {\n proposals: batch.proposals as TProposal[],\n applied: [],\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: batch.proposals.length,\n }\n }\n\n const findingsById = new Map(findings.map((f) => [f.finding_id, f]))\n const safe: TProposal[] = []\n let withheld = 0\n for (const p of batch.proposals as Array<TProposal & { sourceFindingId?: string }>) {\n const src = p.sourceFindingId ? findingsById.get(p.sourceFindingId) : undefined\n if (!src) {\n withheld += 1\n continue\n }\n if (src.confidence < threshold) {\n withheld += 1\n continue\n }\n safe.push(p)\n }\n const result = await adapter.apply(safe)\n log('knowledge.apply', {\n applied: result.written.length,\n withheld_for_review: withheld,\n warnings: result.warnings.length,\n })\n await emit({\n type: 'knowledge-applied',\n runId: opts.runId,\n writtenCount: result.written.length,\n withheldForReview: withheld,\n })\n return {\n proposals: batch.proposals as TProposal[],\n applied: result.written,\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: withheld,\n }\n}\n\nasync function runImprovementAdapter<TEdit>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<ImprovementReport<TEdit>> {\n const adapter = opts.improvementAdapter!\n const batch = await adapter.proposeFromFindings(findings)\n log('improvement.proposeFromFindings', {\n edits: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'improvement-proposed',\n runId: opts.runId,\n editCount: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n const auto = opts.autoApply?.improvement ?? false\n const threshold = opts.autoApply?.improvementConfidenceThreshold ?? 0.9\n\n if (!auto || !adapter.apply) {\n await emit({\n type: 'improvement-applied',\n runId: opts.runId,\n appliedCount: 0,\n withheldForReview: batch.edits.length,\n })\n return {\n edits: batch.edits as TEdit[],\n applied: [],\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: batch.edits.length,\n }\n }\n\n const findingsById = new Map(findings.map((f) => [f.finding_id, f]))\n const safe: TEdit[] = []\n let withheld = 0\n for (const e of batch.edits as Array<TEdit & { sourceFindingId?: string }>) {\n const src = e.sourceFindingId ? findingsById.get(e.sourceFindingId) : undefined\n if (!src || src.confidence < threshold) {\n withheld += 1\n continue\n }\n safe.push(e)\n }\n const result = await adapter.apply(safe)\n log('improvement.apply', {\n applied: result.applied.length,\n withheld_for_review: withheld,\n warnings: result.warnings.length,\n })\n await emit({\n type: 'improvement-applied',\n runId: opts.runId,\n appliedCount: result.applied.length,\n withheldForReview: withheld,\n })\n return {\n edits: batch.edits as TEdit[],\n applied: result.applied,\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: withheld,\n }\n}\n\nfunction defaultLog(msg: string, fields?: Record<string, unknown>): void {\n if (fields) console.log(`[analyst-loop] ${msg}`, fields)\n else console.log(`[analyst-loop] ${msg}`)\n}\n","#!/usr/bin/env node\n/**\n * @experimental\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n * @experimental\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBA;AAAA,EAGE;AAAA,OACK;;;ACXP;AAAA,EAEE;AAAA,EAKA;AAAA,OASK;;;ACZP,SAAS,oBAAoB;AAW7B,eAAsB,eACpB,MACiD;AACjD,QAAM,MAAM,KAAK,OAAO;AACxB,QAAM,WAAW,KAAK,yBAAy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names":[]}
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
DELEGATION_STATUS_DESCRIPTION,
|
|
15
15
|
DELEGATION_STATUS_INPUT_SCHEMA,
|
|
16
16
|
DELEGATION_STATUS_TOOL_NAME
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-QXWGSDAQ.js";
|
|
18
18
|
|
|
19
19
|
// src/mcp/openai-tools.ts
|
|
20
20
|
function buildTool(name, description, parameters) {
|
|
@@ -61,4 +61,4 @@ export {
|
|
|
61
61
|
mcpToolsForRuntimeMcp,
|
|
62
62
|
mcpToolsForRuntimeMcpSubset
|
|
63
63
|
};
|
|
64
|
-
//# sourceMappingURL=chunk-
|
|
64
|
+
//# sourceMappingURL=chunk-EDCVUZZC.js.map
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
coderProfile,
|
|
3
|
-
coderTaskToPrompt
|
|
4
|
-
} from "./chunk-DVQGYDN5.js";
|
|
5
1
|
import {
|
|
6
2
|
composeLoopTraceEmitters,
|
|
7
3
|
detachedTurnEvents,
|
|
@@ -11,7 +7,11 @@ import {
|
|
|
11
7
|
runDetachedTurn,
|
|
12
8
|
runLoop,
|
|
13
9
|
selectValidWinner
|
|
14
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-QXWGSDAQ.js";
|
|
11
|
+
import {
|
|
12
|
+
coderProfile,
|
|
13
|
+
coderTaskToPrompt
|
|
14
|
+
} from "./chunk-DVQGYDN5.js";
|
|
15
15
|
|
|
16
16
|
// src/mcp/executor.ts
|
|
17
17
|
function createSiblingSandboxExecutor(options) {
|
|
@@ -472,4 +472,4 @@ export {
|
|
|
472
472
|
coderTaskFromArgs,
|
|
473
473
|
settleDetachedCoderTurn
|
|
474
474
|
};
|
|
475
|
-
//# sourceMappingURL=chunk-
|
|
475
|
+
//# sourceMappingURL=chunk-L5ZFBVT6.js.map
|