@tangle-network/agent-runtime 0.17.2 → 0.19.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 +0 -1
- package/dist/agent.d.ts +3 -165
- package/dist/agent.js +0 -108
- package/dist/agent.js.map +1 -1
- package/dist/chunk-RZAOYKCO.js +51 -0
- package/dist/chunk-RZAOYKCO.js.map +1 -0
- package/dist/chunk-XLWPTPRP.js +52 -0
- package/dist/chunk-XLWPTPRP.js.map +1 -0
- package/dist/index.d.ts +4 -137
- package/dist/index.js +9 -45
- package/dist/index.js.map +1 -1
- package/dist/loops.d.ts +153 -0
- package/dist/loops.js +379 -0
- package/dist/loops.js.map +1 -0
- package/dist/profiles.d.ts +133 -0
- package/dist/profiles.js +249 -0
- package/dist/profiles.js.map +1 -0
- package/dist/runtime-run-4pbY3Jq5.d.ts +137 -0
- package/dist/{types-ByIhNRFk.d.ts → types-DlyPgeI0.d.ts} +1 -1
- package/dist/types-EKcAHfxI.d.ts +225 -0
- package/package.json +32 -11
package/dist/loops.d.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
export { AgentProfile, CreateSandboxOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox';
|
|
2
|
+
import { D as DefaultVerdict, a as Driver, I as Iteration, A as AgentRunSpec, O as OutputAdapter, V as Validator, E as ExecCtx, L as LoopWinner, b as LoopResult } from './types-EKcAHfxI.js';
|
|
3
|
+
export { c as LoopDecisionPayload, d as LoopEndedPayload, e as LoopIterationEndedPayload, f as LoopIterationStartedPayload, g as LoopSandboxClient, h as LoopStartedPayload, i as LoopTraceEmitter, j as LoopTraceEvent, k as ValidationCtx } from './types-EKcAHfxI.js';
|
|
4
|
+
import './runtime-run-4pbY3Jq5.js';
|
|
5
|
+
import './types-DlyPgeI0.js';
|
|
6
|
+
import '@tangle-network/agent-eval';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @experimental
|
|
10
|
+
*
|
|
11
|
+
* FanoutVote driver — N parallel attempts in iteration 0, pick the highest-
|
|
12
|
+
* scoring valid output. No second iteration: the topology is "spawn N, score,
|
|
13
|
+
* pick winner". The kernel handles heterogeneous fanout via the
|
|
14
|
+
* `agentRuns: AgentRunSpec[]` form on `runLoop`.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
type FanoutVoteDecision = 'pick-winner' | 'fail';
|
|
18
|
+
/** @experimental */
|
|
19
|
+
interface FanoutVoteScored<Task, Output> {
|
|
20
|
+
task: Task;
|
|
21
|
+
output: Output;
|
|
22
|
+
verdict?: DefaultVerdict;
|
|
23
|
+
iterationIndex: number;
|
|
24
|
+
agentRunName: string;
|
|
25
|
+
}
|
|
26
|
+
/** @experimental */
|
|
27
|
+
interface CreateFanoutVoteDriverOptions<Task, Output> {
|
|
28
|
+
/** Number of parallel attempts. Must be >= 1. */
|
|
29
|
+
n: number;
|
|
30
|
+
/**
|
|
31
|
+
* Pick the winner from the scored set. Default: highest `verdict.score`
|
|
32
|
+
* among valid outputs (ties broken by smallest iteration index). When
|
|
33
|
+
* no valid outputs exist, returns `undefined` and `decide()` resolves
|
|
34
|
+
* to `'fail'`. The kernel still records winners structurally — this
|
|
35
|
+
* selector only feeds `decide()`'s pass/fail signal.
|
|
36
|
+
*/
|
|
37
|
+
selector?: (scored: FanoutVoteScored<Task, Output>[]) => FanoutVoteScored<Task, Output> | undefined;
|
|
38
|
+
/** Stable identifier surfaced in trace events. Default `'fanout-vote'`. */
|
|
39
|
+
name?: string;
|
|
40
|
+
}
|
|
41
|
+
/** @experimental */
|
|
42
|
+
declare function createFanoutVoteDriver<Task, Output>(options: CreateFanoutVoteDriverOptions<Task, Output>): Driver<Task, Output, FanoutVoteDecision>;
|
|
43
|
+
/**
|
|
44
|
+
* Test helper: surface the per-iteration scored view a custom `selector`
|
|
45
|
+
* would receive. Exposed so consumers writing a custom selector can test it
|
|
46
|
+
* standalone without driving the full kernel.
|
|
47
|
+
*
|
|
48
|
+
* @experimental
|
|
49
|
+
*/
|
|
50
|
+
declare function scoreFanoutVoteIterations<Task, Output>(iterations: ReadonlyArray<Iteration<Task, Output>>): FanoutVoteScored<Task, Output>[];
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @experimental
|
|
54
|
+
*
|
|
55
|
+
* Refine driver — single task per iteration, validator-gated.
|
|
56
|
+
*
|
|
57
|
+
* `plan` returns `[task]` (possibly transformed via `refineTask`) until the
|
|
58
|
+
* prior verdict is valid OR the local cap is hit, then `[]`.
|
|
59
|
+
* `decide` returns `'stop'` once the latest verdict is valid OR the cap is
|
|
60
|
+
* reached. The kernel's `maxIterations` is an orthogonal safety cap;
|
|
61
|
+
* whichever is lower wins.
|
|
62
|
+
*/
|
|
63
|
+
|
|
64
|
+
type RefineDecision = 'continue' | 'stop';
|
|
65
|
+
/** @experimental */
|
|
66
|
+
interface CreateRefineDriverOptions<Task> {
|
|
67
|
+
/** Hard cap on iterations. Default 5. */
|
|
68
|
+
maxIterations?: number;
|
|
69
|
+
/**
|
|
70
|
+
* Optional task transform applied each round based on the prior verdict.
|
|
71
|
+
* When omitted, the same task is replayed and the agent is expected to
|
|
72
|
+
* inspect the sandbox session state for prior attempts.
|
|
73
|
+
*/
|
|
74
|
+
refineTask?: (task: Task, prior: DefaultVerdict) => Task;
|
|
75
|
+
/** Stable identifier surfaced in trace events. Default `'refine'`. */
|
|
76
|
+
name?: string;
|
|
77
|
+
}
|
|
78
|
+
/** @experimental */
|
|
79
|
+
declare function createRefineDriver<Task, Output>(options?: CreateRefineDriverOptions<Task>): Driver<Task, Output, RefineDecision>;
|
|
80
|
+
/**
|
|
81
|
+
* Test helper: select the last-valid iteration (or the last attempt if
|
|
82
|
+
* none passed). Mirrors the kernel's default selector ordering for refine
|
|
83
|
+
* topologies — the most recent successful attempt wins.
|
|
84
|
+
*
|
|
85
|
+
* @experimental
|
|
86
|
+
*/
|
|
87
|
+
declare function refineWinnerIndex<Task, Output>(iterations: ReadonlyArray<Iteration<Task, Output>>): number | undefined;
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* @experimental
|
|
91
|
+
*
|
|
92
|
+
* `runLoop` — the topology-agnostic kernel built atop the sandbox SDK.
|
|
93
|
+
*
|
|
94
|
+
* Each iteration:
|
|
95
|
+
* 1. `driver.plan(task, history)` → N tasks (1 = refine, N = fanout, 0 = stop)
|
|
96
|
+
* 2. For each task (parallel, bounded by `maxConcurrency`):
|
|
97
|
+
* a. round-robin an `AgentRunSpec` from `agentRuns`
|
|
98
|
+
* b. `sandboxClient.create({ backend: { profile }, ...overrides })`
|
|
99
|
+
* c. iterate `box.streamPrompt(taskToPrompt(task))` and collect events
|
|
100
|
+
* 3. `output.parse(events)` → typed `Output`
|
|
101
|
+
* 4. `validator?.validate(output)` → `DefaultVerdict`
|
|
102
|
+
* 5. Append `Iteration` to history; emit `loop.iteration.ended`
|
|
103
|
+
* 6. `driver.decide(history)` → if terminal, return result + winner
|
|
104
|
+
*
|
|
105
|
+
* The kernel owns: iteration accounting, per-iteration timing, error
|
|
106
|
+
* capture, abort propagation, concurrency cap, cost aggregation, and trace
|
|
107
|
+
* emission. The kernel does NOT own: what the agent runs (sandbox SDK +
|
|
108
|
+
* profile), how outputs are decoded (output adapter), how outputs are
|
|
109
|
+
* scored (validator), or topology (driver).
|
|
110
|
+
*/
|
|
111
|
+
|
|
112
|
+
/** @experimental */
|
|
113
|
+
interface RunLoopOptions<Task, Output, Decision> {
|
|
114
|
+
driver: Driver<Task, Output, Decision>;
|
|
115
|
+
/**
|
|
116
|
+
* Single agent spec — every iteration uses this profile. Mutually
|
|
117
|
+
* exclusive with `agentRuns`.
|
|
118
|
+
*/
|
|
119
|
+
agentRun?: AgentRunSpec<Task>;
|
|
120
|
+
/**
|
|
121
|
+
* Multiple specs for heterogeneous fanout. The kernel round-robins
|
|
122
|
+
* through them when the driver plans N tasks. Mutually exclusive with
|
|
123
|
+
* `agentRun`.
|
|
124
|
+
*/
|
|
125
|
+
agentRuns?: AgentRunSpec<Task>[];
|
|
126
|
+
output: OutputAdapter<Output>;
|
|
127
|
+
validator?: Validator<Output>;
|
|
128
|
+
task: Task;
|
|
129
|
+
ctx: ExecCtx;
|
|
130
|
+
/** Default 10. Hard cap on total iterations across all `plan()` rounds. */
|
|
131
|
+
maxIterations?: number;
|
|
132
|
+
/** Default 4. In-flight worker cap within a single `plan()` batch. */
|
|
133
|
+
maxConcurrency?: number;
|
|
134
|
+
/**
|
|
135
|
+
* Pre-allocated id for trace correlation. Default = `loop-${random}`.
|
|
136
|
+
* Surfaces as `runId` on every emitted `LoopTraceEvent`.
|
|
137
|
+
*/
|
|
138
|
+
runId?: string;
|
|
139
|
+
/**
|
|
140
|
+
* Clock override; default `Date.now`. Deterministic tests pass a
|
|
141
|
+
* monotonic counter to stabilize iteration timing fields.
|
|
142
|
+
*/
|
|
143
|
+
now?: () => number;
|
|
144
|
+
/**
|
|
145
|
+
* Override the default winner selector (highest-valid-score, ties broken
|
|
146
|
+
* by earliest iteration).
|
|
147
|
+
*/
|
|
148
|
+
selectWinner?: (iterations: Iteration<Task, Output>[]) => LoopWinner<Task, Output> | undefined;
|
|
149
|
+
}
|
|
150
|
+
/** @experimental */
|
|
151
|
+
declare function runLoop<Task, Output, Decision>(options: RunLoopOptions<Task, Output, Decision>): Promise<LoopResult<Task, Output, Decision>>;
|
|
152
|
+
|
|
153
|
+
export { AgentRunSpec, type CreateFanoutVoteDriverOptions, type CreateRefineDriverOptions, DefaultVerdict, Driver, ExecCtx, type FanoutVoteDecision, type FanoutVoteScored, Iteration, LoopResult, LoopWinner, OutputAdapter, type RefineDecision, type RunLoopOptions, Validator, createFanoutVoteDriver, createRefineDriver, refineWinnerIndex, runLoop, scoreFanoutVoteIterations };
|
package/dist/loops.js
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createFanoutVoteDriver,
|
|
3
|
+
scoreFanoutVoteIterations
|
|
4
|
+
} from "./chunk-XLWPTPRP.js";
|
|
5
|
+
import {
|
|
6
|
+
ValidationError
|
|
7
|
+
} from "./chunk-RZAOYKCO.js";
|
|
8
|
+
import "./chunk-DGUM43GV.js";
|
|
9
|
+
|
|
10
|
+
// src/loops/drivers/refine.ts
|
|
11
|
+
function createRefineDriver(options = {}) {
|
|
12
|
+
const maxIterations = options.maxIterations ?? 5;
|
|
13
|
+
if (!Number.isFinite(maxIterations) || maxIterations <= 0) {
|
|
14
|
+
throw new ValidationError("createRefineDriver: maxIterations must be > 0");
|
|
15
|
+
}
|
|
16
|
+
const refineTask = options.refineTask;
|
|
17
|
+
return {
|
|
18
|
+
name: options.name ?? "refine",
|
|
19
|
+
async plan(task, history) {
|
|
20
|
+
if (history.length >= maxIterations) return [];
|
|
21
|
+
if (history.length === 0) return [task];
|
|
22
|
+
const prior = history.at(-1);
|
|
23
|
+
if (!prior) return [task];
|
|
24
|
+
if (prior.verdict?.valid === true) return [];
|
|
25
|
+
if (!refineTask || !prior.verdict) return [prior.task];
|
|
26
|
+
return [refineTask(prior.task, prior.verdict)];
|
|
27
|
+
},
|
|
28
|
+
decide(history) {
|
|
29
|
+
const last = history.at(-1);
|
|
30
|
+
if (!last) return "continue";
|
|
31
|
+
if (last.verdict?.valid === true) return "stop";
|
|
32
|
+
if (history.length >= maxIterations) return "stop";
|
|
33
|
+
return "continue";
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function refineWinnerIndex(iterations) {
|
|
38
|
+
for (let i = iterations.length - 1; i >= 0; i -= 1) {
|
|
39
|
+
if (iterations[i]?.verdict?.valid) return i;
|
|
40
|
+
}
|
|
41
|
+
return iterations.length > 0 ? iterations.length - 1 : void 0;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// src/loops/run-loop.ts
|
|
45
|
+
var DEFAULT_MAX_ITERATIONS = 10;
|
|
46
|
+
var DEFAULT_MAX_CONCURRENCY = 4;
|
|
47
|
+
async function runLoop(options) {
|
|
48
|
+
const specs = resolveAgentRuns(options);
|
|
49
|
+
const maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
|
|
50
|
+
if (!Number.isFinite(maxIterations) || maxIterations <= 0) {
|
|
51
|
+
throw new ValidationError("runLoop: maxIterations must be > 0");
|
|
52
|
+
}
|
|
53
|
+
const maxConcurrency = options.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY;
|
|
54
|
+
if (!Number.isFinite(maxConcurrency) || maxConcurrency <= 0) {
|
|
55
|
+
throw new ValidationError("runLoop: maxConcurrency must be > 0");
|
|
56
|
+
}
|
|
57
|
+
if (!options.ctx?.sandboxClient || typeof options.ctx.sandboxClient.create !== "function") {
|
|
58
|
+
throw new ValidationError("runLoop: ctx.sandboxClient.create is required");
|
|
59
|
+
}
|
|
60
|
+
const now = options.now ?? Date.now;
|
|
61
|
+
const runId = options.runId ?? `loop-${randomSuffix()}`;
|
|
62
|
+
const loopStart = now();
|
|
63
|
+
const driverName = options.driver.name ?? "driver";
|
|
64
|
+
const iterations = [];
|
|
65
|
+
await emitTrace(options.ctx.traceEmitter, {
|
|
66
|
+
kind: "loop.started",
|
|
67
|
+
runId,
|
|
68
|
+
timestamp: now(),
|
|
69
|
+
payload: {
|
|
70
|
+
driver: driverName,
|
|
71
|
+
agentRunNames: specs.map((spec) => spec.name ?? spec.profile.name ?? "agent"),
|
|
72
|
+
maxIterations,
|
|
73
|
+
maxConcurrency
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
const controller = new AbortController();
|
|
77
|
+
const onOuterAbort = () => controller.abort();
|
|
78
|
+
if (options.ctx.signal) {
|
|
79
|
+
if (options.ctx.signal.aborted) controller.abort();
|
|
80
|
+
else options.ctx.signal.addEventListener("abort", onOuterAbort, { once: true });
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
while (iterations.length < maxIterations) {
|
|
84
|
+
if (controller.signal.aborted) throwAbort();
|
|
85
|
+
const planned = await options.driver.plan(options.task, iterations);
|
|
86
|
+
if (planned.length === 0) break;
|
|
87
|
+
const remaining = maxIterations - iterations.length;
|
|
88
|
+
const slice = planned.slice(0, remaining);
|
|
89
|
+
const baseIndex = iterations.length;
|
|
90
|
+
for (let i = 0; i < slice.length; i += 1) {
|
|
91
|
+
const spec = specs[(baseIndex + i) % specs.length];
|
|
92
|
+
iterations.push({
|
|
93
|
+
index: baseIndex + i,
|
|
94
|
+
task: slice[i],
|
|
95
|
+
agentRunName: spec.name ?? spec.profile.name ?? "agent",
|
|
96
|
+
events: [],
|
|
97
|
+
startedAt: now(),
|
|
98
|
+
endedAt: 0,
|
|
99
|
+
costUsd: 0
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
await runBatch({
|
|
103
|
+
slice,
|
|
104
|
+
baseIndex,
|
|
105
|
+
iterations,
|
|
106
|
+
specs,
|
|
107
|
+
output: options.output,
|
|
108
|
+
validator: options.validator,
|
|
109
|
+
maxConcurrency,
|
|
110
|
+
signal: controller.signal,
|
|
111
|
+
ctx: options.ctx,
|
|
112
|
+
runId,
|
|
113
|
+
now
|
|
114
|
+
});
|
|
115
|
+
if (controller.signal.aborted) throwAbort();
|
|
116
|
+
const decision2 = await options.driver.decide(iterations);
|
|
117
|
+
await emitTrace(options.ctx.traceEmitter, {
|
|
118
|
+
kind: "loop.decision",
|
|
119
|
+
runId,
|
|
120
|
+
timestamp: now(),
|
|
121
|
+
payload: { decision: serializeDecision(decision2), historyLength: iterations.length }
|
|
122
|
+
});
|
|
123
|
+
if (isTerminalDecision(decision2)) {
|
|
124
|
+
return finalize({
|
|
125
|
+
options,
|
|
126
|
+
decision: decision2,
|
|
127
|
+
iterations,
|
|
128
|
+
startMs: loopStart,
|
|
129
|
+
now,
|
|
130
|
+
runId
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (iterations.length >= maxIterations) {
|
|
135
|
+
const decision2 = await options.driver.decide(iterations);
|
|
136
|
+
await emitTrace(options.ctx.traceEmitter, {
|
|
137
|
+
kind: "loop.decision",
|
|
138
|
+
runId,
|
|
139
|
+
timestamp: now(),
|
|
140
|
+
payload: { decision: serializeDecision(decision2), historyLength: iterations.length }
|
|
141
|
+
});
|
|
142
|
+
return finalize({ options, decision: decision2, iterations, startMs: loopStart, now, runId });
|
|
143
|
+
}
|
|
144
|
+
const decision = await options.driver.decide(iterations);
|
|
145
|
+
await emitTrace(options.ctx.traceEmitter, {
|
|
146
|
+
kind: "loop.decision",
|
|
147
|
+
runId,
|
|
148
|
+
timestamp: now(),
|
|
149
|
+
payload: { decision: serializeDecision(decision), historyLength: iterations.length }
|
|
150
|
+
});
|
|
151
|
+
return finalize({ options, decision, iterations, startMs: loopStart, now, runId });
|
|
152
|
+
} finally {
|
|
153
|
+
if (options.ctx.signal) options.ctx.signal.removeEventListener("abort", onOuterAbort);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
async function runBatch(args) {
|
|
157
|
+
const queue = args.slice.map((task, offset) => ({ task, index: args.baseIndex + offset }));
|
|
158
|
+
const inflight = /* @__PURE__ */ new Set();
|
|
159
|
+
while (queue.length > 0 || inflight.size > 0) {
|
|
160
|
+
while (inflight.size < args.maxConcurrency && queue.length > 0) {
|
|
161
|
+
const item = queue.shift();
|
|
162
|
+
const p = executeIteration({ ...args, item }).finally(() => inflight.delete(p));
|
|
163
|
+
inflight.add(p);
|
|
164
|
+
}
|
|
165
|
+
if (inflight.size === 0) break;
|
|
166
|
+
await Promise.race(inflight);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async function executeIteration(args) {
|
|
170
|
+
const slot = args.iterations[args.item.index];
|
|
171
|
+
if (!slot)
|
|
172
|
+
throw new ValidationError(`runLoop: missing iteration slot at index ${args.item.index}`);
|
|
173
|
+
const spec = args.specs[args.item.index % args.specs.length];
|
|
174
|
+
if (!spec) throw new ValidationError("runLoop: no AgentRunSpec available for iteration");
|
|
175
|
+
slot.startedAt = args.now();
|
|
176
|
+
slot.agentRunName = spec.name ?? spec.profile.name ?? "agent";
|
|
177
|
+
await emitTrace(args.ctx.traceEmitter, {
|
|
178
|
+
kind: "loop.iteration.started",
|
|
179
|
+
runId: args.runId,
|
|
180
|
+
timestamp: args.now(),
|
|
181
|
+
payload: {
|
|
182
|
+
iterationIndex: args.item.index,
|
|
183
|
+
agentRunName: slot.agentRunName,
|
|
184
|
+
taskHash: hashJson(args.item.task)
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
try {
|
|
188
|
+
const box = await createSandboxForSpec(args.ctx.sandboxClient, spec, args.signal);
|
|
189
|
+
const message = spec.taskToPrompt(args.item.task);
|
|
190
|
+
const events = [];
|
|
191
|
+
for await (const event of box.streamPrompt(message, { signal: args.signal })) {
|
|
192
|
+
events.push(event);
|
|
193
|
+
const llmCall = extractLlmCallEvent(event, slot.agentRunName);
|
|
194
|
+
if (llmCall) {
|
|
195
|
+
slot.costUsd += llmCall.costUsd ?? 0;
|
|
196
|
+
args.ctx.runHandle?.observe(llmCall);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
slot.events = events;
|
|
200
|
+
slot.output = args.output.parse(events);
|
|
201
|
+
if (args.validator) {
|
|
202
|
+
slot.verdict = await args.validator.validate(slot.output, {
|
|
203
|
+
iteration: args.item.index,
|
|
204
|
+
signal: args.signal
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
} catch (err) {
|
|
208
|
+
slot.error = err instanceof Error ? err : new Error(String(err));
|
|
209
|
+
} finally {
|
|
210
|
+
slot.endedAt = args.now();
|
|
211
|
+
await emitTrace(args.ctx.traceEmitter, {
|
|
212
|
+
kind: "loop.iteration.ended",
|
|
213
|
+
runId: args.runId,
|
|
214
|
+
timestamp: args.now(),
|
|
215
|
+
payload: {
|
|
216
|
+
iterationIndex: args.item.index,
|
|
217
|
+
agentRunName: slot.agentRunName,
|
|
218
|
+
outputHash: slot.output !== void 0 ? hashJson(slot.output) : void 0,
|
|
219
|
+
verdict: slot.verdict,
|
|
220
|
+
error: slot.error?.message,
|
|
221
|
+
costUsd: slot.costUsd,
|
|
222
|
+
durationMs: slot.endedAt - slot.startedAt
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
async function createSandboxForSpec(client, spec, signal) {
|
|
228
|
+
const overrides = spec.sandboxOverrides ?? {};
|
|
229
|
+
const overrideBackend = overrides.backend;
|
|
230
|
+
const opts = {
|
|
231
|
+
...overrides,
|
|
232
|
+
backend: {
|
|
233
|
+
type: overrideBackend?.type ?? inferBackendType(spec.profile),
|
|
234
|
+
profile: spec.profile,
|
|
235
|
+
...overrideBackend?.model ? { model: overrideBackend.model } : {},
|
|
236
|
+
...overrideBackend?.server ? { server: overrideBackend.server } : {}
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
if (signal.aborted) throwAbort();
|
|
240
|
+
return client.create(opts);
|
|
241
|
+
}
|
|
242
|
+
function inferBackendType(profile) {
|
|
243
|
+
const explicit = profile.metadata?.backendType;
|
|
244
|
+
if (typeof explicit === "string") return explicit;
|
|
245
|
+
return "opencode";
|
|
246
|
+
}
|
|
247
|
+
function finalize(args) {
|
|
248
|
+
const winner = (args.options.selectWinner ?? defaultSelectWinner)(args.iterations);
|
|
249
|
+
const costUsd = args.iterations.reduce((sum, iter) => sum + (iter.costUsd || 0), 0);
|
|
250
|
+
const result = {
|
|
251
|
+
decision: args.decision,
|
|
252
|
+
iterations: args.iterations,
|
|
253
|
+
winner,
|
|
254
|
+
durationMs: args.now() - args.startMs,
|
|
255
|
+
costUsd
|
|
256
|
+
};
|
|
257
|
+
void emitTrace(args.options.ctx.traceEmitter, {
|
|
258
|
+
kind: "loop.ended",
|
|
259
|
+
runId: args.runId,
|
|
260
|
+
timestamp: args.now(),
|
|
261
|
+
payload: {
|
|
262
|
+
winnerIterationIndex: winner?.iterationIndex,
|
|
263
|
+
totalCostUsd: costUsd,
|
|
264
|
+
durationMs: result.durationMs,
|
|
265
|
+
iterations: args.iterations.length
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
return result;
|
|
269
|
+
}
|
|
270
|
+
function defaultSelectWinner(iterations) {
|
|
271
|
+
const candidates = iterations.filter((iter) => iter.output !== void 0 && !iter.error);
|
|
272
|
+
if (candidates.length === 0) return void 0;
|
|
273
|
+
const valid = candidates.filter((iter) => iter.verdict?.valid === true);
|
|
274
|
+
const pool = valid.length > 0 ? valid : candidates;
|
|
275
|
+
const sorted = [...pool].sort(
|
|
276
|
+
(a, b) => (b.verdict?.score ?? 0) - (a.verdict?.score ?? 0) || a.index - b.index
|
|
277
|
+
);
|
|
278
|
+
const top = sorted[0];
|
|
279
|
+
if (!top || top.output === void 0) return void 0;
|
|
280
|
+
return {
|
|
281
|
+
task: top.task,
|
|
282
|
+
output: top.output,
|
|
283
|
+
verdict: top.verdict,
|
|
284
|
+
iterationIndex: top.index,
|
|
285
|
+
agentRunName: top.agentRunName
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
function resolveAgentRuns(options) {
|
|
289
|
+
if (options.agentRun && options.agentRuns) {
|
|
290
|
+
throw new ValidationError("runLoop: pass exactly one of `agentRun` or `agentRuns`");
|
|
291
|
+
}
|
|
292
|
+
if (options.agentRun) return [options.agentRun];
|
|
293
|
+
if (options.agentRuns && options.agentRuns.length > 0) return options.agentRuns;
|
|
294
|
+
throw new ValidationError("runLoop: `agentRun` or non-empty `agentRuns` is required");
|
|
295
|
+
}
|
|
296
|
+
function isTerminalDecision(decision) {
|
|
297
|
+
return decision === "stop" || decision === "pick-winner" || decision === "fail" || decision === "done";
|
|
298
|
+
}
|
|
299
|
+
function serializeDecision(decision) {
|
|
300
|
+
if (typeof decision === "string") return decision;
|
|
301
|
+
if (decision === null || decision === void 0) return "null";
|
|
302
|
+
try {
|
|
303
|
+
return JSON.stringify(decision);
|
|
304
|
+
} catch {
|
|
305
|
+
return String(decision);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
async function emitTrace(emitter, event) {
|
|
309
|
+
if (!emitter) return;
|
|
310
|
+
await emitter.emit(event);
|
|
311
|
+
}
|
|
312
|
+
function randomSuffix(len = 8) {
|
|
313
|
+
return Math.random().toString(36).slice(2, 2 + len);
|
|
314
|
+
}
|
|
315
|
+
function throwAbort() {
|
|
316
|
+
const err = new Error("aborted");
|
|
317
|
+
err.name = "AbortError";
|
|
318
|
+
throw err;
|
|
319
|
+
}
|
|
320
|
+
function extractLlmCallEvent(event, agentRunName) {
|
|
321
|
+
if (!event || typeof event !== "object") return void 0;
|
|
322
|
+
const type = String(event.type ?? "");
|
|
323
|
+
const data = event.data && typeof event.data === "object" ? event.data : {};
|
|
324
|
+
if (type === "llm_call" || type === "cost.usage" || type === "usage") {
|
|
325
|
+
return buildLlmCall(data, agentRunName);
|
|
326
|
+
}
|
|
327
|
+
if (type === "message.completed" || type === "result" || type === "final") {
|
|
328
|
+
const usage = data.usage;
|
|
329
|
+
if (!usage || typeof usage !== "object") return void 0;
|
|
330
|
+
return buildLlmCall({ ...usage, model: data.model ?? usage.model }, agentRunName);
|
|
331
|
+
}
|
|
332
|
+
return void 0;
|
|
333
|
+
}
|
|
334
|
+
function buildLlmCall(data, agentRunName) {
|
|
335
|
+
const tokensIn = pickFiniteNumber(data, ["tokensIn", "inputTokens", "prompt_tokens"]);
|
|
336
|
+
const tokensOut = pickFiniteNumber(data, ["tokensOut", "outputTokens", "completion_tokens"]);
|
|
337
|
+
const costUsd = pickFiniteNumber(data, ["costUsd", "totalCostUsd", "cost_usd", "cost"]);
|
|
338
|
+
if (tokensIn === void 0 && tokensOut === void 0 && costUsd === void 0) {
|
|
339
|
+
return void 0;
|
|
340
|
+
}
|
|
341
|
+
const model = typeof data.model === "string" && data.model.length > 0 ? data.model : agentRunName;
|
|
342
|
+
const event = {
|
|
343
|
+
type: "llm_call",
|
|
344
|
+
model
|
|
345
|
+
};
|
|
346
|
+
if (tokensIn !== void 0) event.tokensIn = tokensIn;
|
|
347
|
+
if (tokensOut !== void 0) event.tokensOut = tokensOut;
|
|
348
|
+
if (costUsd !== void 0) event.costUsd = costUsd;
|
|
349
|
+
return event;
|
|
350
|
+
}
|
|
351
|
+
function pickFiniteNumber(data, keys) {
|
|
352
|
+
for (const key of keys) {
|
|
353
|
+
const value = data[key];
|
|
354
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
355
|
+
}
|
|
356
|
+
return void 0;
|
|
357
|
+
}
|
|
358
|
+
function hashJson(value) {
|
|
359
|
+
let str;
|
|
360
|
+
try {
|
|
361
|
+
str = JSON.stringify(value) ?? String(value);
|
|
362
|
+
} catch {
|
|
363
|
+
str = String(value);
|
|
364
|
+
}
|
|
365
|
+
let h = 2166136261;
|
|
366
|
+
for (let i = 0; i < str.length; i += 1) {
|
|
367
|
+
h ^= str.charCodeAt(i);
|
|
368
|
+
h = Math.imul(h, 16777619);
|
|
369
|
+
}
|
|
370
|
+
return (h >>> 0).toString(16).padStart(8, "0");
|
|
371
|
+
}
|
|
372
|
+
export {
|
|
373
|
+
createFanoutVoteDriver,
|
|
374
|
+
createRefineDriver,
|
|
375
|
+
refineWinnerIndex,
|
|
376
|
+
runLoop,
|
|
377
|
+
scoreFanoutVoteIterations
|
|
378
|
+
};
|
|
379
|
+
//# sourceMappingURL=loops.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/loops/drivers/refine.ts","../src/loops/run-loop.ts"],"sourcesContent":["/**\n * @experimental\n *\n * Refine driver — single task per iteration, validator-gated.\n *\n * `plan` returns `[task]` (possibly transformed via `refineTask`) until the\n * prior verdict is valid OR the local cap is hit, then `[]`.\n * `decide` returns `'stop'` once the latest verdict is valid OR the cap is\n * reached. The kernel's `maxIterations` is an orthogonal safety cap;\n * whichever is lower wins.\n */\n\nimport { ValidationError } from '../../errors'\nimport type { DefaultVerdict, Driver, Iteration } from '../types'\n\nexport type RefineDecision = 'continue' | 'stop'\n\n/** @experimental */\nexport interface CreateRefineDriverOptions<Task> {\n /** Hard cap on iterations. Default 5. */\n maxIterations?: number\n /**\n * Optional task transform applied each round based on the prior verdict.\n * When omitted, the same task is replayed and the agent is expected to\n * inspect the sandbox session state for prior attempts.\n */\n refineTask?: (task: Task, prior: DefaultVerdict) => Task\n /** Stable identifier surfaced in trace events. Default `'refine'`. */\n name?: string\n}\n\n/** @experimental */\nexport function createRefineDriver<Task, Output>(\n options: CreateRefineDriverOptions<Task> = {},\n): Driver<Task, Output, RefineDecision> {\n const maxIterations = options.maxIterations ?? 5\n if (!Number.isFinite(maxIterations) || maxIterations <= 0) {\n throw new ValidationError('createRefineDriver: maxIterations must be > 0')\n }\n const refineTask = options.refineTask\n return {\n name: options.name ?? 'refine',\n async plan(task, history) {\n if (history.length >= maxIterations) return []\n if (history.length === 0) return [task]\n const prior = history.at(-1)\n if (!prior) return [task]\n if (prior.verdict?.valid === true) return []\n // Worker error: replay the same task so the agent can self-correct.\n // The driver has no signal beyond `verdict`; only the validator\n // controls \"good enough\".\n if (!refineTask || !prior.verdict) return [prior.task]\n return [refineTask(prior.task, prior.verdict)]\n },\n decide(history) {\n const last = history.at(-1)\n if (!last) return 'continue'\n if (last.verdict?.valid === true) return 'stop'\n if (history.length >= maxIterations) return 'stop'\n return 'continue'\n },\n }\n}\n\n/**\n * Test helper: select the last-valid iteration (or the last attempt if\n * none passed). Mirrors the kernel's default selector ordering for refine\n * topologies — the most recent successful attempt wins.\n *\n * @experimental\n */\nexport function refineWinnerIndex<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n): number | undefined {\n for (let i = iterations.length - 1; i >= 0; i -= 1) {\n if (iterations[i]?.verdict?.valid) return i\n }\n return iterations.length > 0 ? iterations.length - 1 : undefined\n}\n","/**\n * @experimental\n *\n * `runLoop` — the topology-agnostic kernel built atop the sandbox SDK.\n *\n * Each iteration:\n * 1. `driver.plan(task, history)` → N tasks (1 = refine, N = fanout, 0 = stop)\n * 2. For each task (parallel, bounded by `maxConcurrency`):\n * a. round-robin an `AgentRunSpec` from `agentRuns`\n * b. `sandboxClient.create({ backend: { profile }, ...overrides })`\n * c. iterate `box.streamPrompt(taskToPrompt(task))` and collect events\n * 3. `output.parse(events)` → typed `Output`\n * 4. `validator?.validate(output)` → `DefaultVerdict`\n * 5. Append `Iteration` to history; emit `loop.iteration.ended`\n * 6. `driver.decide(history)` → if terminal, return result + winner\n *\n * The kernel owns: iteration accounting, per-iteration timing, error\n * capture, abort propagation, concurrency cap, cost aggregation, and trace\n * emission. The kernel does NOT own: what the agent runs (sandbox SDK +\n * profile), how outputs are decoded (output adapter), how outputs are\n * scored (validator), or topology (driver).\n */\n\nimport type {\n AgentProfile,\n CreateSandboxOptions,\n SandboxEvent,\n SandboxInstance,\n} from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport type { RuntimeStreamEvent } from '../types'\nimport type {\n AgentRunSpec,\n Driver,\n ExecCtx,\n Iteration,\n LoopResult,\n LoopSandboxClient,\n LoopTraceEmitter,\n LoopTraceEvent,\n LoopWinner,\n OutputAdapter,\n Validator,\n} from './types'\n\nconst DEFAULT_MAX_ITERATIONS = 10\nconst DEFAULT_MAX_CONCURRENCY = 4\n\n/** @experimental */\nexport interface RunLoopOptions<Task, Output, Decision> {\n driver: Driver<Task, Output, Decision>\n /**\n * Single agent spec — every iteration uses this profile. Mutually\n * exclusive with `agentRuns`.\n */\n agentRun?: AgentRunSpec<Task>\n /**\n * Multiple specs for heterogeneous fanout. The kernel round-robins\n * through them when the driver plans N tasks. Mutually exclusive with\n * `agentRun`.\n */\n agentRuns?: AgentRunSpec<Task>[]\n output: OutputAdapter<Output>\n validator?: Validator<Output>\n task: Task\n ctx: ExecCtx\n /** Default 10. Hard cap on total iterations across all `plan()` rounds. */\n maxIterations?: number\n /** Default 4. In-flight worker cap within a single `plan()` batch. */\n maxConcurrency?: number\n /**\n * Pre-allocated id for trace correlation. Default = `loop-${random}`.\n * Surfaces as `runId` on every emitted `LoopTraceEvent`.\n */\n runId?: string\n /**\n * Clock override; default `Date.now`. Deterministic tests pass a\n * monotonic counter to stabilize iteration timing fields.\n */\n now?: () => number\n /**\n * Override the default winner selector (highest-valid-score, ties broken\n * by earliest iteration).\n */\n selectWinner?: (iterations: Iteration<Task, Output>[]) => LoopWinner<Task, Output> | undefined\n}\n\n/** @experimental */\nexport async function runLoop<Task, Output, Decision>(\n options: RunLoopOptions<Task, Output, Decision>,\n): Promise<LoopResult<Task, Output, Decision>> {\n const specs = resolveAgentRuns(options)\n const maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS\n if (!Number.isFinite(maxIterations) || maxIterations <= 0) {\n throw new ValidationError('runLoop: maxIterations must be > 0')\n }\n const maxConcurrency = options.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY\n if (!Number.isFinite(maxConcurrency) || maxConcurrency <= 0) {\n throw new ValidationError('runLoop: maxConcurrency must be > 0')\n }\n if (!options.ctx?.sandboxClient || typeof options.ctx.sandboxClient.create !== 'function') {\n throw new ValidationError('runLoop: ctx.sandboxClient.create is required')\n }\n const now = options.now ?? Date.now\n const runId = options.runId ?? `loop-${randomSuffix()}`\n const loopStart = now()\n const driverName = options.driver.name ?? 'driver'\n const iterations: Iteration<Task, Output>[] = []\n\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.started',\n runId,\n timestamp: now(),\n payload: {\n driver: driverName,\n agentRunNames: specs.map((spec) => spec.name ?? spec.profile.name ?? 'agent'),\n maxIterations,\n maxConcurrency,\n },\n })\n\n const controller = new AbortController()\n const onOuterAbort = () => controller.abort()\n if (options.ctx.signal) {\n if (options.ctx.signal.aborted) controller.abort()\n else options.ctx.signal.addEventListener('abort', onOuterAbort, { once: true })\n }\n\n try {\n while (iterations.length < maxIterations) {\n if (controller.signal.aborted) throwAbort()\n const planned = await options.driver.plan(options.task, iterations)\n if (planned.length === 0) break\n\n const remaining = maxIterations - iterations.length\n const slice = planned.slice(0, remaining)\n const baseIndex = iterations.length\n // Reserve slots up front so concurrent workers may mutate by index.\n for (let i = 0; i < slice.length; i += 1) {\n const spec = specs[(baseIndex + i) % specs.length]!\n iterations.push({\n index: baseIndex + i,\n task: slice[i] as Task,\n agentRunName: spec.name ?? spec.profile.name ?? 'agent',\n events: [],\n startedAt: now(),\n endedAt: 0,\n costUsd: 0,\n })\n }\n\n await runBatch({\n slice,\n baseIndex,\n iterations,\n specs,\n output: options.output,\n validator: options.validator,\n maxConcurrency,\n signal: controller.signal,\n ctx: options.ctx,\n runId,\n now,\n })\n\n if (controller.signal.aborted) throwAbort()\n\n const decision = await options.driver.decide(iterations)\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.decision',\n runId,\n timestamp: now(),\n payload: { decision: serializeDecision(decision), historyLength: iterations.length },\n })\n if (isTerminalDecision(decision)) {\n return finalize({\n options,\n decision,\n iterations,\n startMs: loopStart,\n now,\n runId,\n })\n }\n }\n\n if (iterations.length >= maxIterations) {\n // Cap reached without a terminal decision — ask the driver one more time\n // for its final state, then close out.\n const decision = await options.driver.decide(iterations)\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.decision',\n runId,\n timestamp: now(),\n payload: { decision: serializeDecision(decision), historyLength: iterations.length },\n })\n return finalize({ options, decision, iterations, startMs: loopStart, now, runId })\n }\n // `plan()` returned `[]` before `decide()` reached a terminal state.\n const decision = await options.driver.decide(iterations)\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.decision',\n runId,\n timestamp: now(),\n payload: { decision: serializeDecision(decision), historyLength: iterations.length },\n })\n return finalize({ options, decision, iterations, startMs: loopStart, now, runId })\n } finally {\n if (options.ctx.signal) options.ctx.signal.removeEventListener('abort', onOuterAbort)\n }\n}\n\ninterface RunBatchArgs<Task, Output> {\n slice: Task[]\n baseIndex: number\n iterations: Iteration<Task, Output>[]\n specs: AgentRunSpec<Task>[]\n output: OutputAdapter<Output>\n validator: Validator<Output> | undefined\n maxConcurrency: number\n signal: AbortSignal\n ctx: ExecCtx\n runId: string\n now: () => number\n}\n\nasync function runBatch<Task, Output>(args: RunBatchArgs<Task, Output>) {\n const queue = args.slice.map((task, offset) => ({ task, index: args.baseIndex + offset }))\n const inflight = new Set<Promise<void>>()\n while (queue.length > 0 || inflight.size > 0) {\n while (inflight.size < args.maxConcurrency && queue.length > 0) {\n const item = queue.shift()!\n const p = executeIteration({ ...args, item }).finally(() => inflight.delete(p))\n inflight.add(p)\n }\n if (inflight.size === 0) break\n await Promise.race(inflight)\n }\n}\n\ninterface ExecuteIterationArgs<Task, Output> extends RunBatchArgs<Task, Output> {\n item: { task: Task; index: number }\n}\n\nasync function executeIteration<Task, Output>(args: ExecuteIterationArgs<Task, Output>) {\n const slot = args.iterations[args.item.index]\n if (!slot)\n throw new ValidationError(`runLoop: missing iteration slot at index ${args.item.index}`)\n const spec = args.specs[args.item.index % args.specs.length]\n if (!spec) throw new ValidationError('runLoop: no AgentRunSpec available for iteration')\n slot.startedAt = args.now()\n slot.agentRunName = spec.name ?? spec.profile.name ?? 'agent'\n\n await emitTrace(args.ctx.traceEmitter, {\n kind: 'loop.iteration.started',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n taskHash: hashJson(args.item.task),\n },\n })\n\n try {\n const box = await createSandboxForSpec(args.ctx.sandboxClient, spec, args.signal)\n const message = spec.taskToPrompt(args.item.task)\n const events: SandboxEvent[] = []\n for await (const event of box.streamPrompt(message, { signal: args.signal })) {\n events.push(event)\n const llmCall = extractLlmCallEvent(event, slot.agentRunName)\n if (llmCall) {\n slot.costUsd += llmCall.costUsd ?? 0\n args.ctx.runHandle?.observe(llmCall)\n }\n }\n slot.events = events\n slot.output = args.output.parse(events)\n if (args.validator) {\n slot.verdict = await args.validator.validate(slot.output, {\n iteration: args.item.index,\n signal: args.signal,\n })\n }\n } catch (err) {\n slot.error = err instanceof Error ? err : new Error(String(err))\n } finally {\n slot.endedAt = args.now()\n await emitTrace(args.ctx.traceEmitter, {\n kind: 'loop.iteration.ended',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n outputHash: slot.output !== undefined ? hashJson(slot.output) : undefined,\n verdict: slot.verdict,\n error: slot.error?.message,\n costUsd: slot.costUsd,\n durationMs: slot.endedAt - slot.startedAt,\n },\n })\n }\n}\n\nasync function createSandboxForSpec<Task>(\n client: LoopSandboxClient,\n spec: AgentRunSpec<Task>,\n signal: AbortSignal,\n): Promise<SandboxInstance> {\n const overrides = spec.sandboxOverrides ?? {}\n const overrideBackend = overrides.backend\n const opts: CreateSandboxOptions = {\n ...overrides,\n backend: {\n type: overrideBackend?.type ?? inferBackendType(spec.profile),\n profile: spec.profile satisfies AgentProfile,\n ...(overrideBackend?.model ? { model: overrideBackend.model } : {}),\n ...(overrideBackend?.server ? { server: overrideBackend.server } : {}),\n },\n }\n // Cooperative cancellation: if the abort signal fires while .create is\n // pending, the promise itself is not abortable but the inflight prompt is.\n if (signal.aborted) throwAbort()\n return client.create(opts)\n}\n\nfunction inferBackendType(\n profile: AgentProfile,\n): CreateSandboxOptions['backend'] extends infer B\n ? B extends { type: infer T }\n ? T\n : never\n : never {\n // The sandbox SDK accepts profile-driven backend selection by name. When the\n // profile has no explicit hint we fall through to the SDK's default\n // ('opencode' on the platform side). Returning a literal here would lie\n // about provenance — let the SDK pick.\n type BackendType = NonNullable<CreateSandboxOptions['backend']>['type']\n const explicit = profile.metadata?.backendType\n if (typeof explicit === 'string') return explicit as BackendType\n return 'opencode' as BackendType\n}\n\ninterface FinalizeArgs<Task, Output, Decision> {\n options: RunLoopOptions<Task, Output, Decision>\n decision: Decision\n iterations: Iteration<Task, Output>[]\n startMs: number\n now: () => number\n runId: string\n}\n\nfunction finalize<Task, Output, Decision>(\n args: FinalizeArgs<Task, Output, Decision>,\n): LoopResult<Task, Output, Decision> {\n const winner = (args.options.selectWinner ?? defaultSelectWinner)(args.iterations)\n const costUsd = args.iterations.reduce((sum, iter) => sum + (iter.costUsd || 0), 0)\n const result: LoopResult<Task, Output, Decision> = {\n decision: args.decision,\n iterations: args.iterations,\n winner,\n durationMs: args.now() - args.startMs,\n costUsd,\n }\n void emitTrace(args.options.ctx.traceEmitter, {\n kind: 'loop.ended',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n winnerIterationIndex: winner?.iterationIndex,\n totalCostUsd: costUsd,\n durationMs: result.durationMs,\n iterations: args.iterations.length,\n },\n })\n return result\n}\n\nfunction defaultSelectWinner<Task, Output>(\n iterations: Iteration<Task, Output>[],\n): LoopWinner<Task, Output> | undefined {\n const candidates = iterations.filter((iter) => iter.output !== undefined && !iter.error)\n if (candidates.length === 0) return undefined\n const valid = candidates.filter((iter) => iter.verdict?.valid === true)\n const pool = valid.length > 0 ? valid : candidates\n const sorted = [...pool].sort(\n (a, b) => (b.verdict?.score ?? 0) - (a.verdict?.score ?? 0) || a.index - b.index,\n )\n const top = sorted[0]\n if (!top || top.output === undefined) return undefined\n return {\n task: top.task,\n output: top.output,\n verdict: top.verdict,\n iterationIndex: top.index,\n agentRunName: top.agentRunName,\n }\n}\n\nfunction resolveAgentRuns<Task, Output, Decision>(\n options: RunLoopOptions<Task, Output, Decision>,\n): AgentRunSpec<Task>[] {\n if (options.agentRun && options.agentRuns) {\n throw new ValidationError('runLoop: pass exactly one of `agentRun` or `agentRuns`')\n }\n if (options.agentRun) return [options.agentRun]\n if (options.agentRuns && options.agentRuns.length > 0) return options.agentRuns\n throw new ValidationError('runLoop: `agentRun` or non-empty `agentRuns` is required')\n}\n\nfunction isTerminalDecision(decision: unknown): boolean {\n return (\n decision === 'stop' || decision === 'pick-winner' || decision === 'fail' || decision === 'done'\n )\n}\n\nfunction serializeDecision(decision: unknown): string {\n if (typeof decision === 'string') return decision\n if (decision === null || decision === undefined) return 'null'\n try {\n return JSON.stringify(decision)\n } catch {\n return String(decision)\n }\n}\n\nasync function emitTrace(\n emitter: LoopTraceEmitter | undefined,\n event: LoopTraceEvent,\n): Promise<void> {\n if (!emitter) return\n await emitter.emit(event)\n}\n\nfunction randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n\nfunction throwAbort(): never {\n const err = new Error('aborted')\n err.name = 'AbortError'\n throw err\n}\n\n/**\n * Extract a `RuntimeStreamEvent`-shaped `llm_call` from a sandbox event when\n * the event carries usage/cost data. Returns `undefined` for non-cost events\n * so the kernel can iterate the full stream without branching.\n *\n * Sandbox SDK emits a polymorphic `SandboxEvent = { type, data, id? }`. The\n * canonical cost-carrying types observed in the wild:\n * - `llm_call` — `data: { model, tokensIn, tokensOut, costUsd, ... }`\n * - `message.completed` / `result` — `data: { usage: { inputTokens,\n * outputTokens, totalCostUsd? } }`\n * - `cost.usage` — same shape under a dedicated type\n *\n * Numeric coercion is strict: `Number.isFinite` gates every accumulator\n * write so a sentinel `NaN` from a misbehaving backend cannot poison the\n * ledger.\n */\nfunction extractLlmCallEvent(\n event: SandboxEvent,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'llm_call' || type === 'cost.usage' || type === 'usage') {\n return buildLlmCall(data, agentRunName)\n }\n if (type === 'message.completed' || type === 'result' || type === 'final') {\n const usage = data.usage as Record<string, unknown> | undefined\n if (!usage || typeof usage !== 'object') return undefined\n return buildLlmCall({ ...usage, model: data.model ?? usage.model }, agentRunName)\n }\n return undefined\n}\n\nfunction buildLlmCall(\n data: Record<string, unknown>,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n const tokensIn = pickFiniteNumber(data, ['tokensIn', 'inputTokens', 'prompt_tokens'])\n const tokensOut = pickFiniteNumber(data, ['tokensOut', 'outputTokens', 'completion_tokens'])\n const costUsd = pickFiniteNumber(data, ['costUsd', 'totalCostUsd', 'cost_usd', 'cost'])\n if (tokensIn === undefined && tokensOut === undefined && costUsd === undefined) {\n return undefined\n }\n const model = typeof data.model === 'string' && data.model.length > 0 ? data.model : agentRunName\n const event: RuntimeStreamEvent & { type: 'llm_call' } = {\n type: 'llm_call',\n model,\n }\n if (tokensIn !== undefined) event.tokensIn = tokensIn\n if (tokensOut !== undefined) event.tokensOut = tokensOut\n if (costUsd !== undefined) event.costUsd = costUsd\n return event\n}\n\nfunction pickFiniteNumber(data: Record<string, unknown>, keys: string[]): number | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'number' && Number.isFinite(value)) return value\n }\n return undefined\n}\n\n/**\n * Stable hash for the trace payload. Not cryptographic — only used so\n * downstream eval pipelines can group iterations whose task / output is the\n * same. Bare structural hash; non-JSON values stringify via their `toString`.\n */\nfunction hashJson(value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(value) ?? String(value)\n } catch {\n str = String(value)\n }\n // FNV-1a 32-bit — branch-free, dependency-free, good enough for grouping.\n let h = 0x811c9dc5\n for (let i = 0; i < str.length; i += 1) {\n h ^= str.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return (h >>> 0).toString(16).padStart(8, '0')\n}\n"],"mappings":";;;;;;;;;;AAgCO,SAAS,mBACd,UAA2C,CAAC,GACN;AACtC,QAAM,gBAAgB,QAAQ,iBAAiB;AAC/C,MAAI,CAAC,OAAO,SAAS,aAAa,KAAK,iBAAiB,GAAG;AACzD,UAAM,IAAI,gBAAgB,+CAA+C;AAAA,EAC3E;AACA,QAAM,aAAa,QAAQ;AAC3B,SAAO;AAAA,IACL,MAAM,QAAQ,QAAQ;AAAA,IACtB,MAAM,KAAK,MAAM,SAAS;AACxB,UAAI,QAAQ,UAAU,cAAe,QAAO,CAAC;AAC7C,UAAI,QAAQ,WAAW,EAAG,QAAO,CAAC,IAAI;AACtC,YAAM,QAAQ,QAAQ,GAAG,EAAE;AAC3B,UAAI,CAAC,MAAO,QAAO,CAAC,IAAI;AACxB,UAAI,MAAM,SAAS,UAAU,KAAM,QAAO,CAAC;AAI3C,UAAI,CAAC,cAAc,CAAC,MAAM,Q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