@tangle-network/agent-runtime 10.0.6 → 10.0.8

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 (57) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/{activation-CT-rr2-5.d.ts → activation-Gi19oho7.d.ts} +2 -2
  3. package/dist/{activation-B3qLMoog.js → activation-pRO-xNlo.js} +2 -2
  4. package/dist/{activation-B3qLMoog.js.map → activation-pRO-xNlo.js.map} +1 -1
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +2 -2
  7. package/dist/{delegate-BFP1uCNY.js → delegate-ChsxEeFK.js} +2 -2
  8. package/dist/{delegate-BFP1uCNY.js.map → delegate-ChsxEeFK.js.map} +1 -1
  9. package/dist/{driver-control-acknowledgers-jdlf49OQ.js → driver-control-acknowledgers-DL-lN2Pb.js} +2 -2
  10. package/dist/{driver-control-acknowledgers-jdlf49OQ.js.map → driver-control-acknowledgers-DL-lN2Pb.js.map} +1 -1
  11. package/dist/durable.d.ts +1 -1
  12. package/dist/durable.js +4 -4
  13. package/dist/{graph-CiApRth2.js → graph-CKdDENlv.js} +4 -4
  14. package/dist/{graph-CiApRth2.js.map → graph-CKdDENlv.js.map} +1 -1
  15. package/dist/{improve-LJaiGxdI.js → improve-DNOZVLb-.js} +5 -5
  16. package/dist/{improve-LJaiGxdI.js.map → improve-DNOZVLb-.js.map} +1 -1
  17. package/dist/index.d.ts +3 -3
  18. package/dist/index.js +8 -8
  19. package/dist/intelligence.d.ts +2 -2
  20. package/dist/intelligence.js +3 -3
  21. package/dist/kernel.d.ts +1 -1
  22. package/dist/kernel.js +10 -10
  23. package/dist/{loop-runner-D6egvap-.d.ts → loop-runner-CPxQyiWQ.d.ts} +2 -2
  24. package/dist/{loop-runner-Dgow637w.js → loop-runner-DmDW9BKB.js} +2 -2
  25. package/dist/{loop-runner-Dgow637w.js.map → loop-runner-DmDW9BKB.js.map} +1 -1
  26. package/dist/loop-runner-bin.d.ts +1 -1
  27. package/dist/loop-runner-bin.js +1 -1
  28. package/dist/mcp/bin.js +2 -2
  29. package/dist/mcp/index.d.ts +1 -1
  30. package/dist/mcp/index.js +4 -4
  31. package/dist/profiles.d.ts +1 -1
  32. package/dist/{provision-supervisor-DLOeyFHV.js → provision-supervisor-DdsrpA3I.js} +3 -3
  33. package/dist/{provision-supervisor-DLOeyFHV.js.map → provision-supervisor-DdsrpA3I.js.map} +1 -1
  34. package/dist/{run-state-Bcci4zIN.js → run-state-CX8OTr-9.js} +2 -2
  35. package/dist/{run-state-Bcci4zIN.js.map → run-state-CX8OTr-9.js.map} +1 -1
  36. package/dist/{runtime-DCo0OP4n.js → runtime-ERkXbzFe.js} +10 -10
  37. package/dist/{runtime-DCo0OP4n.js.map → runtime-ERkXbzFe.js.map} +1 -1
  38. package/dist/{search-executor-Dn5YmHsg.js → search-executor-DDb4sT3E.js} +2 -2
  39. package/dist/{search-executor-Dn5YmHsg.js.map → search-executor-DDb4sT3E.js.map} +1 -1
  40. package/dist/{server-DxpG9y6W.js → server-B9tOx3CY.js} +2 -2
  41. package/dist/{server-DxpG9y6W.js.map → server-B9tOx3CY.js.map} +1 -1
  42. package/dist/{structural-rollout-DOmjcEMD.js → structural-rollout-B6RlFKxq.js} +2 -2
  43. package/dist/{structural-rollout-DOmjcEMD.js.map → structural-rollout-B6RlFKxq.js.map} +1 -1
  44. package/dist/{supervise-D7jtypE-.js → supervise-CikShHxF.js} +3 -3
  45. package/dist/{supervise-D7jtypE-.js.map → supervise-CikShHxF.js.map} +1 -1
  46. package/dist/{supervisor-BFs4u2Vo.js → supervisor-BvEe3y0c.js} +13 -9
  47. package/dist/supervisor-BvEe3y0c.js.map +1 -0
  48. package/dist/testing.d.ts +1 -1
  49. package/dist/testing.js +11 -11
  50. package/dist/tool-loop.d.ts +10 -1
  51. package/dist/tool-loop.js +182 -142
  52. package/dist/tool-loop.js.map +1 -1
  53. package/dist/tui/index.d.ts +1 -1
  54. package/dist/tui/index.js +1 -1
  55. package/dist/{types-CKsn_wgO.d.ts → types-BYiwLO2L.d.ts} +10 -1
  56. package/package.json +4 -3
  57. package/dist/supervisor-BFs4u2Vo.js.map +0 -1
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $g as RouterResponseReceipt, $h as Inbox, Aa as Agent, Db as EscalateQuestion, E as Budget, Eb as ChildQuestionInbox, Hb as ContinuityMode, Lx as AnalystRegistry, Rf as RunGraphTestOptions, Sh as SpawnResourceReader, Um as SupervisorFinalizer, Vf as runGraphWithTestBrain, Yb as MapOnSettleRoute, _b as DecideGate, aa as ResultBlobStore, at as MakeWorkerAgent, c_ as ToolLoopToolCall, ct as SpawnPreflight, eh as CoordinationDeliveryEvidence, ft as SuperviseProfileEntry, gb as WorkerWatchOptions, i_ as ToolLoopChat, it as GraphSubtasks, jm as StopRule, kv as DeliverableSpec, lt as SpawnPreflightContext, o_ as ToolLoopCompactionOptions, ot as PeerAuditAccess, pC as HarnessTranscriptCapture, pf as superviseWithTestBrain, r_ as ToolLoopCallContext, rh as PriorCoordination, rt as GraphSubtaskPreparation, s_ as ToolLoopMessageRecord, tt as CoordinationTools, ub as CoordinationEvent, um as supervisorAgentWithTestBrain, ut as SpawnRefusal, vf as SuperviseTestOptions, vx as McpToolDescriptor, wm as ManagerWakePolicy, xb as RouteFlow, xx as BusRecord, yS as RunCancelRequest, ym as SupervisorAgentTestDeps, zb as AuthorizeDownMessage, zx as AnalyzeOnSettleRoute } from "./types-CKsn_wgO.js";
1
+ import { $g as RouterResponseReceipt, $h as Inbox, Aa as Agent, Db as EscalateQuestion, E as Budget, Eb as ChildQuestionInbox, Hb as ContinuityMode, Lx as AnalystRegistry, Rf as RunGraphTestOptions, Sh as SpawnResourceReader, Um as SupervisorFinalizer, Vf as runGraphWithTestBrain, Yb as MapOnSettleRoute, _b as DecideGate, aa as ResultBlobStore, at as MakeWorkerAgent, c_ as ToolLoopToolCall, ct as SpawnPreflight, eh as CoordinationDeliveryEvidence, ft as SuperviseProfileEntry, gb as WorkerWatchOptions, i_ as ToolLoopChat, it as GraphSubtasks, jm as StopRule, kv as DeliverableSpec, lt as SpawnPreflightContext, o_ as ToolLoopCompactionOptions, ot as PeerAuditAccess, pC as HarnessTranscriptCapture, pf as superviseWithTestBrain, r_ as ToolLoopCallContext, rh as PriorCoordination, rt as GraphSubtaskPreparation, s_ as ToolLoopMessageRecord, tt as CoordinationTools, ub as CoordinationEvent, um as supervisorAgentWithTestBrain, ut as SpawnRefusal, vf as SuperviseTestOptions, vx as McpToolDescriptor, wm as ManagerWakePolicy, xb as RouteFlow, xx as BusRecord, yS as RunCancelRequest, ym as SupervisorAgentTestDeps, zb as AuthorizeDownMessage, zx as AnalyzeOnSettleRoute } from "./types-BYiwLO2L.js";
2
2
  import { AgentImprovementProposal, AgentProfile, AgentProfileImprovementMeasuredComparison, SandboxSizePreset } from "@tangle-network/agent-interface";
3
3
  /** What the brain returned for one turn, as the recorder keeps it. */
4
4
  interface RouterTranscriptReply {
package/dist/testing.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { m as canonicalCandidateDigest$1, v as immutableCandidateValue } from "./output-artifacts-AqkZ8lO2.js";
2
2
  import { a as applyExactAgentProfileDiff, v as parseExactAgentProfile } from "./profile-Cxl_Ajl2.js";
3
- import { c as verifyAgentImprovementProposal } from "./activation-B3qLMoog.js";
4
- import { o as supervisorAgentWithTestBrain, p as driverAgent, r as superviseWithTestBrain } from "./supervise-D7jtypE-.js";
5
- import { r as runGraphWithTestBrain } from "./graph-CiApRth2.js";
3
+ import { c as verifyAgentImprovementProposal } from "./activation-pRO-xNlo.js";
4
+ import { o as supervisorAgentWithTestBrain, p as driverAgent, r as superviseWithTestBrain } from "./supervise-CikShHxF.js";
5
+ import { r as runGraphWithTestBrain } from "./graph-CKdDENlv.js";
6
6
  import { SANDBOX_SIZE_PRESET_NAMES, canonicalAgentProfileDigest } from "@tangle-network/agent-interface";
7
7
  // src/testing/fixtures/agent-improvement-proposal.json
8
8
  var agent_improvement_proposal_default = {
9
9
  changedSurfaces: ["prompt"],
10
- digest: "sha256:3184e344f25618dfbe3a0283d5eef83276e9c13beeae5f567076450c396d316c",
10
+ digest: "sha256:f1363ac3680f6ae600028f0d0a303a159a5217e748e393d8fbd4abe5221b4907",
11
11
  evaluation: {
12
12
  "decision": {
13
13
  "contributingChecks": [
@@ -4578,7 +4578,7 @@ var agent_improvement_proposal_default = {
4578
4578
  ],
4579
4579
  "metadata": {
4580
4580
  "fixture": "agent-improvement-proposal",
4581
- "runtimeVersion": "10.0.6"
4581
+ "runtimeVersion": "10.0.8"
4582
4582
  },
4583
4583
  "objectives": [
4584
4584
  {
@@ -4689,8 +4689,8 @@ var agent_improvement_proposal_default = {
4689
4689
  "baselineContentHash": "sha256:5c21ee53e513fc604cb09754e21c392b24a424da0ef37dbf8f1ee4a8a0b08f09",
4690
4690
  "candidateContentHash": "sha256:60fcbb1c728194bd51d7d19cb732d1c3f1881dce7e0a6266b41c8b98cfd65693",
4691
4691
  "kind": "agent-eval-loop",
4692
- "recordDigest": "sha256:3a59451d66b745ba551e44de07fa2c419edd929e9553f31943e83dc2f770543e",
4693
- "runId": "agent-runtime-10.0.6-proposal-fixture",
4692
+ "recordDigest": "sha256:49a1c8b1fef7005ef7b450d0294b50ff42d5b30921231fc7c7b8a4a0e1acf85e",
4693
+ "runId": "agent-runtime-10.0.8-proposal-fixture",
4694
4694
  "schema": "agent-candidate-experiment"
4695
4695
  }
4696
4696
  },
@@ -4713,12 +4713,12 @@ var agent_improvement_proposal_default = {
4713
4713
  }],
4714
4714
  kind: "agent-improvement-proposal",
4715
4715
  proposedAt: "2026-07-10T01:00:00.000Z",
4716
- runId: "agent-runtime-10.0.6-proposal-fixture"
4716
+ runId: "agent-runtime-10.0.8-proposal-fixture"
4717
4717
  };
4718
4718
  // src/testing/fixtures/agent-profile-improvement-proposal.json
4719
4719
  var agent_profile_improvement_proposal_default = {
4720
4720
  changedSurfaces: ["prompt", "skills"],
4721
- digest: "sha256:e9518583c3433a27459791fd7ab8030407694cfbe61cccd1ba1e2dda8c8852af",
4721
+ digest: "sha256:6301ebf6e1a0f10e97e5dd19db142db1e721f841bd4c1c7967d53d0af015004a",
4722
4722
  evaluation: {
4723
4723
  "decision": {
4724
4724
  "contributingChecks": [
@@ -6352,7 +6352,7 @@ var agent_profile_improvement_proposal_default = {
6352
6352
  ],
6353
6353
  "metadata": {
6354
6354
  "fixture": "agent-profile-improvement-proposal",
6355
- "runtimeVersion": "10.0.6"
6355
+ "runtimeVersion": "10.0.8"
6356
6356
  },
6357
6357
  "objectives": [
6358
6358
  {
@@ -6463,7 +6463,7 @@ var agent_profile_improvement_proposal_default = {
6463
6463
  "baselineContentHash": "sha256:21c495a37c418c10bde64fbaa188beddeed31f1f051ea60a6a6582a9ee0db704",
6464
6464
  "candidateContentHash": "sha256:103f77bc8481601eef1ad5fe6ba84a40dffabc3a44f421f8c8559121edab84e9",
6465
6465
  "kind": "agent-eval-loop",
6466
- "recordDigest": "sha256:8f2bed4fafde0d8c60f970fc0724e0fa77edeef86212082fa94866bae5da88b5",
6466
+ "recordDigest": "sha256:28e0876b5fc47cec522f431d2e137250bf0cb2c6db3a9cda4fd51650bfa5da0a",
6467
6467
  "runId": "profile-improvement-1",
6468
6468
  "schema": "agent-profile-improvement-experiment"
6469
6469
  }
@@ -89,7 +89,7 @@ export type ToolLoopEvent = {
89
89
  event: unknown;
90
90
  };
91
91
  /** Why the loop stopped. `completed` = model finished naturally; `stuck-loop` =
92
- * ≥3 consecutive identical tool calls (same tool + args); `backstop` = hit the
92
+ * ≥3 consecutive model turns issuing the same calls (tool + args); `backstop` = hit the
93
93
  * runaway-backstop cap (200 by default); `deadline` = wall-clock deadlineMs
94
94
  * exceeded; `budget` = maxCostUsd exhausted. Non-`completed` stops are infra /
95
95
  * resource outcomes — eval scoring must distinguish them from capability failure. */
@@ -125,6 +125,10 @@ export interface RunToolLoopOptions {
125
125
  maxCostUsd?: number;
126
126
  /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */
127
127
  costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number;
128
+ /** How many of one model turn's calls run at once. Default 1: one at a time, in call order.
129
+ * Above 1, results and tool messages still keep call order; once `maxCostUsd` is spent no
130
+ * further call starts, and the turn stops with `budget` after the started calls settle. */
131
+ maxConcurrentToolCalls?: number;
128
132
  renderResult?: (label: string, outcome: ToolCallOutcome) => string;
129
133
  labelFor?: (call: ToolLoopCall) => string;
130
134
  runId?: string;
@@ -175,6 +179,11 @@ export interface StreamToolLoopOptions<Raw> {
175
179
  maxCostUsd?: number;
176
180
  /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */
177
181
  costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number;
182
+ /** How many of one model turn's calls run at once. Default 1: one at a time, in call order.
183
+ * Above 1, each call's `tool_progress` streams as it lands; `tool_result`s and tool messages
184
+ * keep call order. Once `maxCostUsd` is spent no further call starts, and the turn stops
185
+ * with `budget` after the started calls settle. */
186
+ maxConcurrentToolCalls?: number;
178
187
  renderResult?: (label: string, outcome: ToolCallOutcome) => string;
179
188
  labelFor?: (call: ToolLoopCall) => string;
180
189
  runId?: string;
package/dist/tool-loop.js CHANGED
@@ -1,5 +1,24 @@
1
+ import { t as runTaskQueue } from "./task-queue-DbpZAp6C.js";
1
2
  import { i as notifyRuntimeHookEvent, r as notifyRuntimeDecisionPoint } from "./runtime-hooks-CsW2pfFk.js";
2
3
  // src/tool-loop.ts
4
+ /**
5
+ * Bounded turn-level tool-dispatch loop.
6
+ *
7
+ * `runAgentTaskStream` runs ONE model turn; `runAgentRounds` orchestrates DELEGATED
8
+ * multi-agent topologies (refine / fanout-vote). Neither is the everyday
9
+ * interactive shape: a chat turn where the model may emit tool calls, each is
10
+ * executed, the results are folded back, and the turn re-runs until the model
11
+ * stops (or a turn cap). Every agent app hand-rolls that loop — this is it,
12
+ * as a reusable primitive.
13
+ *
14
+ * Substrate-neutral by design: the caller supplies `streamTurn` (wrapping
15
+ * whatever backend / `runAgentTaskStream` it uses) and `executeToolCall`
16
+ * (routing to its executors). This module owns the LOOP; the caller owns the
17
+ * model and the executors. `Raw` (streaming variant) is the caller's own
18
+ * event type. The only imported contracts are the runtime hook type (hooks are
19
+ * execution-scoped observers, not part of the agent profile) and the task queue
20
+ * a turn's calls run on.
21
+ */
3
22
  /** Runaway-backstop: stops an infinite tool loop where cost is unmetered. Set
4
23
  * far above any legitimate workflow — this is a watchdog, not a policy cap.
5
24
  * Legitimate per-call budgets come from `maxCostUsd` + `costOf`. */
@@ -11,9 +30,11 @@ const FAILURE_RECOVERY_ACTIONS = [
11
30
  "continue",
12
31
  "stop"
13
32
  ];
14
- /** Consecutive identical calls (same tool + canonical-JSON args) that trigger
15
- * stuck-loop detection. The window resets on any different call. */
33
+ /** Consecutive model turns issuing the same call set (tool + canonical-JSON args)
34
+ * that trigger stuck-loop detection. The window resets on any different set. */
16
35
  const STUCK_LOOP_THRESHOLD = 3;
36
+ /** Calls of one model turn that run at once unless `maxConcurrentToolCalls` says otherwise. */
37
+ const DEFAULT_CONCURRENT_TOOL_CALLS = 1;
17
38
  /** A tool-call id is required to key a `role: 'tool'` result back to its call.
18
39
  * When the model omitted one, derive a stable id from the tool name so the
19
40
  * assistant `tool_calls` entry and its `tool` result still match. */
@@ -73,8 +94,9 @@ async function runToolLoop(opts) {
73
94
  let finalText = "";
74
95
  let turns = 0;
75
96
  let accumulatedCostUsd = 0;
76
- let lastCallHash = null;
77
- let consecutiveCount = 0;
97
+ const overBudget = () => opts.maxCostUsd !== void 0 && opts.costOf !== void 0 && accumulatedCostUsd >= opts.maxCostUsd;
98
+ const width = opts.maxConcurrentToolCalls ?? DEFAULT_CONCURRENT_TOOL_CALLS;
99
+ const isStuck = stuckLoopDetector();
78
100
  observer.loopBefore(backstop, messages.length);
79
101
  for (let toolTurn = 0;; toolTurn++) {
80
102
  turns++;
@@ -124,68 +146,44 @@ async function runToolLoop(opts) {
124
146
  cappedOut: true
125
147
  };
126
148
  }
149
+ if (isStuck(pending)) {
150
+ observer.turnAfter(toolTurn, turnEventId, {
151
+ pendingToolCalls: pending.length,
152
+ stopReason: "stuck-loop"
153
+ });
154
+ observer.loopAfter({
155
+ turns,
156
+ toolResults: toolResults.length,
157
+ stopReason: "stuck-loop"
158
+ });
159
+ return {
160
+ finalText,
161
+ toolResults,
162
+ turns,
163
+ stopReason: "stuck-loop",
164
+ cappedOut: true
165
+ };
166
+ }
127
167
  messages.push(assistantToolCallMessage(turnText, pending));
128
- const outcomes = [];
129
- for (const [callIndex, call] of pending.entries()) {
130
- const callHash = canonicalCallHash(call);
131
- if (callHash === lastCallHash) consecutiveCount++;
132
- else {
133
- lastCallHash = callHash;
134
- consecutiveCount = 1;
135
- }
136
- if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {
137
- observer.turnAfter(toolTurn, turnEventId, {
138
- pendingToolCalls: pending.length,
139
- stopReason: "stuck-loop"
140
- });
141
- observer.loopAfter({
142
- turns,
143
- toolResults: toolResults.length,
144
- stopReason: "stuck-loop"
145
- });
146
- return {
147
- finalText,
148
- toolResults,
149
- turns,
150
- stopReason: "stuck-loop",
151
- cappedOut: true
152
- };
153
- }
168
+ const queue = turnCalls(pending, width, overBudget, async (call, callIndex) => {
154
169
  const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call);
155
170
  let settled = false;
156
171
  const outcome = await executeGuarded(opts.executeToolCall, call, (update) => {
157
172
  if (!settled) opts.onToolProgress?.(call, update);
158
173
  });
159
174
  settled = true;
160
- if (opts.maxCostUsd !== void 0 && opts.costOf !== void 0) {
161
- accumulatedCostUsd += opts.costOf(call, outcome);
162
- if (accumulatedCostUsd >= opts.maxCostUsd) {
163
- const label = labelFor(call);
164
- toolResults.push({
165
- call,
166
- label,
167
- outcome
168
- });
169
- messages.push(toolResultMessage(call, render(label, outcome)));
170
- observer.toolCallAfter(toolTurn, callEventId, call, outcome);
171
- observer.turnAfter(toolTurn, turnEventId, {
172
- pendingToolCalls: pending.length,
173
- stopReason: "budget"
174
- });
175
- observer.loopAfter({
176
- turns,
177
- toolResults: toolResults.length,
178
- stopReason: "budget"
179
- });
180
- return {
181
- finalText,
182
- toolResults,
183
- turns,
184
- stopReason: "budget",
185
- cappedOut: true
186
- };
187
- }
188
- }
175
+ if (opts.maxCostUsd !== void 0 && opts.costOf !== void 0) accumulatedCostUsd += opts.costOf(call, outcome);
176
+ observer.toolCallAfter(toolTurn, callEventId, call, outcome);
177
+ return outcome;
178
+ });
179
+ const executed = [];
180
+ for await (const settlement of queue) {
181
+ if (settlement.status === "rejected") throw settlement.reason;
182
+ executed[settlement.task.value] = settlement.value;
183
+ }
184
+ const outcomes = [];
185
+ for (const [callIndex, outcome] of executed.entries()) {
186
+ const call = pending[callIndex];
189
187
  const label = labelFor(call);
190
188
  const rendered = render(label, outcome);
191
189
  toolResults.push({
@@ -200,7 +198,24 @@ async function runToolLoop(opts) {
200
198
  rendered
201
199
  });
202
200
  messages.push(toolResultMessage(call, rendered));
203
- observer.toolCallAfter(toolTurn, callEventId, call, outcome);
201
+ }
202
+ if (overBudget()) {
203
+ observer.turnAfter(toolTurn, turnEventId, {
204
+ pendingToolCalls: pending.length,
205
+ stopReason: "budget"
206
+ });
207
+ observer.loopAfter({
208
+ turns,
209
+ toolResults: toolResults.length,
210
+ stopReason: "budget"
211
+ });
212
+ return {
213
+ finalText,
214
+ toolResults,
215
+ turns,
216
+ stopReason: "budget",
217
+ cappedOut: true
218
+ };
204
219
  }
205
220
  observer.failureRecovery({
206
221
  toolTurn,
@@ -253,8 +268,9 @@ async function* streamToolLoop(opts) {
253
268
  ];
254
269
  const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId);
255
270
  let accumulatedCostUsd = 0;
256
- let lastCallHash = null;
257
- let consecutiveCount = 0;
271
+ const overBudget = () => opts.maxCostUsd !== void 0 && opts.costOf !== void 0 && accumulatedCostUsd >= opts.maxCostUsd;
272
+ const width = opts.maxConcurrentToolCalls ?? DEFAULT_CONCURRENT_TOOL_CALLS;
273
+ const isStuck = stuckLoopDetector();
258
274
  observer.loopBefore(backstop, messages.length);
259
275
  for (let toolTurn = 0;; toolTurn++) {
260
276
  if (opts.deadlineMs !== void 0 && Date.now() >= opts.deadlineMs) {
@@ -306,64 +322,56 @@ async function* streamToolLoop(opts) {
306
322
  };
307
323
  return;
308
324
  }
325
+ if (isStuck(pending)) {
326
+ observer.turnAfter(toolTurn, turnEventId, {
327
+ pendingToolCalls: pending.length,
328
+ stopReason: "stuck-loop"
329
+ });
330
+ observer.loopAfter({
331
+ turns: toolTurn + 1,
332
+ stopReason: "stuck-loop"
333
+ });
334
+ yield {
335
+ kind: "capped",
336
+ pending: pending.length,
337
+ stopReason: "stuck-loop"
338
+ };
339
+ return;
340
+ }
309
341
  messages.push(assistantToolCallMessage(turnText, pending));
310
- const outcomes = [];
311
- for (const [callIndex, call] of pending.entries()) {
312
- const callHash = canonicalCallHash(call);
313
- if (callHash === lastCallHash) consecutiveCount++;
314
- else {
315
- lastCallHash = callHash;
316
- consecutiveCount = 1;
317
- }
318
- if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {
319
- observer.turnAfter(toolTurn, turnEventId, {
320
- pendingToolCalls: pending.length,
321
- stopReason: "stuck-loop"
322
- });
323
- observer.loopAfter({
324
- turns: toolTurn + 1,
325
- stopReason: "stuck-loop"
326
- });
327
- yield {
328
- kind: "capped",
329
- pending: pending.length,
330
- stopReason: "stuck-loop"
331
- };
332
- return;
333
- }
342
+ const progress = [];
343
+ const settled = [];
344
+ let wake;
345
+ const queue = turnCalls(pending, width, overBudget, async (call, callIndex) => {
334
346
  const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call);
335
- const progress = [];
336
- let wake;
337
- let settled = false;
338
- const running = executeGuarded(opts.executeToolCall, call, (update) => {
339
- if (settled) return;
340
- progress.push(update);
341
- wake?.();
342
- }).then((result) => {
343
- settled = true;
347
+ let done = false;
348
+ const outcome = await executeGuarded(opts.executeToolCall, call, (update) => {
349
+ if (done) return;
350
+ progress.push({
351
+ kind: "tool_progress",
352
+ toolName: call.toolName,
353
+ toolCallId: call.toolCallId,
354
+ update
355
+ });
344
356
  wake?.();
345
- return result;
346
357
  });
347
- while (!settled || progress.length > 0) {
358
+ done = true;
359
+ if (opts.maxCostUsd !== void 0 && opts.costOf !== void 0) accumulatedCostUsd += opts.costOf(call, outcome);
360
+ observer.toolCallAfter(toolTurn, callEventId, call, outcome);
361
+ return outcome;
362
+ });
363
+ const outcomes = [];
364
+ let pull;
365
+ try {
366
+ while (outcomes.length < pending.length) {
348
367
  const update = progress.shift();
349
368
  if (update !== void 0) {
350
- yield {
351
- kind: "tool_progress",
352
- toolName: call.toolName,
353
- toolCallId: call.toolCallId,
354
- update
355
- };
369
+ yield update;
356
370
  continue;
357
371
  }
358
- await new Promise((resolve) => {
359
- wake = resolve;
360
- });
361
- wake = void 0;
362
- }
363
- const outcome = await running;
364
- if (opts.maxCostUsd !== void 0 && opts.costOf !== void 0) {
365
- accumulatedCostUsd += opts.costOf(call, outcome);
366
- if (accumulatedCostUsd >= opts.maxCostUsd) {
372
+ const outcome = settled[outcomes.length];
373
+ if (outcome !== void 0) {
374
+ const call = pending[outcomes.length];
367
375
  const label = labelFor(call);
368
376
  yield {
369
377
  kind: "tool_result",
@@ -372,41 +380,46 @@ async function* streamToolLoop(opts) {
372
380
  label,
373
381
  outcome
374
382
  };
375
- messages.push(toolResultMessage(call, render(label, outcome)));
376
- observer.toolCallAfter(toolTurn, callEventId, call, outcome);
377
- observer.turnAfter(toolTurn, turnEventId, {
378
- pendingToolCalls: pending.length,
379
- stopReason: "budget"
380
- });
381
- observer.loopAfter({
382
- turns: toolTurn + 1,
383
- stopReason: "budget"
383
+ const rendered = render(label, outcome);
384
+ outcomes.push({
385
+ call,
386
+ label,
387
+ outcome,
388
+ rendered
384
389
  });
385
- yield {
386
- kind: "capped",
387
- pending: pending.length,
388
- stopReason: "budget"
389
- };
390
- return;
390
+ messages.push(toolResultMessage(call, rendered));
391
+ continue;
391
392
  }
393
+ pull ??= queue.next();
394
+ const woke = new Promise((resolve) => {
395
+ wake = () => resolve(null);
396
+ });
397
+ const step = await Promise.race([pull, woke]);
398
+ wake = void 0;
399
+ if (step === null) continue;
400
+ pull = void 0;
401
+ if (step.done) break;
402
+ if (step.value.status === "rejected") throw step.value.reason;
403
+ settled[step.value.task.value] = step.value.value;
392
404
  }
393
- const label = labelFor(call);
405
+ } finally {
406
+ await queue.return(void 0);
407
+ }
408
+ if (overBudget()) {
409
+ observer.turnAfter(toolTurn, turnEventId, {
410
+ pendingToolCalls: pending.length,
411
+ stopReason: "budget"
412
+ });
413
+ observer.loopAfter({
414
+ turns: toolTurn + 1,
415
+ stopReason: "budget"
416
+ });
394
417
  yield {
395
- kind: "tool_result",
396
- toolName: call.toolName,
397
- toolCallId: call.toolCallId,
398
- label,
399
- outcome
418
+ kind: "capped",
419
+ pending: pending.length,
420
+ stopReason: "budget"
400
421
  };
401
- const rendered = render(label, outcome);
402
- outcomes.push({
403
- call,
404
- label,
405
- outcome,
406
- rendered
407
- });
408
- messages.push(toolResultMessage(call, rendered));
409
- observer.toolCallAfter(toolTurn, callEventId, call, outcome);
422
+ return;
410
423
  }
411
424
  observer.failureRecovery({
412
425
  toolTurn,
@@ -437,6 +450,20 @@ async function executeGuarded(execute, call, progress) {
437
450
  };
438
451
  }
439
452
  }
453
+ /** One model turn's calls as a task queue keyed by call index: admitted in call order, at most
454
+ * `width` at once, each only when the queue is pulled. The turn's first call always starts and
455
+ * no later one starts once the budget is spent, so width 1 checks it after each call. */
456
+ function turnCalls(calls, width, spent, run) {
457
+ let next = 0;
458
+ return runTaskQueue({
459
+ concurrency: width,
460
+ take: () => next < calls.length && (next === 0 || !spent()) ? {
461
+ id: String(next),
462
+ value: next++
463
+ } : void 0,
464
+ execute: ({ value }) => run(calls[value], value)
465
+ });
466
+ }
440
467
  function createToolLoopObserver(hooks, runId, scenarioId) {
441
468
  const loopEventId = `${runId}:agent.run`;
442
469
  return {
@@ -630,6 +657,19 @@ function renderDecisionContext(messages, turnText, outcomes) {
630
657
  ...toolResults
631
658
  ].join("\n\n"), DEFAULT_DECISION_CONTEXT_CHARS);
632
659
  }
660
+ /** Stuck-loop detection across model turns: true once {@link STUCK_LOOP_THRESHOLD}
661
+ * consecutive turns issue the same call set. Repeats inside one parallel batch
662
+ * are not a loop; each runs and its result reaches the model. */
663
+ function stuckLoopDetector() {
664
+ let last;
665
+ let count = 0;
666
+ return (batch) => {
667
+ const signature = [...new Set(batch.map(canonicalCallHash))].sort().join("\n");
668
+ count = signature === last ? count + 1 : 1;
669
+ last = signature;
670
+ return count >= STUCK_LOOP_THRESHOLD;
671
+ };
672
+ }
633
673
  /** Canonical identifier for a tool call used by stuck-loop detection.
634
674
  * Keys are sorted so `{b:1,a:2}` and `{a:2,b:1}` produce the same hash. */
635
675
  function canonicalCallHash(call) {