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