@tangle-network/agent-runtime 10.0.5 → 10.0.7

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 (86) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/{activation-DvvM7gG5.js → activation-B3qLMoog.js} +2 -2
  3. package/dist/{activation-DvvM7gG5.js.map → activation-B3qLMoog.js.map} +1 -1
  4. package/dist/{activation-DyFt-GHq.d.ts → activation-CT-rr2-5.d.ts} +2 -2
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +3 -3
  7. package/dist/{delegate-YBqrrbq7.js → delegate-BFP1uCNY.js} +2 -2
  8. package/dist/{delegate-YBqrrbq7.js.map → delegate-BFP1uCNY.js.map} +1 -1
  9. package/dist/{driver-control-acknowledgers-CNNRjIo9.js → driver-control-acknowledgers-jdlf49OQ.js} +11 -10
  10. package/dist/driver-control-acknowledgers-jdlf49OQ.js.map +1 -0
  11. package/dist/durable-writer-thread.js +2 -2
  12. package/dist/durable.d.ts +1 -1
  13. package/dist/durable.js +11 -11
  14. package/dist/{failure-cause-DoCCGLDH.js → failure-cause-DvYGlOEV.js} +13 -5
  15. package/dist/{failure-cause-DoCCGLDH.js.map → failure-cause-DvYGlOEV.js.map} +1 -1
  16. package/dist/{graph-CUUtx7qT.js → graph-CiApRth2.js} +7 -7
  17. package/dist/graph-CiApRth2.js.map +1 -0
  18. package/dist/{improve-Cy8PZUdw.js → improve-LJaiGxdI.js} +5 -5
  19. package/dist/{improve-Cy8PZUdw.js.map → improve-LJaiGxdI.js.map} +1 -1
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js +10 -10
  22. package/dist/intelligence.d.ts +2 -2
  23. package/dist/intelligence.js +4 -4
  24. package/dist/kernel.d.ts +2 -2
  25. package/dist/kernel.js +16 -16
  26. package/dist/{loop-runner-Icc1iBR-.d.ts → loop-runner-D6egvap-.d.ts} +2 -2
  27. package/dist/{loop-runner-BwkX4ViS.js → loop-runner-Dgow637w.js} +2 -2
  28. package/dist/{loop-runner-BwkX4ViS.js.map → loop-runner-Dgow637w.js.map} +1 -1
  29. package/dist/loop-runner-bin.d.ts +1 -1
  30. package/dist/loop-runner-bin.js +1 -1
  31. package/dist/mcp/bin.js +3 -3
  32. package/dist/mcp/index.d.ts +1 -1
  33. package/dist/mcp/index.js +6 -6
  34. package/dist/mcp/memory-bin.js +1 -1
  35. package/dist/profiles.d.ts +1 -1
  36. package/dist/{provision-supervisor-Dtn8RjHe.js → provision-supervisor-DLOeyFHV.js} +5 -5
  37. package/dist/{provision-supervisor-Dtn8RjHe.js.map → provision-supervisor-DLOeyFHV.js.map} +1 -1
  38. package/dist/{result-blob-store-UGXQYACQ.js → result-blob-store-BMMzqpHa.js} +2 -2
  39. package/dist/{result-blob-store-UGXQYACQ.js.map → result-blob-store-BMMzqpHa.js.map} +1 -1
  40. package/dist/{run-cancellation-BpUQZqBS.js → run-cancellation-Bv7ooTJa.js} +129 -54
  41. package/dist/run-cancellation-Bv7ooTJa.js.map +1 -0
  42. package/dist/{run-reopen-BvF3Gjj9.js → run-reopen-KAnkEJV4.js} +6 -6
  43. package/dist/{run-reopen-BvF3Gjj9.js.map → run-reopen-KAnkEJV4.js.map} +1 -1
  44. package/dist/{run-state-CZcFJjHn.js → run-state-Bcci4zIN.js} +5 -5
  45. package/dist/{run-state-CZcFJjHn.js.map → run-state-Bcci4zIN.js.map} +1 -1
  46. package/dist/{runtime-BvDaNyFf.js → runtime-DCo0OP4n.js} +16 -16
  47. package/dist/{runtime-BvDaNyFf.js.map → runtime-DCo0OP4n.js.map} +1 -1
  48. package/dist/{search-executor-DWQW-9WN.js → search-executor-Dn5YmHsg.js} +4 -4
  49. package/dist/{search-executor-DWQW-9WN.js.map → search-executor-Dn5YmHsg.js.map} +1 -1
  50. package/dist/{server-D5GpuQnT.js → server-DxpG9y6W.js} +4 -4
  51. package/dist/{server-D5GpuQnT.js.map → server-DxpG9y6W.js.map} +1 -1
  52. package/dist/{settle-record-BFhJigPW.js → settle-record-DMdeNy8A.js} +2 -2
  53. package/dist/{settle-record-BFhJigPW.js.map → settle-record-DMdeNy8A.js.map} +1 -1
  54. package/dist/{structural-rollout-D1pZn6Cu.js → structural-rollout-DOmjcEMD.js} +4 -4
  55. package/dist/{structural-rollout-D1pZn6Cu.js.map → structural-rollout-DOmjcEMD.js.map} +1 -1
  56. package/dist/{supervise-fmugf6Y2.js → supervise-D7jtypE-.js} +25 -21
  57. package/dist/supervise-D7jtypE-.js.map +1 -0
  58. package/dist/{supervise-identity-7_7DUghQ.js → supervise-identity-QavM_M4r.js} +2 -2
  59. package/dist/{supervise-identity-7_7DUghQ.js.map → supervise-identity-QavM_M4r.js.map} +1 -1
  60. package/dist/{supervision-discovery-DwRtZNdy.js → supervision-discovery-CFZnbNTB.js} +3 -3
  61. package/dist/{supervision-discovery-DwRtZNdy.js.map → supervision-discovery-CFZnbNTB.js.map} +1 -1
  62. package/dist/{supervisor-BlACe-uO.js → supervisor-BFs4u2Vo.js} +25 -16
  63. package/dist/supervisor-BFs4u2Vo.js.map +1 -0
  64. package/dist/{supervisor-accounting-DuFyM-_h.js → supervisor-accounting-CgipDzYg.js} +11 -3
  65. package/dist/{supervisor-accounting-DuFyM-_h.js.map → supervisor-accounting-CgipDzYg.js.map} +1 -1
  66. package/dist/{supervisor-root-contract-DCMw4u0V.js → supervisor-root-contract-Ca5xp0Vg.js} +3 -3
  67. package/dist/{supervisor-root-contract-DCMw4u0V.js.map → supervisor-root-contract-Ca5xp0Vg.js.map} +1 -1
  68. package/dist/testing.d.ts +1 -1
  69. package/dist/testing.js +11 -11
  70. package/dist/tool-loop.d.ts +1 -1
  71. package/dist/tool-loop.js +51 -52
  72. package/dist/tool-loop.js.map +1 -1
  73. package/dist/{tool-server-DQCdu3am.js → tool-server-Cb7LBW4e.js} +2 -2
  74. package/dist/{tool-server-DQCdu3am.js.map → tool-server-Cb7LBW4e.js.map} +1 -1
  75. package/dist/{top-web-C5vhiOFA.js → top-web-oDO4xhNE.js} +7 -7
  76. package/dist/{top-web-C5vhiOFA.js.map → top-web-oDO4xhNE.js.map} +1 -1
  77. package/dist/tui/bin.js +3 -3
  78. package/dist/tui/index.d.ts +1 -1
  79. package/dist/tui/index.js +2 -2
  80. package/dist/{types-CFmKHKiN.d.ts → types-CKsn_wgO.d.ts} +19 -3
  81. package/package.json +3 -3
  82. package/dist/driver-control-acknowledgers-CNNRjIo9.js.map +0 -1
  83. package/dist/graph-CUUtx7qT.js.map +0 -1
  84. package/dist/run-cancellation-BpUQZqBS.js.map +0 -1
  85. package/dist/supervise-fmugf6Y2.js.map +0 -1
  86. package/dist/supervisor-BlACe-uO.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { M as contentAddress } from "./failure-cause-DoCCGLDH.js";
1
+ import { P as contentAddress } from "./failure-cause-DvYGlOEV.js";
2
2
  import { f as RuntimeRunStateError } from "./errors-DG8yufqX.js";
3
- import { $ as reenteredWorkers, $r as unknownExecutionBindingReceipt, Lr as knownExecutionBindingReceipt, Rr as knownMaterializationReceipt, ei as unknownMaterializationReceipt } from "./supervisor-accounting-DuFyM-_h.js";
3
+ import { Rr as knownExecutionBindingReceipt, ei as unknownExecutionBindingReceipt, et as reenteredWorkers, ti as unknownMaterializationReceipt, zr as knownMaterializationReceipt } from "./supervisor-accounting-CgipDzYg.js";
4
4
  import { sha256DigestSchema } from "@tangle-network/agent-interface";
5
5
  // src/runtime/supervise/supervisor-root-contract.ts
6
6
  /** A resumed process may continue only the exact root contract first recorded for this run id. Its
@@ -162,4 +162,4 @@ function rootStartedAtMs(root) {
162
162
  }
163
163
  export { recordRootReentered as a, rootMaterializationReceipt as c, changesRootProfile as i, rootStartedAtMs as l, assertResumeLimits as n, recordRootSegment as o, assertRootIdentity as r, rootExecutionBindingReceipt as s, assertResumeContract as t };
164
164
 
165
- //# sourceMappingURL=supervisor-root-contract-DCMw4u0V.js.map
165
+ //# sourceMappingURL=supervisor-root-contract-Ca5xp0Vg.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"supervisor-root-contract-DCMw4u0V.js","names":[],"sources":["../src/runtime/supervise/supervisor-root-contract.ts"],"sourcesContent":["import { sha256DigestSchema } from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport { RuntimeRunStateError } from '../../errors'\nimport {\n knownExecutionBindingReceipt,\n knownMaterializationReceipt,\n unknownExecutionBindingReceipt,\n unknownMaterializationReceipt,\n} from './materialization'\nimport type { ScopeResumeState } from './recover-executors'\nimport { reenteredWorkers } from './scope'\nimport type {\n ExecutionBindingReceipt,\n ProfileMaterializationReceipt,\n RootSegmentEntry,\n SpawnEvent,\n SupervisorOpts,\n} from './types'\n\nexport type SpawnedEvent = Extract<SpawnEvent, { kind: 'spawned' }>\n\n/** A resumed process may continue only the exact root contract first recorded for this run id. Its\n * budget is the root's, or the one the run's last budget-carrying `reopened` row recorded. */\nexport function assertResumeContract(events: SpawnEvent[], opts: SupervisorOpts): SpawnedEvent {\n const recorded = assertResumeLimits(events, opts)\n if (!sameOptionalIdentity(recorded.identity, opts.rootIdentity)) {\n throw new RuntimeRunStateError(\n `supervisor: resume identity mismatch for run '${opts.runId}'; ${describeIdentityMismatch(recorded.identity, opts.rootIdentity)}`,\n )\n }\n const receipts = events.filter(\n (event): event is Extract<SpawnEvent, { kind: 'materialized' }> =>\n event.kind === 'materialized' && event.id === opts.runId,\n )\n const expectedReceipt = rootMaterializationReceipt(opts)\n if (expectedReceipt === undefined) {\n if (receipts.length > 1) {\n throw new RuntimeRunStateError(\n `supervisor: resumed run '${opts.runId}' contains duplicate root materialization evidence`,\n )\n }\n } else if (\n receipts.length !== 1 ||\n contentAddress(receipts[0]?.receipt) !== contentAddress(expectedReceipt)\n ) {\n throw new RuntimeRunStateError(\n `supervisor: resume materialization mismatch for run '${opts.runId}'; backend, model, execution identity, and plan must match`,\n )\n }\n return recorded\n}\n\n/**\n * The limits half of the resume contract: one root identity event, the recorded budget and the\n * reservation policy. A reopen checks them before it archives anything (`durable/run-reopen.ts`);\n * `reopenBudget` is the budget that reopen is about to record, which then replaces the recorded one.\n */\nexport function assertResumeLimits(\n events: readonly SpawnEvent[],\n opts: Pick<SupervisorOpts, 'runId' | 'budget' | 'reservationPolicy'>,\n reopenBudget?: SupervisorOpts['budget'],\n): SpawnedEvent {\n const roots = events.filter(\n (event): event is SpawnedEvent => event.kind === 'spawned' && event.parent === undefined,\n )\n if (roots.length !== 1 || roots[0]?.id !== opts.runId) {\n throw new RuntimeRunStateError(\n `supervisor: resumed run '${opts.runId}' must contain exactly one root identity event; found ${roots.length}`,\n )\n }\n const recorded = roots[0]!\n // A reopen may carry a new budget; the last one that did is the budget this run is held to.\n const reopenedBudget =\n reopenBudget ??\n events\n .filter(\n (event): event is Extract<SpawnEvent, { kind: 'reopened' }> =>\n event.kind === 'reopened' && event.id === opts.runId && event.budget !== undefined,\n )\n .at(-1)?.budget\n if (contentAddress(reopenedBudget ?? recorded.budget) !== contentAddress(opts.budget)) {\n throw new RuntimeRunStateError(\n `supervisor: resume budget mismatch for run '${opts.runId}'; use a new runId to change limits`,\n )\n }\n const expectedAdmission = opts.reservationPolicy ? { policy: opts.reservationPolicy } : undefined\n if (\n contentAddress(recorded.recursiveAdmission ?? null) !==\n contentAddress(expectedAdmission ?? null)\n ) {\n throw new RuntimeRunStateError(\n `supervisor: resume reservation policy mismatch for run '${opts.runId}'; use a new runId`,\n )\n }\n return recorded\n}\n\n/** Mint root evidence at the trusted composition boundary. A generic in-process Agent root has no\n * executor declaration and remains explicitly unknown rather than inheriting fabricated details. */\nexport function rootMaterializationReceipt(\n opts: SupervisorOpts,\n): ProfileMaterializationReceipt | undefined {\n const declaration = opts.rootMaterialization\n if (declaration === undefined) {\n return unknownMaterializationReceipt({\n ...(opts.rootIdentity?.profileDigest === undefined\n ? {}\n : { authoredProfileDigest: opts.rootIdentity.profileDigest }),\n runtime: 'inline',\n reason: 'root-agent-did-not-report',\n })\n }\n if (declaration.declaration === 'deferred') return undefined\n if (opts.rootIdentity?.profileDigest === undefined) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' cannot record known root materialization without an exact profileDigest`,\n )\n }\n try {\n return knownMaterializationReceipt({\n authoredProfileDigest: opts.rootIdentity.profileDigest,\n runtime: declaration.runtime,\n declaration: declaration.declaration,\n })\n } catch (error) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' has invalid root materialization evidence`,\n { cause: error },\n )\n }\n}\n\nexport function rootExecutionBindingReceipt(\n opts: SupervisorOpts,\n materialization: ProfileMaterializationReceipt,\n attemptId: string,\n): ExecutionBindingReceipt | undefined {\n const root = opts.rootMaterialization\n if (root?.declaration === 'deferred') return undefined\n if (root === undefined) {\n return unknownExecutionBindingReceipt(materialization, attemptId, 'root-agent-did-not-report')\n }\n try {\n return knownExecutionBindingReceipt(materialization, {\n attemptId,\n ...root.binding,\n })\n } catch (error) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' has invalid root execution binding`,\n { cause: error },\n )\n }\n}\n\n/** Whether a segment changes what the recorded profile runs, apart from the caller's stack. */\nexport function changesRootProfile(entry: RootSegmentEntry): boolean {\n const { stack: _stack, ...current } = entry.current\n return contentAddress(current) !== contentAddress(entry.registered)\n}\n\n/**\n * Append one `root-segment` record when the root enters a segment that differs from the one it\n * last ran. The last record's `to` is what it last ran; a resumed run with no record last ran its\n * recorded profile, and a fresh run ran nothing. Every later entry on the same segment appends\n * nothing, so a resume after a dead supervisor or a lost stream is a boundary, not a segment.\n */\nexport async function recordRootSegment(\n opts: SupervisorOpts,\n events: readonly SpawnEvent[],\n at: string,\n fresh: boolean,\n): Promise<void> {\n const entry = opts.rootSegment\n if (entry === undefined) return\n const records = events.filter(\n (event): event is Extract<SpawnEvent, { kind: 'root-segment' }> =>\n event.kind === 'root-segment' && event.id === opts.runId,\n )\n const last = records.at(-1)?.to ?? (fresh ? undefined : entry.registered)\n if (last !== undefined && contentAddress(last) === contentAddress(entry.current)) return\n await opts.journal.appendEvent(opts.runId, {\n kind: 'root-segment',\n id: opts.runId,\n ...(last === undefined ? {} : { from: last }),\n to: entry.current,\n reason: entry.reason,\n seq: records.length,\n at,\n })\n}\n\n/**\n * Append one `root-reentered` record: this process is supervising a run an earlier process drove.\n * After a host reboot the re-entered root ran two\n * barren continuations and the run settled `no-result-selected`, with three workers still open in\n * the journal and no record that a restart had happened.\n */\nexport async function recordRootReentered(\n opts: SupervisorOpts,\n resumeFrom: ScopeResumeState,\n at: string,\n): Promise<void> {\n await opts.journal.appendEvent(opts.runId, {\n kind: 'root-reentered',\n id: opts.runId,\n ...reenteredWorkers(resumeFrom, opts.runId),\n seq: resumeFrom.events.filter((event) => event.kind === 'root-reentered').length,\n at,\n })\n}\n\nfunction sameOptionalIdentity(\n recorded: SpawnedEvent['identity'],\n requested: SpawnedEvent['identity'],\n): boolean {\n if (recorded === undefined || requested === undefined) return recorded === requested\n return contentAddress(recorded) === contentAddress(requested)\n}\n\n/**\n * Name the identity fields that actually differ, with both values.\n *\n * The identity is compared as one content address, so a mismatch is a single boolean and the\n * message could only list every field that MIGHT have caused it. A caller then has to diff four\n * digests by hand to learn which one moved, and the common cause — a task file regenerated with\n * one character different — is indistinguishable from a genuinely different profile.\n *\n * Digests are truncated because the prefix identifies them and the full 64 characters push the\n * real content off the end of a terminal line.\n */\nfunction describeIdentityMismatch(\n recorded: SpawnedEvent['identity'],\n requested: SpawnedEvent['identity'],\n): string {\n if (recorded === undefined)\n return 'the recorded root carried no identity but this resume supplies one'\n if (requested === undefined)\n return 'the recorded root carried an identity but this resume supplies none'\n const short = (value: unknown): string => {\n if (value === undefined) return '(absent)'\n const text = typeof value === 'string' ? value : JSON.stringify(value)\n return text.length > 20 ? `${text.slice(0, 20)}…` : text\n }\n const differing = (['profileDigest', 'taskDigest', 'candidateDigest', 'correlation'] as const)\n .filter((field) => contentAddress(recorded[field]) !== contentAddress(requested[field]))\n .map(\n (field) =>\n `${field} recorded ${short(recorded[field])} but resumed with ${short(requested[field])}`,\n )\n // A differing content address with no differing field means the shape itself changed (an extra\n // key, a different key order the address is sensitive to). Say that rather than nothing.\n if (differing.length === 0)\n return 'the identity objects differ in shape while every known field matches'\n return `${differing.join('; ')} — a different task or root profile is a new run; a resume may change the root's model, reasoning effort and harness as a new segment of this run (segment)`\n}\n\n/** Validate caller-supplied root identity before any journal access. Fresh runs may omit identity,\n * but once supplied it is trusted durable evidence and therefore must be complete and canonical;\n * resumed runs always require it so the prior root can be matched exactly. */\nexport function assertRootIdentity(opts: SupervisorOpts): void {\n const identity = opts.rootIdentity\n if (identity === undefined) {\n if (opts.resume !== true) return\n throw new RuntimeRunStateError(\n `supervisor: resumed run '${opts.runId}' requires an exact rootIdentity with profileDigest and taskDigest`,\n )\n }\n const unknownFields = Object.keys(identity).filter(\n (key) =>\n key !== 'profileDigest' &&\n key !== 'taskDigest' &&\n key !== 'candidateDigest' &&\n key !== 'correlation',\n )\n const correlation = identity.correlation\n const validCorrelation =\n correlation === undefined ||\n (typeof correlation === 'object' &&\n correlation !== null &&\n !Array.isArray(correlation) &&\n Object.entries(correlation).every(\n ([key, value]) => key.length > 0 && typeof value === 'string' && value.length > 0,\n ))\n if (\n unknownFields.length > 0 ||\n !sha256DigestSchema.safeParse(identity.profileDigest).success ||\n !sha256DigestSchema.safeParse(identity.taskDigest).success ||\n (identity.candidateDigest !== undefined &&\n !sha256DigestSchema.safeParse(identity.candidateDigest).success) ||\n !validCorrelation\n ) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' requires an exact rootIdentity with valid profileDigest, taskDigest, candidateDigest, and correlation`,\n )\n }\n}\n\n/** The instant the run's root was journaled — the anchor for both the absolute deadline and the\n * terminal wall-clock `ms`, so a resumed run measures from its ORIGINAL start, not this\n * process's. */\nexport function rootStartedAtMs(root: SpawnedEvent): number {\n const startedAt = Date.parse(root.at)\n if (!Number.isFinite(startedAt)) {\n throw new RuntimeRunStateError(\n `supervisor: root event for '${root.id}' has an invalid timestamp '${root.at}'`,\n )\n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/E;CAEF,OAAO;AACT"}
1
+ {"version":3,"file":"supervisor-root-contract-Ca5xp0Vg.js","names":[],"sources":["../src/runtime/supervise/supervisor-root-contract.ts"],"sourcesContent":["import { sha256DigestSchema } from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport { RuntimeRunStateError } from '../../errors'\nimport {\n knownExecutionBindingReceipt,\n knownMaterializationReceipt,\n unknownExecutionBindingReceipt,\n unknownMaterializationReceipt,\n} from './materialization'\nimport type { ScopeResumeState } from './recover-executors'\nimport { reenteredWorkers } from './scope'\nimport type {\n ExecutionBindingReceipt,\n ProfileMaterializationReceipt,\n RootSegmentEntry,\n SpawnEvent,\n SupervisorOpts,\n} from './types'\n\nexport type SpawnedEvent = Extract<SpawnEvent, { kind: 'spawned' }>\n\n/** A resumed process may continue only the exact root contract first recorded for this run id. Its\n * budget is the root's, or the one the run's last budget-carrying `reopened` row recorded. */\nexport function assertResumeContract(events: SpawnEvent[], opts: SupervisorOpts): SpawnedEvent {\n const recorded = assertResumeLimits(events, opts)\n if (!sameOptionalIdentity(recorded.identity, opts.rootIdentity)) {\n throw new RuntimeRunStateError(\n `supervisor: resume identity mismatch for run '${opts.runId}'; ${describeIdentityMismatch(recorded.identity, opts.rootIdentity)}`,\n )\n }\n const receipts = events.filter(\n (event): event is Extract<SpawnEvent, { kind: 'materialized' }> =>\n event.kind === 'materialized' && event.id === opts.runId,\n )\n const expectedReceipt = rootMaterializationReceipt(opts)\n if (expectedReceipt === undefined) {\n if (receipts.length > 1) {\n throw new RuntimeRunStateError(\n `supervisor: resumed run '${opts.runId}' contains duplicate root materialization evidence`,\n )\n }\n } else if (\n receipts.length !== 1 ||\n contentAddress(receipts[0]?.receipt) !== contentAddress(expectedReceipt)\n ) {\n throw new RuntimeRunStateError(\n `supervisor: resume materialization mismatch for run '${opts.runId}'; backend, model, execution identity, and plan must match`,\n )\n }\n return recorded\n}\n\n/**\n * The limits half of the resume contract: one root identity event, the recorded budget and the\n * reservation policy. A reopen checks them before it archives anything (`durable/run-reopen.ts`);\n * `reopenBudget` is the budget that reopen is about to record, which then replaces the recorded one.\n */\nexport function assertResumeLimits(\n events: readonly SpawnEvent[],\n opts: Pick<SupervisorOpts, 'runId' | 'budget' | 'reservationPolicy'>,\n reopenBudget?: SupervisorOpts['budget'],\n): SpawnedEvent {\n const roots = events.filter(\n (event): event is SpawnedEvent => event.kind === 'spawned' && event.parent === undefined,\n )\n if (roots.length !== 1 || roots[0]?.id !== opts.runId) {\n throw new RuntimeRunStateError(\n `supervisor: resumed run '${opts.runId}' must contain exactly one root identity event; found ${roots.length}`,\n )\n }\n const recorded = roots[0]!\n // A reopen may carry a new budget; the last one that did is the budget this run is held to.\n const reopenedBudget =\n reopenBudget ??\n events\n .filter(\n (event): event is Extract<SpawnEvent, { kind: 'reopened' }> =>\n event.kind === 'reopened' && event.id === opts.runId && event.budget !== undefined,\n )\n .at(-1)?.budget\n if (contentAddress(reopenedBudget ?? recorded.budget) !== contentAddress(opts.budget)) {\n throw new RuntimeRunStateError(\n `supervisor: resume budget mismatch for run '${opts.runId}'; use a new runId to change limits`,\n )\n }\n const expectedAdmission = opts.reservationPolicy ? { policy: opts.reservationPolicy } : undefined\n if (\n contentAddress(recorded.recursiveAdmission ?? null) !==\n contentAddress(expectedAdmission ?? null)\n ) {\n throw new RuntimeRunStateError(\n `supervisor: resume reservation policy mismatch for run '${opts.runId}'; use a new runId`,\n )\n }\n return recorded\n}\n\n/** Mint root evidence at the trusted composition boundary. A generic in-process Agent root has no\n * executor declaration and remains explicitly unknown rather than inheriting fabricated details. */\nexport function rootMaterializationReceipt(\n opts: SupervisorOpts,\n): ProfileMaterializationReceipt | undefined {\n const declaration = opts.rootMaterialization\n if (declaration === undefined) {\n return unknownMaterializationReceipt({\n ...(opts.rootIdentity?.profileDigest === undefined\n ? {}\n : { authoredProfileDigest: opts.rootIdentity.profileDigest }),\n runtime: 'inline',\n reason: 'root-agent-did-not-report',\n })\n }\n if (declaration.declaration === 'deferred') return undefined\n if (opts.rootIdentity?.profileDigest === undefined) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' cannot record known root materialization without an exact profileDigest`,\n )\n }\n try {\n return knownMaterializationReceipt({\n authoredProfileDigest: opts.rootIdentity.profileDigest,\n runtime: declaration.runtime,\n declaration: declaration.declaration,\n })\n } catch (error) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' has invalid root materialization evidence`,\n { cause: error },\n )\n }\n}\n\nexport function rootExecutionBindingReceipt(\n opts: SupervisorOpts,\n materialization: ProfileMaterializationReceipt,\n attemptId: string,\n): ExecutionBindingReceipt | undefined {\n const root = opts.rootMaterialization\n if (root?.declaration === 'deferred') return undefined\n if (root === undefined) {\n return unknownExecutionBindingReceipt(materialization, attemptId, 'root-agent-did-not-report')\n }\n try {\n return knownExecutionBindingReceipt(materialization, {\n attemptId,\n ...root.binding,\n })\n } catch (error) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' has invalid root execution binding`,\n { cause: error },\n )\n }\n}\n\n/** Whether a segment changes what the recorded profile runs, apart from the caller's stack. */\nexport function changesRootProfile(entry: RootSegmentEntry): boolean {\n const { stack: _stack, ...current } = entry.current\n return contentAddress(current) !== contentAddress(entry.registered)\n}\n\n/**\n * Append one `root-segment` record when the root enters a segment that differs from the one it\n * last ran. The last record's `to` is what it last ran; a resumed run with no record last ran its\n * recorded profile, and a fresh run ran nothing. Every later entry on the same segment appends\n * nothing, so a resume after a dead supervisor or a lost stream is a boundary, not a segment.\n */\nexport async function recordRootSegment(\n opts: SupervisorOpts,\n events: readonly SpawnEvent[],\n at: string,\n fresh: boolean,\n): Promise<void> {\n const entry = opts.rootSegment\n if (entry === undefined) return\n const records = events.filter(\n (event): event is Extract<SpawnEvent, { kind: 'root-segment' }> =>\n event.kind === 'root-segment' && event.id === opts.runId,\n )\n const last = records.at(-1)?.to ?? (fresh ? undefined : entry.registered)\n if (last !== undefined && contentAddress(last) === contentAddress(entry.current)) return\n await opts.journal.appendEvent(opts.runId, {\n kind: 'root-segment',\n id: opts.runId,\n ...(last === undefined ? {} : { from: last }),\n to: entry.current,\n reason: entry.reason,\n seq: records.length,\n at,\n })\n}\n\n/**\n * Append one `root-reentered` record: this process is supervising a run an earlier process drove.\n * After a host reboot the re-entered root ran two\n * barren continuations and the run settled `no-result-selected`, with three workers still open in\n * the journal and no record that a restart had happened.\n */\nexport async function recordRootReentered(\n opts: SupervisorOpts,\n resumeFrom: ScopeResumeState,\n at: string,\n): Promise<void> {\n await opts.journal.appendEvent(opts.runId, {\n kind: 'root-reentered',\n id: opts.runId,\n ...reenteredWorkers(resumeFrom, opts.runId),\n seq: resumeFrom.events.filter((event) => event.kind === 'root-reentered').length,\n at,\n })\n}\n\nfunction sameOptionalIdentity(\n recorded: SpawnedEvent['identity'],\n requested: SpawnedEvent['identity'],\n): boolean {\n if (recorded === undefined || requested === undefined) return recorded === requested\n return contentAddress(recorded) === contentAddress(requested)\n}\n\n/**\n * Name the identity fields that actually differ, with both values.\n *\n * The identity is compared as one content address, so a mismatch is a single boolean and the\n * message could only list every field that MIGHT have caused it. A caller then has to diff four\n * digests by hand to learn which one moved, and the common cause — a task file regenerated with\n * one character different — is indistinguishable from a genuinely different profile.\n *\n * Digests are truncated because the prefix identifies them and the full 64 characters push the\n * real content off the end of a terminal line.\n */\nfunction describeIdentityMismatch(\n recorded: SpawnedEvent['identity'],\n requested: SpawnedEvent['identity'],\n): string {\n if (recorded === undefined)\n return 'the recorded root carried no identity but this resume supplies one'\n if (requested === undefined)\n return 'the recorded root carried an identity but this resume supplies none'\n const short = (value: unknown): string => {\n if (value === undefined) return '(absent)'\n const text = typeof value === 'string' ? value : JSON.stringify(value)\n return text.length > 20 ? `${text.slice(0, 20)}…` : text\n }\n const differing = (['profileDigest', 'taskDigest', 'candidateDigest', 'correlation'] as const)\n .filter((field) => contentAddress(recorded[field]) !== contentAddress(requested[field]))\n .map(\n (field) =>\n `${field} recorded ${short(recorded[field])} but resumed with ${short(requested[field])}`,\n )\n // A differing content address with no differing field means the shape itself changed (an extra\n // key, a different key order the address is sensitive to). Say that rather than nothing.\n if (differing.length === 0)\n return 'the identity objects differ in shape while every known field matches'\n return `${differing.join('; ')} — a different task or root profile is a new run; a resume may change the root's model, reasoning effort and harness as a new segment of this run (segment)`\n}\n\n/** Validate caller-supplied root identity before any journal access. Fresh runs may omit identity,\n * but once supplied it is trusted durable evidence and therefore must be complete and canonical;\n * resumed runs always require it so the prior root can be matched exactly. */\nexport function assertRootIdentity(opts: SupervisorOpts): void {\n const identity = opts.rootIdentity\n if (identity === undefined) {\n if (opts.resume !== true) return\n throw new RuntimeRunStateError(\n `supervisor: resumed run '${opts.runId}' requires an exact rootIdentity with profileDigest and taskDigest`,\n )\n }\n const unknownFields = Object.keys(identity).filter(\n (key) =>\n key !== 'profileDigest' &&\n key !== 'taskDigest' &&\n key !== 'candidateDigest' &&\n key !== 'correlation',\n )\n const correlation = identity.correlation\n const validCorrelation =\n correlation === undefined ||\n (typeof correlation === 'object' &&\n correlation !== null &&\n !Array.isArray(correlation) &&\n Object.entries(correlation).every(\n ([key, value]) => key.length > 0 && typeof value === 'string' && value.length > 0,\n ))\n if (\n unknownFields.length > 0 ||\n !sha256DigestSchema.safeParse(identity.profileDigest).success ||\n !sha256DigestSchema.safeParse(identity.taskDigest).success ||\n (identity.candidateDigest !== undefined &&\n !sha256DigestSchema.safeParse(identity.candidateDigest).success) ||\n !validCorrelation\n ) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' requires an exact rootIdentity with valid profileDigest, taskDigest, candidateDigest, and correlation`,\n )\n }\n}\n\n/** The instant the run's root was journaled — the anchor for both the absolute deadline and the\n * terminal wall-clock `ms`, so a resumed run measures from its ORIGINAL start, not this\n * process's. */\nexport function rootStartedAtMs(root: SpawnedEvent): number {\n const startedAt = Date.parse(root.at)\n if (!Number.isFinite(startedAt)) {\n throw new RuntimeRunStateError(\n `supervisor: root event for '${root.id}' has an invalid timestamp '${root.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K,GAAG,EAC/E;CAEF,OAAO;AACT"}
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, dC as HarnessTranscriptCapture, 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, 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, vS as RunCancelRequest, vf as SuperviseTestOptions, vx as McpToolDescriptor, wm as ManagerWakePolicy, xb as RouteFlow, xx as BusRecord, ym as SupervisorAgentTestDeps, zb as AuthorizeDownMessage, zx as AnalyzeOnSettleRoute } from "./types-CFmKHKiN.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-CKsn_wgO.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-DvvM7gG5.js";
4
- import { o as supervisorAgentWithTestBrain, p as driverAgent, r as superviseWithTestBrain } from "./supervise-fmugf6Y2.js";
5
- import { r as runGraphWithTestBrain } from "./graph-CUUtx7qT.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";
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:6cca21a14e4eb8048113b5f520215475001e11a31e8a4b8658c6d51fdd8d4006",
10
+ digest: "sha256:c5f722a049ff3d9e82c686e5fcdd7786dd9336f0b9c700f1eb4ee069e2b15c4a",
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.5"
4581
+ "runtimeVersion": "10.0.7"
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:0367694669768bfd4bec08a2941b325454aa9986763af88566abee6c39eb5459",
4693
- "runId": "agent-runtime-10.0.5-proposal-fixture",
4692
+ "recordDigest": "sha256:3f21c8b06797665d94174f400f3299c6f25b4b5ee8fe49e4550995e87577e744",
4693
+ "runId": "agent-runtime-10.0.7-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.5-proposal-fixture"
4716
+ runId: "agent-runtime-10.0.7-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:a31f1ccfb42988bc2c3ef895137cf8a3093847110cb62be25b2eda1299d11aab",
4721
+ digest: "sha256:93a253da95531d3e65595b3996daec522eee62bec416bd652ea3dfcc48b7d185",
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.5"
6355
+ "runtimeVersion": "10.0.7"
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:6eec4e974065f66177d12157d230c9f7abc47ae10f18224fd07859e5c78d92a5",
6466
+ "recordDigest": "sha256:38e674a33979aaefa695f252e38447b82a93653cb022c89fdd4a8f7f3a3393a3",
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. */
package/dist/tool-loop.js CHANGED
@@ -11,8 +11,8 @@ const FAILURE_RECOVERY_ACTIONS = [
11
11
  "continue",
12
12
  "stop"
13
13
  ];
14
- /** Consecutive identical calls (same tool + canonical-JSON args) that trigger
15
- * stuck-loop detection. The window resets on any different call. */
14
+ /** Consecutive model turns issuing the same call set (tool + canonical-JSON args)
15
+ * that trigger stuck-loop detection. The window resets on any different set. */
16
16
  const STUCK_LOOP_THRESHOLD = 3;
17
17
  /** A tool-call id is required to key a `role: 'tool'` result back to its call.
18
18
  * When the model omitted one, derive a stable id from the tool name so the
@@ -73,8 +73,7 @@ async function runToolLoop(opts) {
73
73
  let finalText = "";
74
74
  let turns = 0;
75
75
  let accumulatedCostUsd = 0;
76
- let lastCallHash = null;
77
- let consecutiveCount = 0;
76
+ const isStuck = stuckLoopDetector();
78
77
  observer.loopBefore(backstop, messages.length);
79
78
  for (let toolTurn = 0;; toolTurn++) {
80
79
  turns++;
@@ -124,33 +123,27 @@ async function runToolLoop(opts) {
124
123
  cappedOut: true
125
124
  };
126
125
  }
126
+ if (isStuck(pending)) {
127
+ observer.turnAfter(toolTurn, turnEventId, {
128
+ pendingToolCalls: pending.length,
129
+ stopReason: "stuck-loop"
130
+ });
131
+ observer.loopAfter({
132
+ turns,
133
+ toolResults: toolResults.length,
134
+ stopReason: "stuck-loop"
135
+ });
136
+ return {
137
+ finalText,
138
+ toolResults,
139
+ turns,
140
+ stopReason: "stuck-loop",
141
+ cappedOut: true
142
+ };
143
+ }
127
144
  messages.push(assistantToolCallMessage(turnText, pending));
128
145
  const outcomes = [];
129
146
  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
- }
154
147
  const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call);
155
148
  let settled = false;
156
149
  const outcome = await executeGuarded(opts.executeToolCall, call, (update) => {
@@ -253,8 +246,7 @@ async function* streamToolLoop(opts) {
253
246
  ];
254
247
  const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId);
255
248
  let accumulatedCostUsd = 0;
256
- let lastCallHash = null;
257
- let consecutiveCount = 0;
249
+ const isStuck = stuckLoopDetector();
258
250
  observer.loopBefore(backstop, messages.length);
259
251
  for (let toolTurn = 0;; toolTurn++) {
260
252
  if (opts.deadlineMs !== void 0 && Date.now() >= opts.deadlineMs) {
@@ -306,31 +298,25 @@ async function* streamToolLoop(opts) {
306
298
  };
307
299
  return;
308
300
  }
301
+ if (isStuck(pending)) {
302
+ observer.turnAfter(toolTurn, turnEventId, {
303
+ pendingToolCalls: pending.length,
304
+ stopReason: "stuck-loop"
305
+ });
306
+ observer.loopAfter({
307
+ turns: toolTurn + 1,
308
+ stopReason: "stuck-loop"
309
+ });
310
+ yield {
311
+ kind: "capped",
312
+ pending: pending.length,
313
+ stopReason: "stuck-loop"
314
+ };
315
+ return;
316
+ }
309
317
  messages.push(assistantToolCallMessage(turnText, pending));
310
318
  const outcomes = [];
311
319
  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
- }
334
320
  const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call);
335
321
  const progress = [];
336
322
  let wake;
@@ -630,6 +616,19 @@ function renderDecisionContext(messages, turnText, outcomes) {
630
616
  ...toolResults
631
617
  ].join("\n\n"), DEFAULT_DECISION_CONTEXT_CHARS);
632
618
  }
619
+ /** Stuck-loop detection across model turns: true once {@link STUCK_LOOP_THRESHOLD}
620
+ * consecutive turns issue the same call set. Repeats inside one parallel batch
621
+ * are not a loop; each runs and its result reaches the model. */
622
+ function stuckLoopDetector() {
623
+ let last;
624
+ let count = 0;
625
+ return (batch) => {
626
+ const signature = [...new Set(batch.map(canonicalCallHash))].sort().join("\n");
627
+ count = signature === last ? count + 1 : 1;
628
+ last = signature;
629
+ return count >= STUCK_LOOP_THRESHOLD;
630
+ };
631
+ }
633
632
  /** Canonical identifier for a tool call used by stuck-loop detection.
634
633
  * Keys are sorted so `{b:1,a:2}` and `{a:2,b:1}` produce the same hash. */
635
634
  function canonicalCallHash(call) {
@@ -1 +1 @@
1
- {"version":3,"file":"tool-loop.js","names":[],"sources":["../src/tool-loop.ts"],"sourcesContent":["/**\n * Bounded turn-level tool-dispatch loop.\n *\n * `runAgentTaskStream` runs ONE model turn; `runAgentRounds` orchestrates DELEGATED\n * multi-agent topologies (refine / fanout-vote). Neither is the everyday\n * interactive shape: a chat turn where the model may emit tool calls, each is\n * executed, the results are folded back, and the turn re-runs until the model\n * stops (or a turn cap). Every agent app hand-rolls that loop — this is it,\n * as a reusable primitive.\n *\n * Substrate-neutral by design: the caller supplies `streamTurn` (wrapping\n * whatever backend / `runAgentTaskStream` it uses) and `executeToolCall`\n * (routing to its executors). This module owns the LOOP; the caller owns the\n * model and the executors. `Raw` (streaming variant) is the caller's own\n * event type. The only imported contract is the runtime hook type: hooks are\n * execution-scoped observers, not part of the agent profile.\n */\n\nimport type { RuntimeDecisionEvidenceRef, RuntimeHooks } from './runtime-hooks'\nimport { notifyRuntimeDecisionPoint, notifyRuntimeHookEvent } from './runtime-hooks'\n\nexport interface ToolLoopCall {\n toolCallId?: string\n toolName: string\n args: Record<string, unknown>\n /**\n * Provider-specific fields the model attached to this call, echoed back on\n * its assistant `tool_calls` entry in the next request. Gemini 3 returns\n * `extra_content: { google: { thought_signature } }` on each call and answers\n * HTTP 400 when the next request omits it.\n */\n providerFields?: Record<string, unknown>\n}\n\n/** Outcome of one tool dispatch — structurally compatible with a hub/integration\n * tool-outcome union, so callers can fold either through the loop. */\nexport type ToolCallOutcome =\n | { ok: true; result: unknown }\n | { ok: false; code: string; message: string; status?: number }\n\n/** Runaway-backstop: stops an infinite tool loop where cost is unmetered. Set\n * far above any legitimate workflow — this is a watchdog, not a policy cap.\n * Legitimate per-call budgets come from `maxCostUsd` + `costOf`. */\nconst RUNAWAY_BACKSTOP_TURNS = 200\nconst DEFAULT_DECISION_CONTEXT_CHARS = 12_000\nconst FAILURE_RECOVERY_ACTIONS = ['retry', 'verify', 'continue', 'stop']\n/** Consecutive identical calls (same tool + canonical-JSON args) that trigger\n * stuck-loop detection. The window resets on any different call. */\nconst STUCK_LOOP_THRESHOLD = 3\n\n/** One OpenAI-shaped tool-call entry carried on an assistant message, plus any\n * provider-specific fields the model attached to the call (`ToolLoopCall.providerFields`). */\nexport interface ToolLoopAssistantToolCall {\n [providerField: string]: unknown\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n}\n\n/**\n * A message in the running conversation the loop sends to `streamTurn`.\n *\n * The base `{ role, content }` covers `system` / `user` / plain `assistant`\n * turns. Two optional fields carry the OpenAI function-calling contract so a\n * strict model (Claude, and any OpenAI-compatible provider that validates tool\n * history) reads its own tool use back instead of re-issuing the same call:\n *\n * - an assistant turn that emitted tool calls carries `tool_calls`, and its\n * `content` is `null` when the turn was tool-only;\n * - each tool result is its own `{ role: 'tool', tool_call_id, content }`\n * message keyed to the call that produced it.\n *\n * Widening is additive: a `streamTurn` that reads only `role` + `content` still\n * works; one that forwards the whole message to an OpenAI-compatible endpoint\n * now sends correct tool history.\n */\nexport type ToolLoopMessage = {\n role: string\n content: string | null\n tool_calls?: ToolLoopAssistantToolCall[]\n tool_call_id?: string\n}\n\n/** A tool-call id is required to key a `role: 'tool'` result back to its call.\n * When the model omitted one, derive a stable id from the tool name so the\n * assistant `tool_calls` entry and its `tool` result still match. */\nfunction toolCallId(call: ToolLoopCall): string {\n return call.toolCallId ?? `call_${call.toolName}`\n}\n\n/** The assistant turn that emitted `pending`, in OpenAI shape: text content\n * (null when the turn was tool-only) plus its `tool_calls` array. */\nfunction assistantToolCallMessage(turnText: string, pending: ToolLoopCall[]): ToolLoopMessage {\n return {\n role: 'assistant',\n content: turnText.trim() || null,\n tool_calls: pending.map((call) => ({\n ...call.providerFields,\n id: toolCallId(call),\n type: 'function',\n function: { name: call.toolName, arguments: JSON.stringify(call.args) },\n })),\n }\n}\n\n/** One `role: 'tool'` result message keyed to its call by `tool_call_id`. */\nfunction toolResultMessage(call: ToolLoopCall, content: string): ToolLoopMessage {\n return { role: 'tool', tool_call_id: toolCallId(call), content }\n}\n\n/**\n * One progress report from a running tool, shaped like an MCP `notifications/progress`\n * payload: a free-text `message`, a monotonic `progress` count with an optional\n * `total`, and any structured `data` the caller's UI understands.\n */\nexport interface ToolProgressUpdate {\n message?: string\n progress?: number\n total?: number\n data?: unknown\n}\n\n/** What the loop hands a running tool besides its call. */\nexport interface ToolCallContext {\n /**\n * Report progress while the call runs. The streaming loop yields each update as a\n * `tool_progress` step, in order, before the call's `tool_result`; updates sent after\n * the call settles are dropped.\n */\n progress: (update: ToolProgressUpdate) => void\n}\n\n/** Executes one tool call. Implementations that take only the call stay valid. */\nexport type ToolCallExecutor = (\n call: ToolLoopCall,\n context: ToolCallContext,\n) => Promise<ToolCallOutcome>\n\nfunction defaultRender(label: string, outcome: ToolCallOutcome): string {\n if (outcome.ok) return `- ${label} → ok: ${JSON.stringify(outcome.result)}`\n return `- ${label} → failed (${outcome.code}): ${outcome.message}`\n}\n\n// ── Awaitable variant (drain-only callers, tests) ──────────────────────────\n\nexport type ToolLoopEvent =\n | { type: 'text'; text: string }\n | { type: 'tool_call'; call: ToolLoopCall }\n | { type: 'other'; event: unknown }\n\n/** Why the loop stopped. `completed` = model finished naturally; `stuck-loop` =\n * ≥3 consecutive identical tool calls (same tool + args); `backstop` = hit the\n * runaway-backstop cap (200 by default); `deadline` = wall-clock deadlineMs\n * exceeded; `budget` = maxCostUsd exhausted. Non-`completed` stops are infra /\n * resource outcomes — eval scoring must distinguish them from capability failure. */\nexport type ToolLoopStopReason = 'completed' | 'stuck-loop' | 'backstop' | 'deadline' | 'budget'\n\nexport interface ToolLoopResult {\n finalText: string\n toolResults: Array<{ call: ToolLoopCall; label: string; outcome: ToolCallOutcome }>\n turns: number\n stopReason: ToolLoopStopReason\n /** @deprecated Use `stopReason !== 'completed'` instead. */\n cappedOut: boolean\n}\n\nexport interface RunToolLoopOptions {\n systemPrompt: string\n userMessage: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<ToolLoopEvent>\n executeToolCall: ToolCallExecutor\n /** Receives each progress update a running tool reports, in order. */\n onToolProgress?: (call: ToolLoopCall, update: ToolProgressUpdate) => void\n isExecutableTool: (toolName: string) => boolean\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow.\n * For per-workflow limits, use `maxCostUsd` or `deadlineMs` instead. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). When exceeded the\n * loop stops with stopReason `deadline`. */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Run the bounded tool loop and return the final text + every executed tool\n * outcome. Awaitable — callers needing to stream events to a UI use\n * {@link streamToolLoop}. */\nexport async function runToolLoop(opts: RunToolLoopOptions): Promise<ToolLoopResult> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n { role: 'user', content: opts.userMessage },\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n const toolResults: ToolLoopResult['toolResults'] = []\n let finalText = ''\n let turns = 0\n let accumulatedCostUsd = 0\n // Stuck-loop detection: track the last canonical-JSON call signature and how\n // many consecutive times we've seen it.\n let lastCallHash: string | null = null\n let consecutiveCount = 0\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n turns++\n\n // Wall-clock deadline check — before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'deadline' })\n return { finalText, toolResults, turns, stopReason: 'deadline', cappedOut: true }\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const ev of opts.streamTurn([...messages])) {\n if (ev.type === 'text') {\n turnText += ev.text\n finalText += ev.text\n } else if (ev.type === 'tool_call' && opts.isExecutableTool(ev.call.toolName)) {\n pending.push(ev.call)\n }\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: 0,\n finalTextChars: finalText.length,\n })\n break\n }\n\n // Runaway backstop — the model keeps emitting calls past the safety ceiling.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'backstop' })\n return { finalText, toolResults, turns, stopReason: 'backstop', cappedOut: true }\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n const outcomes: ExecutedToolCall[] = []\n for (const [callIndex, call] of pending.entries()) {\n // Stuck-loop detection: hash the first pending call each turn (a model\n // stuck in a loop re-issues the same call repeatedly, not alternating calls).\n const callHash = canonicalCallHash(call)\n if (callHash === lastCallHash) {\n consecutiveCount++\n } else {\n lastCallHash = callHash\n consecutiveCount = 1\n }\n if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'stuck-loop' })\n return { finalText, toolResults, turns, stopReason: 'stuck-loop', cappedOut: true }\n }\n\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n let settled = false\n const outcome = await executeGuarded(opts.executeToolCall, call, (update) => {\n if (!settled) opts.onToolProgress?.(call, update)\n })\n settled = true\n\n // Budget check after each tool call.\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n if (accumulatedCostUsd >= opts.maxCostUsd) {\n const label = labelFor(call)\n toolResults.push({ call, label, outcome })\n messages.push(toolResultMessage(call, render(label, outcome)))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'budget' })\n return { finalText, toolResults, turns, stopReason: 'budget', cappedOut: true }\n }\n }\n\n const label = labelFor(call)\n const rendered = render(label, outcome)\n toolResults.push({ call, label, outcome })\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'completed' })\n return { finalText, toolResults, turns, stopReason: 'completed', cappedOut: false }\n}\n\n// ── Streaming variant (SSE chat runtimes + per-event telemetry) ────────────\n\nexport type StreamToolLoopYield<Raw> =\n | { kind: 'event'; event: Raw }\n | {\n kind: 'tool_progress'\n toolName: string\n toolCallId?: string\n update: ToolProgressUpdate\n }\n | {\n kind: 'tool_result'\n toolName: string\n toolCallId?: string\n label: string\n outcome: ToolCallOutcome\n }\n | {\n kind: 'capped'\n pending: number\n stopReason: Exclude<ToolLoopStopReason, 'completed'>\n /** On `deadline` only: the conversation after the system prompt, every tool call answered.\n * Passing it back as `priorMessages` with no `userMessage` continues the same turn. */\n messages?: ToolLoopMessage[]\n }\n\nexport interface StreamToolLoopOptions<Raw> {\n systemPrompt: string\n /** Omit to continue a checkpointed turn whose `priorMessages` already end with tool results. */\n userMessage?: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<Raw>\n extractText: (event: Raw) => string\n extractToolCall: (event: Raw) => ToolLoopCall | null\n isExecutableTool: (toolName: string) => boolean\n executeToolCall: ToolCallExecutor\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Streaming bounded tool loop: yields each raw turn event (the caller maps +\n * telemetries + re-emits it), each `tool_progress` a running tool reports, and\n * each executed `tool_result`; emits one `capped` if it stops for any\n * non-completed reason with calls still pending. */\nexport async function* streamToolLoop<Raw>(\n opts: StreamToolLoopOptions<Raw>,\n): AsyncGenerator<StreamToolLoopYield<Raw>, void, unknown> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n ...(opts.userMessage !== undefined\n ? [{ role: 'user' as const, content: opts.userMessage }]\n : []),\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n let accumulatedCostUsd = 0\n let lastCallHash: string | null = null\n let consecutiveCount = 0\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n // Wall-clock deadline check before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'deadline' })\n // A turn boundary: every call is answered, so the history is a resumable checkpoint.\n yield { kind: 'capped', pending: 0, stopReason: 'deadline', messages: messages.slice(1) }\n return\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const event of opts.streamTurn([...messages])) {\n yield { kind: 'event', event }\n turnText += opts.extractText(event)\n const call = opts.extractToolCall(event)\n if (call && opts.isExecutableTool(call.toolName)) pending.push(call)\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, { pendingToolCalls: 0 })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'completed' })\n return\n }\n\n // Runaway backstop.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'backstop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'backstop' }\n return\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n const outcomes: ExecutedToolCall[] = []\n for (const [callIndex, call] of pending.entries()) {\n // Stuck-loop detection.\n const callHash = canonicalCallHash(call)\n if (callHash === lastCallHash) {\n consecutiveCount++\n } else {\n lastCallHash = callHash\n consecutiveCount = 1\n }\n if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'stuck-loop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'stuck-loop' }\n return\n }\n\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n // Progress arrives while the call is in flight; yield it as it lands, in order,\n // and stop accepting it once the call settles so it never trails the result.\n const progress: ToolProgressUpdate[] = []\n let wake: (() => void) | undefined\n let settled = false\n const running = executeGuarded(opts.executeToolCall, call, (update) => {\n if (settled) return\n progress.push(update)\n wake?.()\n }).then((result) => {\n settled = true\n wake?.()\n return result\n })\n while (!settled || progress.length > 0) {\n const update = progress.shift()\n if (update !== undefined) {\n yield {\n kind: 'tool_progress',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n update,\n }\n continue\n }\n await new Promise<void>((resolve) => {\n wake = resolve\n })\n wake = undefined\n }\n const outcome = await running\n\n // Budget check after each tool call.\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n if (accumulatedCostUsd >= opts.maxCostUsd) {\n const label = labelFor(call)\n yield {\n kind: 'tool_result',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n label,\n outcome,\n }\n messages.push(toolResultMessage(call, render(label, outcome)))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'budget' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'budget' }\n return\n }\n }\n\n const label = labelFor(call)\n yield {\n kind: 'tool_result',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n label,\n outcome,\n }\n const rendered = render(label, outcome)\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n}\n\n/** Run one call; a thrown executor becomes an `executor_error` outcome. */\nasync function executeGuarded(\n execute: ToolCallExecutor,\n call: ToolLoopCall,\n progress: (update: ToolProgressUpdate) => void,\n): Promise<ToolCallOutcome> {\n try {\n return await execute(call, { progress })\n } catch (err) {\n return {\n ok: false,\n code: 'executor_error',\n message: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\ninterface ExecutedToolCall {\n call: ToolLoopCall\n label: string\n outcome: ToolCallOutcome\n rendered: string\n}\n\ninterface NotifyToolFailureRecoveryOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n stepIndex: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n}\n\ninterface NotifyToolLoopEventOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n target: 'agent.run' | 'agent.turn' | 'agent.tool_call'\n phase: 'before' | 'after' | 'error' | 'event'\n id?: string\n stepIndex?: number\n parentId?: string\n payload?: Record<string, unknown>\n metadata?: Record<string, unknown>\n}\n\ninterface ToolLoopObserver {\n loopBefore(maxToolTurns: number, messageCount: number): void\n loopAfter(payload: Record<string, unknown>): void\n turnBefore(toolTurn: number, messageCount: number): string\n turnAfter(toolTurn: number, turnEventId: string, payload: Record<string, unknown>): void\n toolCallBefore(\n toolTurn: number,\n turnEventId: string,\n callIndex: number,\n call: ToolLoopCall,\n ): string\n toolCallAfter(\n toolTurn: number,\n callEventId: string,\n call: ToolLoopCall,\n outcome: ToolCallOutcome,\n ): void\n failureRecovery(options: {\n toolTurn: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n }): void\n}\n\nfunction createToolLoopObserver(\n hooks: RuntimeHooks | undefined,\n runId: string,\n scenarioId: string | undefined,\n): ToolLoopObserver {\n const loopEventId = `${runId}:agent.run`\n return {\n loopBefore: (maxToolTurns, messageCount) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'before',\n id: `${loopEventId}:before`,\n payload: { maxToolTurns, messageCount },\n })\n },\n loopAfter: (payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'after',\n id: `${loopEventId}:after`,\n payload,\n })\n },\n turnBefore: (toolTurn, messageCount) => {\n const turnEventId = `${loopEventId}:${toolTurn}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'before',\n id: turnEventId,\n stepIndex: toolTurn,\n parentId: loopEventId,\n payload: { messageCount },\n })\n return turnEventId\n },\n turnAfter: (toolTurn, turnEventId, payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'after',\n id: `${turnEventId}:after`,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload,\n })\n },\n toolCallBefore: (toolTurn, turnEventId, callIndex, call) => {\n const callEventId = `${turnEventId}:tool-call:${callIndex}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'before',\n id: callEventId,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload: toolCallPayload(call),\n })\n return callEventId\n },\n toolCallAfter: (toolTurn, callEventId, call, outcome) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'after',\n id: `${callEventId}:after`,\n stepIndex: toolTurn,\n parentId: callEventId,\n payload: { ...toolCallPayload(call), outcome: outcomePayload(outcome) },\n })\n },\n failureRecovery: (options) => {\n notifyToolFailureRecovery({\n hooks,\n runId,\n scenarioId,\n stepIndex: options.toolTurn,\n messages: options.messages,\n turnText: options.turnText,\n outcomes: options.outcomes,\n })\n },\n }\n}\n\nfunction notifyToolLoopEvent(options: NotifyToolLoopEventOptions): void {\n notifyRuntimeHookEvent(options.hooks, {\n id: options.id ?? `${options.runId}:${options.target}:${options.phase}`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n target: options.target,\n phase: options.phase,\n timestamp: Date.now(),\n stepIndex: options.stepIndex,\n parentId: options.parentId,\n payload: options.payload,\n metadata: { producer: 'tool-loop', ...options.metadata },\n })\n}\n\nfunction notifyToolFailureRecovery(options: NotifyToolFailureRecoveryOptions): void {\n const failed = options.outcomes.filter((item) => !item.outcome.ok)\n if (failed.length === 0) return\n\n const evidence: RuntimeDecisionEvidenceRef[] = []\n for (const item of failed) {\n const id = item.call.toolCallId ?? `${options.stepIndex}:${item.label}`\n evidence.push({\n source: 'tool_call',\n id,\n detail: `${item.call.toolName} ${stringifySafe(item.call.args, 2_000)}`,\n metadata: { toolName: item.call.toolName, label: item.label },\n })\n evidence.push({\n source: 'tool_result',\n id: `${id}:result`,\n detail: item.rendered,\n metadata: failureMetadata(item.outcome),\n })\n }\n\n notifyRuntimeDecisionPoint(options.hooks, {\n id: `${options.runId}:agent.turn:${options.stepIndex}:failure-recovery`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n stepIndex: options.stepIndex,\n kind: 'retry',\n candidateActions: [...FAILURE_RECOVERY_ACTIONS],\n context: renderDecisionContext(options.messages, options.turnText, options.outcomes),\n evidence,\n metadata: {\n target: 'failure-recovery',\n source: 'agent.turn',\n failedToolCount: failed.length,\n toolNames: failed.map((item) => item.call.toolName),\n },\n })\n}\n\nfunction toolCallPayload(call: ToolLoopCall): Record<string, unknown> {\n return {\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n argsPreview: stringifySafe(call.args, 2_000),\n }\n}\n\nfunction outcomePayload(outcome: ToolCallOutcome): Record<string, unknown> {\n if (!outcome.ok) {\n return {\n ok: false,\n code: outcome.code,\n message: trimText(outcome.message, 2_000),\n status: outcome.status,\n }\n }\n return {\n ok: true,\n resultPreview: stringifySafe(outcome.result, 2_000),\n }\n}\n\nfunction failureMetadata(outcome: ToolCallOutcome): Record<string, unknown> | undefined {\n if (outcome.ok) return undefined\n return {\n code: outcome.code,\n message: outcome.message,\n status: outcome.status,\n }\n}\n\nfunction renderDecisionContext(\n messages: ToolLoopMessage[],\n turnText: string,\n outcomes: ExecutedToolCall[],\n): string {\n const recent = messages.slice(-6).map((message) => `[${message.role}]\\n${message.content ?? ''}`)\n const assistant = turnText.trim() ? [`[assistant]\\n${turnText}`] : []\n const toolResults = [`[tool results]\\n${outcomes.map((item) => item.rendered).join('\\n')}`]\n return trimText(\n [...recent, ...assistant, ...toolResults].join('\\n\\n'),\n DEFAULT_DECISION_CONTEXT_CHARS,\n )\n}\n\n/** Canonical identifier for a tool call used by stuck-loop detection.\n * Keys are sorted so `{b:1,a:2}` and `{a:2,b:1}` produce the same hash. */\nfunction canonicalCallHash(call: ToolLoopCall): string {\n const sortedArgs = Object.fromEntries(\n Object.entries(call.args).sort(([a], [b]) => a.localeCompare(b)),\n )\n return `${call.toolName}:${JSON.stringify(sortedArgs)}`\n}\n\nfunction stringifySafe(value: unknown, max: number): string {\n let text: string\n try {\n text = JSON.stringify(value) ?? String(value)\n } catch {\n text = String(value)\n }\n return trimText(text, max)\n}\n\nfunction trimText(text: string, max: number): string {\n if (text.length <= max) return text\n return `${text.slice(0, max)}…`\n}\n\nfunction randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n"],"mappings":";;;;;AA2CA,MAAM,yBAAyB;AAC/B,MAAM,iCAAiC;AACvC,MAAM,2BAA2B;CAAC;CAAS;CAAU;CAAY;AAAM;;;AAGvE,MAAM,uBAAuB;;;;AAsC7B,SAAS,WAAW,MAA4B;CAC9C,OAAO,KAAK,cAAc,QAAQ,KAAK;AACzC;;;AAIA,SAAS,yBAAyB,UAAkB,SAA0C;CAC5F,OAAO;EACL,MAAM;EACN,SAAS,SAAS,KAAK,KAAK;EAC5B,YAAY,QAAQ,KAAK,UAAU;GACjC,GAAG,KAAK;GACR,IAAI,WAAW,IAAI;GACnB,MAAM;GACN,UAAU;IAAE,MAAM,KAAK;IAAU,WAAW,KAAK,UAAU,KAAK,IAAI;GAAE;EACxE,EAAE;CACJ;AACF;;AAGA,SAAS,kBAAkB,MAAoB,SAAkC;CAC/E,OAAO;EAAE,MAAM;EAAQ,cAAc,WAAW,IAAI;EAAG;CAAQ;AACjE;AA8BA,SAAS,cAAc,OAAe,SAAkC;CACtE,IAAI,QAAQ,IAAI,OAAO,KAAK,MAAM,SAAS,KAAK,UAAU,QAAQ,MAAM;CACxE,OAAO,KAAK,MAAM,aAAa,QAAQ,KAAK,KAAK,QAAQ;AAC3D;;;;AAsDA,eAAsB,YAAY,MAAmD;CACnF,MAAM,WAAW,KAAK,gBAAgB;CACtC,MAAM,SAAS,KAAK,gBAAgB;CACpC,MAAM,WAAW,KAAK,cAAc,MAAoB,EAAE;CAC1D,MAAM,QAAQ,KAAK,SAAS,aAAa,aAAa;CACtD,MAAM,WAA8B;EAClC;GAAE,MAAM;GAAU,SAAS,KAAK;EAAa;EAC7C,GAAI,KAAK,iBAAiB,CAAC;EAC3B;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,GAAG,IAAI,GAAG;AACrB"}
1
+ {"version":3,"file":"tool-loop.js","names":[],"sources":["../src/tool-loop.ts"],"sourcesContent":["/**\n * Bounded turn-level tool-dispatch loop.\n *\n * `runAgentTaskStream` runs ONE model turn; `runAgentRounds` orchestrates DELEGATED\n * multi-agent topologies (refine / fanout-vote). Neither is the everyday\n * interactive shape: a chat turn where the model may emit tool calls, each is\n * executed, the results are folded back, and the turn re-runs until the model\n * stops (or a turn cap). Every agent app hand-rolls that loop — this is it,\n * as a reusable primitive.\n *\n * Substrate-neutral by design: the caller supplies `streamTurn` (wrapping\n * whatever backend / `runAgentTaskStream` it uses) and `executeToolCall`\n * (routing to its executors). This module owns the LOOP; the caller owns the\n * model and the executors. `Raw` (streaming variant) is the caller's own\n * event type. The only imported contract is the runtime hook type: hooks are\n * execution-scoped observers, not part of the agent profile.\n */\n\nimport type { RuntimeDecisionEvidenceRef, RuntimeHooks } from './runtime-hooks'\nimport { notifyRuntimeDecisionPoint, notifyRuntimeHookEvent } from './runtime-hooks'\n\nexport interface ToolLoopCall {\n toolCallId?: string\n toolName: string\n args: Record<string, unknown>\n /**\n * Provider-specific fields the model attached to this call, echoed back on\n * its assistant `tool_calls` entry in the next request. Gemini 3 returns\n * `extra_content: { google: { thought_signature } }` on each call and answers\n * HTTP 400 when the next request omits it.\n */\n providerFields?: Record<string, unknown>\n}\n\n/** Outcome of one tool dispatch — structurally compatible with a hub/integration\n * tool-outcome union, so callers can fold either through the loop. */\nexport type ToolCallOutcome =\n | { ok: true; result: unknown }\n | { ok: false; code: string; message: string; status?: number }\n\n/** Runaway-backstop: stops an infinite tool loop where cost is unmetered. Set\n * far above any legitimate workflow — this is a watchdog, not a policy cap.\n * Legitimate per-call budgets come from `maxCostUsd` + `costOf`. */\nconst RUNAWAY_BACKSTOP_TURNS = 200\nconst DEFAULT_DECISION_CONTEXT_CHARS = 12_000\nconst FAILURE_RECOVERY_ACTIONS = ['retry', 'verify', 'continue', 'stop']\n/** Consecutive model turns issuing the same call set (tool + canonical-JSON args)\n * that trigger stuck-loop detection. The window resets on any different set. */\nconst STUCK_LOOP_THRESHOLD = 3\n\n/** One OpenAI-shaped tool-call entry carried on an assistant message, plus any\n * provider-specific fields the model attached to the call (`ToolLoopCall.providerFields`). */\nexport interface ToolLoopAssistantToolCall {\n [providerField: string]: unknown\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n}\n\n/**\n * A message in the running conversation the loop sends to `streamTurn`.\n *\n * The base `{ role, content }` covers `system` / `user` / plain `assistant`\n * turns. Two optional fields carry the OpenAI function-calling contract so a\n * strict model (Claude, and any OpenAI-compatible provider that validates tool\n * history) reads its own tool use back instead of re-issuing the same call:\n *\n * - an assistant turn that emitted tool calls carries `tool_calls`, and its\n * `content` is `null` when the turn was tool-only;\n * - each tool result is its own `{ role: 'tool', tool_call_id, content }`\n * message keyed to the call that produced it.\n *\n * Widening is additive: a `streamTurn` that reads only `role` + `content` still\n * works; one that forwards the whole message to an OpenAI-compatible endpoint\n * now sends correct tool history.\n */\nexport type ToolLoopMessage = {\n role: string\n content: string | null\n tool_calls?: ToolLoopAssistantToolCall[]\n tool_call_id?: string\n}\n\n/** A tool-call id is required to key a `role: 'tool'` result back to its call.\n * When the model omitted one, derive a stable id from the tool name so the\n * assistant `tool_calls` entry and its `tool` result still match. */\nfunction toolCallId(call: ToolLoopCall): string {\n return call.toolCallId ?? `call_${call.toolName}`\n}\n\n/** The assistant turn that emitted `pending`, in OpenAI shape: text content\n * (null when the turn was tool-only) plus its `tool_calls` array. */\nfunction assistantToolCallMessage(turnText: string, pending: ToolLoopCall[]): ToolLoopMessage {\n return {\n role: 'assistant',\n content: turnText.trim() || null,\n tool_calls: pending.map((call) => ({\n ...call.providerFields,\n id: toolCallId(call),\n type: 'function',\n function: { name: call.toolName, arguments: JSON.stringify(call.args) },\n })),\n }\n}\n\n/** One `role: 'tool'` result message keyed to its call by `tool_call_id`. */\nfunction toolResultMessage(call: ToolLoopCall, content: string): ToolLoopMessage {\n return { role: 'tool', tool_call_id: toolCallId(call), content }\n}\n\n/**\n * One progress report from a running tool, shaped like an MCP `notifications/progress`\n * payload: a free-text `message`, a monotonic `progress` count with an optional\n * `total`, and any structured `data` the caller's UI understands.\n */\nexport interface ToolProgressUpdate {\n message?: string\n progress?: number\n total?: number\n data?: unknown\n}\n\n/** What the loop hands a running tool besides its call. */\nexport interface ToolCallContext {\n /**\n * Report progress while the call runs. The streaming loop yields each update as a\n * `tool_progress` step, in order, before the call's `tool_result`; updates sent after\n * the call settles are dropped.\n */\n progress: (update: ToolProgressUpdate) => void\n}\n\n/** Executes one tool call. Implementations that take only the call stay valid. */\nexport type ToolCallExecutor = (\n call: ToolLoopCall,\n context: ToolCallContext,\n) => Promise<ToolCallOutcome>\n\nfunction defaultRender(label: string, outcome: ToolCallOutcome): string {\n if (outcome.ok) return `- ${label} → ok: ${JSON.stringify(outcome.result)}`\n return `- ${label} → failed (${outcome.code}): ${outcome.message}`\n}\n\n// ── Awaitable variant (drain-only callers, tests) ──────────────────────────\n\nexport type ToolLoopEvent =\n | { type: 'text'; text: string }\n | { type: 'tool_call'; call: ToolLoopCall }\n | { type: 'other'; event: unknown }\n\n/** Why the loop stopped. `completed` = model finished naturally; `stuck-loop` =\n * ≥3 consecutive model turns issuing the same calls (tool + args); `backstop` = hit the\n * runaway-backstop cap (200 by default); `deadline` = wall-clock deadlineMs\n * exceeded; `budget` = maxCostUsd exhausted. Non-`completed` stops are infra /\n * resource outcomes — eval scoring must distinguish them from capability failure. */\nexport type ToolLoopStopReason = 'completed' | 'stuck-loop' | 'backstop' | 'deadline' | 'budget'\n\nexport interface ToolLoopResult {\n finalText: string\n toolResults: Array<{ call: ToolLoopCall; label: string; outcome: ToolCallOutcome }>\n turns: number\n stopReason: ToolLoopStopReason\n /** @deprecated Use `stopReason !== 'completed'` instead. */\n cappedOut: boolean\n}\n\nexport interface RunToolLoopOptions {\n systemPrompt: string\n userMessage: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<ToolLoopEvent>\n executeToolCall: ToolCallExecutor\n /** Receives each progress update a running tool reports, in order. */\n onToolProgress?: (call: ToolLoopCall, update: ToolProgressUpdate) => void\n isExecutableTool: (toolName: string) => boolean\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow.\n * For per-workflow limits, use `maxCostUsd` or `deadlineMs` instead. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). When exceeded the\n * loop stops with stopReason `deadline`. */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Run the bounded tool loop and return the final text + every executed tool\n * outcome. Awaitable — callers needing to stream events to a UI use\n * {@link streamToolLoop}. */\nexport async function runToolLoop(opts: RunToolLoopOptions): Promise<ToolLoopResult> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n { role: 'user', content: opts.userMessage },\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n const toolResults: ToolLoopResult['toolResults'] = []\n let finalText = ''\n let turns = 0\n let accumulatedCostUsd = 0\n const isStuck = stuckLoopDetector()\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n turns++\n\n // Wall-clock deadline check — before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'deadline' })\n return { finalText, toolResults, turns, stopReason: 'deadline', cappedOut: true }\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const ev of opts.streamTurn([...messages])) {\n if (ev.type === 'text') {\n turnText += ev.text\n finalText += ev.text\n } else if (ev.type === 'tool_call' && opts.isExecutableTool(ev.call.toolName)) {\n pending.push(ev.call)\n }\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: 0,\n finalTextChars: finalText.length,\n })\n break\n }\n\n // Runaway backstop — the model keeps emitting calls past the safety ceiling.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'backstop' })\n return { finalText, toolResults, turns, stopReason: 'backstop', cappedOut: true }\n }\n\n if (isStuck(pending)) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'stuck-loop' })\n return { finalText, toolResults, turns, stopReason: 'stuck-loop', cappedOut: true }\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n const outcomes: ExecutedToolCall[] = []\n for (const [callIndex, call] of pending.entries()) {\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n let settled = false\n const outcome = await executeGuarded(opts.executeToolCall, call, (update) => {\n if (!settled) opts.onToolProgress?.(call, update)\n })\n settled = true\n\n // Budget check after each tool call.\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n if (accumulatedCostUsd >= opts.maxCostUsd) {\n const label = labelFor(call)\n toolResults.push({ call, label, outcome })\n messages.push(toolResultMessage(call, render(label, outcome)))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'budget' })\n return { finalText, toolResults, turns, stopReason: 'budget', cappedOut: true }\n }\n }\n\n const label = labelFor(call)\n const rendered = render(label, outcome)\n toolResults.push({ call, label, outcome })\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n observer.loopAfter({ turns, toolResults: toolResults.length, stopReason: 'completed' })\n return { finalText, toolResults, turns, stopReason: 'completed', cappedOut: false }\n}\n\n// ── Streaming variant (SSE chat runtimes + per-event telemetry) ────────────\n\nexport type StreamToolLoopYield<Raw> =\n | { kind: 'event'; event: Raw }\n | {\n kind: 'tool_progress'\n toolName: string\n toolCallId?: string\n update: ToolProgressUpdate\n }\n | {\n kind: 'tool_result'\n toolName: string\n toolCallId?: string\n label: string\n outcome: ToolCallOutcome\n }\n | {\n kind: 'capped'\n pending: number\n stopReason: Exclude<ToolLoopStopReason, 'completed'>\n /** On `deadline` only: the conversation after the system prompt, every tool call answered.\n * Passing it back as `priorMessages` with no `userMessage` continues the same turn. */\n messages?: ToolLoopMessage[]\n }\n\nexport interface StreamToolLoopOptions<Raw> {\n systemPrompt: string\n /** Omit to continue a checkpointed turn whose `priorMessages` already end with tool results. */\n userMessage?: string\n priorMessages?: ToolLoopMessage[]\n streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<Raw>\n extractText: (event: Raw) => string\n extractToolCall: (event: Raw) => ToolLoopCall | null\n isExecutableTool: (toolName: string) => boolean\n executeToolCall: ToolCallExecutor\n /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow. */\n maxToolTurns?: number\n /** Wall-clock deadline in ms since epoch (Date.now()-based). */\n deadlineMs?: number\n /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */\n maxCostUsd?: number\n /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */\n costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number\n renderResult?: (label: string, outcome: ToolCallOutcome) => string\n labelFor?: (call: ToolLoopCall) => string\n runId?: string\n scenarioId?: string\n hooks?: RuntimeHooks\n}\n\n/** Streaming bounded tool loop: yields each raw turn event (the caller maps +\n * telemetries + re-emits it), each `tool_progress` a running tool reports, and\n * each executed `tool_result`; emits one `capped` if it stops for any\n * non-completed reason with calls still pending. */\nexport async function* streamToolLoop<Raw>(\n opts: StreamToolLoopOptions<Raw>,\n): AsyncGenerator<StreamToolLoopYield<Raw>, void, unknown> {\n const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS\n const render = opts.renderResult ?? defaultRender\n const labelFor = opts.labelFor ?? ((c: ToolLoopCall) => c.toolName)\n const runId = opts.runId ?? `agent-run-${randomSuffix()}`\n const messages: ToolLoopMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.priorMessages ?? []),\n ...(opts.userMessage !== undefined\n ? [{ role: 'user' as const, content: opts.userMessage }]\n : []),\n ]\n const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId)\n let accumulatedCostUsd = 0\n const isStuck = stuckLoopDetector()\n\n observer.loopBefore(backstop, messages.length)\n\n for (let toolTurn = 0; ; toolTurn++) {\n // Wall-clock deadline check before every new turn.\n if (opts.deadlineMs !== undefined && Date.now() >= opts.deadlineMs) {\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'deadline' })\n // A turn boundary: every call is answered, so the history is a resumable checkpoint.\n yield { kind: 'capped', pending: 0, stopReason: 'deadline', messages: messages.slice(1) }\n return\n }\n\n let turnText = ''\n const pending: ToolLoopCall[] = []\n const turnEventId = observer.turnBefore(toolTurn, messages.length)\n for await (const event of opts.streamTurn([...messages])) {\n yield { kind: 'event', event }\n turnText += opts.extractText(event)\n const call = opts.extractToolCall(event)\n if (call && opts.isExecutableTool(call.toolName)) pending.push(call)\n }\n if (pending.length === 0) {\n observer.turnAfter(toolTurn, turnEventId, { pendingToolCalls: 0 })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'completed' })\n return\n }\n\n // Runaway backstop.\n if (toolTurn >= backstop) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'backstop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'backstop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'backstop' }\n return\n }\n\n if (isStuck(pending)) {\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'stuck-loop',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'stuck-loop' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'stuck-loop' }\n return\n }\n\n // The assistant turn that emitted the calls, carrying its tool_calls array,\n // so a strict model reads its own tool use back in OpenAI shape.\n messages.push(assistantToolCallMessage(turnText, pending))\n const outcomes: ExecutedToolCall[] = []\n for (const [callIndex, call] of pending.entries()) {\n const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call)\n // Progress arrives while the call is in flight; yield it as it lands, in order,\n // and stop accepting it once the call settles so it never trails the result.\n const progress: ToolProgressUpdate[] = []\n let wake: (() => void) | undefined\n let settled = false\n const running = executeGuarded(opts.executeToolCall, call, (update) => {\n if (settled) return\n progress.push(update)\n wake?.()\n }).then((result) => {\n settled = true\n wake?.()\n return result\n })\n while (!settled || progress.length > 0) {\n const update = progress.shift()\n if (update !== undefined) {\n yield {\n kind: 'tool_progress',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n update,\n }\n continue\n }\n await new Promise<void>((resolve) => {\n wake = resolve\n })\n wake = undefined\n }\n const outcome = await running\n\n // Budget check after each tool call.\n if (opts.maxCostUsd !== undefined && opts.costOf !== undefined) {\n accumulatedCostUsd += opts.costOf(call, outcome)\n if (accumulatedCostUsd >= opts.maxCostUsd) {\n const label = labelFor(call)\n yield {\n kind: 'tool_result',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n label,\n outcome,\n }\n messages.push(toolResultMessage(call, render(label, outcome)))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n stopReason: 'budget',\n })\n observer.loopAfter({ turns: toolTurn + 1, stopReason: 'budget' })\n yield { kind: 'capped', pending: pending.length, stopReason: 'budget' }\n return\n }\n }\n\n const label = labelFor(call)\n yield {\n kind: 'tool_result',\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n label,\n outcome,\n }\n const rendered = render(label, outcome)\n outcomes.push({ call, label, outcome, rendered })\n // One role:'tool' message per result, keyed to its call by tool_call_id.\n messages.push(toolResultMessage(call, rendered))\n observer.toolCallAfter(toolTurn, callEventId, call, outcome)\n }\n observer.failureRecovery({\n toolTurn,\n messages,\n turnText,\n outcomes,\n })\n observer.turnAfter(toolTurn, turnEventId, {\n pendingToolCalls: pending.length,\n toolResults: outcomes.map((item) => ({\n toolName: item.call.toolName,\n toolCallId: item.call.toolCallId,\n ok: item.outcome.ok,\n })),\n failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length,\n })\n }\n}\n\n/** Run one call; a thrown executor becomes an `executor_error` outcome. */\nasync function executeGuarded(\n execute: ToolCallExecutor,\n call: ToolLoopCall,\n progress: (update: ToolProgressUpdate) => void,\n): Promise<ToolCallOutcome> {\n try {\n return await execute(call, { progress })\n } catch (err) {\n return {\n ok: false,\n code: 'executor_error',\n message: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\ninterface ExecutedToolCall {\n call: ToolLoopCall\n label: string\n outcome: ToolCallOutcome\n rendered: string\n}\n\ninterface NotifyToolFailureRecoveryOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n stepIndex: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n}\n\ninterface NotifyToolLoopEventOptions {\n hooks?: RuntimeHooks\n runId: string\n scenarioId?: string\n target: 'agent.run' | 'agent.turn' | 'agent.tool_call'\n phase: 'before' | 'after' | 'error' | 'event'\n id?: string\n stepIndex?: number\n parentId?: string\n payload?: Record<string, unknown>\n metadata?: Record<string, unknown>\n}\n\ninterface ToolLoopObserver {\n loopBefore(maxToolTurns: number, messageCount: number): void\n loopAfter(payload: Record<string, unknown>): void\n turnBefore(toolTurn: number, messageCount: number): string\n turnAfter(toolTurn: number, turnEventId: string, payload: Record<string, unknown>): void\n toolCallBefore(\n toolTurn: number,\n turnEventId: string,\n callIndex: number,\n call: ToolLoopCall,\n ): string\n toolCallAfter(\n toolTurn: number,\n callEventId: string,\n call: ToolLoopCall,\n outcome: ToolCallOutcome,\n ): void\n failureRecovery(options: {\n toolTurn: number\n messages: ToolLoopMessage[]\n turnText: string\n outcomes: ExecutedToolCall[]\n }): void\n}\n\nfunction createToolLoopObserver(\n hooks: RuntimeHooks | undefined,\n runId: string,\n scenarioId: string | undefined,\n): ToolLoopObserver {\n const loopEventId = `${runId}:agent.run`\n return {\n loopBefore: (maxToolTurns, messageCount) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'before',\n id: `${loopEventId}:before`,\n payload: { maxToolTurns, messageCount },\n })\n },\n loopAfter: (payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.run',\n phase: 'after',\n id: `${loopEventId}:after`,\n payload,\n })\n },\n turnBefore: (toolTurn, messageCount) => {\n const turnEventId = `${loopEventId}:${toolTurn}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'before',\n id: turnEventId,\n stepIndex: toolTurn,\n parentId: loopEventId,\n payload: { messageCount },\n })\n return turnEventId\n },\n turnAfter: (toolTurn, turnEventId, payload) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.turn',\n phase: 'after',\n id: `${turnEventId}:after`,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload,\n })\n },\n toolCallBefore: (toolTurn, turnEventId, callIndex, call) => {\n const callEventId = `${turnEventId}:tool-call:${callIndex}`\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'before',\n id: callEventId,\n stepIndex: toolTurn,\n parentId: turnEventId,\n payload: toolCallPayload(call),\n })\n return callEventId\n },\n toolCallAfter: (toolTurn, callEventId, call, outcome) => {\n notifyToolLoopEvent({\n hooks,\n runId,\n scenarioId,\n target: 'agent.tool_call',\n phase: 'after',\n id: `${callEventId}:after`,\n stepIndex: toolTurn,\n parentId: callEventId,\n payload: { ...toolCallPayload(call), outcome: outcomePayload(outcome) },\n })\n },\n failureRecovery: (options) => {\n notifyToolFailureRecovery({\n hooks,\n runId,\n scenarioId,\n stepIndex: options.toolTurn,\n messages: options.messages,\n turnText: options.turnText,\n outcomes: options.outcomes,\n })\n },\n }\n}\n\nfunction notifyToolLoopEvent(options: NotifyToolLoopEventOptions): void {\n notifyRuntimeHookEvent(options.hooks, {\n id: options.id ?? `${options.runId}:${options.target}:${options.phase}`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n target: options.target,\n phase: options.phase,\n timestamp: Date.now(),\n stepIndex: options.stepIndex,\n parentId: options.parentId,\n payload: options.payload,\n metadata: { producer: 'tool-loop', ...options.metadata },\n })\n}\n\nfunction notifyToolFailureRecovery(options: NotifyToolFailureRecoveryOptions): void {\n const failed = options.outcomes.filter((item) => !item.outcome.ok)\n if (failed.length === 0) return\n\n const evidence: RuntimeDecisionEvidenceRef[] = []\n for (const item of failed) {\n const id = item.call.toolCallId ?? `${options.stepIndex}:${item.label}`\n evidence.push({\n source: 'tool_call',\n id,\n detail: `${item.call.toolName} ${stringifySafe(item.call.args, 2_000)}`,\n metadata: { toolName: item.call.toolName, label: item.label },\n })\n evidence.push({\n source: 'tool_result',\n id: `${id}:result`,\n detail: item.rendered,\n metadata: failureMetadata(item.outcome),\n })\n }\n\n notifyRuntimeDecisionPoint(options.hooks, {\n id: `${options.runId}:agent.turn:${options.stepIndex}:failure-recovery`,\n runId: options.runId,\n scenarioId: options.scenarioId,\n stepIndex: options.stepIndex,\n kind: 'retry',\n candidateActions: [...FAILURE_RECOVERY_ACTIONS],\n context: renderDecisionContext(options.messages, options.turnText, options.outcomes),\n evidence,\n metadata: {\n target: 'failure-recovery',\n source: 'agent.turn',\n failedToolCount: failed.length,\n toolNames: failed.map((item) => item.call.toolName),\n },\n })\n}\n\nfunction toolCallPayload(call: ToolLoopCall): Record<string, unknown> {\n return {\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n argsPreview: stringifySafe(call.args, 2_000),\n }\n}\n\nfunction outcomePayload(outcome: ToolCallOutcome): Record<string, unknown> {\n if (!outcome.ok) {\n return {\n ok: false,\n code: outcome.code,\n message: trimText(outcome.message, 2_000),\n status: outcome.status,\n }\n }\n return {\n ok: true,\n resultPreview: stringifySafe(outcome.result, 2_000),\n }\n}\n\nfunction failureMetadata(outcome: ToolCallOutcome): Record<string, unknown> | undefined {\n if (outcome.ok) return undefined\n return {\n code: outcome.code,\n message: outcome.message,\n status: outcome.status,\n }\n}\n\nfunction renderDecisionContext(\n messages: ToolLoopMessage[],\n turnText: string,\n outcomes: ExecutedToolCall[],\n): string {\n const recent = messages.slice(-6).map((message) => `[${message.role}]\\n${message.content ?? ''}`)\n const assistant = turnText.trim() ? [`[assistant]\\n${turnText}`] : []\n const toolResults = [`[tool results]\\n${outcomes.map((item) => item.rendered).join('\\n')}`]\n return trimText(\n [...recent, ...assistant, ...toolResults].join('\\n\\n'),\n DEFAULT_DECISION_CONTEXT_CHARS,\n )\n}\n\n/** Stuck-loop detection across model turns: true once {@link STUCK_LOOP_THRESHOLD}\n * consecutive turns issue the same call set. Repeats inside one parallel batch\n * are not a loop; each runs and its result reaches the model. */\nfunction stuckLoopDetector(): (batch: ToolLoopCall[]) => boolean {\n let last: string | undefined\n let count = 0\n return (batch) => {\n const signature = [...new Set(batch.map(canonicalCallHash))].sort().join('\\n')\n count = signature === last ? count + 1 : 1\n last = signature\n return count >= STUCK_LOOP_THRESHOLD\n }\n}\n\n/** Canonical identifier for a tool call used by stuck-loop detection.\n * Keys are sorted so `{b:1,a:2}` and `{a:2,b:1}` produce the same hash. */\nfunction canonicalCallHash(call: ToolLoopCall): string {\n const sortedArgs = Object.fromEntries(\n Object.entries(call.args).sort(([a], [b]) => a.localeCompare(b)),\n )\n return `${call.toolName}:${JSON.stringify(sortedArgs)}`\n}\n\nfunction stringifySafe(value: unknown, max: number): string {\n let text: string\n try {\n text = JSON.stringify(value) ?? String(value)\n } catch {\n text = String(value)\n }\n return trimText(text, max)\n}\n\nfunction trimText(text: string, max: number): string {\n if (text.length <= max) return text\n return `${text.slice(0, max)}…`\n}\n\nfunction randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n"],"mappings":";;;;;AA2CA,MAAM,yBAAyB;AAC/B,MAAM,iCAAiC;AACvC,MAAM,2BAA2B;CAAC;CAAS;CAAU;CAAY;AAAM;;;AAGvE,MAAM,uBAAuB;;;;AAsC7B,SAAS,WAAW,MAA4B;CAC9C,OAAO,KAAK,cAAc,QAAQ,KAAK;AACzC;;;AAIA,SAAS,yBAAyB,UAAkB,SAA0C;CAC5F,OAAO;EACL,MAAM;EACN,SAAS,SAAS,KAAK,KAAK;EAC5B,YAAY,QAAQ,KAAK,UAAU;GACjC,GAAG,KAAK;GACR,IAAI,WAAW,IAAI;GACnB,MAAM;GACN,UAAU;IAAE,MAAM,KAAK;IA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AQ,cAAc,OAAO,QAAQ,IAAI;EACzC,OAAO;EACP,OAAO,SAAS;CAClB;AACF;;;AAIA,SAAS,kBAAkB,MAA4B;CACrD,MAAM,aAAa,OAAO,YACxB,OAAO,QAAQ,KAAK,IAAI,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC,CACjE;CACA,OAAO,GAAG,KAAK,SAAS,GAAG,KAAK,UAAU,UAAU;AACtD;AAEA,SAAS,cAAc,OAAgB,KAAqB;CAC1D,IAAI;CACJ,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;CAC9C,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;CACA,OAAO,SAAS,MAAM,GAAG;AAC3B;AAEA,SAAS,SAAS,MAAc,KAAqB;CACnD,IAAI,KAAK,UAAU,KAAK,OAAO;CAC/B,OAAO,GAAG,KAAK,MAAM,GAAG,GAAG,EAAE;AAC/B;AAEA,SAAS,aAAa,MAAM,GAAW;CACrC,OAAO,KAAK,OAAO,CAAC,CACjB,SAAS,EAAE,CAAC,CACZ,MAAM,GAAG,IAAI,GAAG;AACrB"}
@@ -1,5 +1,5 @@
1
1
  import { m as ValidationError } from "./errors-DG8yufqX.js";
2
- import { n as runtimeFailureCause, r as runtimeFailureCauseSchema } from "./failure-cause-DoCCGLDH.js";
2
+ import { n as runtimeFailureCause, r as runtimeFailureCauseSchema } from "./failure-cause-DvYGlOEV.js";
3
3
  import { createInterface } from "node:readline";
4
4
  // src/mcp/tool-server.ts
5
5
  /**
@@ -171,4 +171,4 @@ function writeResponse(output, response) {
171
171
  }
172
172
  export { createStdioToolServer as n, PROTOCOL_VERSION as t };
173
173
 
174
- //# sourceMappingURL=tool-server-DQCdu3am.js.map
174
+ //# sourceMappingURL=tool-server-Cb7LBW4e.js.map