anchor-ai-sdk 0.8.3 → 0.8.5

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 +1 -1
  16. package/dist/engine/loop.d.ts.map +1 -1
  17. package/dist/engine/loop.js +256 -20
  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,7 +17,8 @@ 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
  /**
@@ -37,6 +39,63 @@ const LEDGER_TOOL_NAMES = new Set([
37
39
  "add_failure",
38
40
  "clear_failure",
39
41
  ]);
42
+ /** The child's most recent visible prose, for a budget-exhausted hand-back. */
43
+ function lastAssistantText(messages) {
44
+ for (let index = messages.length - 1; index >= 0; index--) {
45
+ const message = messages[index];
46
+ if (message.role === "assistant" &&
47
+ typeof message.content === "string" &&
48
+ message.content.trim()) {
49
+ return message.content.trim();
50
+ }
51
+ }
52
+ return "";
53
+ }
54
+ /**
55
+ * The last non-empty line of the child's most recent visible prose, capped for
56
+ * a progress record: what a wake-up message can quote as "it was doing X".
57
+ */
58
+ function lastAssistantLine(messages, max = 200) {
59
+ const full = lastAssistantText(messages);
60
+ if (!full)
61
+ return "";
62
+ const line = full
63
+ .split("\n")
64
+ .map((row) => row.trim())
65
+ .filter(Boolean)
66
+ .pop() ?? "";
67
+ return line.length > max ? line.slice(0, max) : line;
68
+ }
69
+ /**
70
+ * Paths named by a turn's tool calls, for progress. Best-effort: an
71
+ * unparseable call contributes nothing, so this can never fail a run.
72
+ */
73
+ function noteTouchedFiles(target, calls) {
74
+ for (const call of calls) {
75
+ try {
76
+ const parsed = call.arguments.trim()
77
+ ? JSON.parse(call.arguments)
78
+ : {};
79
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
80
+ const path = parsed.path;
81
+ if (typeof path === "string" && path.trim())
82
+ target.add(path.trim());
83
+ }
84
+ }
85
+ catch {
86
+ /* an unparseable call is not a file path */
87
+ }
88
+ }
89
+ }
90
+ /** "…, 3/20 steps, $0.42/$1.50" — the numbers a wrap-up nudge cites. */
91
+ function budgetLine(budget, steps) {
92
+ const parts = [`${steps}/${budget.limits.maxSteps} steps`];
93
+ if (budget.limits.maxWallClockMs !== undefined)
94
+ parts.push(`${Math.round(budget.wallClockMs() / 1000)}s/${Math.round(budget.limits.maxWallClockMs / 1000)}s`);
95
+ if (budget.costsKnown)
96
+ parts.push(`$${budget.costUsd.toFixed(2)}/$${budget.limits.maxUsd}`);
97
+ return parts.join(", ");
98
+ }
40
99
  async function runOne(input, opts, chain = {}) {
41
100
  const strategy = opts.strategy ?? opts.agent?.strategy;
42
101
  if (!strategy)
@@ -56,12 +115,24 @@ async function runOne(input, opts, chain = {}) {
56
115
  else
57
116
  opts.signal.addEventListener("abort", abortFromCaller, { once: true });
58
117
  }
118
+ // The signal every tool sees. It is the run's cancel signal plus, for a
119
+ // delegated child, its own wall-clock deadline: a tool call already in
120
+ // flight is aborted at the deadline, and the child concludes
121
+ // `budget_exhausted` with a partial hand-back. The run signal (used for the
122
+ // model call) stays separate, so a deadline never reads as a host cancel.
123
+ const toolController = new AbortController();
124
+ const toolSignal = toolController.signal;
125
+ const abortTools = () => toolController.abort();
126
+ if (signal.aborted)
127
+ toolController.abort();
128
+ else
129
+ signal.addEventListener("abort", abortTools, { once: true });
59
130
  const timers = [];
60
131
  const fanout = opts.traceSinks?.length
61
132
  ? new TraceFanout(opts.traceSinks)
62
133
  : null;
63
134
  let stopped = false;
64
- /** Idempotent: stop the timers, unlink the caller's signal, flush sinks. */
135
+ /** Idempotent: stop the timers, unlink the signals, flush sinks. */
65
136
  const stopLifecycle = async () => {
66
137
  if (stopped)
67
138
  return;
@@ -69,6 +140,7 @@ async function runOne(input, opts, chain = {}) {
69
140
  for (const timer of timers)
70
141
  clearInterval(timer);
71
142
  opts.signal?.removeEventListener("abort", abortFromCaller);
143
+ signal.removeEventListener("abort", abortTools);
72
144
  if (fanout)
73
145
  await fanout.flush();
74
146
  };
@@ -79,6 +151,13 @@ async function runOne(input, opts, chain = {}) {
79
151
  ...(chain.worker ? { worker: chain.worker } : {}),
80
152
  ...(chain.role ? { role: chain.role } : {}),
81
153
  };
154
+ // Activity bookkeeping for a delegated child's stall signal. Every event the
155
+ // child produces is activity; the one record this emits for a silent child
156
+ // is not.
157
+ let lastActivityAt = Date.now();
158
+ let stallReported = false;
159
+ let lastToolName;
160
+ let lastVerbName;
82
161
  const emit = (event) => {
83
162
  const attributed = Object.keys(traceAttribution).length > 0
84
163
  ? { ...event, ...traceAttribution }
@@ -90,6 +169,14 @@ async function runOne(input, opts, chain = {}) {
90
169
  catch {
91
170
  // A subscriber must never kill the run — same rule as sinks.
92
171
  }
172
+ if (event.type === "progress" && event.stalled)
173
+ return;
174
+ lastActivityAt = Date.now();
175
+ stallReported = false;
176
+ if (event.type === "tool_call") {
177
+ lastToolName = event.name;
178
+ lastVerbName = event.verb ?? event.name;
179
+ }
93
180
  };
94
181
  if (opts.repos?.length) {
95
182
  if (!opts.sandbox)
@@ -166,17 +253,19 @@ async function runOne(input, opts, chain = {}) {
166
253
  let summary = prior?.summary;
167
254
  let compaction = prior?.compaction;
168
255
  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
- }));
256
+ const cancelGraceMs = opts.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS;
257
+ const stallAfterMs = opts.stallAfterMs === false
258
+ ? false
259
+ : (opts.stallAfterMs ?? DEFAULT_STALL_AFTER_MS);
260
+ // A child's wall-clock budget must bite at its next tool boundary, not only
261
+ // at turn boundaries: give its tools a signal that aborts at the deadline,
262
+ // so a call already in flight is cut and no new call starts past it.
263
+ const wallClockLimit = budget.limits.maxWallClockMs;
264
+ if (chain.child && wallClockLimit !== undefined && wallClockLimit > 0) {
265
+ const remainingMs = Math.max(0, wallClockLimit - budget.wallClockMs());
266
+ const deadline = setTimeout(() => toolController.abort(), remainingMs);
267
+ deadline.unref?.();
268
+ timers.push(deadline);
180
269
  }
181
270
  // ---- Task contracts and the judge --------------------------------------
182
271
  const verifierOn = opts.verifier !== undefined && opts.verifier !== false;
@@ -809,6 +898,32 @@ async function runOne(input, opts, chain = {}) {
809
898
  let silentToolTurns = 0;
810
899
  let steps = 0;
811
900
  const stepsBefore = chain.stepsBefore ?? 0;
901
+ // ---- Delegated subagents ------------------------------------------------
902
+ // Registered here, after the step counters exist: a child's derived budget
903
+ // is computed from what the leader has left at the moment it delegates.
904
+ if (opts.team && Object.keys(opts.team.members).length > 0) {
905
+ const remaining = () => ({
906
+ steps: Math.max(0, budget.limits.maxSteps - stepsBefore - steps),
907
+ ...(budget.limits.maxWallClockMs !== undefined
908
+ ? { wallClockMs: Math.max(0, budget.limits.maxWallClockMs - budget.wallClockMs()) }
909
+ : {}),
910
+ usd: budget.costsKnown
911
+ ? Math.max(0, budget.limits.maxUsd - budget.costUsd)
912
+ : budget.limits.maxUsd,
913
+ });
914
+ const teamTools = createTeamTools({
915
+ team: opts.team,
916
+ parent: opts,
917
+ budget,
918
+ remaining,
919
+ leaderName: strategy.name,
920
+ emit,
921
+ signal,
922
+ runChild: (input, childOpts, link) => runOne(input, childOpts, link),
923
+ });
924
+ available.set("delegate", teamTools.delegate);
925
+ available.set("steer_worker", teamTools.steer);
926
+ }
812
927
  // Recovery for tools that declare an external effect. Scope defaults to the
813
928
  // thread; a store without either is a wiring bug, not a silent no-op.
814
929
  const operations = opts.operations;
@@ -907,6 +1022,11 @@ async function runOne(input, opts, chain = {}) {
907
1022
  // An empty turn (no text, no tool call) gets one correction. The flag is
908
1023
  // how the next empty turn is recognized as "after the advisory."
909
1024
  let emptyNudged = false;
1025
+ // A delegated child is told to wrap up once, at its soft cap. The hard cap
1026
+ // still ends the loop; the flag keeps the directive one-shot.
1027
+ let softCapNudged = false;
1028
+ /** Files the child has named in its tool calls, for progress. */
1029
+ const touchedFiles = new Set();
910
1030
  const proseCheckpoint = opts.guardrails?.proseCheckpoint ?? true;
911
1031
  // The shared mechanic lives in guardrails.ts; the policy (when a correction
912
1032
  // fires, and when it stops) stays here.
@@ -920,6 +1040,70 @@ async function runOne(input, opts, chain = {}) {
920
1040
  pendingProseCheck = true;
921
1041
  },
922
1042
  });
1043
+ /**
1044
+ * The compact record a host sees while a delegated child runs. One shape for
1045
+ * the per-turn progress and for the stall signal, so a supervisor reads the
1046
+ * same fields either way.
1047
+ */
1048
+ const emitProgress = (extra = {}) => {
1049
+ if (!chain.child || !chain.worker)
1050
+ return;
1051
+ const filesTouched = touchedFiles.size
1052
+ ? [...touchedFiles].slice(0, 20)
1053
+ : undefined;
1054
+ const lastText = lastAssistantLine(messages);
1055
+ const progress = {
1056
+ worker: chain.worker,
1057
+ agent: chain.agent ?? strategy.name,
1058
+ role: chain.role ?? "worker",
1059
+ steps,
1060
+ budgetUsed: budget.usedFraction(stepsBefore + steps),
1061
+ ...(lastToolName ? { lastTool: lastToolName } : {}),
1062
+ ...(lastVerbName ? { lastVerb: lastVerbName } : {}),
1063
+ ...(lastText ? { lastText } : {}),
1064
+ ...(filesTouched ? { filesTouched } : {}),
1065
+ ...(extra.stalled ? { stalled: true } : {}),
1066
+ ...(extra.stalledForMs !== undefined
1067
+ ? { stalledForMs: extra.stalledForMs }
1068
+ : {}),
1069
+ steer: (value) => chain.steer?.push(value) ?? false,
1070
+ nudge: (value) => chain.steer?.push(value) ?? false,
1071
+ };
1072
+ emit({
1073
+ type: "progress",
1074
+ worker: progress.worker,
1075
+ steps: progress.steps,
1076
+ budgetUsed: progress.budgetUsed,
1077
+ ...(progress.lastTool ? { lastTool: progress.lastTool } : {}),
1078
+ ...(progress.lastVerb ? { lastVerb: progress.lastVerb } : {}),
1079
+ ...(progress.lastText ? { lastText: progress.lastText } : {}),
1080
+ ...(progress.filesTouched ? { filesTouched: progress.filesTouched } : {}),
1081
+ ...(progress.stalled ? { stalled: true } : {}),
1082
+ ...(progress.stalledForMs !== undefined
1083
+ ? { stalledForMs: progress.stalledForMs }
1084
+ : {}),
1085
+ });
1086
+ try {
1087
+ opts.onProgress?.(progress);
1088
+ }
1089
+ catch {
1090
+ // A consumer callback must never kill the run.
1091
+ }
1092
+ };
1093
+ // A child that produces no event for `stallAfterMs` is reported ONCE; any
1094
+ // real activity resets the window. The engine neither cancels nor nudges —
1095
+ // the supervisor decides.
1096
+ if (chain.child && chain.worker && stallAfterMs !== false) {
1097
+ const tick = setInterval(() => {
1098
+ const idle = Date.now() - lastActivityAt;
1099
+ if (idle < stallAfterMs || stallReported)
1100
+ return;
1101
+ stallReported = true;
1102
+ emitProgress({ stalled: true, stalledForMs: idle });
1103
+ }, stallAfterMs);
1104
+ tick.unref?.();
1105
+ timers.push(tick);
1106
+ }
923
1107
  let checkpointRef;
924
1108
  let pauseRequested = false;
925
1109
  if (phaseOn) {
@@ -1524,6 +1708,31 @@ async function runOne(input, opts, chain = {}) {
1524
1708
  });
1525
1709
  }
1526
1710
  }
1711
+ // Leader directives land here, at the boundary, as ordinary runtime
1712
+ // messages in the child's own stream — never a tool result, so they
1713
+ // cannot forge evidence.
1714
+ if (chain.steer) {
1715
+ for (const directive of chain.steer.drain()) {
1716
+ messages.push({
1717
+ role: "user",
1718
+ origin: "engine",
1719
+ content: steerDirective(directive),
1720
+ });
1721
+ }
1722
+ }
1723
+ // Soft cap: a child is told to wrap up at 80% of its own budget, once.
1724
+ // It is a nudge, not a stop — the child can still hand back an answer.
1725
+ if (chain.child &&
1726
+ !softCapNudged &&
1727
+ budget.usedFraction(stepsBefore + steps) >= DEFAULT_CHILD_SOFT_CAP) {
1728
+ softCapNudged = true;
1729
+ await courseCorrect({
1730
+ kind: "child_wrap_up",
1731
+ detail: `step ${steps}: child reached ${Math.round(DEFAULT_CHILD_SOFT_CAP * 100)}% of its budget ` +
1732
+ `(${budgetLine(budget, stepsBefore + steps)}) — told to wrap up`,
1733
+ content: wrapUpNudge(Math.max(0, budget.limits.maxSteps - stepsBefore - steps), budgetLine(budget, stepsBefore + steps)),
1734
+ });
1735
+ }
1527
1736
  const over = budget.exceeded(stepsBefore + steps);
1528
1737
  if (over) {
1529
1738
  emit({
@@ -1531,6 +1740,15 @@ async function runOne(input, opts, chain = {}) {
1531
1740
  kind: "budget_exceeded",
1532
1741
  detail: over.detail,
1533
1742
  });
1743
+ // A child out of its OWN budget hands back what it has. The leader's
1744
+ // run continues; a worker hitting its cap is not the leader's failure.
1745
+ if (chain.child) {
1746
+ return conclude("budget_exhausted", {
1747
+ ok: false,
1748
+ summary: lastAssistantText(messages),
1749
+ error: over.detail,
1750
+ });
1751
+ }
1534
1752
  return conclude(over.kind === "steps" ? "max_steps" : "budget_exceeded", { ok: false, error: over.detail });
1535
1753
  }
1536
1754
  if (revivalOn && !revivalWarned) {
@@ -1653,7 +1871,7 @@ async function runOne(input, opts, chain = {}) {
1653
1871
  steps++;
1654
1872
  emit({ type: "llm_call_started", phase, step: steps });
1655
1873
  const modelMessages = forModel();
1656
- const response = await opts.llm.stream({
1874
+ const response = await waitWithCancelGrace(opts.llm.stream({
1657
1875
  messages: modelMessages,
1658
1876
  cacheBreakpoints: cacheBreakpointsFor(modelMessages),
1659
1877
  tools: [...available.values()].map((tool) => ({
@@ -1671,7 +1889,12 @@ async function runOne(input, opts, chain = {}) {
1671
1889
  }, (text) => emit({ type: "llm_text_delta", text }), {
1672
1890
  signal,
1673
1891
  onReasoning: (text) => emit({ type: "llm_reasoning_delta", text }),
1674
- });
1892
+ }), signal, cancelGraceMs);
1893
+ if (response === CANCEL_GRACE)
1894
+ return conclude("cancelled", {
1895
+ ok: false,
1896
+ error: "cancelled by signal",
1897
+ });
1675
1898
  budget.record(response.usage);
1676
1899
  emit({
1677
1900
  type: "llm_call_finished",
@@ -1822,7 +2045,7 @@ async function runOne(input, opts, chain = {}) {
1822
2045
  pendingProseCheck = false;
1823
2046
  let declared;
1824
2047
  let runaway = false;
1825
- const outcome = await dispatchToolCalls({
2048
+ const dispatched = await waitWithCancelGrace(dispatchToolCalls({
1826
2049
  calls: response.toolCalls,
1827
2050
  available,
1828
2051
  steps,
@@ -1836,7 +2059,7 @@ async function runOne(input, opts, chain = {}) {
1836
2059
  emitBackground,
1837
2060
  ...(operationRuntime ? { operations: operationRuntime } : {}),
1838
2061
  onMissingJournal,
1839
- signal,
2062
+ signal: toolSignal,
1840
2063
  pauseRequested: () => pauseRequested,
1841
2064
  onToolResult: (call, result) => {
1842
2065
  // Contract tools describe the ledger; they are not evidence about
@@ -1853,11 +2076,24 @@ async function runOne(input, opts, chain = {}) {
1853
2076
  });
1854
2077
  phaseEvidence.push(evidenceRef);
1855
2078
  },
1856
- });
2079
+ }), signal, cancelGraceMs);
2080
+ if (dispatched === CANCEL_GRACE)
2081
+ return conclude("cancelled", {
2082
+ ok: false,
2083
+ error: "cancelled by signal",
2084
+ });
2085
+ const outcome = dispatched;
1857
2086
  runaway = outcome.runaway;
1858
2087
  declared = outcome.declared;
1859
2088
  outstanding.push(...outcome.jobs);
1860
2089
  pendingSettlements.push(...outcome.settlements);
2090
+ // Progress for a delegated child: the leader's `delegate` call is still
2091
+ // open, so this is how a host sees the work (and may steer it). One
2092
+ // compact record per turn — never the child's transcript.
2093
+ if (chain.child && chain.worker) {
2094
+ noteTouchedFiles(touchedFiles, response.toolCalls);
2095
+ emitProgress();
2096
+ }
1861
2097
  // Materialization advisory (runtime-only, never persisted): a reasoning
1862
2098
  // model's hidden chain is stateless between calls, so after consecutive
1863
2099
  // turns that only call tools, nothing it understood is visible — and