@soiljs/agent 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2504 @@
1
+ import { AgentNotRegisteredError, LeaseLostError, ConcurrencyConflictError, isTerminalTurnStatus, toErrorRecord, isTerminalStepStatus, HostControlError, validateSchemaInput, CommandRejectedError, aggregateUsageTotals, IdempotencyConflictError, SessionBusyError } from '@soiljs/spi';
2
+ export * from '@soiljs/spi';
3
+ import { createHash, randomUUID } from 'crypto';
4
+ import { setTimeout as setTimeout$1 } from 'timers/promises';
5
+
6
+ // src/index.ts
7
+
8
+ // src/definitions/index.ts
9
+ function defineTool(definition) {
10
+ if (!definition.name || !definition.version)
11
+ throw new Error("Tool name and version are required.");
12
+ return Object.freeze({ ...definition });
13
+ }
14
+ function defineContextStrategy(definition) {
15
+ return Object.freeze({ ...definition });
16
+ }
17
+ function defineAgent(definition) {
18
+ if (!definition.id || !definition.version) throw new Error("Agent id and version are required.");
19
+ return Object.freeze({ ...definition });
20
+ }
21
+ function defineSubAgentTool(definition) {
22
+ return Object.freeze({ ...definition, version: definition.version ?? "1", kind: "sub_agent" });
23
+ }
24
+ function fingerprint(value) {
25
+ return JSON.stringify(value, (_key, item) => {
26
+ if (item && typeof item === "object" && !Array.isArray(item))
27
+ return Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b)));
28
+ return item;
29
+ });
30
+ }
31
+ function sameScope(a, b) {
32
+ return fingerprint(a ?? {}) === fingerprint(b ?? {});
33
+ }
34
+ var now = () => (/* @__PURE__ */ new Date()).toISOString();
35
+ function conflict() {
36
+ throw new ConcurrencyConflictError();
37
+ }
38
+ function memoryStorage() {
39
+ let state = {
40
+ sessions: /* @__PURE__ */ new Map(),
41
+ turns: /* @__PURE__ */ new Map(),
42
+ epochs: /* @__PURE__ */ new Map(),
43
+ queue: 0,
44
+ seq: 0,
45
+ events: [],
46
+ commands: /* @__PURE__ */ new Map(),
47
+ admissions: /* @__PURE__ */ new Map()
48
+ };
49
+ const blobs = /* @__PURE__ */ new Map();
50
+ const cursors = /* @__PURE__ */ new Map();
51
+ let gapReason = "retention_ttl";
52
+ function transaction(fn) {
53
+ const previous = structuredClone(state);
54
+ try {
55
+ const result = structuredClone(fn());
56
+ state = structuredClone(state);
57
+ return Promise.resolve(result);
58
+ } catch (error) {
59
+ state = previous;
60
+ return Promise.reject(error);
61
+ }
62
+ }
63
+ function get(id2) {
64
+ const value = state.turns.get(id2);
65
+ if (!value) throw new Error(`Turn ${id2} not found.`);
66
+ return value;
67
+ }
68
+ function session(id2) {
69
+ const value = state.sessions.get(id2);
70
+ if (!value) throw new Error(`Session ${id2} not found.`);
71
+ return value;
72
+ }
73
+ function fence(input) {
74
+ const snap = get(input.turnId);
75
+ const lease = snap.turn.lease;
76
+ if (!lease || lease.holderId !== input.lease.holderId || lease.epoch !== input.lease.epoch || Date.parse(lease.expiresAt) <= Date.now())
77
+ throw new LeaseLostError();
78
+ return snap;
79
+ }
80
+ function event(turn, type, data, step) {
81
+ const seq = ++state.seq;
82
+ state.events.push({
83
+ type,
84
+ seq,
85
+ eventId: `event_${seq}`,
86
+ occurredAt: now(),
87
+ sessionId: turn.sessionId,
88
+ turnId: turn.turnId,
89
+ rootTurnId: turn.rootTurnId,
90
+ ...turn.scope ? { scope: turn.scope } : {},
91
+ ...turn.parentTurnId ? { parentTurnId: turn.parentTurnId } : {},
92
+ traceId: turn.rootTurnId,
93
+ spanId: step?.stepId ?? turn.turnId,
94
+ ...step ? { stepId: step.stepId } : {},
95
+ data: {
96
+ agentId: turn.agentId,
97
+ agentVersion: turn.agentVersion,
98
+ iteration: step?.iteration ?? turn.iteration,
99
+ ...step ? {
100
+ kind: step.kind,
101
+ status: step.status,
102
+ toolName: step.toolName,
103
+ approvalId: step.approvalId,
104
+ ...type === "step.completed" && (step.kind === "model_call" || step.kind === "compaction") ? {
105
+ ...step.usage ? { usage: step.usage } : {},
106
+ ...step.protocolId ? { protocolId: step.protocolId } : {},
107
+ ...step.modelId ? { modelId: step.modelId } : {}
108
+ } : {}
109
+ } : {},
110
+ ...data
111
+ }
112
+ });
113
+ }
114
+ function touch(turn) {
115
+ turn.version++;
116
+ turn.updatedAt = now();
117
+ }
118
+ function claim(turn, request) {
119
+ if (turn.lease && Date.parse(turn.lease.expiresAt) > Date.now()) conflict();
120
+ if (isTerminalTurnStatus(turn.status) || turn.status === "queued") conflict();
121
+ const epoch = (state.epochs.get(turn.turnId) ?? 0) + 1;
122
+ state.epochs.set(turn.turnId, epoch);
123
+ const lease = {
124
+ holderId: request.holderId,
125
+ epoch,
126
+ expiresAt: new Date(Date.now() + request.ttlMs).toISOString()
127
+ };
128
+ turn.lease = lease;
129
+ turn.status = "running";
130
+ turn.wakeRequested = false;
131
+ touch(turn);
132
+ return lease;
133
+ }
134
+ function ordered(snap, step) {
135
+ if (snap.turn.completionIntent) conflict();
136
+ if (snap.turn.toolExecution === "sequential" && snap.steps.some((s) => s.stepSeq < step.stepSeq && !isTerminalStepStatus(s.status)))
137
+ conflict();
138
+ }
139
+ function terminate(snap, step) {
140
+ if (!step.terminatesTurn || step.status !== "completed") return;
141
+ if (snap.turn.toolExecution !== "sequential") conflict();
142
+ snap.turn.completionIntent = { stepId: step.stepId, output: step.output ?? null };
143
+ for (const sibling of snap.steps)
144
+ if (sibling.iteration === step.iteration && sibling.stepSeq > step.stepSeq && (sibling.status === "pending" || sibling.status === "awaiting_approval"))
145
+ terminalStep(snap, sibling, "skipped", "tool_terminated");
146
+ touch(snap.turn);
147
+ }
148
+ function recompute(snap) {
149
+ const turn = snap.turn;
150
+ if (isTerminalTurnStatus(turn.status) || turn.status === "queued") return;
151
+ const eligible = snap.turn.toolExecution === "sequential" ? snap.steps.filter((s) => !isTerminalStepStatus(s.status)).slice(0, 1) : snap.steps;
152
+ const local = eligible.some((s) => s.status === "pending" || s.status === "running");
153
+ const blocker = eligible.some((s) => s.status === "unknown") ? "waiting_resolution" : eligible.some((s) => s.status === "awaiting_approval") ? "waiting_approval" : eligible.some((s) => s.status === "waiting_child") ? "waiting_child" : void 0;
154
+ if (local || !blocker) {
155
+ turn.wakeRequested = !turn.lease;
156
+ touch(turn);
157
+ return;
158
+ }
159
+ const changed = turn.status !== blocker || turn.lease !== void 0;
160
+ turn.status = blocker;
161
+ delete turn.lease;
162
+ turn.wakeRequested = false;
163
+ touch(turn);
164
+ if (changed) event(turn, "turn.paused", { reason: blocker });
165
+ }
166
+ function admit(input) {
167
+ const owner = session(input.sessionId);
168
+ const key = fingerprint([owner.scope, input.sessionId, input.idempotencyKey]);
169
+ const fp = fingerprint({
170
+ input: input.input,
171
+ context: input.context,
172
+ limits: input.limits,
173
+ toolExecution: input.toolExecution,
174
+ mode: input.mode
175
+ });
176
+ const previous = input.idempotencyKey ? state.admissions.get(key) : void 0;
177
+ if (previous) {
178
+ if (previous.fingerprint !== fp) throw new IdempotencyConflictError();
179
+ return { turn: get(previous.turnId).turn, duplicate: true };
180
+ }
181
+ if (state.turns.has(input.turnId)) conflict();
182
+ if (owner.activeTurnId && input.mode === "reject")
183
+ throw new SessionBusyError(owner.activeTurnId);
184
+ const queued = owner.activeTurnId !== void 0;
185
+ const timestamp = now();
186
+ const turn = {
187
+ turnId: input.turnId,
188
+ sessionId: owner.sessionId,
189
+ agentId: owner.agentId,
190
+ agentVersion: owner.agentVersion,
191
+ ...owner.scope ? { scope: owner.scope } : {},
192
+ input: input.input,
193
+ context: { ...owner.context, ...input.context },
194
+ status: queued ? "queued" : "running",
195
+ iteration: 0,
196
+ ...queued ? { queueSeq: ++state.queue } : {},
197
+ ...input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {},
198
+ ...input.limits ? { limits: input.limits } : {},
199
+ ...input.toolExecution ? { toolExecution: input.toolExecution } : {},
200
+ rootTurnId: input.turnId,
201
+ depth: 0,
202
+ wakeRequested: false,
203
+ createdAt: timestamp,
204
+ updatedAt: timestamp,
205
+ version: 1
206
+ };
207
+ state.turns.set(turn.turnId, { turn, steps: [], attempts: [], steering: [], approvals: [] });
208
+ const lease = queued ? void 0 : claim(turn, input.lease);
209
+ if (!queued) owner.activeTurnId = turn.turnId;
210
+ owner.version++;
211
+ owner.updatedAt = timestamp;
212
+ if (input.idempotencyKey) state.admissions.set(key, { fingerprint: fp, turnId: turn.turnId });
213
+ event(turn, queued ? "turn.queued" : "turn.started");
214
+ return { turn, ...lease ? { lease } : {}, duplicate: false };
215
+ }
216
+ function addStep(snap, input, iteration) {
217
+ if (snap.steps.some((s) => s.stepId === input.stepId)) conflict();
218
+ const step = {
219
+ ...input,
220
+ turnId: snap.turn.turnId,
221
+ iteration,
222
+ stepSeq: snap.steps.length + 1,
223
+ status: input.status ?? "pending",
224
+ createdAt: now(),
225
+ version: 1
226
+ };
227
+ snap.steps.push(step);
228
+ return step;
229
+ }
230
+ function doneStep(snap, input, kind, iteration) {
231
+ if (input.continuationArtifact && !input.artifacts?.some((ref) => ref.sha256 === input.continuationArtifact.sha256))
232
+ input = { ...input, artifacts: [...input.artifacts ?? [], input.continuationArtifact] };
233
+ let step = snap.steps.find((s) => s.stepId === input.stepId);
234
+ if (step && (isTerminalStepStatus(step.status) || step.kind !== kind)) conflict();
235
+ step ??= addStep(
236
+ snap,
237
+ {
238
+ stepId: input.stepId,
239
+ operationKey: input.operationKey,
240
+ kind,
241
+ ...input.input !== void 0 ? { input: input.input } : {}
242
+ },
243
+ iteration
244
+ );
245
+ let attempt = snap.attempts.find(
246
+ (a) => a.stepId === step.stepId && a.attemptNo === input.attemptNo
247
+ );
248
+ if (attempt && attempt.status !== "running") conflict();
249
+ if (!attempt) {
250
+ attempt = {
251
+ turnId: snap.turn.turnId,
252
+ stepId: step.stepId,
253
+ attemptNo: input.attemptNo,
254
+ kind: "execute",
255
+ status: "running",
256
+ holderId: snap.turn.lease.holderId,
257
+ leaseEpoch: snap.turn.lease.epoch,
258
+ startedAt: now()
259
+ };
260
+ snap.attempts.push(attempt);
261
+ }
262
+ Object.assign(
263
+ step,
264
+ { status: "completed", output: input.output, completedAt: now(), version: step.version + 1 },
265
+ input.input !== void 0 ? { input: input.input } : {},
266
+ input.protocolId !== void 0 ? { protocolId: input.protocolId } : {},
267
+ input.modelId !== void 0 ? { modelId: input.modelId } : {},
268
+ input.continuation !== void 0 ? { continuation: input.continuation } : {},
269
+ input.continuationArtifact !== void 0 ? { continuationArtifact: input.continuationArtifact } : {},
270
+ input.usage ? { usage: input.usage } : {},
271
+ input.artifacts ? { artifacts: input.artifacts } : {}
272
+ );
273
+ Object.assign(
274
+ attempt,
275
+ { status: "succeeded", output: input.output, completedAt: now() },
276
+ input.usage ? { usage: input.usage } : {},
277
+ input.artifacts ? { artifacts: input.artifacts } : {}
278
+ );
279
+ event(snap.turn, "step.completed", void 0, step);
280
+ return step;
281
+ }
282
+ function terminalStep(snap, step, status, reason) {
283
+ step.status = status;
284
+ step.output = { status, reason };
285
+ step.completedAt = now();
286
+ step.version++;
287
+ event(
288
+ snap.turn,
289
+ status === "failed" ? "step.failed" : "step.completed",
290
+ { reason, error: step.error },
291
+ step
292
+ );
293
+ const approval = snap.approvals.find((a) => a.stepId === step.stepId && a.status === "pending");
294
+ if (approval) {
295
+ approval.status = "rejected";
296
+ approval.reason = reason;
297
+ approval.resolvedAt = now();
298
+ event(snap.turn, "step.approval_resolved", { reason }, step);
299
+ }
300
+ }
301
+ function steer(input) {
302
+ const snap = get(input.turnId);
303
+ if (isTerminalTurnStatus(snap.turn.status)) {
304
+ if (!input.fallbackToNewTurn) return { accepted: false, reason: "turn_already_terminal" };
305
+ const next = admit({
306
+ sessionId: snap.turn.sessionId,
307
+ turnId: input.fallback.turnId,
308
+ input: input.input,
309
+ mode: "follow_up",
310
+ lease: input.fallback.lease,
311
+ context: { ...snap.turn.context },
312
+ ...snap.turn.toolExecution ? { toolExecution: snap.turn.toolExecution } : {},
313
+ ...snap.turn.limits ? { limits: { ...snap.turn.limits } } : {}
314
+ });
315
+ return { accepted: true, mode: "promoted_to_turn", turnId: next.turn.turnId };
316
+ }
317
+ if (snap.turn.status === "queued") conflict();
318
+ if (!snap.steering.some((s) => s.steeringId === input.steeringId)) {
319
+ snap.steering.push({
320
+ steeringId: input.steeringId,
321
+ turnId: input.turnId,
322
+ input: input.input,
323
+ urgency: input.urgency ?? "next_iteration",
324
+ supersedeApprovals: input.supersedeApprovals ?? true,
325
+ status: "pending",
326
+ createdAt: now()
327
+ });
328
+ for (const step of snap.steps) {
329
+ if (step.status === "pending" && (step.kind === "tool_exec" || step.kind === "sub_turn"))
330
+ terminalStep(snap, step, "skipped", "superseded_by_steering");
331
+ if (step.status === "awaiting_approval" && (input.supersedeApprovals ?? true))
332
+ terminalStep(snap, step, "rejected", "superseded_by_steering");
333
+ }
334
+ event(snap.turn, "steering.queued", { steeringId: input.steeringId });
335
+ recompute(snap);
336
+ }
337
+ return { accepted: true, mode: "steered", turnId: input.turnId };
338
+ }
339
+ function finish(input) {
340
+ const snap = fence(input);
341
+ const turn = snap.turn;
342
+ if (isTerminalTurnStatus(turn.status)) conflict();
343
+ if (input.status === "completed" && snap.steps.some((s) => !isTerminalStepStatus(s.status)))
344
+ conflict();
345
+ const previousLease = turn.lease;
346
+ Object.assign(
347
+ turn,
348
+ {
349
+ status: input.status,
350
+ completedAt: now(),
351
+ wakeRequested: false,
352
+ stopReason: input.stopReason ?? (input.status === "completed" ? "end_turn" : input.status === "cancelled" ? "cancelled" : "error"),
353
+ ...input.providerFinishReason ? { providerFinishReason: input.providerFinishReason } : {},
354
+ ...input.partial !== void 0 ? { partial: input.partial } : {}
355
+ },
356
+ input.output !== void 0 ? { output: input.output } : {},
357
+ input.error ? { error: input.error } : {},
358
+ input.artifacts ? { artifacts: input.artifacts } : {}
359
+ );
360
+ delete turn.lease;
361
+ touch(turn);
362
+ const owner = session(turn.sessionId);
363
+ if (owner.activeTurnId === turn.turnId) delete owner.activeTurnId;
364
+ event(turn, `turn.${input.status}`, {
365
+ stopReason: turn.stopReason,
366
+ providerFinishReason: turn.providerFinishReason,
367
+ partial: turn.partial,
368
+ error: turn.error
369
+ });
370
+ const queue = [...state.turns.values()].map((s) => s.turn).filter((t) => t.sessionId === turn.sessionId && t.status === "queued").sort((a, b) => a.queueSeq - b.queueSeq);
371
+ if (input.drainQueued === "cancel")
372
+ for (const queued of queue) cancel(get(queued.turnId), "queue_drained", false);
373
+ const next = input.status === "completed" && input.drainQueued !== "cancel" ? queue[0] : void 0;
374
+ if (next) {
375
+ next.status = "running";
376
+ const nextLease = claim(
377
+ next,
378
+ input.nextLease ?? {
379
+ holderId: previousLease.holderId,
380
+ ttlMs: Math.max(1, Date.parse(previousLease.expiresAt) - Date.now())
381
+ }
382
+ );
383
+ owner.activeTurnId = next.turnId;
384
+ event(next, "turn.started");
385
+ owner.version++;
386
+ return { turn, nextTurn: next, nextLease };
387
+ }
388
+ owner.version++;
389
+ return { turn };
390
+ }
391
+ function backwrite(child, modelOutput) {
392
+ const parent = get(child.turn.parentTurnId);
393
+ const step = parent.steps.find((s) => s.stepId === child.turn.parentStepId);
394
+ if (!isTerminalStepStatus(step.status)) {
395
+ step.status = child.turn.status === "completed" ? "completed" : child.turn.status === "cancelled" ? "cancelled" : "failed";
396
+ step.output = child.turn.output ?? { status: child.turn.status, error: child.turn.error };
397
+ if (modelOutput !== void 0) step.modelOutput = modelOutput;
398
+ step.completedAt = now();
399
+ step.version++;
400
+ const attempt = [...parent.attempts].reverse().find((a) => a.stepId === step.stepId && a.status === "running");
401
+ if (attempt) {
402
+ attempt.status = step.status === "completed" ? "succeeded" : step.status === "cancelled" ? "cancelled" : "failed";
403
+ attempt.output = step.output;
404
+ if (modelOutput !== void 0) attempt.modelOutput = modelOutput;
405
+ attempt.completedAt = now();
406
+ }
407
+ event(
408
+ parent.turn,
409
+ step.status === "completed" ? "step.completed" : "step.failed",
410
+ void 0,
411
+ step
412
+ );
413
+ recompute(parent);
414
+ }
415
+ return { child: child.turn, parent: parent.turn, parentStep: step };
416
+ }
417
+ function cancel(snap, reason, cascade = true) {
418
+ if (isTerminalTurnStatus(snap.turn.status) || snap.turn.completionIntent) return;
419
+ for (const step of snap.steps) {
420
+ if (isTerminalStepStatus(step.status) || step.status === "unknown") continue;
421
+ if (step.status === "running" && step.effect === "external") {
422
+ step.status = "unknown";
423
+ step.version++;
424
+ step.error = { code: "CANCELLED_UNCONFIRMED", message: reason };
425
+ event(snap.turn, "step.unknown", { reason }, step);
426
+ } else terminalStep(snap, step, "cancelled", reason);
427
+ for (const attempt of snap.attempts.filter(
428
+ (a) => a.stepId === step.stepId && a.status === "running"
429
+ )) {
430
+ attempt.status = step.status === "unknown" ? "unknown" : "cancelled";
431
+ attempt.completedAt = now();
432
+ }
433
+ }
434
+ snap.turn.status = "cancelled";
435
+ snap.turn.stopReason = "cancelled";
436
+ snap.turn.completedAt = now();
437
+ snap.turn.wakeRequested = false;
438
+ delete snap.turn.lease;
439
+ touch(snap.turn);
440
+ const owner = session(snap.turn.sessionId);
441
+ if (owner.activeTurnId === snap.turn.turnId) delete owner.activeTurnId;
442
+ event(snap.turn, "turn.cancelled", { reason, stopReason: "cancelled" });
443
+ if (cascade) {
444
+ for (const child of state.turns.values())
445
+ if (child.turn.parentTurnId === snap.turn.turnId && child.turn.propagation?.cancelWithParent !== false)
446
+ cancel(child, reason);
447
+ }
448
+ if (snap.turn.parentTurnId) backwrite(snap);
449
+ }
450
+ const ledger = {
451
+ createSession: (input) => transaction(() => {
452
+ if (state.sessions.has(input.sessionId)) conflict();
453
+ const owner = {
454
+ ...input,
455
+ context: input.context ?? {},
456
+ createdAt: now(),
457
+ updatedAt: now(),
458
+ version: 1
459
+ };
460
+ state.sessions.set(input.sessionId, owner);
461
+ event(
462
+ {
463
+ sessionId: input.sessionId,
464
+ turnId: "",
465
+ rootTurnId: "",
466
+ ...input.scope ? { scope: input.scope } : {}
467
+ },
468
+ "session.created",
469
+ { agentId: input.agentId, agentVersion: input.agentVersion }
470
+ );
471
+ return owner;
472
+ }),
473
+ getSession: async (id2, scope) => {
474
+ const value = state.sessions.get(id2);
475
+ return structuredClone(value && (!scope || sameScope(value.scope, scope)) ? value : null);
476
+ },
477
+ listSessionTurns: async (sessionId, options) => structuredClone(
478
+ [...state.turns.values()].map((snapshot) => snapshot.turn).filter(
479
+ (turn) => turn.sessionId === sessionId && (!options?.scope || sameScope(turn.scope, options.scope))
480
+ ).slice(0, options?.limit ?? Infinity)
481
+ ),
482
+ admitTurn: (input) => transaction(() => admit(input)),
483
+ enqueueSteering: (input) => transaction(() => steer(input)),
484
+ consumeSteeringAndRecord: (input) => transaction(() => {
485
+ const snap = fence(input);
486
+ const pending = snap.steering.filter((s) => s.status === "pending");
487
+ if (!pending.length) return null;
488
+ const step = addStep(
489
+ snap,
490
+ {
491
+ stepId: input.stepId,
492
+ operationKey: input.operationKey,
493
+ kind: "steering_input",
494
+ input: pending.map((s) => s.input)
495
+ },
496
+ input.iteration
497
+ );
498
+ step.status = "completed";
499
+ step.output = pending.map((s) => s.input);
500
+ step.completedAt = now();
501
+ for (const entry of pending) {
502
+ entry.status = "consumed";
503
+ entry.consumedAt = now();
504
+ entry.consumedByStepId = step.stepId;
505
+ }
506
+ event(
507
+ snap.turn,
508
+ "steering.applied",
509
+ { steeringIds: pending.map((s) => s.steeringId) },
510
+ step
511
+ );
512
+ return step;
513
+ }),
514
+ commitCompactionStep: (input) => transaction(() => {
515
+ const snap = fence(input);
516
+ const step = doneStep(snap, input.step, "compaction", input.iteration);
517
+ snap.turn.compactionCursorStepId = input.compactedUpToStepId;
518
+ session(snap.turn.sessionId).compactionCursorStepId = input.compactedUpToStepId;
519
+ event(
520
+ snap.turn,
521
+ "compaction.committed",
522
+ { compactedUpToStepId: input.compactedUpToStepId },
523
+ step
524
+ );
525
+ return step;
526
+ }),
527
+ commitModelAndDispatchSteps: (input) => transaction(() => {
528
+ const snap = fence(input);
529
+ if (input.iteration <= snap.turn.iteration || snap.steps.some((s) => !isTerminalStepStatus(s.status) && s.stepId !== input.model.stepId))
530
+ conflict();
531
+ doneStep(snap, input.model, "model_call", input.iteration);
532
+ snap.turn.iteration = input.iteration;
533
+ for (const child of input.steps) {
534
+ if (child.terminatesTurn && snap.turn.toolExecution !== "sequential") conflict();
535
+ const step = addStep(snap, child, input.iteration);
536
+ event(snap.turn, "step.dispatched", void 0, step);
537
+ if (step.status === "awaiting_approval") {
538
+ if (!step.approvalId) conflict();
539
+ snap.approvals.push({
540
+ approvalId: step.approvalId,
541
+ sessionId: snap.turn.sessionId,
542
+ turnId: input.turnId,
543
+ rootTurnId: snap.turn.rootTurnId,
544
+ ...snap.turn.parentTurnId ? { parentTurnId: snap.turn.parentTurnId } : {},
545
+ stepId: step.stepId,
546
+ status: "pending",
547
+ createdAt: now()
548
+ });
549
+ event(snap.turn, "step.approval_requested", { approvalId: step.approvalId }, step);
550
+ }
551
+ }
552
+ recompute(snap);
553
+ return snap;
554
+ }),
555
+ prepareToolStep: (input) => transaction(() => {
556
+ const snap = fence(input);
557
+ const step = snap.steps.find((s) => s.stepId === input.stepId);
558
+ if (!step || step.status !== "pending" || step.prepared || step.version !== input.expectedStepVersion)
559
+ conflict();
560
+ ordered(snap, step);
561
+ step.prepared = true;
562
+ step.validatedInput = input.validatedInput;
563
+ step.version++;
564
+ if (input.error) {
565
+ step.error = input.error;
566
+ terminalStep(snap, step, "failed", input.error.message);
567
+ } else if (input.approvalId) {
568
+ step.status = "awaiting_approval";
569
+ step.approvalId = input.approvalId;
570
+ snap.approvals.push({
571
+ approvalId: input.approvalId,
572
+ sessionId: snap.turn.sessionId,
573
+ rootTurnId: snap.turn.rootTurnId,
574
+ ...snap.turn.parentTurnId ? { parentTurnId: snap.turn.parentTurnId } : {},
575
+ turnId: snap.turn.turnId,
576
+ stepId: step.stepId,
577
+ status: "pending",
578
+ createdAt: now()
579
+ });
580
+ event(snap.turn, "step.approval_requested", { approvalId: input.approvalId }, step);
581
+ }
582
+ recompute(snap);
583
+ return step;
584
+ }),
585
+ skipSteps: (input) => transaction(() => {
586
+ const snap = fence(input);
587
+ for (const step of snap.steps)
588
+ if (input.stepIds.includes(step.stepId) && (step.status === "pending" || step.status === "awaiting_approval"))
589
+ terminalStep(snap, step, "skipped", input.reason);
590
+ recompute(snap);
591
+ }),
592
+ reserveModelCall: (input) => transaction(() => {
593
+ const snap = fence(input);
594
+ const attempt = snap.attempts.find(
595
+ (a) => a.stepId === input.stepId && a.attemptNo === input.attemptNo && a.status === "running"
596
+ );
597
+ if (!attempt) conflict();
598
+ const count = snap.attempts.reduce(
599
+ (n, a) => n + (a.modelCalls ?? (snap.steps.find((s) => s.stepId === a.stepId)?.kind === "model_call" ? 1 : 0)),
600
+ 0
601
+ );
602
+ if (count >= (snap.turn.limits?.maxModelCalls ?? Infinity)) return false;
603
+ attempt.modelCalls = (attempt.modelCalls ?? 0) + 1;
604
+ return true;
605
+ }),
606
+ startStepAttempt: (input) => transaction(() => {
607
+ const snap = fence(input);
608
+ let step = snap.steps.find((s) => s.stepId === input.stepId);
609
+ if (!step && input.newStep) step = addStep(snap, input.newStep, input.newStep.iteration);
610
+ if (!step || isTerminalStepStatus(step.status) || step.status === "awaiting_approval" || step.status === "waiting_child" || input.expectedStepVersion !== void 0 && input.expectedStepVersion !== step.version)
611
+ conflict();
612
+ ordered(snap, step);
613
+ if (input.kind === "execute" && (step.kind === "tool_exec" || step.kind === "sub_turn")) {
614
+ const count = snap.attempts.filter(
615
+ (a) => a.kind === "execute" && snap.steps.some(
616
+ (s) => s.stepId === a.stepId && (s.kind === "tool_exec" || s.kind === "sub_turn")
617
+ )
618
+ ).length;
619
+ if (count >= (snap.turn.limits?.maxToolCalls ?? Infinity))
620
+ throw new HostControlError({
621
+ code: "MAX_TOOL_CALLS",
622
+ message: "Tool call limit reached.",
623
+ requestStage: "admission_rejected"
624
+ });
625
+ }
626
+ if (step.status === "unknown" && input.kind !== "reconcile") conflict();
627
+ for (const previous of snap.attempts.filter(
628
+ (a) => a.stepId === step.stepId && a.status === "running"
629
+ )) {
630
+ if (previous.leaseEpoch === input.lease.epoch) conflict();
631
+ previous.status = "unknown";
632
+ previous.completedAt = now();
633
+ previous.error = { code: "LEASE_EXPIRED", message: "Previous lease expired." };
634
+ }
635
+ const attempt = {
636
+ turnId: input.turnId,
637
+ stepId: step.stepId,
638
+ attemptNo: snap.attempts.filter((a) => a.stepId === step.stepId).length + 1,
639
+ kind: input.kind,
640
+ modelCalls: 0,
641
+ status: "running",
642
+ holderId: input.lease.holderId,
643
+ leaseEpoch: input.lease.epoch,
644
+ startedAt: now()
645
+ };
646
+ snap.attempts.push(attempt);
647
+ step.status = "running";
648
+ step.version++;
649
+ return { step, attempt };
650
+ }),
651
+ completeStep: (input) => transaction(() => {
652
+ const snap = fence(input);
653
+ const step = snap.steps.find((s) => s.stepId === input.stepId);
654
+ const attempt = snap.attempts.find(
655
+ (a) => a.stepId === input.stepId && a.attemptNo === input.attemptNo
656
+ );
657
+ if (!step || !attempt || step.version !== input.expectedStepVersion || isTerminalStepStatus(step.status) || attempt.status !== "running")
658
+ conflict();
659
+ if (input.status === "pending") {
660
+ const provenNotExecuted = attempt.kind === "reconcile" && input.evidence?.status === "not_executed";
661
+ const retryable = step.effect !== "external" && (step.kind === "model_call" || step.kind === "compaction" || step.kind === "tool_exec" && step.effect === "none") && ["failed", "cancelled", "unknown"].includes(input.attemptStatus);
662
+ if (!provenNotExecuted && !retryable) conflict();
663
+ }
664
+ Object.assign(
665
+ step,
666
+ { status: input.status, version: step.version + 1 },
667
+ input.output !== void 0 ? { output: input.output } : {},
668
+ input.modelOutput !== void 0 ? { modelOutput: input.modelOutput } : {},
669
+ input.artifacts ? { artifacts: input.artifacts } : {},
670
+ input.usage ? { usage: input.usage } : {},
671
+ input.error ? { error: input.error } : {},
672
+ isTerminalStepStatus(input.status) ? { completedAt: now() } : {}
673
+ );
674
+ Object.assign(
675
+ attempt,
676
+ { status: input.attemptStatus, completedAt: now() },
677
+ input.output !== void 0 ? { output: input.output } : {},
678
+ input.modelOutput !== void 0 ? { modelOutput: input.modelOutput } : {},
679
+ input.artifacts ? { artifacts: input.artifacts } : {},
680
+ input.usage ? { usage: input.usage } : {},
681
+ input.error ? { error: input.error } : {},
682
+ input.evidence !== void 0 ? { evidence: input.evidence } : {}
683
+ );
684
+ if (input.status === "pending") {
685
+ delete step.output;
686
+ delete step.modelOutput;
687
+ delete step.error;
688
+ delete step.artifacts;
689
+ delete step.usage;
690
+ delete step.completedAt;
691
+ }
692
+ event(
693
+ snap.turn,
694
+ input.status === "pending" ? "step.dispatched" : input.status === "unknown" ? "step.unknown" : input.status === "failed" ? "step.failed" : "step.completed",
695
+ {
696
+ attemptNo: input.attemptNo,
697
+ attemptStatus: input.attemptStatus,
698
+ error: input.error,
699
+ ...step.terminatesTurn && input.status === "completed" ? { stopReason: "tool_terminated" } : {}
700
+ },
701
+ step
702
+ );
703
+ terminate(snap, step);
704
+ recompute(snap);
705
+ return step;
706
+ }),
707
+ dispatchSubTurn: (input) => transaction(() => {
708
+ const parent = get(input.turnId);
709
+ const previous = parent.steps.find((s) => s.stepId === input.parentStepId);
710
+ if (previous?.childTurnId) return { turn: get(previous.childTurnId).turn, duplicate: true };
711
+ fence(input);
712
+ if (!previous || previous.kind !== "sub_turn" || previous.status !== "running" || input.child.sessionId === parent.turn.sessionId)
713
+ conflict();
714
+ const admitted = admit({
715
+ sessionId: input.child.sessionId,
716
+ turnId: input.child.turnId,
717
+ input: input.child.input,
718
+ mode: "reject",
719
+ lease: input.childLease,
720
+ ...input.child.limits ? { limits: input.child.limits } : {},
721
+ ...input.child.toolExecution ? { toolExecution: input.child.toolExecution } : {}
722
+ });
723
+ Object.assign(admitted.turn, {
724
+ parentTurnId: input.turnId,
725
+ parentStepId: previous.stepId,
726
+ rootTurnId: parent.turn.rootTurnId,
727
+ depth: parent.turn.depth + 1,
728
+ propagation: input.child.propagation ?? { cancelWithParent: true }
729
+ });
730
+ const childEvent = state.events.at(-1);
731
+ state.events[state.events.length - 1] = {
732
+ ...childEvent,
733
+ rootTurnId: parent.turn.rootTurnId,
734
+ parentTurnId: input.turnId,
735
+ traceId: parent.turn.rootTurnId
736
+ };
737
+ previous.childTurnId = admitted.turn.turnId;
738
+ previous.status = "waiting_child";
739
+ previous.version++;
740
+ event(parent.turn, "sub_turn.linked", { childTurnId: admitted.turn.turnId }, previous);
741
+ recompute(parent);
742
+ return admitted;
743
+ }),
744
+ completeChildAndWakeParent: (input) => transaction(() => {
745
+ const child = fence(input);
746
+ if (!child.turn.parentTurnId) conflict();
747
+ finish(input);
748
+ return backwrite(child, input.parentModelOutput);
749
+ }),
750
+ applyCommand: (envelope) => transaction(() => {
751
+ const key = fingerprint([envelope.scope, envelope.commandId]);
752
+ const fp = fingerprint({
753
+ actor: envelope.actor,
754
+ payload: envelope.payload,
755
+ scope: envelope.scope
756
+ });
757
+ const old = state.commands.get(key);
758
+ if (old) {
759
+ if (old.fingerprint !== fp) throw new IdempotencyConflictError();
760
+ return {
761
+ ...old.receipt,
762
+ status: old.receipt.status === "rejected" ? "rejected" : "duplicate"
763
+ };
764
+ }
765
+ const payload = envelope.payload;
766
+ const snap = state.turns.get(payload.turnId);
767
+ let reason;
768
+ let resultTurnId = payload.turnId;
769
+ if (!snap) reason = "not_found";
770
+ else if (!sameScope(snap.turn.scope, envelope.scope)) reason = "scope_mismatch";
771
+ else if (isTerminalTurnStatus(snap.turn.status) && payload.kind !== "steer")
772
+ reason = "turn_already_terminal";
773
+ else {
774
+ switch (payload.kind) {
775
+ case "steer": {
776
+ const result = steer({
777
+ ...payload,
778
+ steeringId: envelope.commandId,
779
+ fallbackToNewTurn: payload.fallbackToNewTurn ?? true,
780
+ fallback: {
781
+ turnId: `turn_${envelope.commandId}`,
782
+ lease: { holderId: "command-admission", ttlMs: 1 }
783
+ }
784
+ });
785
+ if (result.accepted) resultTurnId = result.turnId;
786
+ else reason = result.reason;
787
+ break;
788
+ }
789
+ case "approve": {
790
+ const approval = snap.approvals.find(
791
+ (a) => a.approvalId === payload.approvalId && a.status === "pending"
792
+ );
793
+ const step = approval && snap.steps.find(
794
+ (s) => s.stepId === approval.stepId && s.status === "awaiting_approval"
795
+ );
796
+ if (!approval || !step) {
797
+ reason = "invalid_state";
798
+ break;
799
+ }
800
+ approval.status = payload.decision;
801
+ approval.actor = envelope.actor;
802
+ approval.resolvedAt = now();
803
+ if (payload.reason) approval.reason = payload.reason;
804
+ if (payload.decision === "approved") {
805
+ step.status = "pending";
806
+ step.version++;
807
+ } else terminalStep(snap, step, "rejected", payload.reason ?? "approval_rejected");
808
+ event(snap.turn, "step.approval_resolved", { decision: payload.decision }, step);
809
+ recompute(snap);
810
+ break;
811
+ }
812
+ case "resolve_unknown": {
813
+ const step = snap.steps.find(
814
+ (s) => s.stepId === payload.stepId && s.status === "unknown"
815
+ );
816
+ if (!step) {
817
+ reason = "invalid_state";
818
+ break;
819
+ }
820
+ const resolution = payload.resolution;
821
+ if (resolution.kind === "confirmed_completed") {
822
+ step.status = "completed";
823
+ step.output = resolution.output;
824
+ if (resolution.modelOutput !== void 0) step.modelOutput = resolution.modelOutput;
825
+ terminate(snap, step);
826
+ } else if (resolution.kind === "confirmed_not_executed") {
827
+ step.status = resolution.retry ? "pending" : "cancelled";
828
+ step.output = { status: "not_executed" };
829
+ } else {
830
+ step.status = "failed";
831
+ step.error = { code: "MANUALLY_FAILED", message: resolution.reason };
832
+ }
833
+ step.version++;
834
+ if (isTerminalStepStatus(step.status)) step.completedAt = now();
835
+ event(snap.turn, "step.resolved", { resolution }, step);
836
+ recompute(snap);
837
+ break;
838
+ }
839
+ case "cancel":
840
+ cancel(snap, payload.reason ?? "cancelled_by_command");
841
+ if (payload.drainQueued === "cancel") {
842
+ for (const queued of state.turns.values())
843
+ if (queued.turn.sessionId === snap.turn.sessionId && queued.turn.status === "queued")
844
+ cancel(queued, "queue_drained");
845
+ }
846
+ break;
847
+ case "resume": {
848
+ if (snap.turn.status === "queued") {
849
+ const owner = session(snap.turn.sessionId);
850
+ if (owner.activeTurnId) {
851
+ reason = "invalid_state";
852
+ break;
853
+ }
854
+ snap.turn.status = "running";
855
+ snap.turn.wakeRequested = true;
856
+ owner.activeTurnId = snap.turn.turnId;
857
+ } else {
858
+ recompute(snap);
859
+ }
860
+ break;
861
+ }
862
+ }
863
+ }
864
+ const receipt = {
865
+ commandId: envelope.commandId,
866
+ processedAt: now(),
867
+ status: reason ? "rejected" : "applied",
868
+ ...reason ? { rejectionReason: reason } : { resultTurnId }
869
+ };
870
+ state.commands.set(key, { fingerprint: fp, receipt });
871
+ if (!reason && snap)
872
+ event(snap.turn, "command.applied", {
873
+ commandId: envelope.commandId,
874
+ kind: payload.kind
875
+ });
876
+ return receipt;
877
+ }),
878
+ finishTurnAndDequeue: (input) => transaction(() => finish(input)),
879
+ acquireLease: (input) => transaction(() => claim(get(input.turnId).turn, input)),
880
+ renewLease: (input) => transaction(() => {
881
+ const snap = fence(input);
882
+ const lease = {
883
+ ...snap.turn.lease,
884
+ expiresAt: new Date(Date.now() + input.ttlMs).toISOString()
885
+ };
886
+ snap.turn.lease = lease;
887
+ return lease;
888
+ }),
889
+ releaseLease: (input) => transaction(() => {
890
+ const snap = fence(input);
891
+ delete snap.turn.lease;
892
+ touch(snap.turn);
893
+ }),
894
+ listRecoverableTurns: async (options) => structuredClone(
895
+ [...state.turns.values()].map((s) => s.turn).filter(
896
+ (t) => !isTerminalTurnStatus(t.status) && t.status !== "queued" && (!options.scope || sameScope(t.scope, options.scope)) && (!t.lease || Date.parse(t.lease.expiresAt) <= Date.now())
897
+ ).slice(0, options.limit)
898
+ ),
899
+ getTurnSnapshot: async (id2, options) => {
900
+ const snap = state.turns.get(id2);
901
+ if (!snap || options?.scope && !sameScope(snap.turn.scope, options.scope)) return null;
902
+ const after = options?.afterStepId ? snap.steps.find((s) => s.stepId === options.afterStepId)?.stepSeq : void 0;
903
+ return structuredClone({
904
+ ...snap,
905
+ steps: after === void 0 ? snap.steps : snap.steps.filter((s) => s.stepSeq > after)
906
+ });
907
+ }
908
+ };
909
+ return {
910
+ kind: "memory",
911
+ ledger,
912
+ async open() {
913
+ },
914
+ async close() {
915
+ },
916
+ artifacts: {
917
+ async put(input) {
918
+ const sha256 = createHash("sha256").update(input.data).digest("hex");
919
+ if (!blobs.has(sha256))
920
+ blobs.set(sha256, { data: new Uint8Array(input.data), createdAt: now() });
921
+ return {
922
+ uri: `memory:sha256:${sha256}`,
923
+ sha256,
924
+ byteSize: input.data.byteLength,
925
+ contentType: input.contentType
926
+ };
927
+ },
928
+ async get(ref) {
929
+ const blob = blobs.get(ref.sha256);
930
+ return blob ? new Uint8Array(blob.data) : null;
931
+ },
932
+ async pruneUnreferenced(options) {
933
+ let deletedCount = 0, freedBytes = 0;
934
+ for (const [hash, blob] of blobs) {
935
+ if (deletedCount >= (options.limit ?? Infinity)) break;
936
+ if (blob.createdAt >= options.olderThan || await options.isReferenced(hash)) continue;
937
+ const referenced = [...state.turns.values()].some(
938
+ (s) => [
939
+ ...s.turn.artifacts ?? [],
940
+ ...s.steps.flatMap((step) => step.artifacts ?? []),
941
+ ...s.attempts.flatMap((a) => a.artifacts ?? [])
942
+ ].some((ref) => ref.sha256 === hash)
943
+ );
944
+ if (!referenced && blobs.get(hash) === blob) {
945
+ blobs.delete(hash);
946
+ deletedCount++;
947
+ freedBytes += blob.data.byteLength;
948
+ }
949
+ }
950
+ return { deletedCount, freedBytes };
951
+ }
952
+ },
953
+ outbox: {
954
+ async read(options) {
955
+ const cursor = Math.max(options.afterSeq ?? 0, cursors.get(options.consumerId) ?? 0);
956
+ const oldest = state.events[0]?.seq ?? state.seq + 1;
957
+ return structuredClone({
958
+ events: state.events.filter((e) => e.seq > cursor).slice(0, options.limit),
959
+ ...cursor + 1 < oldest ? { gap: { fromSeq: cursor + 1, toSeq: oldest - 1, reason: gapReason } } : {}
960
+ });
961
+ },
962
+ async ack(options) {
963
+ cursors.set(
964
+ options.consumerId,
965
+ Math.max(cursors.get(options.consumerId) ?? 0, Math.min(options.upToSeq, state.seq))
966
+ );
967
+ },
968
+ async prune(policy) {
969
+ const before = state.events.length;
970
+ if (policy.maxRetentionMs !== void 0) {
971
+ const cutoff = Date.now() - policy.maxRetentionMs;
972
+ state.events = state.events.filter((e) => Date.parse(e.occurredAt) > cutoff);
973
+ if (state.events.length < before) gapReason = "retention_ttl";
974
+ }
975
+ if (policy.maxPendingEvents !== void 0 && state.events.length > policy.maxPendingEvents) {
976
+ state.events = state.events.slice(state.events.length - policy.maxPendingEvents);
977
+ gapReason = "max_pending_exceeded";
978
+ }
979
+ return {
980
+ prunedCount: before - state.events.length,
981
+ oldestAvailableSeq: state.events[0]?.seq ?? state.seq + 1
982
+ };
983
+ }
984
+ }
985
+ };
986
+ }
987
+ function json(value) {
988
+ return JSON.parse(JSON.stringify(value ?? null));
989
+ }
990
+ function projectTurn(snapshot) {
991
+ return [...contextView(snapshot, "").messagesToCompact];
992
+ }
993
+ function plainDialogue(messages) {
994
+ return messages.map((message) => ({
995
+ role: message.role === "tool" ? "user" : message.role,
996
+ content: typeof message.content === "string" ? message.content : message.content.map((part) => part.type === "text" ? part.text : JSON.stringify(part)).join("\n")
997
+ }));
998
+ }
999
+ async function hydrateContinuations(snapshot, artifacts) {
1000
+ const view = contextView(snapshot, "");
1001
+ const live = new Set(view.uncompactedSteps.map((step) => step.stepId));
1002
+ return {
1003
+ ...snapshot,
1004
+ steps: await Promise.all(
1005
+ snapshot.steps.map(async (step) => {
1006
+ if (!live.has(step.stepId) || !step.continuationArtifact) return step;
1007
+ if (step.continuation !== void 0) throw new Error("Ambiguous continuation storage.");
1008
+ const bytes = await artifacts.get(step.continuationArtifact);
1009
+ if (!bytes) throw new Error("Missing continuation artifact.");
1010
+ return { ...step, continuation: JSON.parse(new TextDecoder().decode(bytes)) };
1011
+ })
1012
+ )
1013
+ };
1014
+ }
1015
+ function withoutContinuations(messages) {
1016
+ return messages.map((message) => ({ role: message.role, content: message.content }));
1017
+ }
1018
+ function assertContinuations(messages, model) {
1019
+ for (const message of messages) {
1020
+ const calls = typeof message.content !== "string" && message.content.some((part) => part.type === "tool_call");
1021
+ if (message.role === "assistant" && calls && !message.continuation)
1022
+ throw new Error("Active tool-chain replay requires its original continuation.");
1023
+ if (!message.continuation) continue;
1024
+ if (message.continuation.protocolId !== model.protocolId || message.continuation.model !== model.model)
1025
+ throw new Error("Active tool-chain continuation protocol/model mismatch.");
1026
+ model.replay(message.continuation);
1027
+ }
1028
+ }
1029
+ function assertProjectedContinuations(committed, projected) {
1030
+ let cursor = 0;
1031
+ for (const message of committed) {
1032
+ if (message.role !== "assistant" || !message.continuation && (typeof message.content === "string" || !message.content.some((part) => part.type === "tool_call")))
1033
+ continue;
1034
+ const index = projected.findIndex(
1035
+ (candidate, index2) => index2 >= cursor && JSON.stringify(candidate) === JSON.stringify(message)
1036
+ );
1037
+ if (index < 0)
1038
+ throw new Error("Context projection discarded or changed an active continuation.");
1039
+ cursor = index + 1;
1040
+ }
1041
+ }
1042
+ function projectSteps(steps) {
1043
+ const messages = [];
1044
+ for (const step of steps) {
1045
+ if (!isTerminalStepStatus(step.status)) continue;
1046
+ if (step.kind === "steering_input") {
1047
+ for (const text of step.output) messages.push({ role: "user", content: text });
1048
+ } else if (step.kind === "model_call" && step.status === "completed") {
1049
+ const response = step.output;
1050
+ const calls = response.toolCalls ?? [];
1051
+ messages.push({
1052
+ role: "assistant",
1053
+ content: calls.length ? [
1054
+ ...response.text ? [{ type: "text", text: response.text }] : [],
1055
+ ...calls.map((call) => ({ type: "tool_call", ...call }))
1056
+ ] : response.text ?? "",
1057
+ ...step.continuation !== void 0 ? { continuation: step.continuation } : {}
1058
+ });
1059
+ for (const call of calls) {
1060
+ const result = steps.find(
1061
+ (s) => s.toolCallId === call.id && s.iteration === step.iteration
1062
+ );
1063
+ if (!result || !isTerminalStepStatus(result.status))
1064
+ throw new Error(`Missing terminal tool result for ${call.id}.`);
1065
+ messages.push({
1066
+ role: "tool",
1067
+ content: [
1068
+ {
1069
+ type: "tool_result",
1070
+ toolCallId: call.id,
1071
+ name: call.name,
1072
+ output: json(
1073
+ result.modelOutput !== void 0 ? result.modelOutput : result.output ?? { status: result.status, error: result.error }
1074
+ ),
1075
+ isError: result.status !== "completed"
1076
+ }
1077
+ ]
1078
+ });
1079
+ }
1080
+ }
1081
+ }
1082
+ return messages;
1083
+ }
1084
+ function contextView(snapshot, instructions, history = []) {
1085
+ const compaction = [...snapshot.steps].reverse().find((s) => s.kind === "compaction" && s.status === "completed");
1086
+ const output = compaction?.output;
1087
+ const cut = output ? snapshot.steps.find((s) => s.stepId === output.compactedUpToStepId)?.stepSeq ?? 0 : 0;
1088
+ const steps = snapshot.steps.map((step) => step.modelOutput !== void 0 ? { ...step, output: step.modelOutput } : step).filter(
1089
+ (s) => s.stepSeq > cut && s.kind !== "compaction" && isTerminalStepStatus(s.status)
1090
+ );
1091
+ const messages = projectSteps(steps);
1092
+ const base = output ? [{ role: "user", content: output.summary }] : [...history, { role: "user", content: snapshot.turn.input }];
1093
+ return {
1094
+ sessionId: snapshot.turn.sessionId,
1095
+ turnId: snapshot.turn.turnId,
1096
+ iteration: snapshot.turn.iteration + 1,
1097
+ systemPrompt: instructions,
1098
+ estimatedTokens: Math.ceil(JSON.stringify([instructions, base, messages]).length / 4),
1099
+ uncompactedSteps: steps,
1100
+ cutPointStepId: steps.at(-1)?.stepId ?? "",
1101
+ ...output && compaction ? { latestCompaction: { stepId: compaction.stepId, ...output } } : {},
1102
+ messagesToCompact: plainDialogue([...base, ...messages])
1103
+ };
1104
+ }
1105
+ function assertToolPairs(messages) {
1106
+ const pending = /* @__PURE__ */ new Set();
1107
+ for (const message of messages) {
1108
+ if (pending.size && message.role !== "tool")
1109
+ throw new Error("Tool calls must be paired before the next message.");
1110
+ if (typeof message.content === "string") {
1111
+ if (pending.size) throw new Error("Tool calls must be paired before the next message.");
1112
+ continue;
1113
+ }
1114
+ for (const part of message.content) {
1115
+ if (part.type === "tool_call") {
1116
+ if (pending.has(part.id)) throw new Error("Duplicate tool call id.");
1117
+ pending.add(part.id);
1118
+ }
1119
+ if (part.type === "tool_result") {
1120
+ if (!pending.delete(part.toolCallId)) throw new Error("Tool result has no matching call.");
1121
+ }
1122
+ }
1123
+ if (message.role !== "assistant" && message.role !== "tool" && pending.size)
1124
+ throw new Error("Incomplete tool group.");
1125
+ }
1126
+ if (pending.size) throw new Error("BoundModel projection contains unpaired tool calls.");
1127
+ }
1128
+
1129
+ // src/runtime/index.ts
1130
+ var unknownUsage = {
1131
+ inputTokens: null,
1132
+ outputTokens: null,
1133
+ cacheReadTokens: null,
1134
+ cacheWriteTokens: null,
1135
+ completeness: "unknown"
1136
+ };
1137
+ function combinedUsage(usages) {
1138
+ if (!usages.length) return { ...unknownUsage };
1139
+ const sum = (key) => usages.some((usage) => usage[key] === null) ? null : usages.reduce((total, usage) => total + (usage[key] ?? 0), 0);
1140
+ const counts = {
1141
+ inputTokens: sum("inputTokens"),
1142
+ outputTokens: sum("outputTokens"),
1143
+ cacheReadTokens: sum("cacheReadTokens"),
1144
+ cacheWriteTokens: sum("cacheWriteTokens")
1145
+ };
1146
+ return {
1147
+ ...counts,
1148
+ completeness: usages.every((usage) => usage.completeness === "complete") ? "complete" : Object.values(counts).every((value) => value === null) ? "unknown" : "partial"
1149
+ };
1150
+ }
1151
+ var id = (prefix) => `${prefix}_${randomUUID()}`;
1152
+ function durableToolInput(value, ancestors = /* @__PURE__ */ new Set()) {
1153
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
1154
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1155
+ if (typeof value !== "object" || ancestors.has(value))
1156
+ throw new Error("Validated tool input must be acyclic JSON.");
1157
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
1158
+ throw new Error("Validated tool input must contain only JSON objects.");
1159
+ ancestors.add(value);
1160
+ const result = Array.isArray(value) ? Array.from(value, (item) => durableToolInput(item, ancestors)) : Object.fromEntries(
1161
+ Object.entries(value).map(([key, item]) => [key, durableToolInput(item, ancestors)])
1162
+ );
1163
+ ancestors.delete(value);
1164
+ return result;
1165
+ }
1166
+ function abortable(promise, signal) {
1167
+ if (signal.aborted) {
1168
+ void promise.catch(() => {
1169
+ });
1170
+ return Promise.reject(signal.reason);
1171
+ }
1172
+ return new Promise((resolve, reject) => {
1173
+ const abort = () => {
1174
+ signal.removeEventListener("abort", abort);
1175
+ reject(signal.reason);
1176
+ };
1177
+ signal.addEventListener("abort", abort, { once: true });
1178
+ void promise.then(
1179
+ (value) => {
1180
+ signal.removeEventListener("abort", abort);
1181
+ resolve(value);
1182
+ },
1183
+ (error) => {
1184
+ signal.removeEventListener("abort", abort);
1185
+ reject(error);
1186
+ }
1187
+ );
1188
+ });
1189
+ }
1190
+ var SessionHandle = class {
1191
+ constructor(runtime, snapshot) {
1192
+ this.runtime = runtime;
1193
+ this.snapshot = snapshot;
1194
+ this.id = snapshot.sessionId;
1195
+ }
1196
+ runtime;
1197
+ snapshot;
1198
+ id;
1199
+ send(input, opts) {
1200
+ return this.runtime.send(this.id, input, opts);
1201
+ }
1202
+ followUp(input, opts) {
1203
+ return this.send(input, { ...opts, mode: "follow_up" });
1204
+ }
1205
+ async steer(input, opts) {
1206
+ const session = await this.runtime.storage.ledger.getSession(this.id);
1207
+ if (!session?.activeTurnId) {
1208
+ const turn = await this.send(input);
1209
+ return { accepted: true, mode: "promoted_to_turn", turnId: turn.id };
1210
+ }
1211
+ return (await this.runtime.getTurn(session.activeTurnId)).steer(input, opts);
1212
+ }
1213
+ };
1214
+ var TurnHandle = class {
1215
+ constructor(runtime, id2) {
1216
+ this.runtime = runtime;
1217
+ this.id = id2;
1218
+ }
1219
+ runtime;
1220
+ id;
1221
+ wait() {
1222
+ return this.runtime.wait(this.id);
1223
+ }
1224
+ stream(opts) {
1225
+ return this.runtime.stream(this.id, opts);
1226
+ }
1227
+ approve(approvalId, options) {
1228
+ return this.runtime.commands.approve({ ...options, turnId: this.id, approvalId });
1229
+ }
1230
+ resolveUnknown(stepId, options) {
1231
+ return this.runtime.commands.resolveUnknown({ ...options, turnId: this.id, stepId });
1232
+ }
1233
+ cancel(options) {
1234
+ return this.runtime.commands.cancel({ ...options, turnId: this.id });
1235
+ }
1236
+ steer(input, opts) {
1237
+ return this.runtime.steer(this.id, input, opts);
1238
+ }
1239
+ };
1240
+ var Runtime = class {
1241
+ constructor(config) {
1242
+ this.config = config;
1243
+ if (config.agent !== void 0 && config.agents !== void 0)
1244
+ throw new Error("Runtime config must specify either agent or agents, not both.");
1245
+ if (config.continuationInlineThresholdBytes !== void 0 && (!Number.isSafeInteger(config.continuationInlineThresholdBytes) || config.continuationInlineThresholdBytes < 0))
1246
+ throw new Error("Continuation inline threshold must be a nonnegative integer.");
1247
+ this.storage = config.storage ?? memoryStorage();
1248
+ }
1249
+ config;
1250
+ storage;
1251
+ commands = {
1252
+ dispatch: (envelope) => this.dispatch(envelope),
1253
+ approve: (input) => this.command("approve", input),
1254
+ resolveUnknown: (input) => this.command("resolve_unknown", input),
1255
+ cancel: (input) => this.command("cancel", input),
1256
+ steer: (input) => this.command("steer", input),
1257
+ resume: (input) => this.command("resume", input)
1258
+ };
1259
+ holderId = id("runtime");
1260
+ agents = /* @__PURE__ */ new Map();
1261
+ tools = /* @__PURE__ */ new Map();
1262
+ jobs = /* @__PURE__ */ new Map();
1263
+ controllers = /* @__PURE__ */ new Map();
1264
+ listeners = /* @__PURE__ */ new Set();
1265
+ realtime = /* @__PURE__ */ new Set();
1266
+ history = /* @__PURE__ */ new Map();
1267
+ providers = /* @__PURE__ */ new Set();
1268
+ failures = /* @__PURE__ */ new Map();
1269
+ hookCursor = 0;
1270
+ closed = false;
1271
+ closePromise;
1272
+ timer;
1273
+ key(agent) {
1274
+ return `${agent.id}@${agent.version}`;
1275
+ }
1276
+ agent(turn) {
1277
+ const agent = this.agents.get(`${turn.agentId}@${turn.agentVersion}`);
1278
+ if (!agent) throw new AgentNotRegisteredError(turn.agentId, turn.agentVersion);
1279
+ return agent;
1280
+ }
1281
+ model(binding) {
1282
+ const model = typeof binding === "string" ? this.config.models?.[binding] : binding;
1283
+ if (!model) throw new Error(`BoundModel alias ${String(binding)} is not registered.`);
1284
+ return model;
1285
+ }
1286
+ async initialize() {
1287
+ await this.storage.open();
1288
+ try {
1289
+ const agents = this.config.agent ? [this.config.agent] : this.config.agents ?? [];
1290
+ for (const agent of agents) await this.register(agent);
1291
+ await this.config.cloud?.open(this);
1292
+ if (this.config.recovery !== "manual") {
1293
+ await this.recover(true);
1294
+ this.timer = setInterval(() => {
1295
+ void this.recover().catch(() => {
1296
+ });
1297
+ }, 100);
1298
+ this.timer.unref();
1299
+ }
1300
+ await this.flush();
1301
+ } catch (error) {
1302
+ await this.close();
1303
+ throw error;
1304
+ }
1305
+ }
1306
+ async register(agent) {
1307
+ const key = this.key(agent);
1308
+ if (this.agents.has(key)) return;
1309
+ if (!agent.resolveModel) this.model(agent.model);
1310
+ for (const value of Object.values(agent.limits ?? {}))
1311
+ if (!Number.isSafeInteger(value) || value < 0)
1312
+ throw new Error("Run limits must be nonnegative integers.");
1313
+ const registry = /* @__PURE__ */ new Map();
1314
+ for (const entry of agent.tools ?? []) {
1315
+ if ("listTools" in entry) {
1316
+ const provider = entry;
1317
+ if (!this.providers.has(provider)) {
1318
+ await provider.open(this.config.services ?? {});
1319
+ this.providers.add(provider);
1320
+ }
1321
+ for (const tool of await provider.listTools()) {
1322
+ if (registry.has(tool.name)) throw new Error(`Duplicate tool ${tool.name}.`);
1323
+ registry.set(tool.name, tool);
1324
+ }
1325
+ } else {
1326
+ if (registry.has(entry.name)) throw new Error(`Duplicate tool ${entry.name}.`);
1327
+ registry.set(entry.name, entry);
1328
+ }
1329
+ }
1330
+ if (agent.toolExecution !== "sequential" && [...registry.values()].some((tool) => "terminatesTurn" in tool && tool.terminatesTurn))
1331
+ throw new Error("Terminating tools require sequential toolExecution.");
1332
+ this.agents.set(key, agent);
1333
+ this.tools.set(key, registry);
1334
+ }
1335
+ async openSession(agent, opts = {}) {
1336
+ this.assertOpen();
1337
+ const definition = typeof agent === "string" ? [...this.agents.values()].find((a) => a.id === agent) : agent;
1338
+ if (!definition) throw new AgentNotRegisteredError(String(agent));
1339
+ await this.register(definition);
1340
+ const session = await this.storage.ledger.createSession({
1341
+ sessionId: id("session"),
1342
+ agentId: definition.id,
1343
+ agentVersion: definition.version,
1344
+ ...opts
1345
+ });
1346
+ await this.flush();
1347
+ return new SessionHandle(this, session);
1348
+ }
1349
+ async getSession(sessionId) {
1350
+ this.assertOpen();
1351
+ const session = await this.storage.ledger.getSession(sessionId);
1352
+ if (!session) throw new Error(`Session ${sessionId} not found.`);
1353
+ return new SessionHandle(this, session);
1354
+ }
1355
+ async getTurn(turnId) {
1356
+ this.assertOpen();
1357
+ await this.snapshot(turnId);
1358
+ return new TurnHandle(this, turnId);
1359
+ }
1360
+ async run(agent, input, opts) {
1361
+ const session = await this.openSession(agent, opts);
1362
+ return (await session.send(input, opts)).wait();
1363
+ }
1364
+ async send(sessionId, input, opts = {}) {
1365
+ this.assertOpen();
1366
+ const session = await this.storage.ledger.getSession(sessionId);
1367
+ if (!session) throw new Error("Session not found.");
1368
+ const agent = this.agents.get(`${session.agentId}@${session.agentVersion}`);
1369
+ const limits = { ...agent.limits, ...opts.limits };
1370
+ for (const value of Object.values(limits))
1371
+ if (!Number.isSafeInteger(value) || value < 0)
1372
+ throw new Error("Run limits must be nonnegative integers.");
1373
+ const admitted = await this.storage.ledger.admitTurn({
1374
+ sessionId,
1375
+ turnId: id("turn"),
1376
+ input,
1377
+ ...opts,
1378
+ limits,
1379
+ toolExecution: agent.toolExecution ?? "parallel",
1380
+ mode: opts.mode ?? "reject",
1381
+ lease: { holderId: this.holderId, ttlMs: 3e4 }
1382
+ });
1383
+ await this.flush();
1384
+ if (admitted.lease && !admitted.duplicate) this.schedule(admitted.turn.turnId);
1385
+ return new TurnHandle(this, admitted.turn.turnId);
1386
+ }
1387
+ assertOpen() {
1388
+ if (this.closed) throw new Error("Runtime is closed.");
1389
+ }
1390
+ async snapshot(turnId) {
1391
+ const snapshot = await this.storage.ledger.getTurnSnapshot(turnId);
1392
+ if (!snapshot) throw new Error(`Turn ${turnId} not found.`);
1393
+ return snapshot;
1394
+ }
1395
+ notify() {
1396
+ for (const listener of this.listeners) listener();
1397
+ }
1398
+ async flush() {
1399
+ const batch = await this.storage.outbox.read({
1400
+ consumerId: `${this.holderId}:hooks`,
1401
+ afterSeq: this.hookCursor,
1402
+ limit: 1e4
1403
+ });
1404
+ const events = batch.events.filter((e) => e.seq > this.hookCursor);
1405
+ if (events.length) this.hookCursor = events.at(-1).seq;
1406
+ for (const event of events)
1407
+ for (const hook of this.config.hooks ?? []) {
1408
+ try {
1409
+ await hook.onDurableEvent(event);
1410
+ } catch {
1411
+ }
1412
+ }
1413
+ this.notify();
1414
+ }
1415
+ /** Ephemeral events only; listeners are isolated from execution and never awaited. */
1416
+ subscribeRealtime(listener) {
1417
+ this.assertOpen();
1418
+ this.realtime.add(listener);
1419
+ return () => {
1420
+ this.realtime.delete(listener);
1421
+ };
1422
+ }
1423
+ emit(turn, type, stepId, data) {
1424
+ const event = {
1425
+ type,
1426
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1427
+ sessionId: turn.sessionId,
1428
+ rootTurnId: turn.rootTurnId,
1429
+ turnId: turn.turnId,
1430
+ traceId: turn.rootTurnId,
1431
+ spanId: stepId,
1432
+ stepId,
1433
+ ...turn.parentTurnId ? { parentTurnId: turn.parentTurnId } : {},
1434
+ ...turn.scope ? { scope: turn.scope } : {},
1435
+ ...data
1436
+ };
1437
+ for (const listener of this.realtime) {
1438
+ try {
1439
+ void Promise.resolve(listener(event)).catch(() => {
1440
+ });
1441
+ } catch {
1442
+ }
1443
+ }
1444
+ for (const hook of this.config.hooks ?? []) {
1445
+ try {
1446
+ void Promise.resolve(hook.onRealtimeEvent?.(event)).catch(() => {
1447
+ });
1448
+ } catch {
1449
+ }
1450
+ }
1451
+ this.notify();
1452
+ }
1453
+ async recover(initial = false) {
1454
+ if (this.closed) return;
1455
+ for (const turn of await this.storage.ledger.listRecoverableTurns({ limit: 1e4 })) {
1456
+ if (turn.status === "running" || turn.wakeRequested || initial && turn.status === "waiting_resolution")
1457
+ this.schedule(turn.turnId);
1458
+ }
1459
+ }
1460
+ schedule(turnId) {
1461
+ if (this.closed || this.jobs.has(turnId)) return;
1462
+ const job = new Promise((resolve) => setTimeout(resolve, 0)).then(() => this.drive(turnId)).catch(async (error) => {
1463
+ if (error instanceof LeaseLostError || error instanceof ConcurrencyConflictError || this.closed)
1464
+ return;
1465
+ try {
1466
+ const snap = await this.snapshot(turnId);
1467
+ if (!isTerminalTurnStatus(snap.turn.status) && snap.turn.lease?.holderId === this.holderId)
1468
+ await this.finish(
1469
+ snap.turn,
1470
+ snap.turn.lease,
1471
+ "failed",
1472
+ void 0,
1473
+ toErrorRecord(error)
1474
+ );
1475
+ else this.failures.set(turnId, error);
1476
+ } catch (failure) {
1477
+ this.failures.set(turnId, failure);
1478
+ }
1479
+ }).finally(async () => {
1480
+ this.jobs.delete(turnId);
1481
+ await this.flush();
1482
+ if (!this.closed) {
1483
+ const snap = await this.snapshot(turnId);
1484
+ if (snap.turn.wakeRequested && !isTerminalTurnStatus(snap.turn.status))
1485
+ this.schedule(turnId);
1486
+ }
1487
+ });
1488
+ this.jobs.set(turnId, job);
1489
+ }
1490
+ control(turn, step, external = false) {
1491
+ const controller = new AbortController();
1492
+ const entry = { controller, external };
1493
+ const set = this.controllers.get(turn.turnId) ?? /* @__PURE__ */ new Set();
1494
+ set.add(entry);
1495
+ this.controllers.set(turn.turnId, set);
1496
+ const context = {
1497
+ sessionId: turn.sessionId,
1498
+ turnId: turn.turnId,
1499
+ stepId: step.stepId,
1500
+ attemptNo: 0,
1501
+ operationKey: step.operationKey,
1502
+ ...turn.scope ? { scope: turn.scope } : {},
1503
+ context: turn.context,
1504
+ services: this.config.services ?? {},
1505
+ signal: controller.signal,
1506
+ artifacts: this.storage.artifacts,
1507
+ reportProgress: (message, data) => this.emit(turn, "tool.progress", step.stepId, { message, ...data ? { data } : {} })
1508
+ };
1509
+ return {
1510
+ controller,
1511
+ context,
1512
+ dispose: () => {
1513
+ set.delete(entry);
1514
+ if (!set.size) this.controllers.delete(turn.turnId);
1515
+ }
1516
+ };
1517
+ }
1518
+ async lease(turn) {
1519
+ if (turn.lease?.holderId === this.holderId && Date.parse(turn.lease.expiresAt) > Date.now())
1520
+ return turn.lease;
1521
+ return this.storage.ledger.acquireLease({
1522
+ turnId: turn.turnId,
1523
+ holderId: this.holderId,
1524
+ ttlMs: 3e4
1525
+ });
1526
+ }
1527
+ async resolveAgent(agent, turn, iteration) {
1528
+ const ctx = {
1529
+ turnContext: turn.context,
1530
+ services: this.config.services ?? {},
1531
+ sessionId: turn.sessionId,
1532
+ turnId: turn.turnId,
1533
+ iteration,
1534
+ ...turn.scope ? { scope: turn.scope } : {}
1535
+ };
1536
+ return {
1537
+ ...agent,
1538
+ model: agent.resolveModel ? await agent.resolveModel(ctx) : agent.model,
1539
+ instructions: agent.resolveInstructions ? await agent.resolveInstructions(ctx) : agent.instructions ?? ""
1540
+ };
1541
+ }
1542
+ async drive(turnId) {
1543
+ let snap = await this.snapshot(turnId);
1544
+ if (isTerminalTurnStatus(snap.turn.status) || snap.turn.status === "queued") return;
1545
+ if (snap.turn.status.startsWith("waiting_") && !snap.turn.wakeRequested && !snap.steps.some(
1546
+ (s) => s.status === "unknown" && s.toolName && "reconcile" in (this.tools.get(this.key(this.agent(snap.turn)))?.get(s.toolName) ?? {})
1547
+ ))
1548
+ return;
1549
+ let lease = await this.lease(snap.turn);
1550
+ let stopped = false;
1551
+ const heartbeat = setInterval(() => {
1552
+ void this.storage.ledger.renewLease({ turnId, lease, ttlMs: 3e4 }).then((value) => {
1553
+ lease = value;
1554
+ }).catch(() => {
1555
+ stopped = true;
1556
+ for (const entry of this.controllers.get(turnId) ?? []) entry.controller.abort();
1557
+ });
1558
+ }, 1e4);
1559
+ heartbeat.unref();
1560
+ const probed = /* @__PURE__ */ new Set();
1561
+ try {
1562
+ while (!this.closed && !stopped) {
1563
+ snap = await this.snapshot(turnId);
1564
+ if (isTerminalTurnStatus(snap.turn.status)) return;
1565
+ const agent = this.agent(snap.turn);
1566
+ const tools = this.tools.get(this.key(agent));
1567
+ if (snap.turn.completionIntent) {
1568
+ await this.finish(
1569
+ snap.turn,
1570
+ lease,
1571
+ "completed",
1572
+ snap.turn.completionIntent.output,
1573
+ void 0,
1574
+ "tool_terminated"
1575
+ );
1576
+ return;
1577
+ }
1578
+ const hostFailure = snap.steps.find((s) => s.status === "failed" && s.error?.requestStage);
1579
+ if (hostFailure) {
1580
+ lease = await this.lease(snap.turn);
1581
+ await this.storage.ledger.skipSteps({
1582
+ turnId,
1583
+ lease,
1584
+ stepIds: snap.steps.filter((s) => s.status === "pending" || s.status === "awaiting_approval").map((s) => s.stepId),
1585
+ reason: "host_control_error"
1586
+ });
1587
+ await this.finish(snap.turn, lease, "failed", void 0, hostFailure.error);
1588
+ return;
1589
+ }
1590
+ const modelResult = [...snap.steps].reverse().find((s) => s.kind === "model_call" && s.status === "completed")?.output;
1591
+ if (modelResult && ["length", "content_filter"].includes(modelResult.finishReason)) {
1592
+ await this.storage.ledger.skipSteps({
1593
+ turnId,
1594
+ lease,
1595
+ stepIds: snap.steps.filter((s) => s.status === "pending").map((s) => s.stepId),
1596
+ reason: modelResult.finishReason
1597
+ });
1598
+ const reason = modelResult.finishReason === "length" ? "max_tokens" : "content_filter";
1599
+ const failed = reason === "max_tokens" && agent.onMaxTokens === "fail";
1600
+ await this.finish(
1601
+ snap.turn,
1602
+ lease,
1603
+ failed ? "failed" : "completed",
1604
+ modelResult.text,
1605
+ failed ? { code: "MAX_TOKENS", message: "Model output was truncated." } : void 0,
1606
+ reason,
1607
+ modelResult.finishReason,
1608
+ true
1609
+ );
1610
+ return;
1611
+ }
1612
+ const eligible = snap.turn.toolExecution === "sequential" ? snap.steps.filter((s) => !isTerminalStepStatus(s.status)).slice(0, 1) : snap.steps;
1613
+ let runnable = eligible.filter(
1614
+ (s) => (s.kind === "tool_exec" || s.kind === "sub_turn") && (s.status === "pending" || s.status === "running")
1615
+ );
1616
+ const unknown = eligible.filter(
1617
+ (s) => s.status === "unknown" && !probed.has(s.stepId) && s.toolName && "reconcile" in (tools.get(s.toolName) ?? {})
1618
+ );
1619
+ const interrupted = snap.steps.filter(
1620
+ (s) => s.status === "running" && (s.kind === "model_call" || s.kind === "compaction")
1621
+ );
1622
+ if (!snap.turn.lease) {
1623
+ if (!(runnable.length || unknown.length || snap.turn.wakeRequested)) return;
1624
+ lease = await this.lease(snap.turn);
1625
+ snap = await this.snapshot(turnId);
1626
+ }
1627
+ if (interrupted.length) {
1628
+ const step = interrupted[0];
1629
+ if (step.kind === "model_call") {
1630
+ await this.callModel(
1631
+ snap,
1632
+ lease,
1633
+ await this.resolveAgent(agent, snap.turn, step.iteration),
1634
+ tools,
1635
+ step
1636
+ );
1637
+ await this.flush();
1638
+ continue;
1639
+ }
1640
+ await this.compact(
1641
+ snap,
1642
+ lease,
1643
+ await this.resolveAgent(agent, snap.turn, step.iteration),
1644
+ step
1645
+ );
1646
+ continue;
1647
+ }
1648
+ if (runnable.length || unknown.length) {
1649
+ const used = snap.attempts.filter(
1650
+ (a) => a.kind === "execute" && snap.steps.some(
1651
+ (s) => s.stepId === a.stepId && (s.kind === "tool_exec" || s.kind === "sub_turn")
1652
+ )
1653
+ ).length;
1654
+ const remaining = Math.max(0, (snap.turn.limits?.maxToolCalls ?? Infinity) - used);
1655
+ const fresh = runnable.filter((s) => s.status !== "running");
1656
+ const excess = fresh.slice(remaining);
1657
+ if (excess.length) {
1658
+ await this.storage.ledger.skipSteps({
1659
+ turnId,
1660
+ lease,
1661
+ stepIds: excess.map((s) => s.stepId),
1662
+ reason: "max_tool_calls"
1663
+ });
1664
+ runnable = runnable.filter((s) => !excess.includes(s));
1665
+ }
1666
+ await Promise.all(
1667
+ [...runnable, ...unknown].map(async (step) => {
1668
+ if (step.status === "unknown") probed.add(step.stepId);
1669
+ await this.executeStep(snap.turn, lease, step, tools);
1670
+ })
1671
+ );
1672
+ await this.flush();
1673
+ continue;
1674
+ }
1675
+ if (snap.steps.some((s) => !isTerminalStepStatus(s.status))) {
1676
+ if (snap.turn.lease) await this.storage.ledger.releaseLease({ turnId, lease });
1677
+ return;
1678
+ }
1679
+ if (snap.steps.some(
1680
+ (s) => s.status === "skipped" && s.output?.reason === "max_tool_calls"
1681
+ )) {
1682
+ await this.finish(
1683
+ snap.turn,
1684
+ lease,
1685
+ "failed",
1686
+ void 0,
1687
+ { code: "MAX_TOOL_CALLS", message: "Tool call limit reached." },
1688
+ "max_tool_calls"
1689
+ );
1690
+ return;
1691
+ }
1692
+ const final = [...snap.steps].reverse().find((s) => s.kind === "model_call");
1693
+ if (final && final.status === "completed" && !final.output.toolCalls?.length && !snap.steps.some((s) => s.kind === "steering_input" && s.stepSeq > final.stepSeq) && !snap.steering.some((s) => s.status === "pending")) {
1694
+ const response = final.output;
1695
+ const reason = response.finishReason === "length" ? "max_tokens" : response.finishReason === "content_filter" ? "content_filter" : response.finishReason === "stop" ? "end_turn" : "unknown";
1696
+ const failed = reason === "max_tokens" && agent.onMaxTokens === "fail";
1697
+ await this.finish(
1698
+ snap.turn,
1699
+ lease,
1700
+ failed ? "failed" : "completed",
1701
+ response.text,
1702
+ failed ? { code: "MAX_TOKENS", message: "Model output was truncated." } : void 0,
1703
+ reason,
1704
+ String(response.finishReason),
1705
+ reason === "max_tokens"
1706
+ );
1707
+ return;
1708
+ }
1709
+ if (snap.turn.iteration >= (snap.turn.limits?.maxIterations ?? agent.limits?.maxIterations ?? 50)) {
1710
+ await this.finish(
1711
+ snap.turn,
1712
+ lease,
1713
+ "failed",
1714
+ void 0,
1715
+ {
1716
+ code: "MAX_ITERATIONS",
1717
+ message: "Agent iteration limit reached."
1718
+ },
1719
+ "max_iterations"
1720
+ );
1721
+ return;
1722
+ }
1723
+ const resolved = await this.resolveAgent(agent, snap.turn, snap.turn.iteration + 1);
1724
+ const iteration = snap.turn.iteration + 1;
1725
+ await this.storage.ledger.consumeSteeringAndRecord({
1726
+ turnId,
1727
+ lease,
1728
+ iteration,
1729
+ stepId: id("steering"),
1730
+ operationKey: id("operation")
1731
+ });
1732
+ snap = await this.snapshot(turnId);
1733
+ const view = contextView(
1734
+ await hydrateContinuations(this.mapSubOutputs(snap, agent), this.storage.artifacts),
1735
+ resolved.instructions ?? "",
1736
+ await this.sessionHistory(snap.turn)
1737
+ );
1738
+ if (agent.contextStrategy?.shouldCompact(view)) {
1739
+ await this.compact(snap, lease, resolved);
1740
+ snap = await this.snapshot(turnId);
1741
+ }
1742
+ await this.callModel(snap, lease, resolved, tools);
1743
+ await this.flush();
1744
+ }
1745
+ } finally {
1746
+ clearInterval(heartbeat);
1747
+ }
1748
+ }
1749
+ async sessionHistory(turn) {
1750
+ const cached = this.history.get(turn.sessionId);
1751
+ if (cached) return cached;
1752
+ const turns = await this.storage.ledger.listSessionTurns(turn.sessionId, {
1753
+ ...turn.scope ? { scope: turn.scope } : {}
1754
+ });
1755
+ const messages = [];
1756
+ for (const previous of turns) {
1757
+ if (previous.turnId === turn.turnId) break;
1758
+ if (previous.status !== "completed") continue;
1759
+ const old = await this.snapshot(previous.turnId);
1760
+ messages.push(...projectTurn(this.mapSubOutputs(old, this.agent(old.turn))));
1761
+ }
1762
+ this.history.set(turn.sessionId, messages);
1763
+ return messages;
1764
+ }
1765
+ async messages(snap, agent) {
1766
+ const history = await this.sessionHistory(snap.turn);
1767
+ const view = contextView(
1768
+ await hydrateContinuations(this.mapSubOutputs(snap, agent), this.storage.artifacts),
1769
+ agent.instructions ?? "",
1770
+ history
1771
+ );
1772
+ const model = this.model(agent.model);
1773
+ for (const step of view.uncompactedSteps) {
1774
+ if (step.kind !== "model_call" || step.status !== "completed") continue;
1775
+ if (step.protocolId !== model.protocolId || step.modelId !== model.model)
1776
+ throw new Error("Active tool-chain Step protocol/model mismatch.");
1777
+ }
1778
+ const committed = projectSteps(view.uncompactedSteps);
1779
+ assertContinuations(committed, model);
1780
+ let result;
1781
+ if (agent.contextStrategy?.project)
1782
+ result = agent.contextStrategy.project(view).map(
1783
+ (message) => ({
1784
+ role: message.role,
1785
+ content: message.content,
1786
+ ...message.continuation !== void 0 ? { continuation: message.continuation } : {}
1787
+ })
1788
+ );
1789
+ else
1790
+ result = [
1791
+ { role: "system", content: agent.instructions ?? "" },
1792
+ ...view.latestCompaction ? [{ role: "user", content: view.latestCompaction.summary }] : history,
1793
+ ...!view.latestCompaction ? [{ role: "user", content: snap.turn.input }] : [],
1794
+ ...committed
1795
+ ];
1796
+ assertToolPairs(result);
1797
+ assertProjectedContinuations(committed, result);
1798
+ assertContinuations(result, model);
1799
+ const previous = [...snap.steps].reverse().find((s) => s.kind === "model_call" && s.status === "completed" && s.input !== void 0);
1800
+ const latestCompaction = [...snap.steps].reverse().find((s) => s.kind === "compaction" && s.status === "completed");
1801
+ if (previous && (!latestCompaction || latestCompaction.stepSeq < previous.stepSeq)) {
1802
+ const prefix = previous.input;
1803
+ if (JSON.stringify(withoutContinuations(result.slice(0, prefix.length))) !== JSON.stringify(withoutContinuations(prefix)))
1804
+ throw new Error("Context projection changed its committed prefix between compactions.");
1805
+ }
1806
+ return result;
1807
+ }
1808
+ mapSubOutputs(snap, agent) {
1809
+ const tools = this.tools.get(this.key(agent));
1810
+ return {
1811
+ ...snap,
1812
+ steps: snap.steps.map((step) => {
1813
+ const tool = tools?.get(step.toolName ?? "");
1814
+ if (step.modelOutput !== void 0 || step.kind !== "sub_turn" || step.status !== "completed" || !tool || !("kind" in tool) || !tool.mapOutput)
1815
+ return step;
1816
+ return {
1817
+ ...step,
1818
+ output: tool.mapOutput({
1819
+ status: "completed",
1820
+ output: step.output,
1821
+ outputText: typeof step.output === "string" ? step.output : "",
1822
+ turnId: step.childTurnId
1823
+ })
1824
+ };
1825
+ })
1826
+ };
1827
+ }
1828
+ toolSpecs(tools) {
1829
+ return [...tools.values()].map((tool) => {
1830
+ const schema = tool.modelInputSchema ?? ("~standard" in tool.inputSchema ? { type: "object" } : tool.inputSchema);
1831
+ return {
1832
+ name: tool.name,
1833
+ description: tool.description,
1834
+ inputSchema: json(schema)
1835
+ };
1836
+ });
1837
+ }
1838
+ async callModel(snap, lease, agent, tools, existing) {
1839
+ const stepId = existing?.stepId ?? id("model");
1840
+ const iteration = existing?.iteration ?? snap.turn.iteration + 1;
1841
+ const started = await this.storage.ledger.startStepAttempt({
1842
+ turnId: snap.turn.turnId,
1843
+ lease,
1844
+ stepId,
1845
+ kind: "execute",
1846
+ ...!existing ? {
1847
+ newStep: {
1848
+ stepId,
1849
+ kind: "model_call",
1850
+ operationKey: id("operation"),
1851
+ iteration
1852
+ }
1853
+ } : {}
1854
+ });
1855
+ const ctl = this.control(snap.turn, started.step);
1856
+ let response;
1857
+ try {
1858
+ const request = {
1859
+ messages: await this.messages(snap, agent),
1860
+ tools: this.toolSpecs(tools),
1861
+ signal: ctl.controller.signal
1862
+ };
1863
+ await this.reserveModel(snap.turn, lease, started.step, started.attempt.attemptNo);
1864
+ const iterator = this.model(agent.model).stream(request)[Symbol.asyncIterator]();
1865
+ while (true) {
1866
+ const item = await abortable(iterator.next(), ctl.controller.signal);
1867
+ if (item.done) break;
1868
+ const event = item.value;
1869
+ if (event.type === "response.completed") response = event.response;
1870
+ else if (event.type === "text.delta" || event.type === "reasoning.delta")
1871
+ this.emit(snap.turn, event.type, stepId, { delta: event.delta });
1872
+ else if (event.type === "tool_call.delta")
1873
+ this.emit(snap.turn, "tool.call.delta", stepId, {
1874
+ delta: event.delta,
1875
+ data: { toolCallId: event.id }
1876
+ });
1877
+ }
1878
+ if (!response) throw new Error("BoundModel stream did not contain a completed response.");
1879
+ const model = this.model(agent.model);
1880
+ if (response.protocolId !== model.protocolId || response.model !== model.model)
1881
+ throw new Error("Model result protocol/model mismatch.");
1882
+ assertContinuations(
1883
+ [
1884
+ {
1885
+ role: "assistant",
1886
+ content: response.toolCalls.map((call) => ({ type: "tool_call", ...call })),
1887
+ ...response.continuation ? { continuation: response.continuation } : {}
1888
+ }
1889
+ ],
1890
+ model
1891
+ );
1892
+ if (ctl.controller.signal.aborted) throw ctl.controller.signal.reason;
1893
+ const steps = [];
1894
+ const callIds = /* @__PURE__ */ new Set();
1895
+ for (const call of response.toolCalls) {
1896
+ if (callIds.has(call.id)) throw new Error(`Duplicate toolCallId ${call.id}.`);
1897
+ callIds.add(call.id);
1898
+ const tool = tools.get(call.name);
1899
+ steps.push({
1900
+ stepId: id("step"),
1901
+ operationKey: id("operation"),
1902
+ kind: tool && "kind" in tool ? "sub_turn" : "tool_exec",
1903
+ input: call.input,
1904
+ toolCallId: call.id,
1905
+ toolName: call.name,
1906
+ toolVersion: tool?.version ?? "missing",
1907
+ effect: tool && !("kind" in tool) ? tool.effect : "none",
1908
+ ...tool && "terminatesTurn" in tool && tool.terminatesTurn ? { terminatesTurn: true } : {}
1909
+ });
1910
+ }
1911
+ if (ctl.controller.signal.aborted) throw ctl.controller.signal.reason;
1912
+ const { continuation, rawResponse: _rawResponse, ...output } = response;
1913
+ const encoded = continuation === void 0 ? void 0 : new TextEncoder().encode(JSON.stringify(continuation));
1914
+ const continuationArtifact = encoded && encoded.byteLength > (this.config.continuationInlineThresholdBytes ?? 65536) ? await this.storage.artifacts.put({
1915
+ data: encoded,
1916
+ contentType: "application/json",
1917
+ ...snap.turn.scope ? { scope: snap.turn.scope } : {}
1918
+ }) : void 0;
1919
+ if (ctl.controller.signal.aborted) throw ctl.controller.signal.reason;
1920
+ await this.storage.ledger.commitModelAndDispatchSteps({
1921
+ turnId: snap.turn.turnId,
1922
+ lease,
1923
+ iteration,
1924
+ model: {
1925
+ stepId,
1926
+ operationKey: started.step.operationKey,
1927
+ attemptNo: started.attempt.attemptNo,
1928
+ input: withoutContinuations(request.messages),
1929
+ output,
1930
+ protocolId: response.protocolId,
1931
+ modelId: response.model,
1932
+ ...continuationArtifact ? { continuationArtifact, artifacts: [continuationArtifact] } : continuation === void 0 ? {} : { continuation },
1933
+ usage: response.usage
1934
+ },
1935
+ steps
1936
+ });
1937
+ await this.span(snap.turn, started.step, started.attempt.startedAt, "ok", response.usage);
1938
+ } catch (error) {
1939
+ const current = await this.snapshot(snap.turn.turnId);
1940
+ const step = current.steps.find((s) => s.stepId === stepId);
1941
+ if (current.turn.lease && step.status === "running") {
1942
+ await this.storage.ledger.completeStep({
1943
+ turnId: snap.turn.turnId,
1944
+ lease,
1945
+ stepId,
1946
+ expectedStepVersion: step.version,
1947
+ attemptNo: started.attempt.attemptNo,
1948
+ status: ctl.controller.signal.aborted ? "cancelled" : "failed",
1949
+ attemptStatus: ctl.controller.signal.aborted ? "cancelled" : "failed",
1950
+ ...response ? { usage: response.usage } : {},
1951
+ error: toErrorRecord(error, "MODEL_CALL_FAILED")
1952
+ });
1953
+ }
1954
+ if (!ctl.controller.signal.aborted) throw error;
1955
+ } finally {
1956
+ ctl.dispose();
1957
+ }
1958
+ }
1959
+ async compact(snap, lease, agent, existing) {
1960
+ const strategy = agent.contextStrategy;
1961
+ if (!strategy) throw new Error("Compaction strategy is no longer registered.");
1962
+ const stepId = existing?.stepId ?? id("compaction");
1963
+ const started = await this.storage.ledger.startStepAttempt({
1964
+ turnId: snap.turn.turnId,
1965
+ lease,
1966
+ stepId,
1967
+ kind: "execute",
1968
+ ...!existing ? {
1969
+ newStep: {
1970
+ stepId,
1971
+ kind: "compaction",
1972
+ operationKey: id("operation"),
1973
+ iteration: snap.turn.iteration + 1
1974
+ }
1975
+ } : {}
1976
+ });
1977
+ const ctl = this.control(snap.turn, started.step);
1978
+ const usages = [];
1979
+ let modelCalls = 0;
1980
+ let compactionModel;
1981
+ let mixedModels = false;
1982
+ try {
1983
+ const output = await abortable(
1984
+ strategy.compact(
1985
+ contextView(
1986
+ await hydrateContinuations(this.mapSubOutputs(snap, agent), this.storage.artifacts),
1987
+ agent.instructions ?? "",
1988
+ await this.sessionHistory(snap.turn)
1989
+ ),
1990
+ {
1991
+ signal: ctl.controller.signal,
1992
+ artifacts: this.storage.artifacts,
1993
+ callModel: async (request) => {
1994
+ await this.reserveModel(snap.turn, lease, started.step, started.attempt.attemptNo);
1995
+ modelCalls++;
1996
+ const usageIndex = usages.push({ ...unknownUsage }) - 1;
1997
+ const model = this.model(request.model ?? agent.model);
1998
+ if (compactionModel && (compactionModel.protocolId !== model.protocolId || compactionModel.model !== model.model))
1999
+ mixedModels = true;
2000
+ compactionModel ??= model;
2001
+ const response = await abortable(
2002
+ model.generate({
2003
+ messages: request.messages.map(
2004
+ (m) => ({
2005
+ role: m.role,
2006
+ content: m.content,
2007
+ ...m.continuation !== void 0 ? { continuation: m.continuation } : {}
2008
+ })
2009
+ ),
2010
+ signal: ctl.controller.signal,
2011
+ ...request.maxOutputTokens !== void 0 ? { maxOutputTokens: request.maxOutputTokens } : {}
2012
+ }),
2013
+ ctl.controller.signal
2014
+ );
2015
+ usages[usageIndex] = response.usage;
2016
+ if (response.protocolId !== model.protocolId || response.model !== model.model)
2017
+ throw new Error("Compaction model result protocol/model mismatch.");
2018
+ return { text: response.text, usage: response.usage };
2019
+ }
2020
+ }
2021
+ ),
2022
+ ctl.controller.signal
2023
+ );
2024
+ if (typeof output.summary !== "string")
2025
+ throw new Error("Compaction must return a summary string.");
2026
+ if (output.compactedUpToStepId) {
2027
+ const cut = snap.steps.find((step) => step.stepId === output.compactedUpToStepId);
2028
+ if (!cut || !isTerminalStepStatus(cut.status))
2029
+ throw new Error("Compaction cut point must be a committed Step.");
2030
+ projectSteps(snap.steps.filter((step) => step.stepSeq <= cut.stepSeq));
2031
+ }
2032
+ await this.storage.ledger.commitCompactionStep({
2033
+ turnId: snap.turn.turnId,
2034
+ lease,
2035
+ iteration: started.step.iteration,
2036
+ compactedUpToStepId: output.compactedUpToStepId,
2037
+ step: {
2038
+ stepId,
2039
+ operationKey: started.step.operationKey,
2040
+ attemptNo: started.attempt.attemptNo,
2041
+ output,
2042
+ ...modelCalls ? { usage: combinedUsage(usages) } : {},
2043
+ ...compactionModel && !mixedModels ? { protocolId: compactionModel.protocolId, modelId: compactionModel.model } : {},
2044
+ ...output.artifactRef ? { artifacts: [output.artifactRef] } : {}
2045
+ }
2046
+ });
2047
+ await this.span(
2048
+ snap.turn,
2049
+ started.step,
2050
+ started.attempt.startedAt,
2051
+ "ok",
2052
+ modelCalls ? combinedUsage(usages) : void 0
2053
+ );
2054
+ } catch (error) {
2055
+ await this.storage.ledger.completeStep({
2056
+ turnId: snap.turn.turnId,
2057
+ lease,
2058
+ stepId,
2059
+ attemptNo: started.attempt.attemptNo,
2060
+ expectedStepVersion: started.step.version,
2061
+ status: "failed",
2062
+ attemptStatus: "failed",
2063
+ ...modelCalls ? { usage: combinedUsage(usages) } : {},
2064
+ error: toErrorRecord(error, "COMPACTION_FAILED")
2065
+ });
2066
+ throw error;
2067
+ } finally {
2068
+ ctl.dispose();
2069
+ }
2070
+ }
2071
+ async reserveModel(turn, lease, step, attemptNo) {
2072
+ if (!await this.storage.ledger.reserveModelCall({
2073
+ turnId: turn.turnId,
2074
+ lease,
2075
+ stepId: step.stepId,
2076
+ attemptNo
2077
+ }))
2078
+ throw new HostControlError({
2079
+ code: "MAX_MODEL_CALLS",
2080
+ message: "Model call limit reached.",
2081
+ requestStage: "admission_rejected"
2082
+ });
2083
+ }
2084
+ async executeStep(turn, lease, step, tools) {
2085
+ const current = await this.snapshot(turn.turnId);
2086
+ let latest = current.steps.find((s) => s.stepId === step.stepId);
2087
+ if (isTerminalStepStatus(latest.status)) return;
2088
+ const tool = tools.get(step.toolName ?? "");
2089
+ if (latest.status === "pending" && !latest.prepared) {
2090
+ let validatedInput;
2091
+ let approvalId;
2092
+ let error;
2093
+ try {
2094
+ if (!tool || tool.version !== step.toolVersion)
2095
+ throw new Error("Registered tool version unavailable.");
2096
+ validatedInput = durableToolInput(await validateSchemaInput(tool.inputSchema, step.input));
2097
+ if (!("kind" in tool)) {
2098
+ const decision = typeof tool.approval === "function" ? await tool.approval({
2099
+ input: validatedInput,
2100
+ context: turn.context,
2101
+ ...turn.scope ? { scope: turn.scope } : {}
2102
+ }) : tool.approval;
2103
+ if (decision === "required") approvalId = id("approval");
2104
+ }
2105
+ } catch (failure) {
2106
+ error = toErrorRecord(failure, "TOOL_VALIDATION_FAILED");
2107
+ }
2108
+ latest = await this.storage.ledger.prepareToolStep({
2109
+ turnId: turn.turnId,
2110
+ lease,
2111
+ stepId: step.stepId,
2112
+ expectedStepVersion: latest.version,
2113
+ validatedInput,
2114
+ ...approvalId ? { approvalId } : {},
2115
+ ...error ? { error } : {}
2116
+ });
2117
+ if (latest.status !== "pending") return;
2118
+ }
2119
+ const reconcile = latest.status === "unknown" || latest.status === "running" && step.effect === "external";
2120
+ const started = await this.storage.ledger.startStepAttempt({
2121
+ turnId: turn.turnId,
2122
+ lease,
2123
+ stepId: step.stepId,
2124
+ kind: reconcile ? "reconcile" : "execute",
2125
+ expectedStepVersion: latest.version
2126
+ });
2127
+ const ctl = this.control(turn, step, step.effect === "external");
2128
+ const context = { ...ctl.context, attemptNo: started.attempt.attemptNo };
2129
+ let status = "completed";
2130
+ let output;
2131
+ let modelOutput;
2132
+ let evidence;
2133
+ let errorRecord;
2134
+ let invokedExternal = false;
2135
+ let invokedTool = false;
2136
+ try {
2137
+ if (!tool || tool.version !== step.toolVersion)
2138
+ throw new Error(`Tool ${step.toolName}@${step.toolVersion} is not registered.`);
2139
+ if (!reconcile && !("kind" in tool) && tool.effect === "none") {
2140
+ const previous = current.attempts.filter((a) => a.stepId === step.stepId).at(-1);
2141
+ const remaining = previous?.completedAt ? Date.parse(previous.completedAt) + (tool.retryPolicy?.backoffMs ?? 0) - Date.now() : 0;
2142
+ if (remaining > 0) await setTimeout$1(remaining, void 0, { signal: ctl.controller.signal });
2143
+ }
2144
+ const input = latest.prepared ? latest.validatedInput : await validateSchemaInput(tool.inputSchema, step.input);
2145
+ if ("kind" in tool) {
2146
+ if (turn.depth >= (this.config.limits?.maxSubTurnDepth ?? 8))
2147
+ throw new Error("maxSubTurnDepth exceeded.");
2148
+ const childAgent = [...this.agents.values()].find((a) => a.id === tool.targetAgent);
2149
+ if (!childAgent) throw new AgentNotRegisteredError(tool.targetAgent);
2150
+ const mapped = tool.mapInput(input, context);
2151
+ const childSession = await this.openSession(childAgent, {
2152
+ ...turn.scope ? { scope: turn.scope } : {},
2153
+ ...mapped.context ? { context: mapped.context } : {}
2154
+ });
2155
+ const child = await this.storage.ledger.dispatchSubTurn({
2156
+ turnId: turn.turnId,
2157
+ lease,
2158
+ parentStepId: step.stepId,
2159
+ child: {
2160
+ sessionId: childSession.id,
2161
+ turnId: id("turn"),
2162
+ input: mapped.prompt,
2163
+ ...childAgent.limits ? { limits: { ...childAgent.limits } } : {},
2164
+ toolExecution: childAgent.toolExecution ?? "parallel",
2165
+ propagation: { cancelWithParent: tool.propagation?.cancelWithParent ?? true }
2166
+ },
2167
+ childLease: { holderId: this.holderId, ttlMs: 3e4 }
2168
+ });
2169
+ this.schedule(child.turn.turnId);
2170
+ await this.flush();
2171
+ return;
2172
+ }
2173
+ if (reconcile) {
2174
+ const result = tool.reconcile ? await abortable(tool.reconcile(input, context), ctl.controller.signal) : { status: "unknown" };
2175
+ evidence = result;
2176
+ if (result.status === "completed") output = result.output;
2177
+ else if (result.status === "not_executed") status = "pending";
2178
+ else if (result.status === "failed") {
2179
+ status = "failed";
2180
+ errorRecord = { code: "RECONCILE_FAILED", message: result.reason };
2181
+ } else status = "unknown";
2182
+ } else {
2183
+ invokedExternal = tool.effect === "external";
2184
+ invokedTool = true;
2185
+ output = await abortable(tool.execute(input, context), ctl.controller.signal);
2186
+ }
2187
+ if (status === "completed")
2188
+ modelOutput = tool.toModelResult ? json(await tool.toModelResult(output, context)) : json(output);
2189
+ } catch (error) {
2190
+ status = reconcile || invokedExternal ? "unknown" : ctl.controller.signal.aborted ? "cancelled" : "failed";
2191
+ errorRecord = toErrorRecord(error, reconcile ? "RECONCILE_UNKNOWN" : "TOOL_FAILED");
2192
+ if (errorRecord.requestStage === "admission_rejected") status = "failed";
2193
+ } finally {
2194
+ ctl.dispose();
2195
+ }
2196
+ const after = await this.snapshot(turn.turnId);
2197
+ const afterStep = after.steps.find((s) => s.stepId === step.stepId);
2198
+ if (isTerminalTurnStatus(after.turn.status) || !after.turn.lease || isTerminalStepStatus(afterStep.status))
2199
+ return;
2200
+ const attemptStatus = status === "completed" || status === "pending" ? "succeeded" : status;
2201
+ if (status === "failed" && invokedTool && errorRecord?.requestStage !== "admission_rejected" && !reconcile && step.effect === "none" && tool && !("kind" in tool) && current.attempts.filter((a) => a.stepId === step.stepId && a.kind === "execute").length + 1 < (tool.retryPolicy?.maxAttempts ?? 1))
2202
+ status = "pending";
2203
+ await this.storage.ledger.completeStep({
2204
+ turnId: turn.turnId,
2205
+ lease,
2206
+ stepId: step.stepId,
2207
+ attemptNo: started.attempt.attemptNo,
2208
+ expectedStepVersion: started.step.version,
2209
+ status,
2210
+ attemptStatus,
2211
+ ...output !== void 0 ? { output } : {},
2212
+ ...modelOutput !== void 0 ? { modelOutput } : {},
2213
+ ...evidence !== void 0 ? { evidence } : {},
2214
+ ...errorRecord ? { error: errorRecord } : {}
2215
+ });
2216
+ await this.span(
2217
+ turn,
2218
+ step,
2219
+ started.attempt.startedAt,
2220
+ attemptStatus === "succeeded" ? "ok" : attemptStatus
2221
+ );
2222
+ await this.flush();
2223
+ }
2224
+ async span(turn, step, startedAt, status, usage) {
2225
+ for (const hook of this.config.hooks ?? []) {
2226
+ try {
2227
+ await hook.onSpanEnd?.({
2228
+ name: step.kind,
2229
+ startedAt,
2230
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
2231
+ status: status === "failed" ? "error" : status,
2232
+ sessionId: turn.sessionId,
2233
+ rootTurnId: turn.rootTurnId,
2234
+ turnId: turn.turnId,
2235
+ stepId: step.stepId,
2236
+ traceId: turn.rootTurnId,
2237
+ spanId: step.stepId,
2238
+ ...usage ? { usage } : {}
2239
+ });
2240
+ } catch {
2241
+ }
2242
+ }
2243
+ }
2244
+ async finish(turn, lease, status, output, error, stopReason, providerFinishReason, partial) {
2245
+ const input = {
2246
+ turnId: turn.turnId,
2247
+ lease,
2248
+ status,
2249
+ stopReason: stopReason ?? (error?.code === "MAX_MODEL_CALLS" ? "max_model_calls" : error?.code === "MAX_TOOL_CALLS" ? "max_tool_calls" : status === "completed" ? "end_turn" : "error"),
2250
+ ...providerFinishReason ? { providerFinishReason } : {},
2251
+ ...partial !== void 0 ? { partial } : {},
2252
+ ...output !== void 0 ? { output } : {},
2253
+ ...error ? { error } : {}
2254
+ };
2255
+ if (turn.parentTurnId) {
2256
+ const parent = await this.snapshot(turn.parentTurnId);
2257
+ const parentStep = parent.steps.find((s) => s.stepId === turn.parentStepId);
2258
+ const tool = this.tools.get(this.key(this.agent(parent.turn)))?.get(parentStep.toolName ?? "");
2259
+ let parentModelOutput = json(output ?? { status, error });
2260
+ if (status === "completed" && tool && "kind" in tool) {
2261
+ const mapped = tool.mapOutput ? tool.mapOutput({
2262
+ status,
2263
+ output,
2264
+ outputText: typeof output === "string" ? output : "",
2265
+ turnId: turn.turnId
2266
+ }) : output;
2267
+ const ctl = this.control(parent.turn, parentStep);
2268
+ try {
2269
+ parentModelOutput = tool.toModelResult ? json(await tool.toModelResult(mapped, ctl.context)) : json(mapped);
2270
+ } finally {
2271
+ ctl.dispose();
2272
+ }
2273
+ }
2274
+ const result = await this.storage.ledger.completeChildAndWakeParent({
2275
+ ...input,
2276
+ parentModelOutput
2277
+ });
2278
+ this.schedule(result.parent.turnId);
2279
+ } else {
2280
+ const result = await this.storage.ledger.finishTurnAndDequeue(input);
2281
+ if (result.nextTurn) this.schedule(result.nextTurn.turnId);
2282
+ }
2283
+ this.history.delete(turn.sessionId);
2284
+ await this.flush();
2285
+ }
2286
+ async steer(turnId, input, opts = {}) {
2287
+ const receipt = await this.commands.steer({ turnId, input, ...opts });
2288
+ if (receipt.status === "rejected")
2289
+ return { accepted: false, reason: receipt.rejectionReason ?? "invalid_state" };
2290
+ return {
2291
+ accepted: true,
2292
+ mode: receipt.resultTurnId === turnId ? "steered" : "promoted_to_turn",
2293
+ turnId: receipt.resultTurnId
2294
+ };
2295
+ }
2296
+ async command(kind, input) {
2297
+ const { commandId, actor, scope, ...payload } = input;
2298
+ const turn = (await this.snapshot(input.turnId)).turn;
2299
+ return this.dispatch({
2300
+ commandId: commandId ?? id("command"),
2301
+ issuedAt: (/* @__PURE__ */ new Date()).toISOString(),
2302
+ actor: { id: actor?.id ?? "local", ...actor, source: actor?.source ?? "local_api" },
2303
+ ...scope ?? turn.scope ? { scope: scope ?? turn.scope } : {},
2304
+ payload: { kind, ...payload }
2305
+ });
2306
+ }
2307
+ async dispatch(envelope) {
2308
+ this.assertOpen();
2309
+ const target = await this.storage.ledger.getTurnSnapshot(envelope.payload.turnId);
2310
+ if (target && this.config.authorizeCommand) {
2311
+ const authorization = await this.config.authorizeCommand(envelope, target.turn);
2312
+ if (!authorization.allowed) throw new CommandRejectedError("unauthorized");
2313
+ } else if (envelope.actor.source === "cloud_console")
2314
+ throw new CommandRejectedError("unauthorized");
2315
+ if (target && envelope.payload.kind === "resolve_unknown" && envelope.payload.resolution.kind === "confirmed_completed") {
2316
+ const step = target.steps.find(
2317
+ (s) => s.stepId === envelope.payload.stepId
2318
+ );
2319
+ const tool = this.tools.get(this.key(this.agent(target.turn)))?.get(step?.toolName ?? "");
2320
+ if (step && tool && !("kind" in tool)) {
2321
+ const ctl = this.control(target.turn, step);
2322
+ try {
2323
+ const resolution = envelope.payload.resolution;
2324
+ const modelOutput = step.status === "completed" && step.modelOutput !== void 0 ? step.modelOutput : tool.toModelResult ? json(await tool.toModelResult(resolution.output, ctl.context)) : json(resolution.output);
2325
+ envelope = {
2326
+ ...envelope,
2327
+ payload: { ...envelope.payload, resolution: { ...resolution, modelOutput } }
2328
+ };
2329
+ } finally {
2330
+ ctl.dispose();
2331
+ }
2332
+ }
2333
+ }
2334
+ const receipt = await this.storage.ledger.applyCommand(envelope);
2335
+ if (receipt.status === "applied") {
2336
+ if (envelope.payload.kind === "cancel" || envelope.payload.kind === "steer" && envelope.payload.urgency === "interrupt") {
2337
+ for (const [turnId, entries] of this.controllers) {
2338
+ const turn = (await this.snapshot(turnId)).turn;
2339
+ if (turnId === envelope.payload.turnId || envelope.payload.kind === "cancel" && isTerminalTurnStatus(turn.status)) {
2340
+ for (const entry of entries)
2341
+ if (envelope.payload.kind === "cancel" || !entry.external) entry.controller.abort();
2342
+ }
2343
+ }
2344
+ }
2345
+ if (receipt.resultTurnId) this.schedule(receipt.resultTurnId);
2346
+ if (target?.turn.parentTurnId) this.schedule(target.turn.parentTurnId);
2347
+ await this.flush();
2348
+ }
2349
+ return receipt;
2350
+ }
2351
+ async wait(turnId) {
2352
+ while (true) {
2353
+ let wake;
2354
+ const changed = new Promise((resolve) => {
2355
+ wake = resolve;
2356
+ });
2357
+ this.listeners.add(wake);
2358
+ try {
2359
+ const snap = await this.snapshot(turnId);
2360
+ const status = snap.turn.status;
2361
+ if (isTerminalTurnStatus(status) || status !== "queued" && status !== "running" && !snap.turn.wakeRequested && !this.jobs.has(turnId)) {
2362
+ const error = snap.turn.error ?? snap.steps.find((step) => step.status === "unknown" && step.error?.requestStage)?.error;
2363
+ return {
2364
+ status,
2365
+ turnId,
2366
+ outputText: typeof snap.turn.output === "string" ? snap.turn.output : "",
2367
+ ...snap.turn.output !== void 0 ? { output: snap.turn.output } : {},
2368
+ ...snap.turn.stopReason ? { stopReason: snap.turn.stopReason } : {},
2369
+ ...snap.turn.providerFinishReason ? { providerFinishReason: snap.turn.providerFinishReason } : {},
2370
+ ...snap.turn.partial !== void 0 ? { partial: snap.turn.partial } : {},
2371
+ unknownSteps: snap.steps.filter((s) => s.status === "unknown"),
2372
+ approvals: snap.approvals.filter((a) => a.status === "pending"),
2373
+ childSteps: snap.steps.filter((s) => s.status === "waiting_child"),
2374
+ usage: aggregateUsageTotals(
2375
+ snap.attempts.filter(
2376
+ (attempt) => attempt.status !== "running" && snap.steps.some(
2377
+ (step) => step.stepId === attempt.stepId && (step.kind === "model_call" || step.kind === "compaction" && attempt.usage !== void 0)
2378
+ )
2379
+ ).map((attempt) => attempt.usage ?? unknownUsage)
2380
+ ),
2381
+ ...error ? { error } : {}
2382
+ };
2383
+ }
2384
+ if (this.failures.has(turnId)) throw this.failures.get(turnId);
2385
+ if (this.closed) throw new Error("Runtime closed before Turn reached a resting state.");
2386
+ await changed;
2387
+ } finally {
2388
+ this.listeners.delete(wake);
2389
+ }
2390
+ }
2391
+ }
2392
+ async *stream(turnId, opts = {}) {
2393
+ let cursor = 0;
2394
+ if (opts.fromEventId) {
2395
+ const replay = await this.storage.outbox.read({
2396
+ consumerId: `${this.holderId}:cursor`,
2397
+ limit: Number.MAX_SAFE_INTEGER
2398
+ });
2399
+ const event = replay.events.find((event2) => event2.eventId === opts.fromEventId);
2400
+ if (!event) throw new Error("Stream event cursor is unavailable or was pruned.");
2401
+ cursor = event.seq;
2402
+ }
2403
+ const pending = [];
2404
+ const receive = (event) => {
2405
+ if (event.turnId === turnId || event.rootTurnId === turnId) {
2406
+ if (pending.length >= 1024) pending.shift();
2407
+ pending.push(event);
2408
+ }
2409
+ };
2410
+ this.realtime.add(receive);
2411
+ try {
2412
+ while (true) {
2413
+ let wake;
2414
+ const changed = new Promise((resolve) => {
2415
+ wake = resolve;
2416
+ });
2417
+ this.listeners.add(wake);
2418
+ try {
2419
+ const batch = await this.storage.outbox.read({
2420
+ consumerId: `${this.holderId}:stream:${turnId}`,
2421
+ afterSeq: cursor,
2422
+ limit: 1e4
2423
+ });
2424
+ let resting = false;
2425
+ for (const event of batch.events) {
2426
+ cursor = event.seq;
2427
+ if (event.turnId === turnId || event.rootTurnId === turnId) {
2428
+ yield event;
2429
+ if (event.turnId === turnId && ["turn.paused", "turn.completed", "turn.failed", "turn.cancelled"].includes(
2430
+ event.type
2431
+ ))
2432
+ resting = true;
2433
+ }
2434
+ }
2435
+ while (pending.length) yield pending.shift();
2436
+ const snap = await this.snapshot(turnId);
2437
+ if (resting || this.closed) return;
2438
+ if (isTerminalTurnStatus(snap.turn.status) || snap.turn.status.startsWith("waiting_") && !this.jobs.has(turnId) && !snap.turn.wakeRequested) {
2439
+ const tail = await this.storage.outbox.read({
2440
+ consumerId: `${this.holderId}:stream:${turnId}`,
2441
+ afterSeq: cursor,
2442
+ limit: 1e4
2443
+ });
2444
+ for (const event of tail.events)
2445
+ if (event.turnId === turnId || event.rootTurnId === turnId) yield event;
2446
+ return;
2447
+ }
2448
+ await changed;
2449
+ } finally {
2450
+ this.listeners.delete(wake);
2451
+ }
2452
+ }
2453
+ } finally {
2454
+ this.realtime.delete(receive);
2455
+ }
2456
+ }
2457
+ close() {
2458
+ this.closePromise ??= this.shutdown();
2459
+ return this.closePromise;
2460
+ }
2461
+ async shutdown() {
2462
+ this.closed = true;
2463
+ const owned = [...this.jobs.keys()];
2464
+ if (this.timer) clearInterval(this.timer);
2465
+ for (const entries of this.controllers.values())
2466
+ for (const entry of entries) entry.controller.abort();
2467
+ await Promise.allSettled([...this.jobs.values()]);
2468
+ for (const turnId of owned) {
2469
+ const snapshot = await this.snapshot(turnId);
2470
+ if (snapshot.turn.lease?.holderId === this.holderId) {
2471
+ try {
2472
+ await this.storage.ledger.releaseLease({ turnId, lease: snapshot.turn.lease });
2473
+ } catch (error) {
2474
+ if (!(error instanceof LeaseLostError)) throw error;
2475
+ }
2476
+ }
2477
+ }
2478
+ await this.config.cloud?.close();
2479
+ this.realtime.clear();
2480
+ for (const provider of this.providers) await provider.close();
2481
+ await this.storage.close();
2482
+ this.notify();
2483
+ }
2484
+ [Symbol.asyncDispose]() {
2485
+ return this.close();
2486
+ }
2487
+ };
2488
+ async function openRuntime(config = {}) {
2489
+ const runtime = new Runtime(config);
2490
+ await runtime.initialize();
2491
+ return runtime;
2492
+ }
2493
+ async function runAgent(agent, input, opts) {
2494
+ const runtime = await openRuntime({ agent });
2495
+ try {
2496
+ return await runtime.run(agent, input, opts);
2497
+ } finally {
2498
+ await runtime.close();
2499
+ }
2500
+ }
2501
+
2502
+ export { Runtime, SessionHandle, TurnHandle, defineAgent, defineContextStrategy, defineSubAgentTool, defineTool, memoryStorage, openRuntime, runAgent };
2503
+ //# sourceMappingURL=index.js.map
2504
+ //# sourceMappingURL=index.js.map