@soiljs/agent 0.1.0 → 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 CHANGED
@@ -1,4 +1,4 @@
1
- import { AgentNotRegisteredError, LeaseLostError, ConcurrencyConflictError, isTerminalTurnStatus, isTerminalStepStatus, validateSchemaInput, CommandRejectedError, aggregateUsageTotals, IdempotencyConflictError, SessionBusyError } from '@soiljs/spi';
1
+ import { AgentNotRegisteredError, LeaseLostError, ConcurrencyConflictError, isTerminalTurnStatus, toErrorRecord, isTerminalStepStatus, HostControlError, validateSchemaInput, CommandRejectedError, aggregateUsageTotals, IdempotencyConflictError, SessionBusyError } from '@soiljs/spi';
2
2
  export * from '@soiljs/spi';
3
3
  import { createHash, randomUUID } from 'crypto';
4
4
  import { setTimeout as setTimeout$1 } from 'timers/promises';
@@ -131,11 +131,26 @@ function memoryStorage() {
131
131
  touch(turn);
132
132
  return lease;
133
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
+ }
134
148
  function recompute(snap) {
135
149
  const turn = snap.turn;
136
150
  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;
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;
139
154
  if (local || !blocker) {
140
155
  turn.wakeRequested = !turn.lease;
141
156
  touch(turn);
@@ -155,6 +170,7 @@ function memoryStorage() {
155
170
  input: input.input,
156
171
  context: input.context,
157
172
  limits: input.limits,
173
+ toolExecution: input.toolExecution,
158
174
  mode: input.mode
159
175
  });
160
176
  const previous = input.idempotencyKey ? state.admissions.get(key) : void 0;
@@ -180,6 +196,7 @@ function memoryStorage() {
180
196
  ...queued ? { queueSeq: ++state.queue } : {},
181
197
  ...input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {},
182
198
  ...input.limits ? { limits: input.limits } : {},
199
+ ...input.toolExecution ? { toolExecution: input.toolExecution } : {},
183
200
  rootTurnId: input.turnId,
184
201
  depth: 0,
185
202
  wakeRequested: false,
@@ -267,6 +284,12 @@ function memoryStorage() {
267
284
  step.output = { status, reason };
268
285
  step.completedAt = now();
269
286
  step.version++;
287
+ event(
288
+ snap.turn,
289
+ status === "failed" ? "step.failed" : "step.completed",
290
+ { reason, error: step.error },
291
+ step
292
+ );
270
293
  const approval = snap.approvals.find((a) => a.stepId === step.stepId && a.status === "pending");
271
294
  if (approval) {
272
295
  approval.status = "rejected";
@@ -285,7 +308,9 @@ function memoryStorage() {
285
308
  input: input.input,
286
309
  mode: "follow_up",
287
310
  lease: input.fallback.lease,
288
- context: { ...snap.turn.context }
311
+ context: { ...snap.turn.context },
312
+ ...snap.turn.toolExecution ? { toolExecution: snap.turn.toolExecution } : {},
313
+ ...snap.turn.limits ? { limits: { ...snap.turn.limits } } : {}
289
314
  });
290
315
  return { accepted: true, mode: "promoted_to_turn", turnId: next.turn.turnId };
291
316
  }
@@ -320,7 +345,14 @@ function memoryStorage() {
320
345
  const previousLease = turn.lease;
321
346
  Object.assign(
322
347
  turn,
323
- { status: input.status, completedAt: now(), wakeRequested: false },
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
+ },
324
356
  input.output !== void 0 ? { output: input.output } : {},
325
357
  input.error ? { error: input.error } : {},
326
358
  input.artifacts ? { artifacts: input.artifacts } : {}
@@ -329,7 +361,12 @@ function memoryStorage() {
329
361
  touch(turn);
330
362
  const owner = session(turn.sessionId);
331
363
  if (owner.activeTurnId === turn.turnId) delete owner.activeTurnId;
332
- event(turn, `turn.${input.status}`);
364
+ event(turn, `turn.${input.status}`, {
365
+ stopReason: turn.stopReason,
366
+ providerFinishReason: turn.providerFinishReason,
367
+ partial: turn.partial,
368
+ error: turn.error
369
+ });
333
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);
334
371
  if (input.drainQueued === "cancel")
335
372
  for (const queued of queue) cancel(get(queued.turnId), "queue_drained", false);
@@ -351,18 +388,20 @@ function memoryStorage() {
351
388
  owner.version++;
352
389
  return { turn };
353
390
  }
354
- function backwrite(child) {
391
+ function backwrite(child, modelOutput) {
355
392
  const parent = get(child.turn.parentTurnId);
356
393
  const step = parent.steps.find((s) => s.stepId === child.turn.parentStepId);
357
394
  if (!isTerminalStepStatus(step.status)) {
358
395
  step.status = child.turn.status === "completed" ? "completed" : child.turn.status === "cancelled" ? "cancelled" : "failed";
359
396
  step.output = child.turn.output ?? { status: child.turn.status, error: child.turn.error };
397
+ if (modelOutput !== void 0) step.modelOutput = modelOutput;
360
398
  step.completedAt = now();
361
399
  step.version++;
362
400
  const attempt = [...parent.attempts].reverse().find((a) => a.stepId === step.stepId && a.status === "running");
363
401
  if (attempt) {
364
402
  attempt.status = step.status === "completed" ? "succeeded" : step.status === "cancelled" ? "cancelled" : "failed";
365
403
  attempt.output = step.output;
404
+ if (modelOutput !== void 0) attempt.modelOutput = modelOutput;
366
405
  attempt.completedAt = now();
367
406
  }
368
407
  event(
@@ -376,7 +415,7 @@ function memoryStorage() {
376
415
  return { child: child.turn, parent: parent.turn, parentStep: step };
377
416
  }
378
417
  function cancel(snap, reason, cascade = true) {
379
- if (isTerminalTurnStatus(snap.turn.status)) return;
418
+ if (isTerminalTurnStatus(snap.turn.status) || snap.turn.completionIntent) return;
380
419
  for (const step of snap.steps) {
381
420
  if (isTerminalStepStatus(step.status) || step.status === "unknown") continue;
382
421
  if (step.status === "running" && step.effect === "external") {
@@ -393,13 +432,14 @@ function memoryStorage() {
393
432
  }
394
433
  }
395
434
  snap.turn.status = "cancelled";
435
+ snap.turn.stopReason = "cancelled";
396
436
  snap.turn.completedAt = now();
397
437
  snap.turn.wakeRequested = false;
398
438
  delete snap.turn.lease;
399
439
  touch(snap.turn);
400
440
  const owner = session(snap.turn.sessionId);
401
441
  if (owner.activeTurnId === snap.turn.turnId) delete owner.activeTurnId;
402
- event(snap.turn, "turn.cancelled", { reason });
442
+ event(snap.turn, "turn.cancelled", { reason, stopReason: "cancelled" });
403
443
  if (cascade) {
404
444
  for (const child of state.turns.values())
405
445
  if (child.turn.parentTurnId === snap.turn.turnId && child.turn.propagation?.cancelWithParent !== false)
@@ -491,6 +531,7 @@ function memoryStorage() {
491
531
  doneStep(snap, input.model, "model_call", input.iteration);
492
532
  snap.turn.iteration = input.iteration;
493
533
  for (const child of input.steps) {
534
+ if (child.terminatesTurn && snap.turn.toolExecution !== "sequential") conflict();
494
535
  const step = addStep(snap, child, input.iteration);
495
536
  event(snap.turn, "step.dispatched", void 0, step);
496
537
  if (step.status === "awaiting_approval") {
@@ -511,12 +552,77 @@ function memoryStorage() {
511
552
  recompute(snap);
512
553
  return snap;
513
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
+ }),
514
606
  startStepAttempt: (input) => transaction(() => {
515
607
  const snap = fence(input);
516
608
  let step = snap.steps.find((s) => s.stepId === input.stepId);
517
609
  if (!step && input.newStep) step = addStep(snap, input.newStep, input.newStep.iteration);
518
610
  if (!step || isTerminalStepStatus(step.status) || step.status === "awaiting_approval" || step.status === "waiting_child" || input.expectedStepVersion !== void 0 && input.expectedStepVersion !== step.version)
519
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
+ }
520
626
  if (step.status === "unknown" && input.kind !== "reconcile") conflict();
521
627
  for (const previous of snap.attempts.filter(
522
628
  (a) => a.stepId === step.stepId && a.status === "running"
@@ -531,6 +637,7 @@ function memoryStorage() {
531
637
  stepId: step.stepId,
532
638
  attemptNo: snap.attempts.filter((a) => a.stepId === step.stepId).length + 1,
533
639
  kind: input.kind,
640
+ modelCalls: 0,
534
641
  status: "running",
535
642
  holderId: input.lease.holderId,
536
643
  leaseEpoch: input.lease.epoch,
@@ -558,6 +665,7 @@ function memoryStorage() {
558
665
  step,
559
666
  { status: input.status, version: step.version + 1 },
560
667
  input.output !== void 0 ? { output: input.output } : {},
668
+ input.modelOutput !== void 0 ? { modelOutput: input.modelOutput } : {},
561
669
  input.artifacts ? { artifacts: input.artifacts } : {},
562
670
  input.usage ? { usage: input.usage } : {},
563
671
  input.error ? { error: input.error } : {},
@@ -567,6 +675,7 @@ function memoryStorage() {
567
675
  attempt,
568
676
  { status: input.attemptStatus, completedAt: now() },
569
677
  input.output !== void 0 ? { output: input.output } : {},
678
+ input.modelOutput !== void 0 ? { modelOutput: input.modelOutput } : {},
570
679
  input.artifacts ? { artifacts: input.artifacts } : {},
571
680
  input.usage ? { usage: input.usage } : {},
572
681
  input.error ? { error: input.error } : {},
@@ -574,6 +683,7 @@ function memoryStorage() {
574
683
  );
575
684
  if (input.status === "pending") {
576
685
  delete step.output;
686
+ delete step.modelOutput;
577
687
  delete step.error;
578
688
  delete step.artifacts;
579
689
  delete step.usage;
@@ -582,9 +692,15 @@ function memoryStorage() {
582
692
  event(
583
693
  snap.turn,
584
694
  input.status === "pending" ? "step.dispatched" : input.status === "unknown" ? "step.unknown" : input.status === "failed" ? "step.failed" : "step.completed",
585
- { attemptNo: input.attemptNo, attemptStatus: input.attemptStatus },
695
+ {
696
+ attemptNo: input.attemptNo,
697
+ attemptStatus: input.attemptStatus,
698
+ error: input.error,
699
+ ...step.terminatesTurn && input.status === "completed" ? { stopReason: "tool_terminated" } : {}
700
+ },
586
701
  step
587
702
  );
703
+ terminate(snap, step);
588
704
  recompute(snap);
589
705
  return step;
590
706
  }),
@@ -601,7 +717,8 @@ function memoryStorage() {
601
717
  input: input.child.input,
602
718
  mode: "reject",
603
719
  lease: input.childLease,
604
- ...input.child.limits ? { limits: input.child.limits } : {}
720
+ ...input.child.limits ? { limits: input.child.limits } : {},
721
+ ...input.child.toolExecution ? { toolExecution: input.child.toolExecution } : {}
605
722
  });
606
723
  Object.assign(admitted.turn, {
607
724
  parentTurnId: input.turnId,
@@ -628,7 +745,7 @@ function memoryStorage() {
628
745
  const child = fence(input);
629
746
  if (!child.turn.parentTurnId) conflict();
630
747
  finish(input);
631
- return backwrite(child);
748
+ return backwrite(child, input.parentModelOutput);
632
749
  }),
633
750
  applyCommand: (envelope) => transaction(() => {
634
751
  const key = fingerprint([envelope.scope, envelope.commandId]);
@@ -704,6 +821,8 @@ function memoryStorage() {
704
821
  if (resolution.kind === "confirmed_completed") {
705
822
  step.status = "completed";
706
823
  step.output = resolution.output;
824
+ if (resolution.modelOutput !== void 0) step.modelOutput = resolution.modelOutput;
825
+ terminate(snap, step);
707
826
  } else if (resolution.kind === "confirmed_not_executed") {
708
827
  step.status = resolution.retry ? "pending" : "cancelled";
709
828
  step.output = { status: "not_executed" };
@@ -950,7 +1069,9 @@ function projectSteps(steps) {
950
1069
  type: "tool_result",
951
1070
  toolCallId: call.id,
952
1071
  name: call.name,
953
- output: json(result.output ?? { status: result.status, error: result.error }),
1072
+ output: json(
1073
+ result.modelOutput !== void 0 ? result.modelOutput : result.output ?? { status: result.status, error: result.error }
1074
+ ),
954
1075
  isError: result.status !== "completed"
955
1076
  }
956
1077
  ]
@@ -964,7 +1085,7 @@ function contextView(snapshot, instructions, history = []) {
964
1085
  const compaction = [...snapshot.steps].reverse().find((s) => s.kind === "compaction" && s.status === "completed");
965
1086
  const output = compaction?.output;
966
1087
  const cut = output ? snapshot.steps.find((s) => s.stepId === output.compactedUpToStepId)?.stepSeq ?? 0 : 0;
967
- const steps = snapshot.steps.filter(
1088
+ const steps = snapshot.steps.map((step) => step.modelOutput !== void 0 ? { ...step, output: step.modelOutput } : step).filter(
968
1089
  (s) => s.stepSeq > cut && s.kind !== "compaction" && isTerminalStepStatus(s.status)
969
1090
  );
970
1091
  const messages = projectSteps(steps);
@@ -1028,6 +1149,20 @@ function combinedUsage(usages) {
1028
1149
  };
1029
1150
  }
1030
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
+ }
1031
1166
  function abortable(promise, signal) {
1032
1167
  if (signal.aborted) {
1033
1168
  void promise.catch(() => {
@@ -1171,7 +1306,10 @@ var Runtime = class {
1171
1306
  async register(agent) {
1172
1307
  const key = this.key(agent);
1173
1308
  if (this.agents.has(key)) return;
1174
- this.model(agent.model);
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.");
1175
1313
  const registry = /* @__PURE__ */ new Map();
1176
1314
  for (const entry of agent.tools ?? []) {
1177
1315
  if ("listTools" in entry) {
@@ -1189,6 +1327,8 @@ var Runtime = class {
1189
1327
  registry.set(entry.name, entry);
1190
1328
  }
1191
1329
  }
1330
+ if (agent.toolExecution !== "sequential" && [...registry.values()].some((tool) => "terminatesTurn" in tool && tool.terminatesTurn))
1331
+ throw new Error("Terminating tools require sequential toolExecution.");
1192
1332
  this.agents.set(key, agent);
1193
1333
  this.tools.set(key, registry);
1194
1334
  }
@@ -1223,11 +1363,20 @@ var Runtime = class {
1223
1363
  }
1224
1364
  async send(sessionId, input, opts = {}) {
1225
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.");
1226
1373
  const admitted = await this.storage.ledger.admitTurn({
1227
1374
  sessionId,
1228
1375
  turnId: id("turn"),
1229
1376
  input,
1230
1377
  ...opts,
1378
+ limits,
1379
+ toolExecution: agent.toolExecution ?? "parallel",
1231
1380
  mode: opts.mode ?? "reject",
1232
1381
  lease: { holderId: this.holderId, ttlMs: 3e4 }
1233
1382
  });
@@ -1316,10 +1465,13 @@ var Runtime = class {
1316
1465
  try {
1317
1466
  const snap = await this.snapshot(turnId);
1318
1467
  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
- });
1468
+ await this.finish(
1469
+ snap.turn,
1470
+ snap.turn.lease,
1471
+ "failed",
1472
+ void 0,
1473
+ toErrorRecord(error)
1474
+ );
1323
1475
  else this.failures.set(turnId, error);
1324
1476
  } catch (failure) {
1325
1477
  this.failures.set(turnId, failure);
@@ -1372,6 +1524,21 @@ var Runtime = class {
1372
1524
  ttlMs: 3e4
1373
1525
  });
1374
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
+ }
1375
1542
  async drive(turnId) {
1376
1543
  let snap = await this.snapshot(turnId);
1377
1544
  if (isTerminalTurnStatus(snap.turn.status) || snap.turn.status === "queued") return;
@@ -1397,10 +1564,56 @@ var Runtime = class {
1397
1564
  if (isTerminalTurnStatus(snap.turn.status)) return;
1398
1565
  const agent = this.agent(snap.turn);
1399
1566
  const tools = this.tools.get(this.key(agent));
1400
- const runnable = snap.steps.filter(
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(
1401
1614
  (s) => (s.kind === "tool_exec" || s.kind === "sub_turn") && (s.status === "pending" || s.status === "running")
1402
1615
  );
1403
- const unknown = snap.steps.filter(
1616
+ const unknown = eligible.filter(
1404
1617
  (s) => s.status === "unknown" && !probed.has(s.stepId) && s.toolName && "reconcile" in (tools.get(s.toolName) ?? {})
1405
1618
  );
1406
1619
  const interrupted = snap.steps.filter(
@@ -1414,14 +1627,42 @@ var Runtime = class {
1414
1627
  if (interrupted.length) {
1415
1628
  const step = interrupted[0];
1416
1629
  if (step.kind === "model_call") {
1417
- await this.callModel(snap, lease, agent, tools, step);
1630
+ await this.callModel(
1631
+ snap,
1632
+ lease,
1633
+ await this.resolveAgent(agent, snap.turn, step.iteration),
1634
+ tools,
1635
+ step
1636
+ );
1418
1637
  await this.flush();
1419
1638
  continue;
1420
1639
  }
1421
- await this.compact(snap, lease, agent, step);
1640
+ await this.compact(
1641
+ snap,
1642
+ lease,
1643
+ await this.resolveAgent(agent, snap.turn, step.iteration),
1644
+ step
1645
+ );
1422
1646
  continue;
1423
1647
  }
1424
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
+ }
1425
1666
  await Promise.all(
1426
1667
  [...runnable, ...unknown].map(async (step) => {
1427
1668
  if (step.status === "unknown") probed.add(step.stepId);
@@ -1435,18 +1676,51 @@ var Runtime = class {
1435
1676
  if (snap.turn.lease) await this.storage.ledger.releaseLease({ turnId, lease });
1436
1677
  return;
1437
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
+ }
1438
1692
  const final = [...snap.steps].reverse().find((s) => s.kind === "model_call");
1439
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")) {
1440
- await this.finish(snap.turn, lease, "completed", final.output.text);
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
+ );
1441
1707
  return;
1442
1708
  }
1443
1709
  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
- });
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
+ );
1448
1721
  return;
1449
1722
  }
1723
+ const resolved = await this.resolveAgent(agent, snap.turn, snap.turn.iteration + 1);
1450
1724
  const iteration = snap.turn.iteration + 1;
1451
1725
  await this.storage.ledger.consumeSteeringAndRecord({
1452
1726
  turnId,
@@ -1458,14 +1732,14 @@ var Runtime = class {
1458
1732
  snap = await this.snapshot(turnId);
1459
1733
  const view = contextView(
1460
1734
  await hydrateContinuations(this.mapSubOutputs(snap, agent), this.storage.artifacts),
1461
- agent.instructions,
1735
+ resolved.instructions ?? "",
1462
1736
  await this.sessionHistory(snap.turn)
1463
1737
  );
1464
1738
  if (agent.contextStrategy?.shouldCompact(view)) {
1465
- await this.compact(snap, lease, agent);
1739
+ await this.compact(snap, lease, resolved);
1466
1740
  snap = await this.snapshot(turnId);
1467
1741
  }
1468
- await this.callModel(snap, lease, agent, tools);
1742
+ await this.callModel(snap, lease, resolved, tools);
1469
1743
  await this.flush();
1470
1744
  }
1471
1745
  } finally {
@@ -1492,7 +1766,7 @@ var Runtime = class {
1492
1766
  const history = await this.sessionHistory(snap.turn);
1493
1767
  const view = contextView(
1494
1768
  await hydrateContinuations(this.mapSubOutputs(snap, agent), this.storage.artifacts),
1495
- agent.instructions,
1769
+ agent.instructions ?? "",
1496
1770
  history
1497
1771
  );
1498
1772
  const model = this.model(agent.model);
@@ -1514,7 +1788,7 @@ var Runtime = class {
1514
1788
  );
1515
1789
  else
1516
1790
  result = [
1517
- { role: "system", content: agent.instructions },
1791
+ { role: "system", content: agent.instructions ?? "" },
1518
1792
  ...view.latestCompaction ? [{ role: "user", content: view.latestCompaction.summary }] : history,
1519
1793
  ...!view.latestCompaction ? [{ role: "user", content: snap.turn.input }] : [],
1520
1794
  ...committed
@@ -1537,7 +1811,7 @@ var Runtime = class {
1537
1811
  ...snap,
1538
1812
  steps: snap.steps.map((step) => {
1539
1813
  const tool = tools?.get(step.toolName ?? "");
1540
- if (step.kind !== "sub_turn" || step.status !== "completed" || !tool || !("kind" in tool) || !tool.mapOutput)
1814
+ if (step.modelOutput !== void 0 || step.kind !== "sub_turn" || step.status !== "completed" || !tool || !("kind" in tool) || !tool.mapOutput)
1541
1815
  return step;
1542
1816
  return {
1543
1817
  ...step,
@@ -1553,7 +1827,7 @@ var Runtime = class {
1553
1827
  }
1554
1828
  toolSpecs(tools) {
1555
1829
  return [...tools.values()].map((tool) => {
1556
- const schema = "~standard" in tool.inputSchema ? { type: "object" } : tool.inputSchema;
1830
+ const schema = tool.modelInputSchema ?? ("~standard" in tool.inputSchema ? { type: "object" } : tool.inputSchema);
1557
1831
  return {
1558
1832
  name: tool.name,
1559
1833
  description: tool.description,
@@ -1586,6 +1860,7 @@ var Runtime = class {
1586
1860
  tools: this.toolSpecs(tools),
1587
1861
  signal: ctl.controller.signal
1588
1862
  };
1863
+ await this.reserveModel(snap.turn, lease, started.step, started.attempt.attemptNo);
1589
1864
  const iterator = this.model(agent.model).stream(request)[Symbol.asyncIterator]();
1590
1865
  while (true) {
1591
1866
  const item = await abortable(iterator.next(), ctl.controller.signal);
@@ -1621,19 +1896,6 @@ var Runtime = class {
1621
1896
  if (callIds.has(call.id)) throw new Error(`Duplicate toolCallId ${call.id}.`);
1622
1897
  callIds.add(call.id);
1623
1898
  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
1899
  steps.push({
1638
1900
  stepId: id("step"),
1639
1901
  operationKey: id("operation"),
@@ -1643,7 +1905,7 @@ var Runtime = class {
1643
1905
  toolName: call.name,
1644
1906
  toolVersion: tool?.version ?? "missing",
1645
1907
  effect: tool && !("kind" in tool) ? tool.effect : "none",
1646
- ...approval ? { status: "awaiting_approval", approvalId: id("approval") } : {}
1908
+ ...tool && "terminatesTurn" in tool && tool.terminatesTurn ? { terminatesTurn: true } : {}
1647
1909
  });
1648
1910
  }
1649
1911
  if (ctl.controller.signal.aborted) throw ctl.controller.signal.reason;
@@ -1686,10 +1948,7 @@ var Runtime = class {
1686
1948
  status: ctl.controller.signal.aborted ? "cancelled" : "failed",
1687
1949
  attemptStatus: ctl.controller.signal.aborted ? "cancelled" : "failed",
1688
1950
  ...response ? { usage: response.usage } : {},
1689
- error: {
1690
- code: "MODEL_CALL_FAILED",
1691
- message: error instanceof Error ? error.message : "BoundModel interrupted."
1692
- }
1951
+ error: toErrorRecord(error, "MODEL_CALL_FAILED")
1693
1952
  });
1694
1953
  }
1695
1954
  if (!ctl.controller.signal.aborted) throw error;
@@ -1725,13 +1984,14 @@ var Runtime = class {
1725
1984
  strategy.compact(
1726
1985
  contextView(
1727
1986
  await hydrateContinuations(this.mapSubOutputs(snap, agent), this.storage.artifacts),
1728
- agent.instructions,
1987
+ agent.instructions ?? "",
1729
1988
  await this.sessionHistory(snap.turn)
1730
1989
  ),
1731
1990
  {
1732
1991
  signal: ctl.controller.signal,
1733
1992
  artifacts: this.storage.artifacts,
1734
1993
  callModel: async (request) => {
1994
+ await this.reserveModel(snap.turn, lease, started.step, started.attempt.attemptNo);
1735
1995
  modelCalls++;
1736
1996
  const usageIndex = usages.push({ ...unknownUsage }) - 1;
1737
1997
  const model = this.model(request.model ?? agent.model);
@@ -1801,21 +2061,61 @@ var Runtime = class {
1801
2061
  status: "failed",
1802
2062
  attemptStatus: "failed",
1803
2063
  ...modelCalls ? { usage: combinedUsage(usages) } : {},
1804
- error: {
1805
- code: "COMPACTION_FAILED",
1806
- message: error instanceof Error ? error.message : "Compaction failed."
1807
- }
2064
+ error: toErrorRecord(error, "COMPACTION_FAILED")
1808
2065
  });
1809
2066
  throw error;
1810
2067
  } finally {
1811
2068
  ctl.dispose();
1812
2069
  }
1813
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
+ }
1814
2084
  async executeStep(turn, lease, step, tools) {
1815
2085
  const current = await this.snapshot(turn.turnId);
1816
- const latest = current.steps.find((s) => s.stepId === step.stepId);
2086
+ let latest = current.steps.find((s) => s.stepId === step.stepId);
1817
2087
  if (isTerminalStepStatus(latest.status)) return;
1818
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
+ }
1819
2119
  const reconcile = latest.status === "unknown" || latest.status === "running" && step.effect === "external";
1820
2120
  const started = await this.storage.ledger.startStepAttempt({
1821
2121
  turnId: turn.turnId,
@@ -1828,6 +2128,7 @@ var Runtime = class {
1828
2128
  const context = { ...ctl.context, attemptNo: started.attempt.attemptNo };
1829
2129
  let status = "completed";
1830
2130
  let output;
2131
+ let modelOutput;
1831
2132
  let evidence;
1832
2133
  let errorRecord;
1833
2134
  let invokedExternal = false;
@@ -1840,7 +2141,7 @@ var Runtime = class {
1840
2141
  const remaining = previous?.completedAt ? Date.parse(previous.completedAt) + (tool.retryPolicy?.backoffMs ?? 0) - Date.now() : 0;
1841
2142
  if (remaining > 0) await setTimeout$1(remaining, void 0, { signal: ctl.controller.signal });
1842
2143
  }
1843
- const input = await validateSchemaInput(tool.inputSchema, step.input);
2144
+ const input = latest.prepared ? latest.validatedInput : await validateSchemaInput(tool.inputSchema, step.input);
1844
2145
  if ("kind" in tool) {
1845
2146
  if (turn.depth >= (this.config.limits?.maxSubTurnDepth ?? 8))
1846
2147
  throw new Error("maxSubTurnDepth exceeded.");
@@ -1859,7 +2160,8 @@ var Runtime = class {
1859
2160
  sessionId: childSession.id,
1860
2161
  turnId: id("turn"),
1861
2162
  input: mapped.prompt,
1862
- ...childAgent.limits?.maxIterations !== void 0 ? { limits: { maxIterations: childAgent.limits.maxIterations } } : {},
2163
+ ...childAgent.limits ? { limits: { ...childAgent.limits } } : {},
2164
+ toolExecution: childAgent.toolExecution ?? "parallel",
1863
2165
  propagation: { cancelWithParent: tool.propagation?.cancelWithParent ?? true }
1864
2166
  },
1865
2167
  childLease: { holderId: this.holderId, ttlMs: 3e4 }
@@ -1882,12 +2184,12 @@ var Runtime = class {
1882
2184
  invokedTool = true;
1883
2185
  output = await abortable(tool.execute(input, context), ctl.controller.signal);
1884
2186
  }
2187
+ if (status === "completed")
2188
+ modelOutput = tool.toModelResult ? json(await tool.toModelResult(output, context)) : json(output);
1885
2189
  } catch (error) {
1886
2190
  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
- };
2191
+ errorRecord = toErrorRecord(error, reconcile ? "RECONCILE_UNKNOWN" : "TOOL_FAILED");
2192
+ if (errorRecord.requestStage === "admission_rejected") status = "failed";
1891
2193
  } finally {
1892
2194
  ctl.dispose();
1893
2195
  }
@@ -1896,7 +2198,7 @@ var Runtime = class {
1896
2198
  if (isTerminalTurnStatus(after.turn.status) || !after.turn.lease || isTerminalStepStatus(afterStep.status))
1897
2199
  return;
1898
2200
  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))
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))
1900
2202
  status = "pending";
1901
2203
  await this.storage.ledger.completeStep({
1902
2204
  turnId: turn.turnId,
@@ -1907,6 +2209,7 @@ var Runtime = class {
1907
2209
  status,
1908
2210
  attemptStatus,
1909
2211
  ...output !== void 0 ? { output } : {},
2212
+ ...modelOutput !== void 0 ? { modelOutput } : {},
1910
2213
  ...evidence !== void 0 ? { evidence } : {},
1911
2214
  ...errorRecord ? { error: errorRecord } : {}
1912
2215
  });
@@ -1938,16 +2241,40 @@ var Runtime = class {
1938
2241
  }
1939
2242
  }
1940
2243
  }
1941
- async finish(turn, lease, status, output, error) {
2244
+ async finish(turn, lease, status, output, error, stopReason, providerFinishReason, partial) {
1942
2245
  const input = {
1943
2246
  turnId: turn.turnId,
1944
2247
  lease,
1945
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 } : {},
1946
2252
  ...output !== void 0 ? { output } : {},
1947
2253
  ...error ? { error } : {}
1948
2254
  };
1949
2255
  if (turn.parentTurnId) {
1950
- const result = await this.storage.ledger.completeChildAndWakeParent(input);
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
+ });
1951
2278
  this.schedule(result.parent.turnId);
1952
2279
  } else {
1953
2280
  const result = await this.storage.ledger.finishTurnAndDequeue(input);
@@ -1985,6 +2312,25 @@ var Runtime = class {
1985
2312
  if (!authorization.allowed) throw new CommandRejectedError("unauthorized");
1986
2313
  } else if (envelope.actor.source === "cloud_console")
1987
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
+ }
1988
2334
  const receipt = await this.storage.ledger.applyCommand(envelope);
1989
2335
  if (receipt.status === "applied") {
1990
2336
  if (envelope.payload.kind === "cancel" || envelope.payload.kind === "steer" && envelope.payload.urgency === "interrupt") {
@@ -2013,11 +2359,15 @@ var Runtime = class {
2013
2359
  const snap = await this.snapshot(turnId);
2014
2360
  const status = snap.turn.status;
2015
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;
2016
2363
  return {
2017
2364
  status,
2018
2365
  turnId,
2019
2366
  outputText: typeof snap.turn.output === "string" ? snap.turn.output : "",
2020
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 } : {},
2021
2371
  unknownSteps: snap.steps.filter((s) => s.status === "unknown"),
2022
2372
  approvals: snap.approvals.filter((a) => a.status === "pending"),
2023
2373
  childSteps: snap.steps.filter((s) => s.status === "waiting_child"),
@@ -2028,7 +2378,7 @@ var Runtime = class {
2028
2378
  )
2029
2379
  ).map((attempt) => attempt.usage ?? unknownUsage)
2030
2380
  ),
2031
- ...snap.turn.error ? { error: snap.turn.error } : {}
2381
+ ...error ? { error } : {}
2032
2382
  };
2033
2383
  }
2034
2384
  if (this.failures.has(turnId)) throw this.failures.get(turnId);