@tangle-network/agent-runtime 0.109.0 → 0.109.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +1 -0
  2. package/dist/{activation-DRpnplEm.js → activation-CM-L6TtL.js} +2 -2
  3. package/dist/{activation-DRpnplEm.js.map → activation-CM-L6TtL.js.map} +1 -1
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +2 -2
  6. package/dist/analyst-loop.d.ts +1 -1
  7. package/dist/{environment-provider-D0NXc4Qz.d.ts → environment-provider-CMqSAp-O.d.ts} +3 -2
  8. package/dist/environment-provider.d.ts +1 -1
  9. package/dist/{improvement-cycle-CRnDDdX0.js → improvement-cycle-9O4iVFOA.js} +3 -3
  10. package/dist/{improvement-cycle-CRnDDdX0.js.map → improvement-cycle-9O4iVFOA.js.map} +1 -1
  11. package/dist/{index-CqWEbmGh.d.ts → index-BwY61sh3.d.ts} +3 -3
  12. package/dist/{index-B6p86EqB.d.ts → index-CFJ_1m1U.d.ts} +11 -9
  13. package/dist/{index-lpqu3wdI.d.ts → index-HsQm1Rrr.d.ts} +6 -152
  14. package/dist/index.d.ts +8 -7
  15. package/dist/index.js +11 -635
  16. package/dist/index.js.map +1 -1
  17. package/dist/intelligence.d.ts +2 -2
  18. package/dist/intelligence.js +2 -2
  19. package/dist/kernel.d.ts +3 -3
  20. package/dist/kernel.js +4 -4
  21. package/dist/{knowledge-DwVmEJyG.js → knowledge-1a38bcUT.js} +3 -3
  22. package/dist/{knowledge-DwVmEJyG.js.map → knowledge-1a38bcUT.js.map} +1 -1
  23. package/dist/knowledge.d.ts +1 -1
  24. package/dist/knowledge.js +1 -1
  25. package/dist/{loop-runner-bin-C6gjS2Ar.js → loop-runner-bin-C35m19w0.js} +3 -3
  26. package/dist/{loop-runner-bin-C6gjS2Ar.js.map → loop-runner-bin-C35m19w0.js.map} +1 -1
  27. package/dist/{loop-runner-bin-D55_d9K8.d.ts → loop-runner-bin-DUQF0bYz.d.ts} +3 -3
  28. package/dist/loop-runner-bin.d.ts +1 -1
  29. package/dist/loop-runner-bin.js +1 -1
  30. package/dist/mcp/bin.js +1 -1
  31. package/dist/mcp/index.d.ts +2 -2
  32. package/dist/mcp/index.js +4 -4
  33. package/dist/{openai-tools-B17qCuEc.js → openai-tools-DT9FH2_t.js} +2 -2
  34. package/dist/{openai-tools-B17qCuEc.js.map → openai-tools-DT9FH2_t.js.map} +1 -1
  35. package/dist/primeintellect/index.d.ts +1 -1
  36. package/dist/profiles.d.ts +1 -1
  37. package/dist/profiles.js.map +1 -1
  38. package/dist/{runtime-bCvzR6fc.js → runtime-dpJZmZtt.js} +16 -16
  39. package/dist/runtime-dpJZmZtt.js.map +1 -0
  40. package/dist/runtime-hooks-C7iJOWm3.js +99 -0
  41. package/dist/runtime-hooks-C7iJOWm3.js.map +1 -0
  42. package/dist/runtime-hooks-sbRpjStq.d.ts +88 -0
  43. package/dist/{structural-rollout-BC81Otmc.js → structural-rollout-ASQLr4-v.js} +2 -2
  44. package/dist/{structural-rollout-BC81Otmc.js.map → structural-rollout-ASQLr4-v.js.map} +1 -1
  45. package/dist/{supervise-DXjtclYS.js → supervise-DyPmmhJ6.js} +5 -4
  46. package/dist/supervise-DyPmmhJ6.js.map +1 -0
  47. package/dist/{supervisor-B2LzaWRb.js → supervisor-sTJC9psT.js} +3 -98
  48. package/dist/supervisor-sTJC9psT.js.map +1 -0
  49. package/dist/testing.js +8 -8
  50. package/dist/tool-loop.d.ts +149 -0
  51. package/dist/tool-loop.js +629 -0
  52. package/dist/tool-loop.js.map +1 -0
  53. package/dist/{types-BevOjfTY.d.ts → types-DnNGJ5Gz.d.ts} +3 -88
  54. package/package.json +17 -6
  55. package/dist/runtime-bCvzR6fc.js.map +0 -1
  56. package/dist/supervise-DXjtclYS.js.map +0 -1
  57. package/dist/supervisor-B2LzaWRb.js.map +0 -1
package/dist/index.js CHANGED
@@ -5,15 +5,16 @@ import { i as sealAgentCandidateBundle, n as captureAgentCandidateWorkspaceFiles
5
5
  import { i as buildAgentCandidateBundle, n as disposePreparedAgentCandidateExecution, r as FileAgentCandidateExecutionClaimStore, t as recoverExpiredAgentCandidateExecution } from "./candidate-execution-nYMa-bc-.js";
6
6
  import { n as exactProcessProviderAsCandidateExecutor, t as createProtectedAgentCandidateModelPort } from "./protected-model-port-uthtDNqu.js";
7
7
  import { C as makePerAttemptSignal, S as defaultIsRetryable, _ as readDepth, a as FileConversationJournal, b as DeadlineExceededError, c as createConversationBackend, d as slugifySpeaker, f as turnId, g as isDepthExceeded, h as buildForwardHeaders, i as d1ToSqlAdapter, l as runConversation, m as FORWARD_HEADERS, n as runPersonaDispatch, o as InMemoryConversationJournal, p as DEFAULT_MAX_DEPTH, r as SqlConversationJournal, s as defineConversation, t as runPersonaConversation, u as runConversationStream, v as CircuitBreakerState, w as sleep, x as computeBackoff, y as CircuitOpenError } from "./conversation-BpLQZGPH.js";
8
- import { C as notifyRuntimeDecisionPoint, R as runLocalHarness, S as defineRuntimeHooks, k as runBrainLoop, w as notifyRuntimeHookEvent, x as composeRuntimeHooks } from "./supervisor-B2LzaWRb.js";
9
- import { D as researchDriverNote, E as optimizerMethod, O as strategyAuthorMethod, T as buildDriverSystem } from "./structural-rollout-BC81Otmc.js";
10
- import { A as improve, B as agenticGenerator, F as normalizeRolloutPolicy, G as summarizeFindings, H as defaultBuildPrompt, I as parseRolloutPolicy, K as worktreeChangedPaths, L as serializeRolloutPolicy, M as rawTraceDistiller, N as ROLLOUT_POLICY_EXTENSION, P as applyRolloutPolicyToProfile, R as structuralRolloutPolicyFromProfile, U as rawTraceEvidenceProblem, V as commandVerifier, W as requiresRawTraceEvidence, j as withMethodRuntimeControls, z as AGENTIC_PROFILE_RESOURCE_ROOT } from "./improvement-cycle-CRnDDdX0.js";
11
- import { bt as connectStdioMcp, yt as McpSpawnFault } from "./runtime-bCvzR6fc.js";
8
+ import { P as runLocalHarness, T as runBrainLoop } from "./supervisor-sTJC9psT.js";
9
+ import { D as researchDriverNote, E as optimizerMethod, O as strategyAuthorMethod, T as buildDriverSystem } from "./structural-rollout-ASQLr4-v.js";
10
+ import { A as improve, B as agenticGenerator, F as normalizeRolloutPolicy, G as summarizeFindings, H as defaultBuildPrompt, I as parseRolloutPolicy, K as worktreeChangedPaths, L as serializeRolloutPolicy, M as rawTraceDistiller, N as ROLLOUT_POLICY_EXTENSION, P as applyRolloutPolicyToProfile, R as structuralRolloutPolicyFromProfile, U as rawTraceEvidenceProblem, V as commandVerifier, W as requiresRawTraceEvidence, j as withMethodRuntimeControls, z as AGENTIC_PROFILE_RESOURCE_ROOT } from "./improvement-cycle-9O4iVFOA.js";
11
+ import { i as notifyRuntimeHookEvent, n as defineRuntimeHooks, r as notifyRuntimeDecisionPoint, t as composeRuntimeHooks } from "./runtime-hooks-C7iJOWm3.js";
12
+ import { bt as connectStdioMcp, yt as McpSpawnFault } from "./runtime-dpJZmZtt.js";
12
13
  import { n as defaultRedactorIdentityMaterial, r as resolveRedactor, t as defaultRedactor } from "./redact-D-u-rrcn.js";
13
- import { a as createSupervisedKnowledgeUpdater, c as runSupervisedKnowledgeUpdate, i as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, l as createKnowledgeImprovementActivationExecutor, n as createAgentKnowledgeReadinessCheck, o as formatSupervisedKnowledgeTask, r as runKnowledgeImprovementJob, s as knowledgeReadinessDeliverable, t as buildKnowledgeImprovementExperimentBundles } from "./knowledge-DwVmEJyG.js";
14
+ import { a as createSupervisedKnowledgeUpdater, c as runSupervisedKnowledgeUpdate, i as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, l as createKnowledgeImprovementActivationExecutor, n as createAgentKnowledgeReadinessCheck, o as formatSupervisedKnowledgeTask, r as runKnowledgeImprovementJob, s as knowledgeReadinessDeliverable, t as buildKnowledgeImprovementExperimentBundles } from "./knowledge-1a38bcUT.js";
14
15
  import { a as createOtelExporter, c as loopEventToOtelSpan, d as sanitizeAgentRuntimeEvent, f as sanitizeKnowledgeReadinessReport, i as buildRuntimeEventOtelSpans, l as createRuntimeEventCollector, n as buildLoopOtelSpans, o as exportEvalRuns, p as sanitizeRuntimeStreamEvent, r as buildLoopSpanNodes, t as INTELLIGENCE_WIRE_VERSION, u as createRuntimeStreamEventCollector } from "./otel-export-D34IQW1C.js";
15
- import { a as isDelegatedLoopMode, c as worktreeLoopRunner, i as auditLoopRunner, n as runLoopRunnerCli, o as researchLoopRunner, r as DELEGATED_LOOP_MODES, s as runDelegatedLoop, t as parseLoopRunnerArgv } from "./loop-runner-bin-C6gjS2Ar.js";
16
- import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "./openai-tools-B17qCuEc.js";
16
+ import { a as isDelegatedLoopMode, c as worktreeLoopRunner, i as auditLoopRunner, n as runLoopRunnerCli, o as researchLoopRunner, r as DELEGATED_LOOP_MODES, s as runDelegatedLoop, t as parseLoopRunnerArgv } from "./loop-runner-bin-C35m19w0.js";
17
+ import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "./openai-tools-DT9FH2_t.js";
17
18
  import { a as resolveRouterBaseUrl, i as resolveChatModel, n as cleanModelId, o as validateChatModelId, r as getModels, t as DEFAULT_ROUTER_BASE_URL } from "./model-resolution-Btd9iIKV.js";
18
19
  import { FAILURE_CLASSES, acquisitionPlansForKnowledgeGaps, blockingKnowledgeEval, canonicalJson, runAgentControlLoop, scoreKnowledgeReadiness, userQuestionsForKnowledgeGaps } from "@tangle-network/agent-eval";
19
20
  import { gepaOptimizationMethod, skillOptOptimizationMethod } from "@tangle-network/agent-eval/campaign";
@@ -1351,7 +1352,7 @@ function startRuntimeRun(options) {
1351
1352
  const now = options.now ?? Date.now;
1352
1353
  const startedAtMs = now();
1353
1354
  const startedAt = new Date(startedAtMs).toISOString();
1354
- const id = options.id ?? `${options.taskSpec.id}:${randomSuffix$1()}`;
1355
+ const id = options.id ?? `${options.taskSpec.id}:${randomSuffix()}`;
1355
1356
  let status = "running";
1356
1357
  let completedAtMs;
1357
1358
  let resultSummary;
@@ -1438,7 +1439,7 @@ function mergeMetadata(base, extra) {
1438
1439
  ...extra ?? {}
1439
1440
  };
1440
1441
  }
1441
- function randomSuffix$1() {
1442
+ function randomSuffix() {
1442
1443
  return Math.random().toString(36).slice(2, 10);
1443
1444
  }
1444
1445
  //#endregion
@@ -1478,631 +1479,6 @@ function stripNewlines(value) {
1478
1479
  return value.replace(/[\r\n]/g, " ");
1479
1480
  }
1480
1481
  //#endregion
1481
- //#region src/tool-loop.ts
1482
- /** Runaway-backstop: stops an infinite tool loop where cost is unmetered. Set
1483
- * far above any legitimate workflow — this is a watchdog, not a policy cap.
1484
- * Legitimate per-call budgets come from `maxCostUsd` + `costOf`. */
1485
- const RUNAWAY_BACKSTOP_TURNS = 200;
1486
- const DEFAULT_DECISION_CONTEXT_CHARS = 12e3;
1487
- const FAILURE_RECOVERY_ACTIONS = [
1488
- "retry",
1489
- "verify",
1490
- "continue",
1491
- "stop"
1492
- ];
1493
- /** Consecutive identical calls (same tool + canonical-JSON args) that trigger
1494
- * stuck-loop detection. The window resets on any different call. */
1495
- const STUCK_LOOP_THRESHOLD = 3;
1496
- /** A tool-call id is required to key a `role: 'tool'` result back to its call.
1497
- * When the model omitted one, derive a stable id from the tool name so the
1498
- * assistant `tool_calls` entry and its `tool` result still match. */
1499
- function toolCallId(call) {
1500
- return call.toolCallId ?? `call_${call.toolName}`;
1501
- }
1502
- /** The assistant turn that emitted `pending`, in OpenAI shape: text content
1503
- * (null when the turn was tool-only) plus its `tool_calls` array. */
1504
- function assistantToolCallMessage(turnText, pending) {
1505
- return {
1506
- role: "assistant",
1507
- content: turnText.trim() || null,
1508
- tool_calls: pending.map((call) => ({
1509
- id: toolCallId(call),
1510
- type: "function",
1511
- function: {
1512
- name: call.toolName,
1513
- arguments: JSON.stringify(call.args)
1514
- }
1515
- }))
1516
- };
1517
- }
1518
- /** One `role: 'tool'` result message keyed to its call by `tool_call_id`. */
1519
- function toolResultMessage(call, content) {
1520
- return {
1521
- role: "tool",
1522
- tool_call_id: toolCallId(call),
1523
- content
1524
- };
1525
- }
1526
- function defaultRender(label, outcome) {
1527
- if (outcome.ok) return `- ${label} → ok: ${JSON.stringify(outcome.result)}`;
1528
- return `- ${label} → failed (${outcome.code}): ${outcome.message}`;
1529
- }
1530
- /** Run the bounded tool loop and return the final text + every executed tool
1531
- * outcome. Awaitable — callers needing to stream events to a UI use
1532
- * {@link streamToolLoop}. */
1533
- async function runToolLoop(opts) {
1534
- const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS;
1535
- const render = opts.renderResult ?? defaultRender;
1536
- const labelFor = opts.labelFor ?? ((c) => c.toolName);
1537
- const runId = opts.runId ?? `agent-run-${randomSuffix()}`;
1538
- const messages = [
1539
- {
1540
- role: "system",
1541
- content: opts.systemPrompt
1542
- },
1543
- ...opts.priorMessages ?? [],
1544
- {
1545
- role: "user",
1546
- content: opts.userMessage
1547
- }
1548
- ];
1549
- const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId);
1550
- const toolResults = [];
1551
- let finalText = "";
1552
- let turns = 0;
1553
- let accumulatedCostUsd = 0;
1554
- let lastCallHash = null;
1555
- let consecutiveCount = 0;
1556
- observer.loopBefore(backstop, messages.length);
1557
- for (let toolTurn = 0;; toolTurn++) {
1558
- turns++;
1559
- if (opts.deadlineMs !== void 0 && Date.now() >= opts.deadlineMs) {
1560
- observer.loopAfter({
1561
- turns,
1562
- toolResults: toolResults.length,
1563
- stopReason: "deadline"
1564
- });
1565
- return {
1566
- finalText,
1567
- toolResults,
1568
- turns,
1569
- stopReason: "deadline",
1570
- cappedOut: true
1571
- };
1572
- }
1573
- let turnText = "";
1574
- const pending = [];
1575
- const turnEventId = observer.turnBefore(toolTurn, messages.length);
1576
- for await (const ev of opts.streamTurn([...messages])) if (ev.type === "text") {
1577
- turnText += ev.text;
1578
- finalText += ev.text;
1579
- } else if (ev.type === "tool_call" && opts.isExecutableTool(ev.call.toolName)) pending.push(ev.call);
1580
- if (pending.length === 0) {
1581
- observer.turnAfter(toolTurn, turnEventId, {
1582
- pendingToolCalls: 0,
1583
- finalTextChars: finalText.length
1584
- });
1585
- break;
1586
- }
1587
- if (toolTurn >= backstop) {
1588
- observer.turnAfter(toolTurn, turnEventId, {
1589
- pendingToolCalls: pending.length,
1590
- stopReason: "backstop"
1591
- });
1592
- observer.loopAfter({
1593
- turns,
1594
- toolResults: toolResults.length,
1595
- stopReason: "backstop"
1596
- });
1597
- return {
1598
- finalText,
1599
- toolResults,
1600
- turns,
1601
- stopReason: "backstop",
1602
- cappedOut: true
1603
- };
1604
- }
1605
- messages.push(assistantToolCallMessage(turnText, pending));
1606
- const outcomes = [];
1607
- for (const [callIndex, call] of pending.entries()) {
1608
- const callHash = canonicalCallHash(call);
1609
- if (callHash === lastCallHash) consecutiveCount++;
1610
- else {
1611
- lastCallHash = callHash;
1612
- consecutiveCount = 1;
1613
- }
1614
- if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {
1615
- observer.turnAfter(toolTurn, turnEventId, {
1616
- pendingToolCalls: pending.length,
1617
- stopReason: "stuck-loop"
1618
- });
1619
- observer.loopAfter({
1620
- turns,
1621
- toolResults: toolResults.length,
1622
- stopReason: "stuck-loop"
1623
- });
1624
- return {
1625
- finalText,
1626
- toolResults,
1627
- turns,
1628
- stopReason: "stuck-loop",
1629
- cappedOut: true
1630
- };
1631
- }
1632
- const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call);
1633
- let outcome;
1634
- try {
1635
- outcome = await opts.executeToolCall(call);
1636
- } catch (err) {
1637
- outcome = {
1638
- ok: false,
1639
- code: "executor_error",
1640
- message: err instanceof Error ? err.message : String(err)
1641
- };
1642
- }
1643
- if (opts.maxCostUsd !== void 0 && opts.costOf !== void 0) {
1644
- accumulatedCostUsd += opts.costOf(call, outcome);
1645
- if (accumulatedCostUsd >= opts.maxCostUsd) {
1646
- const label = labelFor(call);
1647
- toolResults.push({
1648
- call,
1649
- label,
1650
- outcome
1651
- });
1652
- messages.push(toolResultMessage(call, render(label, outcome)));
1653
- observer.toolCallAfter(toolTurn, callEventId, call, outcome);
1654
- observer.turnAfter(toolTurn, turnEventId, {
1655
- pendingToolCalls: pending.length,
1656
- stopReason: "budget"
1657
- });
1658
- observer.loopAfter({
1659
- turns,
1660
- toolResults: toolResults.length,
1661
- stopReason: "budget"
1662
- });
1663
- return {
1664
- finalText,
1665
- toolResults,
1666
- turns,
1667
- stopReason: "budget",
1668
- cappedOut: true
1669
- };
1670
- }
1671
- }
1672
- const label = labelFor(call);
1673
- const rendered = render(label, outcome);
1674
- toolResults.push({
1675
- call,
1676
- label,
1677
- outcome
1678
- });
1679
- outcomes.push({
1680
- call,
1681
- label,
1682
- outcome,
1683
- rendered
1684
- });
1685
- messages.push(toolResultMessage(call, rendered));
1686
- observer.toolCallAfter(toolTurn, callEventId, call, outcome);
1687
- }
1688
- observer.failureRecovery({
1689
- toolTurn,
1690
- messages,
1691
- turnText,
1692
- outcomes
1693
- });
1694
- observer.turnAfter(toolTurn, turnEventId, {
1695
- pendingToolCalls: pending.length,
1696
- toolResults: outcomes.map((item) => ({
1697
- toolName: item.call.toolName,
1698
- toolCallId: item.call.toolCallId,
1699
- ok: item.outcome.ok
1700
- })),
1701
- failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length
1702
- });
1703
- }
1704
- observer.loopAfter({
1705
- turns,
1706
- toolResults: toolResults.length,
1707
- stopReason: "completed"
1708
- });
1709
- return {
1710
- finalText,
1711
- toolResults,
1712
- turns,
1713
- stopReason: "completed",
1714
- cappedOut: false
1715
- };
1716
- }
1717
- /** Streaming bounded tool loop: yields each raw turn event (the caller maps +
1718
- * telemetries + re-emits it) and each executed `tool_result`; emits one
1719
- * `capped` if it stops for any non-completed reason with calls still pending. */
1720
- async function* streamToolLoop(opts) {
1721
- const backstop = opts.maxToolTurns ?? RUNAWAY_BACKSTOP_TURNS;
1722
- const render = opts.renderResult ?? defaultRender;
1723
- const labelFor = opts.labelFor ?? ((c) => c.toolName);
1724
- const runId = opts.runId ?? `agent-run-${randomSuffix()}`;
1725
- const messages = [
1726
- {
1727
- role: "system",
1728
- content: opts.systemPrompt
1729
- },
1730
- ...opts.priorMessages ?? [],
1731
- {
1732
- role: "user",
1733
- content: opts.userMessage
1734
- }
1735
- ];
1736
- const observer = createToolLoopObserver(opts.hooks, runId, opts.scenarioId);
1737
- let accumulatedCostUsd = 0;
1738
- let lastCallHash = null;
1739
- let consecutiveCount = 0;
1740
- observer.loopBefore(backstop, messages.length);
1741
- for (let toolTurn = 0;; toolTurn++) {
1742
- if (opts.deadlineMs !== void 0 && Date.now() >= opts.deadlineMs) {
1743
- observer.loopAfter({
1744
- turns: toolTurn + 1,
1745
- stopReason: "deadline"
1746
- });
1747
- yield {
1748
- kind: "capped",
1749
- pending: 0,
1750
- stopReason: "deadline"
1751
- };
1752
- return;
1753
- }
1754
- let turnText = "";
1755
- const pending = [];
1756
- const turnEventId = observer.turnBefore(toolTurn, messages.length);
1757
- for await (const event of opts.streamTurn([...messages])) {
1758
- yield {
1759
- kind: "event",
1760
- event
1761
- };
1762
- turnText += opts.extractText(event);
1763
- const call = opts.extractToolCall(event);
1764
- if (call && opts.isExecutableTool(call.toolName)) pending.push(call);
1765
- }
1766
- if (pending.length === 0) {
1767
- observer.turnAfter(toolTurn, turnEventId, { pendingToolCalls: 0 });
1768
- observer.loopAfter({
1769
- turns: toolTurn + 1,
1770
- stopReason: "completed"
1771
- });
1772
- return;
1773
- }
1774
- if (toolTurn >= backstop) {
1775
- observer.turnAfter(toolTurn, turnEventId, {
1776
- pendingToolCalls: pending.length,
1777
- stopReason: "backstop"
1778
- });
1779
- observer.loopAfter({
1780
- turns: toolTurn + 1,
1781
- stopReason: "backstop"
1782
- });
1783
- yield {
1784
- kind: "capped",
1785
- pending: pending.length,
1786
- stopReason: "backstop"
1787
- };
1788
- return;
1789
- }
1790
- messages.push(assistantToolCallMessage(turnText, pending));
1791
- const outcomes = [];
1792
- for (const [callIndex, call] of pending.entries()) {
1793
- const callHash = canonicalCallHash(call);
1794
- if (callHash === lastCallHash) consecutiveCount++;
1795
- else {
1796
- lastCallHash = callHash;
1797
- consecutiveCount = 1;
1798
- }
1799
- if (consecutiveCount >= STUCK_LOOP_THRESHOLD) {
1800
- observer.turnAfter(toolTurn, turnEventId, {
1801
- pendingToolCalls: pending.length,
1802
- stopReason: "stuck-loop"
1803
- });
1804
- observer.loopAfter({
1805
- turns: toolTurn + 1,
1806
- stopReason: "stuck-loop"
1807
- });
1808
- yield {
1809
- kind: "capped",
1810
- pending: pending.length,
1811
- stopReason: "stuck-loop"
1812
- };
1813
- return;
1814
- }
1815
- const callEventId = observer.toolCallBefore(toolTurn, turnEventId, callIndex, call);
1816
- let outcome;
1817
- try {
1818
- outcome = await opts.executeToolCall(call);
1819
- } catch (err) {
1820
- outcome = {
1821
- ok: false,
1822
- code: "executor_error",
1823
- message: err instanceof Error ? err.message : String(err)
1824
- };
1825
- }
1826
- if (opts.maxCostUsd !== void 0 && opts.costOf !== void 0) {
1827
- accumulatedCostUsd += opts.costOf(call, outcome);
1828
- if (accumulatedCostUsd >= opts.maxCostUsd) {
1829
- const label = labelFor(call);
1830
- yield {
1831
- kind: "tool_result",
1832
- toolName: call.toolName,
1833
- toolCallId: call.toolCallId,
1834
- label,
1835
- outcome
1836
- };
1837
- messages.push(toolResultMessage(call, render(label, outcome)));
1838
- observer.toolCallAfter(toolTurn, callEventId, call, outcome);
1839
- observer.turnAfter(toolTurn, turnEventId, {
1840
- pendingToolCalls: pending.length,
1841
- stopReason: "budget"
1842
- });
1843
- observer.loopAfter({
1844
- turns: toolTurn + 1,
1845
- stopReason: "budget"
1846
- });
1847
- yield {
1848
- kind: "capped",
1849
- pending: pending.length,
1850
- stopReason: "budget"
1851
- };
1852
- return;
1853
- }
1854
- }
1855
- const label = labelFor(call);
1856
- yield {
1857
- kind: "tool_result",
1858
- toolName: call.toolName,
1859
- toolCallId: call.toolCallId,
1860
- label,
1861
- outcome
1862
- };
1863
- const rendered = render(label, outcome);
1864
- outcomes.push({
1865
- call,
1866
- label,
1867
- outcome,
1868
- rendered
1869
- });
1870
- messages.push(toolResultMessage(call, rendered));
1871
- observer.toolCallAfter(toolTurn, callEventId, call, outcome);
1872
- }
1873
- observer.failureRecovery({
1874
- toolTurn,
1875
- messages,
1876
- turnText,
1877
- outcomes
1878
- });
1879
- observer.turnAfter(toolTurn, turnEventId, {
1880
- pendingToolCalls: pending.length,
1881
- toolResults: outcomes.map((item) => ({
1882
- toolName: item.call.toolName,
1883
- toolCallId: item.call.toolCallId,
1884
- ok: item.outcome.ok
1885
- })),
1886
- failedToolCalls: outcomes.filter((item) => !item.outcome.ok).length
1887
- });
1888
- }
1889
- }
1890
- function createToolLoopObserver(hooks, runId, scenarioId) {
1891
- const loopEventId = `${runId}:agent.run`;
1892
- return {
1893
- loopBefore: (maxToolTurns, messageCount) => {
1894
- notifyToolLoopEvent({
1895
- hooks,
1896
- runId,
1897
- scenarioId,
1898
- target: "agent.run",
1899
- phase: "before",
1900
- id: `${loopEventId}:before`,
1901
- payload: {
1902
- maxToolTurns,
1903
- messageCount
1904
- }
1905
- });
1906
- },
1907
- loopAfter: (payload) => {
1908
- notifyToolLoopEvent({
1909
- hooks,
1910
- runId,
1911
- scenarioId,
1912
- target: "agent.run",
1913
- phase: "after",
1914
- id: `${loopEventId}:after`,
1915
- payload
1916
- });
1917
- },
1918
- turnBefore: (toolTurn, messageCount) => {
1919
- const turnEventId = `${loopEventId}:${toolTurn}`;
1920
- notifyToolLoopEvent({
1921
- hooks,
1922
- runId,
1923
- scenarioId,
1924
- target: "agent.turn",
1925
- phase: "before",
1926
- id: turnEventId,
1927
- stepIndex: toolTurn,
1928
- parentId: loopEventId,
1929
- payload: { messageCount }
1930
- });
1931
- return turnEventId;
1932
- },
1933
- turnAfter: (toolTurn, turnEventId, payload) => {
1934
- notifyToolLoopEvent({
1935
- hooks,
1936
- runId,
1937
- scenarioId,
1938
- target: "agent.turn",
1939
- phase: "after",
1940
- id: `${turnEventId}:after`,
1941
- stepIndex: toolTurn,
1942
- parentId: turnEventId,
1943
- payload
1944
- });
1945
- },
1946
- toolCallBefore: (toolTurn, turnEventId, callIndex, call) => {
1947
- const callEventId = `${turnEventId}:tool-call:${callIndex}`;
1948
- notifyToolLoopEvent({
1949
- hooks,
1950
- runId,
1951
- scenarioId,
1952
- target: "agent.tool_call",
1953
- phase: "before",
1954
- id: callEventId,
1955
- stepIndex: toolTurn,
1956
- parentId: turnEventId,
1957
- payload: toolCallPayload(call)
1958
- });
1959
- return callEventId;
1960
- },
1961
- toolCallAfter: (toolTurn, callEventId, call, outcome) => {
1962
- notifyToolLoopEvent({
1963
- hooks,
1964
- runId,
1965
- scenarioId,
1966
- target: "agent.tool_call",
1967
- phase: "after",
1968
- id: `${callEventId}:after`,
1969
- stepIndex: toolTurn,
1970
- parentId: callEventId,
1971
- payload: {
1972
- ...toolCallPayload(call),
1973
- outcome: outcomePayload(outcome)
1974
- }
1975
- });
1976
- },
1977
- failureRecovery: (options) => {
1978
- notifyToolFailureRecovery({
1979
- hooks,
1980
- runId,
1981
- scenarioId,
1982
- stepIndex: options.toolTurn,
1983
- messages: options.messages,
1984
- turnText: options.turnText,
1985
- outcomes: options.outcomes
1986
- });
1987
- }
1988
- };
1989
- }
1990
- function notifyToolLoopEvent(options) {
1991
- notifyRuntimeHookEvent(options.hooks, {
1992
- id: options.id ?? `${options.runId}:${options.target}:${options.phase}`,
1993
- runId: options.runId,
1994
- scenarioId: options.scenarioId,
1995
- target: options.target,
1996
- phase: options.phase,
1997
- timestamp: Date.now(),
1998
- stepIndex: options.stepIndex,
1999
- parentId: options.parentId,
2000
- payload: options.payload,
2001
- metadata: {
2002
- producer: "tool-loop",
2003
- ...options.metadata
2004
- }
2005
- });
2006
- }
2007
- function notifyToolFailureRecovery(options) {
2008
- const failed = options.outcomes.filter((item) => !item.outcome.ok);
2009
- if (failed.length === 0) return;
2010
- const evidence = [];
2011
- for (const item of failed) {
2012
- const id = item.call.toolCallId ?? `${options.stepIndex}:${item.label}`;
2013
- evidence.push({
2014
- source: "tool_call",
2015
- id,
2016
- detail: `${item.call.toolName} ${stringifySafe(item.call.args, 2e3)}`,
2017
- metadata: {
2018
- toolName: item.call.toolName,
2019
- label: item.label
2020
- }
2021
- });
2022
- evidence.push({
2023
- source: "tool_result",
2024
- id: `${id}:result`,
2025
- detail: item.rendered,
2026
- metadata: failureMetadata(item.outcome)
2027
- });
2028
- }
2029
- notifyRuntimeDecisionPoint(options.hooks, {
2030
- id: `${options.runId}:agent.turn:${options.stepIndex}:failure-recovery`,
2031
- runId: options.runId,
2032
- scenarioId: options.scenarioId,
2033
- stepIndex: options.stepIndex,
2034
- kind: "retry",
2035
- candidateActions: [...FAILURE_RECOVERY_ACTIONS],
2036
- context: renderDecisionContext(options.messages, options.turnText, options.outcomes),
2037
- evidence,
2038
- metadata: {
2039
- target: "failure-recovery",
2040
- source: "agent.turn",
2041
- failedToolCount: failed.length,
2042
- toolNames: failed.map((item) => item.call.toolName)
2043
- }
2044
- });
2045
- }
2046
- function toolCallPayload(call) {
2047
- return {
2048
- toolName: call.toolName,
2049
- toolCallId: call.toolCallId,
2050
- argsPreview: stringifySafe(call.args, 2e3)
2051
- };
2052
- }
2053
- function outcomePayload(outcome) {
2054
- if (!outcome.ok) return {
2055
- ok: false,
2056
- code: outcome.code,
2057
- message: trimText(outcome.message, 2e3),
2058
- status: outcome.status
2059
- };
2060
- return {
2061
- ok: true,
2062
- resultPreview: stringifySafe(outcome.result, 2e3)
2063
- };
2064
- }
2065
- function failureMetadata(outcome) {
2066
- if (outcome.ok) return void 0;
2067
- return {
2068
- code: outcome.code,
2069
- message: outcome.message,
2070
- status: outcome.status
2071
- };
2072
- }
2073
- function renderDecisionContext(messages, turnText, outcomes) {
2074
- const recent = messages.slice(-6).map((message) => `[${message.role}]\n${message.content ?? ""}`);
2075
- const assistant = turnText.trim() ? [`[assistant]\n${turnText}`] : [];
2076
- const toolResults = [`[tool results]\n${outcomes.map((item) => item.rendered).join("\n")}`];
2077
- return trimText([
2078
- ...recent,
2079
- ...assistant,
2080
- ...toolResults
2081
- ].join("\n\n"), DEFAULT_DECISION_CONTEXT_CHARS);
2082
- }
2083
- /** Canonical identifier for a tool call used by stuck-loop detection.
2084
- * Keys are sorted so `{b:1,a:2}` and `{a:2,b:1}` produce the same hash. */
2085
- function canonicalCallHash(call) {
2086
- const sortedArgs = Object.fromEntries(Object.entries(call.args).sort(([a], [b]) => a.localeCompare(b)));
2087
- return `${call.toolName}:${JSON.stringify(sortedArgs)}`;
2088
- }
2089
- function stringifySafe(value, max) {
2090
- let text;
2091
- try {
2092
- text = JSON.stringify(value) ?? String(value);
2093
- } catch {
2094
- text = String(value);
2095
- }
2096
- return trimText(text, max);
2097
- }
2098
- function trimText(text, max) {
2099
- if (text.length <= max) return text;
2100
- return `${text.slice(0, max)}…`;
2101
- }
2102
- function randomSuffix(len = 8) {
2103
- return Math.random().toString(36).slice(2, 2 + len);
2104
- }
2105
- //#endregion
2106
- export { AGENTIC_PROFILE_RESOURCE_ROOT, AGENT_CANDIDATE_EXECUTION_SUPPORT, AgentEvalError, BackendTransportError, CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, CANDIDATE_KNOWLEDGE_ROOT_ENV, CANDIDATE_TRACE_ENV, CANDIDATE_TRACE_TAGS, CircuitBreakerState, CircuitOpenError, ConfigError, DEFAULT_MAX_DEPTH, DEFAULT_ROUTER_BASE_URL, DELEGATED_LOOP_MODES, DeadlineExceededError, FORWARD_HEADERS, FileAgentCandidateExecutionClaimStore, FileConversationJournal, INTELLIGENCE_WIRE_VERSION, InMemoryAgentCandidateExecutionClaimStore, InMemoryConversationJournal, InMemoryRuntimeSessionStore, JudgeError, NotFoundError, OfficialOptimizerUnavailableError, PlannerError, RESEARCH_SUPERVISOR_SYSTEM_PROMPT, ROLLOUT_POLICY_EXTENSION, RuntimeRunStateError, SqlConversationJournal, ValidationError, agenticGenerator, applyExactAgentProfileDiff, applyRolloutPolicyToProfile, applyRunRecordDefaults, assertCandidateProfileBinding, auditLoopRunner, buildAgentCandidateBundle, buildDriverSystem, buildForwardHeaders, buildKnowledgeImprovementExperimentBundles, buildLoopOtelSpans, buildLoopSpanNodes, buildRuntimeEventOtelSpans, candidateExecutionClaim, candidateKnowledgeExecutionPaths, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, cleanModelId, commandVerifier, composeRuntimeHooks, computeBackoff, createAgentCandidateWorkspacePort, createAgentKnowledgeReadinessCheck, createConversationBackend, createIterableBackend, createKnowledgeImprovementActivationExecutor, createOpenAICompatibleBackend, createOtelExporter, createProtectedAgentCandidateModelPort, createRuntimeEventCollector, createRuntimeStreamEventCollector, createSandboxPromptBackend, createSupervisedKnowledgeUpdater, d1ToSqlAdapter, decideKnowledgeReadiness, defaultBuildPrompt, defaultIsRetryable, defineConversation, defineRuntimeHooks, disposePreparedAgentCandidateExecution, driverLoopGenerator, exactProcessProviderAsCandidateExecutor, executePreparedAgentCandidate, exportEvalRuns, findingLines, formatSupervisedKnowledgeTask, getModels, improve, isDelegatedLoopMode, isDepthExceeded, knowledgeReadinessDeliverable, loopEventToOtelSpan, makePerAttemptSignal, mcpBuildPrompt, mcpServeVerifier, mcpToolsForRuntimeMcp, mcpToolsForRuntimeMcpSubset, normalizeRolloutPolicy, notifyRuntimeDecisionPoint, notifyRuntimeHookEvent, officialGepa, officialSkillOpt, optimizerMethod, parseExactAgentProfile, parseExactAgentProfileDiff, parseLoopRunnerArgv, parseRolloutPolicy, persistCandidateOutputArtifact, prepareAgentCandidateExecution, rawTraceDistiller, readDepth, readinessServerSentEvent, recoverExpiredAgentCandidateExecution, reflectiveGenerator, researchDriverNote, researchLoopRunner, resolveAgentBackend, resolveChatModel, resolveRouterBaseUrl, runAgentTask, runAgentTaskStream, runConversation, runConversationStream, runDelegatedLoop, runKnowledgeImprovementJob, runLoopRunnerCli, runPersonaConversation, runPersonaDispatch, runSupervisedKnowledgeUpdate, runToolLoop, runtimeStreamServerSentEvent, sanitizeAgentRuntimeEvent, sanitizeKnowledgeReadinessReport, sanitizeRuntimeStreamEvent, sealAgentCandidateBundle, serializeRolloutPolicy, sleep, slugifySpeaker, startRuntimeRun, strategyAuthorMethod, streamToolLoop, structuralRolloutPolicyFromProfile, toolBuildPrompt, turnId, validateChatModelId, verifyAgentCandidateBundle, worktreeLoopRunner };
1482
+ export { AGENTIC_PROFILE_RESOURCE_ROOT, AGENT_CANDIDATE_EXECUTION_SUPPORT, AgentEvalError, BackendTransportError, CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, CANDIDATE_KNOWLEDGE_ROOT_ENV, CANDIDATE_TRACE_ENV, CANDIDATE_TRACE_TAGS, CircuitBreakerState, CircuitOpenError, ConfigError, DEFAULT_MAX_DEPTH, DEFAULT_ROUTER_BASE_URL, DELEGATED_LOOP_MODES, DeadlineExceededError, FORWARD_HEADERS, FileAgentCandidateExecutionClaimStore, FileConversationJournal, INTELLIGENCE_WIRE_VERSION, InMemoryAgentCandidateExecutionClaimStore, InMemoryConversationJournal, InMemoryRuntimeSessionStore, JudgeError, NotFoundError, OfficialOptimizerUnavailableError, PlannerError, RESEARCH_SUPERVISOR_SYSTEM_PROMPT, ROLLOUT_POLICY_EXTENSION, RuntimeRunStateError, SqlConversationJournal, ValidationError, agenticGenerator, applyExactAgentProfileDiff, applyRolloutPolicyToProfile, applyRunRecordDefaults, assertCandidateProfileBinding, auditLoopRunner, buildAgentCandidateBundle, buildDriverSystem, buildForwardHeaders, buildKnowledgeImprovementExperimentBundles, buildLoopOtelSpans, buildLoopSpanNodes, buildRuntimeEventOtelSpans, candidateExecutionClaim, candidateKnowledgeExecutionPaths, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, cleanModelId, commandVerifier, composeRuntimeHooks, computeBackoff, createAgentCandidateWorkspacePort, createAgentKnowledgeReadinessCheck, createConversationBackend, createIterableBackend, createKnowledgeImprovementActivationExecutor, createOpenAICompatibleBackend, createOtelExporter, createProtectedAgentCandidateModelPort, createRuntimeEventCollector, createRuntimeStreamEventCollector, createSandboxPromptBackend, createSupervisedKnowledgeUpdater, d1ToSqlAdapter, decideKnowledgeReadiness, defaultBuildPrompt, defaultIsRetryable, defineConversation, defineRuntimeHooks, disposePreparedAgentCandidateExecution, driverLoopGenerator, exactProcessProviderAsCandidateExecutor, executePreparedAgentCandidate, exportEvalRuns, findingLines, formatSupervisedKnowledgeTask, getModels, improve, isDelegatedLoopMode, isDepthExceeded, knowledgeReadinessDeliverable, loopEventToOtelSpan, makePerAttemptSignal, mcpBuildPrompt, mcpServeVerifier, mcpToolsForRuntimeMcp, mcpToolsForRuntimeMcpSubset, normalizeRolloutPolicy, notifyRuntimeDecisionPoint, notifyRuntimeHookEvent, officialGepa, officialSkillOpt, optimizerMethod, parseExactAgentProfile, parseExactAgentProfileDiff, parseLoopRunnerArgv, parseRolloutPolicy, persistCandidateOutputArtifact, prepareAgentCandidateExecution, rawTraceDistiller, readDepth, readinessServerSentEvent, recoverExpiredAgentCandidateExecution, reflectiveGenerator, researchDriverNote, researchLoopRunner, resolveAgentBackend, resolveChatModel, resolveRouterBaseUrl, runAgentTask, runAgentTaskStream, runConversation, runConversationStream, runDelegatedLoop, runKnowledgeImprovementJob, runLoopRunnerCli, runPersonaConversation, runPersonaDispatch, runSupervisedKnowledgeUpdate, runtimeStreamServerSentEvent, sanitizeAgentRuntimeEvent, sanitizeKnowledgeReadinessReport, sanitizeRuntimeStreamEvent, sealAgentCandidateBundle, serializeRolloutPolicy, sleep, slugifySpeaker, startRuntimeRun, strategyAuthorMethod, structuralRolloutPolicyFromProfile, toolBuildPrompt, turnId, validateChatModelId, verifyAgentCandidateBundle, worktreeLoopRunner };
2107
1483
 
2108
1484
  //# sourceMappingURL=index.js.map