anchor-ai-sdk 0.8.3 → 0.8.6

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.
Files changed (50) hide show
  1. package/README.md +25 -3
  2. package/dist/engine/budgets.d.ts +65 -2
  3. package/dist/engine/budgets.d.ts.map +1 -1
  4. package/dist/engine/budgets.js +76 -1
  5. package/dist/engine/budgets.js.map +1 -1
  6. package/dist/engine/dispatch.d.ts.map +1 -1
  7. package/dist/engine/dispatch.js +3 -2
  8. package/dist/engine/dispatch.js.map +1 -1
  9. package/dist/engine/events.d.ts +26 -2
  10. package/dist/engine/events.d.ts.map +1 -1
  11. package/dist/engine/guardrails.d.ts +7 -0
  12. package/dist/engine/guardrails.d.ts.map +1 -1
  13. package/dist/engine/guardrails.js +12 -0
  14. package/dist/engine/guardrails.js.map +1 -1
  15. package/dist/engine/loop.d.ts +2 -2
  16. package/dist/engine/loop.d.ts.map +1 -1
  17. package/dist/engine/loop.js +260 -73
  18. package/dist/engine/loop.js.map +1 -1
  19. package/dist/engine/revival.d.ts.map +1 -1
  20. package/dist/engine/revival.js +2 -1
  21. package/dist/engine/revival.js.map +1 -1
  22. package/dist/engine/supervision.d.ts +34 -0
  23. package/dist/engine/supervision.d.ts.map +1 -0
  24. package/dist/engine/supervision.js +72 -0
  25. package/dist/engine/supervision.js.map +1 -0
  26. package/dist/engine/types.d.ts +75 -2
  27. package/dist/engine/types.d.ts.map +1 -1
  28. package/dist/index.d.ts +2 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +1 -0
  31. package/dist/index.js.map +1 -1
  32. package/dist/teams/delegate.d.ts +24 -5
  33. package/dist/teams/delegate.d.ts.map +1 -1
  34. package/dist/teams/delegate.js +136 -33
  35. package/dist/teams/delegate.js.map +1 -1
  36. package/dist/teams/index.d.ts +1 -0
  37. package/dist/teams/index.d.ts.map +1 -1
  38. package/dist/teams/index.js +1 -0
  39. package/dist/teams/index.js.map +1 -1
  40. package/dist/teams/steer.d.ts +40 -0
  41. package/dist/teams/steer.d.ts.map +1 -0
  42. package/dist/teams/steer.js +60 -0
  43. package/dist/teams/steer.js.map +1 -0
  44. package/dist/teams/types.d.ts +15 -1
  45. package/dist/teams/types.d.ts.map +1 -1
  46. package/dist/teams/types.js.map +1 -1
  47. package/dist/tools/types.d.ts +8 -0
  48. package/dist/tools/types.d.ts.map +1 -1
  49. package/dist/tools/types.js.map +1 -1
  50. package/package.json +1 -1
@@ -1,13 +1,14 @@
1
1
  import { createFinishTool } from "../tools/finish.js";
2
2
  import { validateRepos } from "../repo.js";
3
- import { BudgetTracker, DEFAULT_BUDGET_LIMITS, DEFAULT_MAX_OUTPUT_TOKENS, } from "./budgets.js";
3
+ import { BudgetTracker, DEFAULT_BUDGET_LIMITS, DEFAULT_CHILD_SOFT_CAP, DEFAULT_MAX_OUTPUT_TOKENS, } from "./budgets.js";
4
4
  import { DEFAULT_TRUNCATED_REPLY_CHARS, DEFAULT_MAX_ASSISTANT_CHARS, elideReply, spillReply, } from "./elision.js";
5
5
  import { compactConversation, compactConversationStructured, DEFAULT_COMPACTION, estimateTokens, renderCompactionHandoff, } from "./compaction.js";
6
6
  import { assistantMessage, conversationHistory, } from "./context.js";
7
7
  import { renderInboxTurn, } from "./inbox.js";
8
8
  import { defineTool } from "../tools/types.js";
9
9
  import { gitSnapshot } from "./snapshot.js";
10
- import { createDelegateTool } from "../teams/delegate.js";
10
+ import { createTeamTools } from "../teams/delegate.js";
11
+ import { steerDirective } from "../teams/steer.js";
11
12
  import { TraceFanout } from "../trace/sink.js";
12
13
  import { budgetWarning, revivalBlock, warnPercent as revivalWarnPercent, } from "./revival.js";
13
14
  import { phaseDisciplineBlock } from "./phase-discipline.js";
@@ -16,19 +17,19 @@ import { addRequirement, compileLedger, createLedger, ledgerGate, linkEvidence,
16
17
  import { llmJudge } from "../verify/index.js";
17
18
  import { dispatchToolCalls, } from "./dispatch.js";
18
19
  import { mintOperationId, reconcilePendingOperations, settleFromResult, } from "./operations.js";
19
- import { RepeatTracker, cappedReplyNudge, createCourseCorrect, emptyTurnNudge, proseCheckpoint as proseCheckpointMessage, repeatedCallNudge, silentNudge, verboseNudge, visibleOutputTokens, } from "./guardrails.js";
20
+ import { RepeatTracker, cappedReplyNudge, createCourseCorrect, emptyTurnNudge, proseCheckpoint as proseCheckpointMessage, repeatedCallNudge, silentNudge, verboseNudge, visibleOutputTokens, wrapUpNudge, } from "./guardrails.js";
21
+ import { CANCEL_GRACE, DEFAULT_CANCEL_GRACE_MS, DEFAULT_STALL_AFTER_MS, waitWithCancelGrace, } from "./supervision.js";
20
22
  import { pollBackgroundJobs, renderBackgroundResult, renderLostJob, waitForBackgroundJobs, } from "./background.js";
21
23
  export { userTurn } from "./types.js";
22
24
  /**
23
25
  * Ledger tools answer "what is the task", not "what did the work". Calling one
24
26
  * must never be captured as evidence about the work inside the ledger it
25
- * manages. `update_ledger` is the deprecated shim; the rest are its split
27
+ * manages. These are the split
26
28
  * successors.
27
29
  */
28
30
  const LEDGER_TOOL_NAMES = new Set([
29
31
  "create_task",
30
32
  "finish",
31
- "update_ledger",
32
33
  "add_requirement",
33
34
  "set_requirement_status",
34
35
  "link_evidence",
@@ -37,6 +38,63 @@ const LEDGER_TOOL_NAMES = new Set([
37
38
  "add_failure",
38
39
  "clear_failure",
39
40
  ]);
41
+ /** The child's most recent visible prose, for a budget-exhausted hand-back. */
42
+ function lastAssistantText(messages) {
43
+ for (let index = messages.length - 1; index >= 0; index--) {
44
+ const message = messages[index];
45
+ if (message.role === "assistant" &&
46
+ typeof message.content === "string" &&
47
+ message.content.trim()) {
48
+ return message.content.trim();
49
+ }
50
+ }
51
+ return "";
52
+ }
53
+ /**
54
+ * The last non-empty line of the child's most recent visible prose, capped for
55
+ * a progress record: what a wake-up message can quote as "it was doing X".
56
+ */
57
+ function lastAssistantLine(messages, max = 200) {
58
+ const full = lastAssistantText(messages);
59
+ if (!full)
60
+ return "";
61
+ const line = full
62
+ .split("\n")
63
+ .map((row) => row.trim())
64
+ .filter(Boolean)
65
+ .pop() ?? "";
66
+ return line.length > max ? line.slice(0, max) : line;
67
+ }
68
+ /**
69
+ * Paths named by a turn's tool calls, for progress. Best-effort: an
70
+ * unparseable call contributes nothing, so this can never fail a run.
71
+ */
72
+ function noteTouchedFiles(target, calls) {
73
+ for (const call of calls) {
74
+ try {
75
+ const parsed = call.arguments.trim()
76
+ ? JSON.parse(call.arguments)
77
+ : {};
78
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
79
+ const path = parsed.path;
80
+ if (typeof path === "string" && path.trim())
81
+ target.add(path.trim());
82
+ }
83
+ }
84
+ catch {
85
+ /* an unparseable call is not a file path */
86
+ }
87
+ }
88
+ }
89
+ /** "…, 3/20 steps, $0.42/$1.50" — the numbers a wrap-up nudge cites. */
90
+ function budgetLine(budget, steps) {
91
+ const parts = [`${steps}/${budget.limits.maxSteps} steps`];
92
+ if (budget.limits.maxWallClockMs !== undefined)
93
+ parts.push(`${Math.round(budget.wallClockMs() / 1000)}s/${Math.round(budget.limits.maxWallClockMs / 1000)}s`);
94
+ if (budget.costsKnown)
95
+ parts.push(`$${budget.costUsd.toFixed(2)}/$${budget.limits.maxUsd}`);
96
+ return parts.join(", ");
97
+ }
40
98
  async function runOne(input, opts, chain = {}) {
41
99
  const strategy = opts.strategy ?? opts.agent?.strategy;
42
100
  if (!strategy)
@@ -56,12 +114,24 @@ async function runOne(input, opts, chain = {}) {
56
114
  else
57
115
  opts.signal.addEventListener("abort", abortFromCaller, { once: true });
58
116
  }
117
+ // The signal every tool sees. It is the run's cancel signal plus, for a
118
+ // delegated child, its own wall-clock deadline: a tool call already in
119
+ // flight is aborted at the deadline, and the child concludes
120
+ // `budget_exhausted` with a partial hand-back. The run signal (used for the
121
+ // model call) stays separate, so a deadline never reads as a host cancel.
122
+ const toolController = new AbortController();
123
+ const toolSignal = toolController.signal;
124
+ const abortTools = () => toolController.abort();
125
+ if (signal.aborted)
126
+ toolController.abort();
127
+ else
128
+ signal.addEventListener("abort", abortTools, { once: true });
59
129
  const timers = [];
60
130
  const fanout = opts.traceSinks?.length
61
131
  ? new TraceFanout(opts.traceSinks)
62
132
  : null;
63
133
  let stopped = false;
64
- /** Idempotent: stop the timers, unlink the caller's signal, flush sinks. */
134
+ /** Idempotent: stop the timers, unlink the signals, flush sinks. */
65
135
  const stopLifecycle = async () => {
66
136
  if (stopped)
67
137
  return;
@@ -69,6 +139,7 @@ async function runOne(input, opts, chain = {}) {
69
139
  for (const timer of timers)
70
140
  clearInterval(timer);
71
141
  opts.signal?.removeEventListener("abort", abortFromCaller);
142
+ signal.removeEventListener("abort", abortTools);
72
143
  if (fanout)
73
144
  await fanout.flush();
74
145
  };
@@ -79,6 +150,13 @@ async function runOne(input, opts, chain = {}) {
79
150
  ...(chain.worker ? { worker: chain.worker } : {}),
80
151
  ...(chain.role ? { role: chain.role } : {}),
81
152
  };
153
+ // Activity bookkeeping for a delegated child's stall signal. Every event the
154
+ // child produces is activity; the one record this emits for a silent child
155
+ // is not.
156
+ let lastActivityAt = Date.now();
157
+ let stallReported = false;
158
+ let lastToolName;
159
+ let lastVerbName;
82
160
  const emit = (event) => {
83
161
  const attributed = Object.keys(traceAttribution).length > 0
84
162
  ? { ...event, ...traceAttribution }
@@ -90,6 +168,14 @@ async function runOne(input, opts, chain = {}) {
90
168
  catch {
91
169
  // A subscriber must never kill the run — same rule as sinks.
92
170
  }
171
+ if (event.type === "progress" && event.stalled)
172
+ return;
173
+ lastActivityAt = Date.now();
174
+ stallReported = false;
175
+ if (event.type === "tool_call") {
176
+ lastToolName = event.name;
177
+ lastVerbName = event.verb ?? event.name;
178
+ }
93
179
  };
94
180
  if (opts.repos?.length) {
95
181
  if (!opts.sandbox)
@@ -166,17 +252,19 @@ async function runOne(input, opts, chain = {}) {
166
252
  let summary = prior?.summary;
167
253
  let compaction = prior?.compaction;
168
254
  const budget = chain.budget ?? new BudgetTracker(opts.budgets);
169
- // ---- Delegated subagents ------------------------------------------------
170
- if (opts.team && Object.keys(opts.team.members).length > 0) {
171
- available.set("delegate", createDelegateTool({
172
- team: opts.team,
173
- parent: opts,
174
- budget,
175
- leaderName: strategy.name,
176
- emit,
177
- signal,
178
- runChild: (input, childOpts, link) => runOne(input, childOpts, link),
179
- }));
255
+ const cancelGraceMs = opts.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS;
256
+ const stallAfterMs = opts.stallAfterMs === false
257
+ ? false
258
+ : (opts.stallAfterMs ?? DEFAULT_STALL_AFTER_MS);
259
+ // A child's wall-clock budget must bite at its next tool boundary, not only
260
+ // at turn boundaries: give its tools a signal that aborts at the deadline,
261
+ // so a call already in flight is cut and no new call starts past it.
262
+ const wallClockLimit = budget.limits.maxWallClockMs;
263
+ if (chain.child && wallClockLimit !== undefined && wallClockLimit > 0) {
264
+ const remainingMs = Math.max(0, wallClockLimit - budget.wallClockMs());
265
+ const deadline = setTimeout(() => toolController.abort(), remainingMs);
266
+ deadline.unref?.();
267
+ timers.push(deadline);
180
268
  }
181
269
  // ---- Task contracts and the judge --------------------------------------
182
270
  const verifierOn = opts.verifier !== undefined && opts.verifier !== false;
@@ -251,8 +339,7 @@ async function runOne(input, opts, chain = {}) {
251
339
  // `op` and every field anyone might need let models mix operations up: an
252
340
  // "add" carrying `status`, `failure` and an existing id, repeated verbatim
253
341
  // until the engine stalled the turn. Each tool below does one job and asks
254
- // for only the fields that job needs. `update_ledger` stays as a deprecated
255
- // shim for callers that still name it.
342
+ // for only the fields that job needs; the old shim is gone.
256
343
  const runLedgerOp = async (op, input) => {
257
344
  const dependencyError = (requirementId) => {
258
345
  const requirement = ledger.requirements.find((item) => item.id === requirementId);
@@ -512,54 +599,7 @@ async function runOne(input, opts, chain = {}) {
512
599
  additionalProperties: false,
513
600
  },
514
601
  }, (input) => runLedgerOp("clear_failure", input), { verb: "Clearing a failure" }), "clear_failure");
515
- // Deprecated: the same operations, by name, with one open field list.
516
- const shim = defineTool({
517
- name: "update_ledger",
518
- description: "Deprecated — prefer add_requirement, set_requirement_status, link_evidence, verify_requirement, set_next_step, add_failure and clear_failure; each does one job with only the fields it needs. Kept for callers that still name it: add_requirement — text; link_evidence / verify — requirementId, evidenceId, claim; set_status — requirementId, status; set_next_step — text; add_failure / clear_failure — failure.",
519
- parameters: {
520
- type: "object",
521
- properties: {
522
- op: {
523
- type: "string",
524
- enum: [
525
- "add_requirement",
526
- "link_evidence",
527
- "verify",
528
- "set_status",
529
- "set_next_step",
530
- "add_failure",
531
- "clear_failure",
532
- ],
533
- },
534
- text: { type: "string" },
535
- required: { type: "boolean" },
536
- id: { type: "string" },
537
- phase: { type: "string" },
538
- dependsOn: { type: "array", items: { type: "string" } },
539
- requirementId: { type: "string" },
540
- evidenceId: { type: "string" },
541
- claim: { type: "string" },
542
- status: {
543
- type: "string",
544
- enum: ["open", "in_progress", "verified", "blocked", "waived"],
545
- },
546
- failure: { type: "string" },
547
- },
548
- required: ["op"],
549
- additionalProperties: false,
550
- },
551
- }, async (input) => {
552
- const raw = input;
553
- const op = String(raw.op ?? "") || inferLedgerOp(raw);
554
- if (!op)
555
- return {
556
- ok: false,
557
- content: 'Say which op, or call the focused tool: add_requirement {"text":"…"}, set_requirement_status {"requirementId":"r2","status":"blocked"}, add_failure {"failure":"…"}, set_next_step {"text":"…"}.',
558
- };
559
- return runLedgerOp(op, raw);
560
- }, { verb: "Updating the progress ledger" });
561
- install(shim, "update_ledger");
562
- return shim;
602
+ return available.get("add_requirement");
563
603
  };
564
604
  const installCompletionGate = () => {
565
605
  completionGate = async (summaryText, success) => {
@@ -809,6 +849,32 @@ async function runOne(input, opts, chain = {}) {
809
849
  let silentToolTurns = 0;
810
850
  let steps = 0;
811
851
  const stepsBefore = chain.stepsBefore ?? 0;
852
+ // ---- Delegated subagents ------------------------------------------------
853
+ // Registered here, after the step counters exist: a child's derived budget
854
+ // is computed from what the leader has left at the moment it delegates.
855
+ if (opts.team && Object.keys(opts.team.members).length > 0) {
856
+ const remaining = () => ({
857
+ steps: Math.max(0, budget.limits.maxSteps - stepsBefore - steps),
858
+ ...(budget.limits.maxWallClockMs !== undefined
859
+ ? { wallClockMs: Math.max(0, budget.limits.maxWallClockMs - budget.wallClockMs()) }
860
+ : {}),
861
+ usd: budget.costsKnown
862
+ ? Math.max(0, budget.limits.maxUsd - budget.costUsd)
863
+ : budget.limits.maxUsd,
864
+ });
865
+ const teamTools = createTeamTools({
866
+ team: opts.team,
867
+ parent: opts,
868
+ budget,
869
+ remaining,
870
+ leaderName: strategy.name,
871
+ emit,
872
+ signal,
873
+ runChild: (input, childOpts, link) => runOne(input, childOpts, link),
874
+ });
875
+ available.set("delegate", teamTools.delegate);
876
+ available.set("steer_worker", teamTools.steer);
877
+ }
812
878
  // Recovery for tools that declare an external effect. Scope defaults to the
813
879
  // thread; a store without either is a wiring bug, not a silent no-op.
814
880
  const operations = opts.operations;
@@ -907,6 +973,11 @@ async function runOne(input, opts, chain = {}) {
907
973
  // An empty turn (no text, no tool call) gets one correction. The flag is
908
974
  // how the next empty turn is recognized as "after the advisory."
909
975
  let emptyNudged = false;
976
+ // A delegated child is told to wrap up once, at its soft cap. The hard cap
977
+ // still ends the loop; the flag keeps the directive one-shot.
978
+ let softCapNudged = false;
979
+ /** Files the child has named in its tool calls, for progress. */
980
+ const touchedFiles = new Set();
910
981
  const proseCheckpoint = opts.guardrails?.proseCheckpoint ?? true;
911
982
  // The shared mechanic lives in guardrails.ts; the policy (when a correction
912
983
  // fires, and when it stops) stays here.
@@ -920,6 +991,70 @@ async function runOne(input, opts, chain = {}) {
920
991
  pendingProseCheck = true;
921
992
  },
922
993
  });
994
+ /**
995
+ * The compact record a host sees while a delegated child runs. One shape for
996
+ * the per-turn progress and for the stall signal, so a supervisor reads the
997
+ * same fields either way.
998
+ */
999
+ const emitProgress = (extra = {}) => {
1000
+ if (!chain.child || !chain.worker)
1001
+ return;
1002
+ const filesTouched = touchedFiles.size
1003
+ ? [...touchedFiles].slice(0, 20)
1004
+ : undefined;
1005
+ const lastText = lastAssistantLine(messages);
1006
+ const progress = {
1007
+ worker: chain.worker,
1008
+ agent: chain.agent ?? strategy.name,
1009
+ role: chain.role ?? "worker",
1010
+ steps,
1011
+ budgetUsed: budget.usedFraction(stepsBefore + steps),
1012
+ ...(lastToolName ? { lastTool: lastToolName } : {}),
1013
+ ...(lastVerbName ? { lastVerb: lastVerbName } : {}),
1014
+ ...(lastText ? { lastText } : {}),
1015
+ ...(filesTouched ? { filesTouched } : {}),
1016
+ ...(extra.stalled ? { stalled: true } : {}),
1017
+ ...(extra.stalledForMs !== undefined
1018
+ ? { stalledForMs: extra.stalledForMs }
1019
+ : {}),
1020
+ steer: (value) => chain.steer?.push(value) ?? false,
1021
+ nudge: (value) => chain.steer?.push(value) ?? false,
1022
+ };
1023
+ emit({
1024
+ type: "progress",
1025
+ worker: progress.worker,
1026
+ steps: progress.steps,
1027
+ budgetUsed: progress.budgetUsed,
1028
+ ...(progress.lastTool ? { lastTool: progress.lastTool } : {}),
1029
+ ...(progress.lastVerb ? { lastVerb: progress.lastVerb } : {}),
1030
+ ...(progress.lastText ? { lastText: progress.lastText } : {}),
1031
+ ...(progress.filesTouched ? { filesTouched: progress.filesTouched } : {}),
1032
+ ...(progress.stalled ? { stalled: true } : {}),
1033
+ ...(progress.stalledForMs !== undefined
1034
+ ? { stalledForMs: progress.stalledForMs }
1035
+ : {}),
1036
+ });
1037
+ try {
1038
+ opts.onProgress?.(progress);
1039
+ }
1040
+ catch {
1041
+ // A consumer callback must never kill the run.
1042
+ }
1043
+ };
1044
+ // A child that produces no event for `stallAfterMs` is reported ONCE; any
1045
+ // real activity resets the window. The engine neither cancels nor nudges —
1046
+ // the supervisor decides.
1047
+ if (chain.child && chain.worker && stallAfterMs !== false) {
1048
+ const tick = setInterval(() => {
1049
+ const idle = Date.now() - lastActivityAt;
1050
+ if (idle < stallAfterMs || stallReported)
1051
+ return;
1052
+ stallReported = true;
1053
+ emitProgress({ stalled: true, stalledForMs: idle });
1054
+ }, stallAfterMs);
1055
+ tick.unref?.();
1056
+ timers.push(tick);
1057
+ }
923
1058
  let checkpointRef;
924
1059
  let pauseRequested = false;
925
1060
  if (phaseOn) {
@@ -1524,6 +1659,31 @@ async function runOne(input, opts, chain = {}) {
1524
1659
  });
1525
1660
  }
1526
1661
  }
1662
+ // Leader directives land here, at the boundary, as ordinary runtime
1663
+ // messages in the child's own stream — never a tool result, so they
1664
+ // cannot forge evidence.
1665
+ if (chain.steer) {
1666
+ for (const directive of chain.steer.drain()) {
1667
+ messages.push({
1668
+ role: "user",
1669
+ origin: "engine",
1670
+ content: steerDirective(directive),
1671
+ });
1672
+ }
1673
+ }
1674
+ // Soft cap: a child is told to wrap up at 80% of its own budget, once.
1675
+ // It is a nudge, not a stop — the child can still hand back an answer.
1676
+ if (chain.child &&
1677
+ !softCapNudged &&
1678
+ budget.usedFraction(stepsBefore + steps) >= DEFAULT_CHILD_SOFT_CAP) {
1679
+ softCapNudged = true;
1680
+ await courseCorrect({
1681
+ kind: "child_wrap_up",
1682
+ detail: `step ${steps}: child reached ${Math.round(DEFAULT_CHILD_SOFT_CAP * 100)}% of its budget ` +
1683
+ `(${budgetLine(budget, stepsBefore + steps)}) — told to wrap up`,
1684
+ content: wrapUpNudge(Math.max(0, budget.limits.maxSteps - stepsBefore - steps), budgetLine(budget, stepsBefore + steps)),
1685
+ });
1686
+ }
1527
1687
  const over = budget.exceeded(stepsBefore + steps);
1528
1688
  if (over) {
1529
1689
  emit({
@@ -1531,6 +1691,15 @@ async function runOne(input, opts, chain = {}) {
1531
1691
  kind: "budget_exceeded",
1532
1692
  detail: over.detail,
1533
1693
  });
1694
+ // A child out of its OWN budget hands back what it has. The leader's
1695
+ // run continues; a worker hitting its cap is not the leader's failure.
1696
+ if (chain.child) {
1697
+ return conclude("budget_exhausted", {
1698
+ ok: false,
1699
+ summary: lastAssistantText(messages),
1700
+ error: over.detail,
1701
+ });
1702
+ }
1534
1703
  return conclude(over.kind === "steps" ? "max_steps" : "budget_exceeded", { ok: false, error: over.detail });
1535
1704
  }
1536
1705
  if (revivalOn && !revivalWarned) {
@@ -1653,7 +1822,7 @@ async function runOne(input, opts, chain = {}) {
1653
1822
  steps++;
1654
1823
  emit({ type: "llm_call_started", phase, step: steps });
1655
1824
  const modelMessages = forModel();
1656
- const response = await opts.llm.stream({
1825
+ const response = await waitWithCancelGrace(opts.llm.stream({
1657
1826
  messages: modelMessages,
1658
1827
  cacheBreakpoints: cacheBreakpointsFor(modelMessages),
1659
1828
  tools: [...available.values()].map((tool) => ({
@@ -1671,7 +1840,12 @@ async function runOne(input, opts, chain = {}) {
1671
1840
  }, (text) => emit({ type: "llm_text_delta", text }), {
1672
1841
  signal,
1673
1842
  onReasoning: (text) => emit({ type: "llm_reasoning_delta", text }),
1674
- });
1843
+ }), signal, cancelGraceMs);
1844
+ if (response === CANCEL_GRACE)
1845
+ return conclude("cancelled", {
1846
+ ok: false,
1847
+ error: "cancelled by signal",
1848
+ });
1675
1849
  budget.record(response.usage);
1676
1850
  emit({
1677
1851
  type: "llm_call_finished",
@@ -1822,7 +1996,7 @@ async function runOne(input, opts, chain = {}) {
1822
1996
  pendingProseCheck = false;
1823
1997
  let declared;
1824
1998
  let runaway = false;
1825
- const outcome = await dispatchToolCalls({
1999
+ const dispatched = await waitWithCancelGrace(dispatchToolCalls({
1826
2000
  calls: response.toolCalls,
1827
2001
  available,
1828
2002
  steps,
@@ -1836,7 +2010,7 @@ async function runOne(input, opts, chain = {}) {
1836
2010
  emitBackground,
1837
2011
  ...(operationRuntime ? { operations: operationRuntime } : {}),
1838
2012
  onMissingJournal,
1839
- signal,
2013
+ signal: toolSignal,
1840
2014
  pauseRequested: () => pauseRequested,
1841
2015
  onToolResult: (call, result) => {
1842
2016
  // Contract tools describe the ledger; they are not evidence about
@@ -1853,11 +2027,24 @@ async function runOne(input, opts, chain = {}) {
1853
2027
  });
1854
2028
  phaseEvidence.push(evidenceRef);
1855
2029
  },
1856
- });
2030
+ }), signal, cancelGraceMs);
2031
+ if (dispatched === CANCEL_GRACE)
2032
+ return conclude("cancelled", {
2033
+ ok: false,
2034
+ error: "cancelled by signal",
2035
+ });
2036
+ const outcome = dispatched;
1857
2037
  runaway = outcome.runaway;
1858
2038
  declared = outcome.declared;
1859
2039
  outstanding.push(...outcome.jobs);
1860
2040
  pendingSettlements.push(...outcome.settlements);
2041
+ // Progress for a delegated child: the leader's `delegate` call is still
2042
+ // open, so this is how a host sees the work (and may steer it). One
2043
+ // compact record per turn — never the child's transcript.
2044
+ if (chain.child && chain.worker) {
2045
+ noteTouchedFiles(touchedFiles, response.toolCalls);
2046
+ emitProgress();
2047
+ }
1861
2048
  // Materialization advisory (runtime-only, never persisted): a reasoning
1862
2049
  // model's hidden chain is stateless between calls, so after consecutive
1863
2050
  // turns that only call tools, nothing it understood is visible — and
@@ -1984,7 +2171,7 @@ function usageDelta(now, before) {
1984
2171
  }
1985
2172
  /** A required obligation still needs work, or an open failure blocks finish. */
1986
2173
  /**
1987
- * The op an `update_ledger` call means when it names none, from the fields it
2174
+ * The op a legacy ledger call means when it names none, from the fields it
1988
2175
  * carries — only where they point to exactly one op. A model that sends
1989
2176
  * `{requirementId, status}` meant set_status; refusing it costs a turn and
1990
2177
  * invites the same call again.