@librechat/agents 3.4.0 → 3.4.1

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 (114) hide show
  1. package/dist/cjs/graphs/Graph.cjs +111 -27
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/hooks/HookRegistry.cjs +83 -0
  4. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  5. package/dist/cjs/hooks/executeHooks.cjs +60 -14
  6. package/dist/cjs/hooks/executeHooks.cjs.map +1 -1
  7. package/dist/cjs/hooks/index.cjs.map +1 -1
  8. package/dist/cjs/hooks/types.cjs +2 -0
  9. package/dist/cjs/hooks/types.cjs.map +1 -1
  10. package/dist/cjs/llm/init.cjs +3 -3
  11. package/dist/cjs/llm/invoke.cjs +2 -2
  12. package/dist/cjs/main.cjs +14 -13
  13. package/dist/cjs/messages/format.cjs +40 -23
  14. package/dist/cjs/messages/format.cjs.map +1 -1
  15. package/dist/cjs/run.cjs +82 -15
  16. package/dist/cjs/run.cjs.map +1 -1
  17. package/dist/cjs/session/AgentSession.cjs +37 -2
  18. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  19. package/dist/cjs/stream.cjs +1 -1
  20. package/dist/cjs/summarization/node.cjs +6 -3
  21. package/dist/cjs/summarization/node.cjs.map +1 -1
  22. package/dist/cjs/tools/BashExecutor.cjs +1 -1
  23. package/dist/cjs/tools/CodeExecutor.cjs +1 -1
  24. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +1 -1
  25. package/dist/cjs/tools/ToolNode.cjs +316 -94
  26. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  27. package/dist/cjs/tools/ToolSearch.cjs +1 -1
  28. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +630 -78
  29. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  30. package/dist/cjs/tools/subagent/SubagentReplay.cjs +175 -0
  31. package/dist/cjs/tools/subagent/SubagentReplay.cjs.map +1 -0
  32. package/dist/cjs/tools/toolOutputReferences.cjs +20 -0
  33. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  34. package/dist/cjs/utils/index.cjs +2 -2
  35. package/dist/esm/graphs/Graph.mjs +111 -27
  36. package/dist/esm/graphs/Graph.mjs.map +1 -1
  37. package/dist/esm/hooks/HookRegistry.mjs +83 -0
  38. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  39. package/dist/esm/hooks/executeHooks.mjs +60 -14
  40. package/dist/esm/hooks/executeHooks.mjs.map +1 -1
  41. package/dist/esm/hooks/index.mjs.map +1 -1
  42. package/dist/esm/hooks/types.mjs +2 -1
  43. package/dist/esm/hooks/types.mjs.map +1 -1
  44. package/dist/esm/llm/init.mjs +1 -1
  45. package/dist/esm/llm/invoke.mjs +2 -2
  46. package/dist/esm/main.mjs +11 -11
  47. package/dist/esm/messages/format.mjs +40 -23
  48. package/dist/esm/messages/format.mjs.map +1 -1
  49. package/dist/esm/run.mjs +83 -16
  50. package/dist/esm/run.mjs.map +1 -1
  51. package/dist/esm/session/AgentSession.mjs +37 -2
  52. package/dist/esm/session/AgentSession.mjs.map +1 -1
  53. package/dist/esm/stream.mjs +1 -1
  54. package/dist/esm/summarization/node.mjs +6 -3
  55. package/dist/esm/summarization/node.mjs.map +1 -1
  56. package/dist/esm/tools/BashExecutor.mjs +1 -1
  57. package/dist/esm/tools/CodeExecutor.mjs +1 -1
  58. package/dist/esm/tools/ProgrammaticToolCalling.mjs +1 -1
  59. package/dist/esm/tools/ToolNode.mjs +317 -95
  60. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  61. package/dist/esm/tools/ToolSearch.mjs +1 -1
  62. package/dist/esm/tools/subagent/SubagentExecutor.mjs +631 -79
  63. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  64. package/dist/esm/tools/subagent/SubagentReplay.mjs +168 -0
  65. package/dist/esm/tools/subagent/SubagentReplay.mjs.map +1 -0
  66. package/dist/esm/tools/toolOutputReferences.mjs +20 -0
  67. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  68. package/dist/esm/utils/index.mjs +2 -2
  69. package/dist/types/graphs/Graph.d.ts +16 -1
  70. package/dist/types/hooks/HookRegistry.d.ts +10 -1
  71. package/dist/types/hooks/executeHooks.d.ts +5 -1
  72. package/dist/types/hooks/index.d.ts +2 -2
  73. package/dist/types/hooks/types.d.ts +12 -0
  74. package/dist/types/run.d.ts +4 -1
  75. package/dist/types/session/AgentSession.d.ts +1 -0
  76. package/dist/types/tools/ToolNode.d.ts +23 -15
  77. package/dist/types/tools/subagent/SubagentExecutor.d.ts +46 -7
  78. package/dist/types/tools/subagent/SubagentReplay.d.ts +81 -0
  79. package/dist/types/tools/toolOutputReferences.d.ts +12 -0
  80. package/dist/types/types/graph.d.ts +5 -5
  81. package/dist/types/types/hitl.d.ts +15 -0
  82. package/package.json +6 -2
  83. package/src/graphs/Graph.ts +246 -52
  84. package/src/graphs/__tests__/Graph.breakerLifecycle.test.ts +48 -9
  85. package/src/graphs/__tests__/Graph.contextOverflow.test.ts +1 -1
  86. package/src/graphs/__tests__/Graph.subagentResumeState.test.ts +80 -0
  87. package/src/hooks/HookRegistry.ts +151 -1
  88. package/src/hooks/__tests__/HookRegistry.test.ts +96 -0
  89. package/src/hooks/__tests__/executeHooks.test.ts +160 -0
  90. package/src/hooks/executeHooks.ts +133 -15
  91. package/src/hooks/index.ts +3 -1
  92. package/src/hooks/types.ts +16 -0
  93. package/src/messages/format.ts +54 -26
  94. package/src/messages/formatAgentMessages.reducer.test.ts +162 -0
  95. package/src/messages/formatAgentMessages.steer.test.ts +16 -11
  96. package/src/messages/formatAgentMessages.test.ts +7 -2
  97. package/src/run.ts +164 -18
  98. package/src/session/AgentSession.ts +52 -2
  99. package/src/session/__tests__/JsonlSessionStore.test.ts +53 -0
  100. package/src/summarization/__tests__/node.test.ts +32 -14
  101. package/src/summarization/node.ts +15 -11
  102. package/src/tools/ToolNode.ts +631 -157
  103. package/src/tools/__tests__/SubagentExecutor.test.ts +542 -6
  104. package/src/tools/__tests__/SubagentReplay.test.ts +300 -0
  105. package/src/tools/__tests__/ToolNode.breakerSignal.test.ts +208 -2
  106. package/src/tools/__tests__/directToolHITLResumeScope.test.ts +486 -2
  107. package/src/tools/__tests__/hitl.test.ts +234 -5
  108. package/src/tools/__tests__/subagentHooks.test.ts +1040 -62
  109. package/src/tools/__tests__/toolOutputReferences.test.ts +19 -2
  110. package/src/tools/subagent/SubagentExecutor.ts +1369 -131
  111. package/src/tools/subagent/SubagentReplay.ts +575 -0
  112. package/src/tools/toolOutputReferences.ts +40 -1
  113. package/src/types/graph.ts +5 -5
  114. package/src/types/hitl.ts +16 -0
@@ -0,0 +1,175 @@
1
+ //#region src/tools/subagent/SubagentReplay.ts
2
+ const SUBAGENT_RESUME_MANIFEST_CONFIG_KEY = "__librechat_subagent_resume_manifest";
3
+ const SUBAGENT_RESUME_ATTEMPT_CONFIG_KEY = "__librechat_subagent_resume_attempt";
4
+ const SUBAGENT_PARENT_BATCH_CONFIG_KEY = "__librechat_subagent_parent_batch";
5
+ const SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY = "__librechat_subagent_resume_manifest";
6
+ const SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY = "__librechat_subagent_resume_payload";
7
+ const SUBAGENT_RESUME_WRAPPER_VERSION_KEY = "__librechat_subagent_resume_wrapper";
8
+ const SUBAGENT_RESUME_PRIVATE_PAYLOAD_KEYS = [
9
+ SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY,
10
+ SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY,
11
+ SUBAGENT_RESUME_WRAPPER_VERSION_KEY
12
+ ];
13
+ const MAX_RESUME_MANIFEST_DEPTH = 32;
14
+ function isString(value) {
15
+ return typeof value === "string" && value.length > 0;
16
+ }
17
+ function isNonnegativeInteger(value) {
18
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
19
+ }
20
+ function isApprovalReplaySnapshot(value) {
21
+ if (value == null || typeof value !== "object") return false;
22
+ const snapshot = value;
23
+ const key = snapshot.key;
24
+ const result = snapshot.result;
25
+ return key != null && isString(key.executionScope) && typeof key.agentId === "string" && isString(key.toolUseId) && result != null && result.decision === "ask" && Array.isArray(result.additionalContexts) && Array.isArray(result.injectedMessages) && Array.isArray(result.errors);
26
+ }
27
+ function isCheckpointReference(value) {
28
+ if (value == null || typeof value !== "object") return false;
29
+ const checkpoint = value;
30
+ return isString(checkpoint.threadId) && isString(checkpoint.checkpointId) && typeof checkpoint.checkpointNs === "string";
31
+ }
32
+ function isToolCallStepReference(value) {
33
+ if (value == null || typeof value !== "object") return false;
34
+ const reference = value;
35
+ return isString(reference.toolCallId) && isString(reference.stepId);
36
+ }
37
+ function isToolSessionReference(value) {
38
+ if (value == null || typeof value !== "object") return false;
39
+ const reference = value;
40
+ const context = reference.context;
41
+ return isString(reference.toolName) && context != null && typeof context === "object" && isString(context.session_id) && Number.isFinite(context.lastUpdated) && (context.files == null || Array.isArray(context.files));
42
+ }
43
+ function isToolUsageCountReference(value) {
44
+ if (value == null || typeof value !== "object") return false;
45
+ const entry = value;
46
+ return isString(entry.toolName) && isNonnegativeInteger(entry.count);
47
+ }
48
+ function isDirectPathTurnReference(value) {
49
+ if (value == null || typeof value !== "object") return false;
50
+ const entry = value;
51
+ return isString(entry.toolCallId) && isNonnegativeInteger(entry.turn);
52
+ }
53
+ function isToolNodeResumeState(value) {
54
+ if (value == null || typeof value !== "object") return false;
55
+ const state = value;
56
+ if (!isString(state.stateKey) || !Array.isArray(state.toolUsageCounts) || !Array.isArray(state.directPathTurns)) return false;
57
+ const validUsageCounts = state.toolUsageCounts.every(isToolUsageCountReference);
58
+ const validDirectTurns = state.directPathTurns.every(isDirectPathTurnReference);
59
+ if (!validUsageCounts || !validDirectTurns) return false;
60
+ const usageToolNames = new Set(state.toolUsageCounts.map((entry) => entry.toolName));
61
+ const directToolCallIds = new Set(state.directPathTurns.map((entry) => entry.toolCallId));
62
+ return usageToolNames.size === state.toolUsageCounts.length && directToolCallIds.size === state.directPathTurns.length;
63
+ }
64
+ function isEagerToolUsageState(value) {
65
+ if (value == null || typeof value !== "object") return false;
66
+ const state = value;
67
+ if (typeof state.agentId !== "string" || !Array.isArray(state.toolUsageCounts) || !state.toolUsageCounts.every(isToolUsageCountReference)) return false;
68
+ return new Set(state.toolUsageCounts.map((entry) => entry.toolName)).size === state.toolUsageCounts.length;
69
+ }
70
+ function isToolOutputReferenceEntry(value) {
71
+ if (value == null || typeof value !== "object") return false;
72
+ const entry = value;
73
+ return isString(entry.key) && typeof entry.value === "string";
74
+ }
75
+ function isToolOutputReferenceState(value) {
76
+ if (value == null || typeof value !== "object") return false;
77
+ const state = value;
78
+ if (!Array.isArray(state.entries) || !state.entries.every(isToolOutputReferenceEntry) || !isNonnegativeInteger(state.turnCounter) || !Array.isArray(state.warnedNonStringTools) || !state.warnedNonStringTools.every(isString)) return false;
79
+ const entryKeys = new Set(state.entries.map((entry) => entry.key));
80
+ const warnedTools = new Set(state.warnedNonStringTools);
81
+ return entryKeys.size === state.entries.length && warnedTools.size === state.warnedNonStringTools.length;
82
+ }
83
+ function isGraphResumeState(value) {
84
+ if (value == null || typeof value !== "object") return false;
85
+ const state = value;
86
+ if (!Array.isArray(state.toolCallSteps) || !state.toolCallSteps.every(isToolCallStepReference) || !Array.isArray(state.toolSessions) || !state.toolSessions.every(isToolSessionReference) || !Array.isArray(state.toolNodes) || !state.toolNodes.every(isToolNodeResumeState) || !Array.isArray(state.eagerToolUsage) || !state.eagerToolUsage.every(isEagerToolUsageState) || !Array.isArray(state.eagerToolSuppressions) || !state.eagerToolSuppressions.every(isString) || state.toolOutputReferences != null && !isToolOutputReferenceState(state.toolOutputReferences)) return false;
87
+ const toolCallIds = new Set(state.toolCallSteps.map((reference) => reference.toolCallId));
88
+ const toolNames = new Set(state.toolSessions.map((reference) => reference.toolName));
89
+ const toolNodeKeys = new Set(state.toolNodes.map((node) => node.stateKey));
90
+ const eagerAgentIds = new Set(state.eagerToolUsage.map((usage) => usage.agentId));
91
+ const eagerSuppressions = new Set(state.eagerToolSuppressions);
92
+ return toolCallIds.size === state.toolCallSteps.length && toolNames.size === state.toolSessions.length && toolNodeKeys.size === state.toolNodes.length && eagerAgentIds.size === state.eagerToolUsage.length && eagerSuppressions.size === state.eagerToolSuppressions.length;
93
+ }
94
+ function isSubagentResumeExecution(value, seen, depth) {
95
+ if (value == null || typeof value !== "object") return false;
96
+ const execution = value;
97
+ const childRunId = execution.childRunId;
98
+ const approvalExecutionScope = execution.approvalExecutionScope;
99
+ const checkpoints = execution.checkpoints;
100
+ const graphState = execution.graphState;
101
+ const approvalReplays = execution.approvalReplays;
102
+ if (!isString(execution.parentToolCallId) || !isString(childRunId) || !isString(approvalExecutionScope) || !Array.isArray(checkpoints) || checkpoints.length === 0 || !checkpoints.every(isCheckpointReference) || !isGraphResumeState(graphState) || !Array.isArray(approvalReplays)) return false;
103
+ const checkpointThreadId = checkpoints[0].threadId;
104
+ const checkpointNamespaces = new Set(checkpoints.map((checkpoint) => checkpoint.checkpointNs));
105
+ if (!approvalReplays.every((snapshot) => isApprovalReplaySnapshot(snapshot) && snapshot.key.executionScope === approvalExecutionScope)) return false;
106
+ const approvalKeys = new Set(approvalReplays.map((snapshot) => JSON.stringify([
107
+ snapshot.key.executionScope,
108
+ snapshot.key.agentId,
109
+ snapshot.key.toolUseId
110
+ ])));
111
+ return checkpoints.every((checkpoint) => checkpoint.threadId === checkpointThreadId) && checkpointNamespaces.size === checkpoints.length && approvalKeys.size === approvalReplays.length && (execution.descendant == null || isSubagentResumeManifest(execution.descendant, seen, depth + 1));
112
+ }
113
+ function isSubagentResumeManifest(value, seen = /* @__PURE__ */ new Set(), depth = 0) {
114
+ if (value == null || typeof value !== "object" || depth > MAX_RESUME_MANIFEST_DEPTH || seen.has(value)) return false;
115
+ seen.add(value);
116
+ const manifest = value;
117
+ if (manifest.version !== 1 || !Array.isArray(manifest.executions) || manifest.executions.length === 0 || !manifest.executions.every((execution) => isSubagentResumeExecution(execution, seen, depth))) return false;
118
+ return new Set(manifest.executions.map((execution) => execution.parentToolCallId)).size === manifest.executions.length;
119
+ }
120
+ function getSubagentResumeManifest(payload) {
121
+ if (payload == null || typeof payload !== "object") return;
122
+ if (!Object.prototype.hasOwnProperty.call(payload, SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY)) return;
123
+ const manifest = payload[SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY];
124
+ return isSubagentResumeManifest(manifest) ? manifest : void 0;
125
+ }
126
+ function requireValidSubagentResumeManifest(payload) {
127
+ if (payload == null || typeof payload !== "object" || !Object.prototype.hasOwnProperty.call(payload, SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY)) return;
128
+ const manifest = getSubagentResumeManifest(payload);
129
+ if (manifest == null) throw new Error("Invalid subagent resume manifest.");
130
+ return manifest;
131
+ }
132
+ function canAttachSubagentResumeManifestInline(payload) {
133
+ if (payload == null || typeof payload !== "object" || Array.isArray(payload) || Object.getPrototypeOf(payload) !== Object.prototype) return false;
134
+ return SUBAGENT_RESUME_PRIVATE_PAYLOAD_KEYS.every((key) => !Object.prototype.hasOwnProperty.call(payload, key));
135
+ }
136
+ function isInlineSubagentResumePayload(payload) {
137
+ return payload != null && typeof payload === "object" && !Array.isArray(payload) && Object.getPrototypeOf(payload) === Object.prototype && !Object.prototype.hasOwnProperty.call(payload, SUBAGENT_RESUME_WRAPPER_VERSION_KEY) && !Object.prototype.hasOwnProperty.call(payload, SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY) && getSubagentResumeManifest(payload) != null;
138
+ }
139
+ function attachSubagentResumeManifest(payload, manifest) {
140
+ if (isWrappedSubagentResumePayload(payload) || isInlineSubagentResumePayload(payload)) return {
141
+ ...payload,
142
+ [SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY]: manifest
143
+ };
144
+ if (!canAttachSubagentResumeManifestInline(payload)) return {
145
+ [SUBAGENT_RESUME_WRAPPER_VERSION_KEY]: 1,
146
+ [SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY]: payload,
147
+ [SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY]: manifest
148
+ };
149
+ return {
150
+ ...payload,
151
+ [SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY]: manifest
152
+ };
153
+ }
154
+ function stripSubagentResumeManifest(payload) {
155
+ if (isWrappedSubagentResumePayload(payload)) return payload[SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY];
156
+ if (payload == null || typeof payload !== "object" || getSubagentResumeManifest(payload) == null) return payload;
157
+ return Object.fromEntries(Object.entries(payload).filter(([key]) => key !== SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY));
158
+ }
159
+ function isWrappedSubagentResumePayload(payload) {
160
+ if (payload == null || typeof payload !== "object" || Array.isArray(payload) || Object.getPrototypeOf(payload) !== Object.prototype || Object.keys(payload).length !== SUBAGENT_RESUME_PRIVATE_PAYLOAD_KEYS.length) return false;
161
+ const wrapper = payload;
162
+ return wrapper[SUBAGENT_RESUME_WRAPPER_VERSION_KEY] === 1 && Object.prototype.hasOwnProperty.call(wrapper, SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY) && getSubagentResumeManifest(wrapper) != null;
163
+ }
164
+ const SUBAGENT_REPLAY_CONTROLLER = Symbol.for("@librechat/agents/subagent-replay-controller");
165
+ //#endregion
166
+ exports.SUBAGENT_PARENT_BATCH_CONFIG_KEY = SUBAGENT_PARENT_BATCH_CONFIG_KEY;
167
+ exports.SUBAGENT_REPLAY_CONTROLLER = SUBAGENT_REPLAY_CONTROLLER;
168
+ exports.SUBAGENT_RESUME_ATTEMPT_CONFIG_KEY = SUBAGENT_RESUME_ATTEMPT_CONFIG_KEY;
169
+ exports.SUBAGENT_RESUME_MANIFEST_CONFIG_KEY = SUBAGENT_RESUME_MANIFEST_CONFIG_KEY;
170
+ exports.attachSubagentResumeManifest = attachSubagentResumeManifest;
171
+ exports.getSubagentResumeManifest = getSubagentResumeManifest;
172
+ exports.requireValidSubagentResumeManifest = requireValidSubagentResumeManifest;
173
+ exports.stripSubagentResumeManifest = stripSubagentResumeManifest;
174
+
175
+ //# sourceMappingURL=SubagentReplay.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SubagentReplay.cjs","names":[],"sources":["../../../../src/tools/subagent/SubagentReplay.ts"],"sourcesContent":["import type { ToolCall, ToolMessage } from '@langchain/core/messages/tool';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type { ToolOutputReferenceState } from '@/tools/toolOutputReferences';\nimport type { ToolApprovalReplaySnapshot } from '@/hooks';\nimport type { ToolSessionContext } from '@/types';\n\nexport const SUBAGENT_RESUME_MANIFEST_CONFIG_KEY =\n '__librechat_subagent_resume_manifest';\nexport const SUBAGENT_RESUME_ATTEMPT_CONFIG_KEY =\n '__librechat_subagent_resume_attempt';\nexport const SUBAGENT_PARENT_BATCH_CONFIG_KEY =\n '__librechat_subagent_parent_batch';\n\nconst SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY =\n '__librechat_subagent_resume_manifest';\nconst SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY =\n '__librechat_subagent_resume_payload';\nconst SUBAGENT_RESUME_WRAPPER_VERSION_KEY =\n '__librechat_subagent_resume_wrapper';\nconst SUBAGENT_RESUME_PRIVATE_PAYLOAD_KEYS = [\n SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY,\n SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY,\n SUBAGENT_RESUME_WRAPPER_VERSION_KEY,\n] as const;\nconst MAX_RESUME_MANIFEST_DEPTH = 32;\n\nexport interface SubagentCheckpointReference {\n threadId: string;\n checkpointId: string;\n checkpointNs: string;\n}\n\nexport interface SubagentToolCallStepReference {\n toolCallId: string;\n stepId: string;\n}\n\nexport interface SubagentToolSessionReference {\n toolName: string;\n context: ToolSessionContext;\n}\n\nexport interface SubagentToolNodeResumeState {\n stateKey: string;\n toolUsageCounts: Array<{ toolName: string; count: number }>;\n directPathTurns: Array<{ toolCallId: string; turn: number }>;\n}\n\nexport interface SubagentEagerToolUsageState {\n agentId: string;\n toolUsageCounts: Array<{ toolName: string; count: number }>;\n}\n\nexport interface SubagentGraphResumeState {\n toolCallSteps: SubagentToolCallStepReference[];\n toolSessions: SubagentToolSessionReference[];\n toolNodes: SubagentToolNodeResumeState[];\n eagerToolUsage: SubagentEagerToolUsageState[];\n eagerToolSuppressions: string[];\n toolOutputReferences?: ToolOutputReferenceState;\n}\n\n/** Private checkpoint payload linking a parent pause to an exact child state. */\nexport interface SubagentResumeExecution {\n parentToolCallId: string;\n childRunId: string;\n approvalExecutionScope: string;\n checkpoints: SubagentCheckpointReference[];\n graphState: SubagentGraphResumeState;\n approvalReplays: ToolApprovalReplaySnapshot[];\n descendant?: SubagentResumeManifest;\n}\n\n/** Private checkpoint payload linking a parent pause to every child state. */\nexport interface SubagentResumeManifest {\n version: 1;\n executions: SubagentResumeExecution[];\n}\n\ntype PayloadWithSubagentResumeManifest = {\n [SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY]?: unknown;\n};\n\ntype WrappedSubagentResumePayload = PayloadWithSubagentResumeManifest & {\n [SUBAGENT_RESUME_WRAPPER_VERSION_KEY]: 1;\n [SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY]: unknown;\n};\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\nfunction isNonnegativeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isApprovalReplaySnapshot(\n value: unknown\n): value is ToolApprovalReplaySnapshot {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const snapshot = value as Partial<ToolApprovalReplaySnapshot>;\n const key = snapshot.key;\n const result = snapshot.result;\n return (\n key != null &&\n isString(key.executionScope) &&\n typeof key.agentId === 'string' &&\n isString(key.toolUseId) &&\n result != null &&\n result.decision === 'ask' &&\n Array.isArray(result.additionalContexts) &&\n Array.isArray(result.injectedMessages) &&\n Array.isArray(result.errors)\n );\n}\n\nfunction isCheckpointReference(\n value: unknown\n): value is SubagentCheckpointReference {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const checkpoint = value as Partial<SubagentCheckpointReference>;\n return (\n isString(checkpoint.threadId) &&\n isString(checkpoint.checkpointId) &&\n typeof checkpoint.checkpointNs === 'string'\n );\n}\n\nfunction isToolCallStepReference(\n value: unknown\n): value is SubagentToolCallStepReference {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const reference = value as Partial<SubagentToolCallStepReference>;\n return isString(reference.toolCallId) && isString(reference.stepId);\n}\n\nfunction isToolSessionReference(\n value: unknown\n): value is SubagentToolSessionReference {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const reference = value as Partial<SubagentToolSessionReference>;\n const context = reference.context;\n return (\n isString(reference.toolName) &&\n context != null &&\n typeof context === 'object' &&\n isString(context.session_id) &&\n Number.isFinite(context.lastUpdated) &&\n (context.files == null || Array.isArray(context.files))\n );\n}\n\nfunction isToolUsageCountReference(\n value: unknown\n): value is SubagentToolNodeResumeState['toolUsageCounts'][number] {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const entry = value as Partial<\n SubagentToolNodeResumeState['toolUsageCounts'][number]\n >;\n return isString(entry.toolName) && isNonnegativeInteger(entry.count);\n}\n\nfunction isDirectPathTurnReference(\n value: unknown\n): value is SubagentToolNodeResumeState['directPathTurns'][number] {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const entry = value as Partial<\n SubagentToolNodeResumeState['directPathTurns'][number]\n >;\n return isString(entry.toolCallId) && isNonnegativeInteger(entry.turn);\n}\n\nfunction isToolNodeResumeState(\n value: unknown\n): value is SubagentToolNodeResumeState {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const state = value as Partial<SubagentToolNodeResumeState>;\n if (\n !isString(state.stateKey) ||\n !Array.isArray(state.toolUsageCounts) ||\n !Array.isArray(state.directPathTurns)\n ) {\n return false;\n }\n const validUsageCounts = state.toolUsageCounts.every(\n isToolUsageCountReference\n );\n const validDirectTurns = state.directPathTurns.every(\n isDirectPathTurnReference\n );\n if (!validUsageCounts || !validDirectTurns) {\n return false;\n }\n const usageToolNames = new Set(\n state.toolUsageCounts.map((entry) => entry.toolName)\n );\n const directToolCallIds = new Set(\n state.directPathTurns.map((entry) => entry.toolCallId)\n );\n return (\n usageToolNames.size === state.toolUsageCounts.length &&\n directToolCallIds.size === state.directPathTurns.length\n );\n}\n\nfunction isEagerToolUsageState(\n value: unknown\n): value is SubagentEagerToolUsageState {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const state = value as Partial<SubagentEagerToolUsageState>;\n if (\n typeof state.agentId !== 'string' ||\n !Array.isArray(state.toolUsageCounts) ||\n !state.toolUsageCounts.every(isToolUsageCountReference)\n ) {\n return false;\n }\n const toolNames = new Set(\n state.toolUsageCounts.map((entry) => entry.toolName)\n );\n return toolNames.size === state.toolUsageCounts.length;\n}\n\nfunction isToolOutputReferenceEntry(\n value: unknown\n): value is ToolOutputReferenceState['entries'][number] {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const entry = value as Partial<ToolOutputReferenceState['entries'][number]>;\n return isString(entry.key) && typeof entry.value === 'string';\n}\n\nfunction isToolOutputReferenceState(\n value: unknown\n): value is ToolOutputReferenceState {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const state = value as Partial<ToolOutputReferenceState>;\n if (\n !Array.isArray(state.entries) ||\n !state.entries.every(isToolOutputReferenceEntry) ||\n !isNonnegativeInteger(state.turnCounter) ||\n !Array.isArray(state.warnedNonStringTools) ||\n !state.warnedNonStringTools.every(isString)\n ) {\n return false;\n }\n const entryKeys = new Set(state.entries.map((entry) => entry.key));\n const warnedTools = new Set(state.warnedNonStringTools);\n return (\n entryKeys.size === state.entries.length &&\n warnedTools.size === state.warnedNonStringTools.length\n );\n}\n\nfunction isGraphResumeState(value: unknown): value is SubagentGraphResumeState {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const state = value as Partial<SubagentGraphResumeState>;\n if (\n !Array.isArray(state.toolCallSteps) ||\n !state.toolCallSteps.every(isToolCallStepReference) ||\n !Array.isArray(state.toolSessions) ||\n !state.toolSessions.every(isToolSessionReference) ||\n !Array.isArray(state.toolNodes) ||\n !state.toolNodes.every(isToolNodeResumeState) ||\n !Array.isArray(state.eagerToolUsage) ||\n !state.eagerToolUsage.every(isEagerToolUsageState) ||\n !Array.isArray(state.eagerToolSuppressions) ||\n !state.eagerToolSuppressions.every(isString) ||\n (state.toolOutputReferences != null &&\n !isToolOutputReferenceState(state.toolOutputReferences))\n ) {\n return false;\n }\n const toolCallIds = new Set(\n state.toolCallSteps.map((reference) => reference.toolCallId)\n );\n const toolNames = new Set(\n state.toolSessions.map((reference) => reference.toolName)\n );\n const toolNodeKeys = new Set(state.toolNodes.map((node) => node.stateKey));\n const eagerAgentIds = new Set(\n state.eagerToolUsage.map((usage) => usage.agentId)\n );\n const eagerSuppressions = new Set(state.eagerToolSuppressions);\n return (\n toolCallIds.size === state.toolCallSteps.length &&\n toolNames.size === state.toolSessions.length &&\n toolNodeKeys.size === state.toolNodes.length &&\n eagerAgentIds.size === state.eagerToolUsage.length &&\n eagerSuppressions.size === state.eagerToolSuppressions.length\n );\n}\n\nfunction isSubagentResumeExecution(\n value: unknown,\n seen: Set<object>,\n depth: number\n): value is SubagentResumeExecution {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const execution = value as Partial<SubagentResumeExecution>;\n const childRunId = execution.childRunId;\n const approvalExecutionScope = execution.approvalExecutionScope;\n const checkpoints = execution.checkpoints;\n const graphState = execution.graphState;\n const approvalReplays = execution.approvalReplays;\n if (\n !isString(execution.parentToolCallId) ||\n !isString(childRunId) ||\n !isString(approvalExecutionScope) ||\n !Array.isArray(checkpoints) ||\n checkpoints.length === 0 ||\n !checkpoints.every(isCheckpointReference) ||\n !isGraphResumeState(graphState) ||\n !Array.isArray(approvalReplays)\n ) {\n return false;\n }\n const checkpointThreadId = checkpoints[0].threadId;\n const checkpointNamespaces = new Set(\n checkpoints.map((checkpoint) => checkpoint.checkpointNs)\n );\n const validApprovalReplays = approvalReplays.every(\n (snapshot) =>\n isApprovalReplaySnapshot(snapshot) &&\n snapshot.key.executionScope === approvalExecutionScope\n );\n if (!validApprovalReplays) {\n return false;\n }\n const approvalKeys = new Set(\n approvalReplays.map((snapshot) =>\n JSON.stringify([\n snapshot.key.executionScope,\n snapshot.key.agentId,\n snapshot.key.toolUseId,\n ])\n )\n );\n return (\n checkpoints.every(\n (checkpoint) => checkpoint.threadId === checkpointThreadId\n ) &&\n checkpointNamespaces.size === checkpoints.length &&\n approvalKeys.size === approvalReplays.length &&\n (execution.descendant == null ||\n isSubagentResumeManifest(execution.descendant, seen, depth + 1))\n );\n}\n\nfunction isSubagentResumeManifest(\n value: unknown,\n seen: Set<object> = new Set(),\n depth = 0\n): value is SubagentResumeManifest {\n if (\n value == null ||\n typeof value !== 'object' ||\n depth > MAX_RESUME_MANIFEST_DEPTH ||\n seen.has(value)\n ) {\n return false;\n }\n seen.add(value);\n const manifest = value as Partial<SubagentResumeManifest>;\n if (\n manifest.version !== 1 ||\n !Array.isArray(manifest.executions) ||\n manifest.executions.length === 0 ||\n !manifest.executions.every((execution) =>\n isSubagentResumeExecution(execution, seen, depth)\n )\n ) {\n return false;\n }\n const parentToolCallIds = new Set(\n manifest.executions.map((execution) => execution.parentToolCallId)\n );\n return parentToolCallIds.size === manifest.executions.length;\n}\n\nexport function getSubagentResumeManifest(\n payload: unknown\n): SubagentResumeManifest | undefined {\n if (payload == null || typeof payload !== 'object') {\n return undefined;\n }\n if (\n !Object.prototype.hasOwnProperty.call(\n payload,\n SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY\n )\n ) {\n return undefined;\n }\n const manifest = (payload as PayloadWithSubagentResumeManifest)[\n SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY\n ];\n return isSubagentResumeManifest(manifest) ? manifest : undefined;\n}\n\nexport function requireValidSubagentResumeManifest(\n payload: unknown\n): SubagentResumeManifest | undefined {\n if (\n payload == null ||\n typeof payload !== 'object' ||\n !Object.prototype.hasOwnProperty.call(\n payload,\n SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY\n )\n ) {\n return undefined;\n }\n const manifest = getSubagentResumeManifest(payload);\n if (manifest == null) {\n throw new Error('Invalid subagent resume manifest.');\n }\n return manifest;\n}\n\nfunction canAttachSubagentResumeManifestInline(\n payload: unknown\n): payload is Record<string, unknown> {\n if (\n payload == null ||\n typeof payload !== 'object' ||\n Array.isArray(payload) ||\n Object.getPrototypeOf(payload) !== Object.prototype\n ) {\n return false;\n }\n return SUBAGENT_RESUME_PRIVATE_PAYLOAD_KEYS.every(\n (key) => !Object.prototype.hasOwnProperty.call(payload, key)\n );\n}\n\nfunction isInlineSubagentResumePayload(\n payload: unknown\n): payload is PayloadWithSubagentResumeManifest & Record<string, unknown> {\n return (\n payload != null &&\n typeof payload === 'object' &&\n !Array.isArray(payload) &&\n Object.getPrototypeOf(payload) === Object.prototype &&\n !Object.prototype.hasOwnProperty.call(\n payload,\n SUBAGENT_RESUME_WRAPPER_VERSION_KEY\n ) &&\n !Object.prototype.hasOwnProperty.call(\n payload,\n SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY\n ) &&\n getSubagentResumeManifest(payload) != null\n );\n}\n\nexport function attachSubagentResumeManifest(\n payload: unknown,\n manifest: SubagentResumeManifest\n): object {\n if (\n isWrappedSubagentResumePayload(payload) ||\n isInlineSubagentResumePayload(payload)\n ) {\n return {\n ...payload,\n [SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY]: manifest,\n };\n }\n if (!canAttachSubagentResumeManifestInline(payload)) {\n return {\n [SUBAGENT_RESUME_WRAPPER_VERSION_KEY]: 1,\n [SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY]: payload,\n [SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY]: manifest,\n };\n }\n return {\n ...payload,\n [SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY]: manifest,\n };\n}\n\nexport function stripSubagentResumeManifest(payload: unknown): unknown {\n if (isWrappedSubagentResumePayload(payload)) {\n return payload[SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY];\n }\n if (\n payload == null ||\n typeof payload !== 'object' ||\n getSubagentResumeManifest(payload) == null\n ) {\n return payload;\n }\n return Object.fromEntries(\n Object.entries(payload).filter(\n ([key]) => key !== SUBAGENT_RESUME_MANIFEST_PAYLOAD_KEY\n )\n );\n}\n\nfunction isWrappedSubagentResumePayload(\n payload: unknown\n): payload is WrappedSubagentResumePayload {\n if (\n payload == null ||\n typeof payload !== 'object' ||\n Array.isArray(payload) ||\n Object.getPrototypeOf(payload) !== Object.prototype ||\n Object.keys(payload).length !== SUBAGENT_RESUME_PRIVATE_PAYLOAD_KEYS.length\n ) {\n return false;\n }\n const wrapper = payload as Partial<WrappedSubagentResumePayload>;\n return (\n wrapper[SUBAGENT_RESUME_WRAPPER_VERSION_KEY] === 1 &&\n Object.prototype.hasOwnProperty.call(\n wrapper,\n SUBAGENT_RESUME_WRAPPED_PAYLOAD_KEY\n ) &&\n getSubagentResumeManifest(wrapper) != null\n );\n}\n\nexport const SUBAGENT_REPLAY_CONTROLLER = Symbol.for(\n '@librechat/agents/subagent-replay-controller'\n);\n\nexport type SettledSubagentToolOutput = {\n output: ToolMessage;\n additionalContexts: string[];\n resolvedArgs?: Record<string, unknown>;\n referenceContent?: string;\n};\n\nexport interface SubagentReplayController {\n getResumeManifest?(\n parentToolCallIds?: ReadonlySet<string>\n ): Promise<SubagentResumeManifest | undefined>;\n getSettledOutput(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<SettledSubagentToolOutput | undefined>;\n persistSettledOutput(\n call: ToolCall,\n config: RunnableConfig,\n settled: SettledSubagentToolOutput\n ): Promise<void>;\n}\n\nexport type ReplayableSubagentTool = {\n [SUBAGENT_REPLAY_CONTROLLER]?: SubagentReplayController;\n};\n"],"mappings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,MAAa,6BAA6B,OAAO,IAC/C,8CACF"}
@@ -269,6 +269,26 @@ var ToolOutputReferenceRegistry = class ToolOutputReferenceRegistry {
269
269
  const entries = bucket ? new Map(bucket.entries) : EMPTY_ENTRIES;
270
270
  return { resolve: (args, options) => this.resolveAgainst(entries, args, options) };
271
271
  }
272
+ /** Captures the checkpoint-safe state needed to resume one run bucket. */
273
+ snapshotState(runId) {
274
+ const bucket = this.runStates.get(this.keyFor(runId));
275
+ return {
276
+ entries: [...bucket?.entries ?? EMPTY_ENTRIES].map(([key, value]) => ({
277
+ key,
278
+ value
279
+ })),
280
+ turnCounter: bucket?.turnCounter ?? 0,
281
+ warnedNonStringTools: [...bucket?.warnedNonStringTools ?? []]
282
+ };
283
+ }
284
+ /** Restores a checkpointed run bucket under the current resume scope. */
285
+ restoreState(runId, state) {
286
+ this.releaseRun(runId);
287
+ const bucket = this.getOrCreate(runId);
288
+ for (const { key, value } of state.entries) this.set(runId, key, value);
289
+ bucket.turnCounter = state.turnCounter;
290
+ for (const toolName of state.warnedNonStringTools) bucket.warnedNonStringTools.add(toolName);
291
+ }
272
292
  resolveAgainst(entries, args, options) {
273
293
  if (!hasAnyPlaceholder(args)) return {
274
294
  resolved: args,
@@ -1 +1 @@
1
- {"version":3,"file":"toolOutputReferences.cjs","names":["HARD_MAX_TOOL_RESULT_CHARS","HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE","calculateMaxTotalToolOutputSize","isComputerCallOutputMessage","ToolMessage"],"sources":["../../../src/tools/toolOutputReferences.ts"],"sourcesContent":["/**\n * Tool output reference registry.\n *\n * When enabled via `RunConfig.toolOutputReferences.enabled`, ToolNode\n * stores each successful tool output under a stable key\n * (`tool<idx>turn<turn>`) where `idx` is the tool's position within a\n * ToolNode batch and `turn` is the batch index within the run\n * (incremented once per ToolNode invocation).\n *\n * Subsequent tool calls can pipe a previous output into their args by\n * embedding `{{tool<idx>turn<turn>}}` inside any string argument;\n * {@link ToolOutputReferenceRegistry.resolve} walks the args and\n * substitutes the placeholders immediately before invocation.\n *\n * The registry stores the *raw, untruncated* tool output so a later\n * `{{…}}` substitution pipes the full payload into the next tool —\n * even when the LLM only saw a head+tail-truncated preview in\n * `ToolMessage.content`. Outputs are stored without any annotation\n * (the `_ref` key or the `[ref: ...]` prefix seen by the LLM is\n * strictly a UX signal attached to `ToolMessage.content`). Keeping the\n * registry pristine means downstream bash/jq piping receives the\n * complete, verbatim output with no injected fields.\n */\n\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport {\n calculateMaxTotalToolOutputSize,\n HARD_MAX_TOOL_RESULT_CHARS,\n HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE,\n} from '@/utils/truncation';\nimport { isComputerCallOutputMessage } from '@/utils/toolContent';\nimport { INTENT_ARG } from '@/tools/intentArg';\n\n/** Parses a stringified JSON object arg; undefined for anything else. */\nfunction parseStringifiedArgsObject(\n value: string\n): Record<string, unknown> | undefined {\n if (!value.trim().startsWith('{')) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(value) as unknown;\n if (parsed != null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\n/**\n * Non-global matcher for a single `{{tool<i>turn<n>}}` placeholder.\n * Exported for consumers that want to detect references (e.g., syntax\n * highlighting, docs). The stateful `g` variant lives inside the\n * registry so nobody trips on `lastIndex`.\n */\nexport const TOOL_OUTPUT_REF_PATTERN = /\\{\\{(tool\\d+turn\\d+)\\}\\}/;\n\n/** Object key used when a parsed-object output has `_ref` injected. */\nexport const TOOL_OUTPUT_REF_KEY = '_ref';\n\n/**\n * Object key used to carry unresolved reference warnings on a parsed-\n * object output. Using a dedicated field instead of a trailing text\n * line keeps the annotated `ToolMessage.content` parseable as JSON for\n * downstream consumers that rely on the object shape.\n */\nexport const TOOL_OUTPUT_UNRESOLVED_KEY = '_unresolved_refs';\n\n/** Single-line prefix prepended to non-object tool outputs so the LLM sees the reference key. */\nexport function buildReferencePrefix(key: string): string {\n return `[ref: ${key}]`;\n}\n\n/** Stable registry key for a tool output. */\nexport function buildReferenceKey(toolIndex: number, turn: number): string {\n return `tool${toolIndex}turn${turn}`;\n}\n\nexport type ToolOutputReferenceRegistryOptions = {\n /** Maximum characters stored per registered output. */\n maxOutputSize?: number;\n /** Maximum total characters retained across all registered outputs. */\n maxTotalSize?: number;\n /**\n * Upper bound on the number of concurrently-tracked runs. When\n * exceeded, the oldest run bucket is evicted (FIFO). Defaults to 32.\n */\n maxActiveRuns?: number;\n};\n\n/**\n * Result of resolving placeholders in tool args.\n */\nexport type ResolveResult<T> = {\n /** Arguments with placeholders replaced. Same shape as the input. */\n resolved: T;\n /** Reference keys that were referenced but had no stored value. */\n unresolved: string[];\n};\n\n/**\n * Read-only view over a frozen registry snapshot. Returned by\n * {@link ToolOutputReferenceRegistry.snapshot} for callers that need\n * to resolve placeholders against the registry state at a specific\n * point in time, ignoring any subsequent registrations.\n */\nexport interface ToolOutputResolveView {\n resolve<T>(args: T, options?: ResolveOptions): ResolveResult<T>;\n}\n\n/**\n * Per-call resolution options. `substituteIntentKey` opts the top-level\n * `intent` key back INTO placeholder substitution: the exemption protects\n * the injected display label, but a tool whose own schema declares a\n * business parameter named `intent` (the injectors skip such tools) still\n * needs references piped into it like any other argument.\n */\nexport type ResolveOptions = {\n substituteIntentKey?: boolean;\n};\n\n/**\n * Pre-resolved arg map keyed by `toolCallId`. Used by the mixed\n * direct+event dispatch path to feed event calls' resolved args\n * (captured pre-batch) into the dispatcher without re-resolving\n * against the now-stale live registry.\n */\nexport type PreResolvedArgsMap = Map<\n string,\n { resolved: Record<string, unknown>; unresolved: string[] }\n>;\n\n/**\n * Per-call sink for resolved args, keyed by `toolCallId`. Threaded\n * as a per-batch local map so concurrent `ToolNode.run()` calls do\n * not race on shared sink state.\n */\nexport type ResolvedArgsByCallId = Map<string, Record<string, unknown>>;\n\nconst EMPTY_ENTRIES: ReadonlyMap<string, string> = new Map<string, string>();\n\n/**\n * Per-run state bucket held inside the registry. Each distinct\n * `run_id` gets its own bucket so overlapping concurrent runs on a\n * shared registry cannot leak outputs, turn counters, or warn-memos\n * into one another.\n */\nclass RunStateBucket {\n entries: Map<string, string> = new Map();\n totalSize: number = 0;\n turnCounter: number = 0;\n warnedNonStringTools: Set<string> = new Set();\n}\n\n/**\n * Anonymous (`run_id` absent) bucket key. Anonymous batches are\n * treated as fresh runs on every invocation — see `nextTurn`.\n */\nconst ANON_RUN_KEY = '\\0anon';\n\n/**\n * Default upper bound on the number of concurrently-tracked runs per\n * registry. When exceeded, the oldest run's bucket (by insertion\n * order) is evicted. Keeps memory bounded when a ToolNode is reused\n * across many runs without explicit `releaseRun` calls.\n */\nconst DEFAULT_MAX_ACTIVE_RUNS = 32;\n\n/**\n * Ordered map of reference-key → stored output, partitioned by run so\n * concurrent / interleaved runs sharing one registry cannot leak\n * outputs between each other.\n *\n * Each public method takes a `runId` which selects the run's bucket.\n * Hosts typically get one registry per run via `Graph`, in which\n * case only a single bucket is ever populated; the partitioning\n * exists so the registry also behaves correctly when a single\n * instance is reused directly.\n */\nexport class ToolOutputReferenceRegistry {\n private runStates: Map<string, RunStateBucket> = new Map();\n private readonly maxOutputSize: number;\n private readonly maxTotalSize: number;\n private readonly maxActiveRuns: number;\n /**\n * Local stateful matcher used only by `replaceInString`. Kept\n * off-module so callers of the exported `TOOL_OUTPUT_REF_PATTERN`\n * never see a stale `lastIndex`.\n */\n private static readonly PLACEHOLDER_MATCHER = /\\{\\{(tool\\d+turn\\d+)\\}\\}/g;\n\n constructor(options: ToolOutputReferenceRegistryOptions = {}) {\n /**\n * Per-output default is the same ~400 KB budget as the standard\n * tool-result truncation (`HARD_MAX_TOOL_RESULT_CHARS`). This\n * keeps a single `{{…}}` substitution at a size that is safe to\n * pass through typical shell `ARG_MAX` limits and matches what\n * the LLM would otherwise have seen. Hosts that want larger per-\n * output payloads (API consumers, long JSON streams) can raise\n * the cap explicitly up to the 5 MB total budget.\n */\n const perOutput =\n options.maxOutputSize != null && options.maxOutputSize > 0\n ? options.maxOutputSize\n : HARD_MAX_TOOL_RESULT_CHARS;\n /**\n * Clamp a caller-supplied `maxTotalSize` to\n * `HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE` (5 MB) so the documented\n * absolute cap is enforced regardless of host config —\n * `calculateMaxTotalToolOutputSize` already applies the same\n * upper bound on its computed default, but the user-provided\n * branch was bypassing it.\n */\n const totalRaw =\n options.maxTotalSize != null && options.maxTotalSize > 0\n ? Math.min(options.maxTotalSize, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE)\n : calculateMaxTotalToolOutputSize(perOutput);\n this.maxTotalSize = totalRaw;\n /**\n * The per-output cap can never exceed the per-run aggregate cap:\n * if a single entry were allowed to be larger than `maxTotalSize`,\n * the eviction loop would either blow the cap (to keep the entry)\n * or self-evict a just-stored value. Clamping here turns\n * `maxTotalSize` into a hard upper bound on *any* state the\n * registry retains per run.\n */\n this.maxOutputSize = Math.min(perOutput, totalRaw);\n this.maxActiveRuns =\n options.maxActiveRuns != null && options.maxActiveRuns > 0\n ? options.maxActiveRuns\n : DEFAULT_MAX_ACTIVE_RUNS;\n }\n\n private keyFor(runId: string | undefined): string {\n return runId ?? ANON_RUN_KEY;\n }\n\n private getOrCreate(runId: string | undefined): RunStateBucket {\n const key = this.keyFor(runId);\n let state = this.runStates.get(key);\n if (state == null) {\n state = new RunStateBucket();\n this.runStates.set(key, state);\n if (this.runStates.size > this.maxActiveRuns) {\n const oldest = this.runStates.keys().next().value;\n if (oldest != null && oldest !== key) {\n this.runStates.delete(oldest);\n }\n }\n }\n return state;\n }\n\n /** Registers (or replaces) the output stored under `key` for `runId`. */\n set(runId: string | undefined, key: string, value: string): void {\n const bucket = this.getOrCreate(runId);\n const clipped =\n value.length > this.maxOutputSize\n ? value.slice(0, this.maxOutputSize)\n : value;\n const existing = bucket.entries.get(key);\n if (existing != null) {\n bucket.totalSize -= existing.length;\n bucket.entries.delete(key);\n }\n bucket.entries.set(key, clipped);\n bucket.totalSize += clipped.length;\n this.evictWithinBucket(bucket);\n }\n\n /** Returns the stored value for `key` in `runId`'s bucket, or `undefined`. */\n get(runId: string | undefined, key: string): string | undefined {\n return this.runStates.get(this.keyFor(runId))?.entries.get(key);\n }\n\n /**\n * Returns `true` when `key` is currently stored in `runId`'s bucket.\n * Used by {@link annotateMessagesForLLM} to gate transient annotation\n * on whether the registry still owns the referenced output (a stale\n * `_refKey` from a prior run silently no-ops here).\n */\n has(runId: string | undefined, key: string): boolean {\n return this.runStates.get(this.keyFor(runId))?.entries.has(key) ?? false;\n }\n\n /** Total number of registered outputs across every run bucket. */\n get size(): number {\n let n = 0;\n for (const bucket of this.runStates.values()) {\n n += bucket.entries.size;\n }\n return n;\n }\n\n /** Maximum characters retained per output (post-clip). */\n get perOutputLimit(): number {\n return this.maxOutputSize;\n }\n\n /** Maximum total characters retained *per run*. */\n get totalLimit(): number {\n return this.maxTotalSize;\n }\n\n /** Drops every run's state. */\n clear(): void {\n this.runStates.clear();\n }\n\n /**\n * Explicitly release `runId`'s state. Safe to call when a run has\n * finished. Hosts sharing one registry across runs should call this\n * to reclaim memory deterministically; otherwise LRU eviction kicks\n * in when `maxActiveRuns` runs accumulate.\n */\n releaseRun(runId: string | undefined): void {\n this.runStates.delete(this.keyFor(runId));\n }\n\n /**\n * Claims the next batch turn synchronously from `runId`'s bucket.\n *\n * Must be called once at the start of each ToolNode batch before\n * any `await`, so concurrent invocations within the same run see\n * distinct turn values (reads are effectively atomic by JS's\n * single-threaded execution of the sync prefix).\n *\n * If `runId` is missing the anonymous bucket is dropped and a\n * fresh one created so each anonymous call behaves as its own run.\n */\n nextTurn(runId: string | undefined): number {\n if (runId == null) {\n this.runStates.delete(ANON_RUN_KEY);\n }\n const bucket = this.getOrCreate(runId);\n return bucket.turnCounter++;\n }\n\n /**\n * Records that `toolName` has been warned about in `runId` (returns\n * `true` on the first call per run, `false` after). Used by\n * ToolNode to emit one log line per offending tool per run when a\n * `ToolMessage.content` isn't a string.\n */\n claimWarnOnce(runId: string | undefined, toolName: string): boolean {\n const bucket = this.getOrCreate(runId);\n if (bucket.warnedNonStringTools.has(toolName)) {\n return false;\n }\n bucket.warnedNonStringTools.add(toolName);\n return true;\n }\n\n /**\n * Walks `args` and replaces every `{{tool<i>turn<n>}}` placeholder in\n * string values with the stored output *from `runId`'s bucket*. Non-\n * string values and object keys are left untouched. Unresolved\n * references are left in-place and reported so the caller can\n * surface them to the LLM. When no placeholder appears anywhere in\n * the serialized args, the original input is returned without\n * walking the tree.\n */\n resolve<T>(\n runId: string | undefined,\n args: T,\n options?: ResolveOptions\n ): ResolveResult<T> {\n if (!hasAnyPlaceholder(args)) {\n return { resolved: args, unresolved: [] };\n }\n const bucket = this.runStates.get(this.keyFor(runId));\n return this.resolveAgainst(bucket?.entries ?? EMPTY_ENTRIES, args, options);\n }\n\n /**\n * Captures a frozen snapshot of `runId`'s current entries and\n * returns a view that resolves placeholders against *only* that\n * snapshot. The snapshot is decoupled from the live registry, so\n * subsequent `set()` calls (for example, same-turn direct outputs\n * registering while an event branch is still in flight) are\n * invisible to the snapshot's `resolve`. Used by the mixed\n * direct+event dispatch path to preserve same-turn isolation when\n * a `PreToolUse` hook rewrites event args after directs have\n * completed.\n */\n snapshot(runId: string | undefined): ToolOutputResolveView {\n const bucket = this.runStates.get(this.keyFor(runId));\n const entries: ReadonlyMap<string, string> = bucket\n ? new Map(bucket.entries)\n : EMPTY_ENTRIES;\n return {\n resolve: <T>(args: T, options?: ResolveOptions): ResolveResult<T> =>\n this.resolveAgainst(entries, args, options),\n };\n }\n\n private resolveAgainst<T>(\n entries: ReadonlyMap<string, string>,\n args: T,\n options?: ResolveOptions\n ): ResolveResult<T> {\n if (!hasAnyPlaceholder(args)) {\n return { resolved: args, unresolved: [] };\n }\n const exemptIntentKey = options?.substituteIntentKey !== true;\n const unresolved = new Set<string>();\n /**\n * Providers may deliver the args OBJECT as a JSON string. A plain\n * string-root transform would expand placeholders inside the `intent`\n * label too, bypassing the top-level exclusion below — parse, transform\n * key-aware, and re-serialize so the label stays verbatim while every\n * other field still substitutes. Only taken when an `intent` key is\n * actually present; other strings keep the fast raw-string path.\n */\n if (exemptIntentKey && typeof args === 'string') {\n const parsedRoot = parseStringifiedArgsObject(args);\n if (parsedRoot != null && INTENT_ARG in parsedRoot) {\n const resolved = JSON.stringify(\n this.transform(entries, parsedRoot, unresolved, true)\n ) as T;\n return { resolved, unresolved: Array.from(unresolved) };\n }\n }\n const resolved = this.transform(\n entries,\n args,\n unresolved,\n exemptIntentKey\n ) as T;\n return { resolved, unresolved: Array.from(unresolved) };\n }\n\n private transform(\n entries: ReadonlyMap<string, string>,\n value: unknown,\n unresolved: Set<string>,\n exemptRootIntent = false\n ): unknown {\n if (typeof value === 'string') {\n return this.replaceInString(entries, value, unresolved);\n }\n if (Array.isArray(value)) {\n return value.map((item) => this.transform(entries, item, unresolved));\n }\n if (value !== null && typeof value === 'object') {\n const source = value as Record<string, unknown>;\n const next: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(source)) {\n /**\n * The top-level `intent` arg is a display label, never a data\n * channel: expanding a `{{tool<i>turn<n>}}` placeholder there would\n * dump a stored output (up to the registry cap) into a single-line\n * UI label and persist it with the message. Left verbatim instead.\n */\n next[key] =\n exemptRootIntent && key === INTENT_ARG\n ? item\n : this.transform(entries, item, unresolved);\n }\n return next;\n }\n return value;\n }\n\n private replaceInString(\n entries: ReadonlyMap<string, string>,\n input: string,\n unresolved: Set<string>\n ): string {\n if (input.indexOf('{{tool') === -1) {\n return input;\n }\n return input.replace(\n ToolOutputReferenceRegistry.PLACEHOLDER_MATCHER,\n (match, key: string) => {\n const stored = entries.get(key);\n if (stored == null) {\n unresolved.add(key);\n return match;\n }\n return stored;\n }\n );\n }\n\n private evictWithinBucket(bucket: RunStateBucket): void {\n if (bucket.totalSize <= this.maxTotalSize) {\n return;\n }\n for (const key of bucket.entries.keys()) {\n if (bucket.totalSize <= this.maxTotalSize) {\n return;\n }\n const entry = bucket.entries.get(key);\n if (entry == null) {\n continue;\n }\n bucket.totalSize -= entry.length;\n bucket.entries.delete(key);\n }\n }\n}\n\n/**\n * Cheap pre-check: returns true if any string value in `args` contains\n * the `{{tool` substring. Lets `resolve()` skip the deep tree walk (and\n * its object allocations) for the common case of plain args.\n */\nfunction hasAnyPlaceholder(value: unknown): boolean {\n if (typeof value === 'string') {\n return value.indexOf('{{tool') !== -1;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n if (hasAnyPlaceholder(item)) {\n return true;\n }\n }\n return false;\n }\n if (value !== null && typeof value === 'object') {\n for (const item of Object.values(value as Record<string, unknown>)) {\n if (hasAnyPlaceholder(item)) {\n return true;\n }\n }\n return false;\n }\n return false;\n}\n\n/**\n * Annotates `content` with a reference key and/or unresolved-ref\n * warnings so the LLM sees both alongside the tool output.\n *\n * Behavior:\n * - If `content` parses as a plain (non-array, non-null) JSON object\n * and the object does not already have a conflicting `_ref` key,\n * the reference key and (when present) `_unresolved_refs` array\n * are injected as object fields, preserving JSON validity for\n * downstream consumers that parse the output.\n * - Otherwise (string output, JSON array/primitive, parse failure,\n * or `_ref` collision), a `[ref: <key>]\\n` prefix line is\n * prepended and unresolved refs are appended as a trailing\n * `[unresolved refs: …]` line.\n *\n * The annotated string is what the LLM sees as `ToolMessage.content`.\n * The *original* (un-annotated) value is what gets stored in the\n * registry, so downstream piping remains pristine.\n *\n * @param content Raw (post-truncation) tool output.\n * @param key Reference key for this output, or undefined when\n * there is nothing to register (errors etc.).\n * @param unresolved Reference keys that failed to resolve during\n * argument substitution. Surfaced so the LLM can\n * self-correct its next tool call.\n */\nexport function annotateToolOutputWithReference(\n content: string,\n key: string | undefined,\n unresolved: string[] = []\n): string {\n const hasRefKey = key != null;\n const hasUnresolved = unresolved.length > 0;\n if (!hasRefKey && !hasUnresolved) {\n return content;\n }\n const trimmed = content.trimStart();\n if (trimmed.startsWith('{')) {\n const annotated = tryInjectRefIntoJsonObject(content, key, unresolved);\n if (annotated != null) {\n return annotated;\n }\n }\n const prefix = hasRefKey ? `${buildReferencePrefix(key!)}\\n` : '';\n const trailer = hasUnresolved\n ? `\\n[unresolved refs: ${unresolved.join(', ')}]`\n : '';\n return `${prefix}${content}${trailer}`;\n}\n\nfunction tryInjectRefIntoJsonObject(\n content: string,\n key: string | undefined,\n unresolved: string[]\n): string | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n return null;\n }\n\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return null;\n }\n\n const obj = parsed as Record<string, unknown>;\n const injectingRef = key != null;\n const injectingUnresolved = unresolved.length > 0;\n\n /**\n * Reject the JSON-injection path (fall back to prefix form) when\n * either of our keys collides with real payload data:\n * - `_ref` collision: existing value is non-null and differs from\n * the key we're about to inject.\n * - `_unresolved_refs` collision: existing value is non-null and\n * is not a deep-equal match for the array we'd inject.\n * This keeps us from silently overwriting legitimate tool output.\n */\n if (\n injectingRef &&\n TOOL_OUTPUT_REF_KEY in obj &&\n obj[TOOL_OUTPUT_REF_KEY] !== key &&\n obj[TOOL_OUTPUT_REF_KEY] != null\n ) {\n return null;\n }\n if (\n injectingUnresolved &&\n TOOL_OUTPUT_UNRESOLVED_KEY in obj &&\n obj[TOOL_OUTPUT_UNRESOLVED_KEY] != null &&\n !arraysShallowEqual(obj[TOOL_OUTPUT_UNRESOLVED_KEY], unresolved)\n ) {\n return null;\n }\n\n /**\n * Only strip the framework-owned key we're actually injecting —\n * leave everything else (including a pre-existing `_ref` on the\n * unresolved-only path, or a pre-existing `_unresolved_refs` on a\n * plain-annotation path) untouched so we annotate rather than\n * mutate downstream payload data. Our injected keys land first in\n * the serialized JSON so the LLM sees them before the body.\n */\n const omitKeys = new Set<string>();\n if (injectingRef) omitKeys.add(TOOL_OUTPUT_REF_KEY);\n if (injectingUnresolved) omitKeys.add(TOOL_OUTPUT_UNRESOLVED_KEY);\n const rest: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (!omitKeys.has(k)) {\n rest[k] = v;\n }\n }\n const injected: Record<string, unknown> = {};\n if (injectingRef) {\n injected[TOOL_OUTPUT_REF_KEY] = key;\n }\n if (injectingUnresolved) {\n injected[TOOL_OUTPUT_UNRESOLVED_KEY] = unresolved;\n }\n Object.assign(injected, rest);\n\n const pretty = /^\\{\\s*\\n/.test(content);\n return pretty ? JSON.stringify(injected, null, 2) : JSON.stringify(injected);\n}\n\nfunction arraysShallowEqual(a: unknown, b: readonly string[]): boolean {\n if (!Array.isArray(a) || a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Lazy projection that, given a registry and a runId, returns a new\n * `messages` array where each `ToolMessage` carrying ref metadata is\n * projected into a transient copy with annotated content (when the ref\n * is live in the registry) and with the framework-owned `additional_\n * kwargs` keys (`_refKey`, `_refScope`, `_unresolvedRefs`) stripped\n * regardless of whether annotation applied. The original input array\n * and its messages are never mutated.\n *\n * Annotation is gated on registry presence: a stale `_refKey` from a\n * prior run (e.g. one that survived in persisted history) silently\n * no-ops on the *content* side. The strip-metadata side still runs so\n * stale framework keys never leak onto the wire under any custom or\n * future provider serializer that might transmit `additional_kwargs`.\n * `_unresolvedRefs` is always meaningful and is not gated.\n *\n * **Feature-disabled fast path:** when the host hasn't enabled the\n * tool-output-reference feature, the registry is `undefined` and this\n * function returns the input array reference-equal *without iterating\n * a single message*. The loop is exclusive to the feature-enabled\n * code path.\n */\nexport function annotateMessagesForLLM(\n messages: BaseMessage[],\n registry: ToolOutputReferenceRegistry | undefined,\n runId: string | undefined\n): BaseMessage[] {\n if (registry == null) return messages;\n\n /**\n * Lazy-allocate the output array so the common case (no ToolMessage\n * carries framework metadata) returns the input reference-equal with\n * zero allocations beyond the per-message predicate checks.\n */\n let out: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n if (m._getType() !== 'tool') continue;\n /**\n * `additional_kwargs` is untyped at the LangChain layer\n * (`Record<string, unknown>`), so persisted or client-supplied\n * ToolMessages can carry arbitrary shapes — including primitives\n * (a malformed serializer might write a string, or `null`).\n * Guard with a runtime object check before the `in` probes\n * because the `in` operator throws `TypeError` on primitives.\n * A single malformed message must never crash the provider call\n * path; skip its annotation/strip and continue.\n */\n const rawMeta = m.additional_kwargs as unknown;\n if (rawMeta == null || typeof rawMeta !== 'object') continue;\n const meta = rawMeta as Record<string, unknown>;\n const hasRefKey = '_refKey' in meta;\n const hasRefScope = '_refScope' in meta;\n const hasUnresolvedField = '_unresolvedRefs' in meta;\n if (!hasRefKey && !hasRefScope && !hasUnresolvedField) continue;\n if (isComputerCallOutputMessage(m)) {\n out ??= messages.slice();\n out[i] = cloneToolMessageWithContent(m as ToolMessage, m.content);\n continue;\n }\n\n const refKey = readRefKey(meta);\n const unresolved = readUnresolvedRefs(meta);\n\n /**\n * Prefer the message-stamped `_refScope` for the registry lookup.\n * For named runs it equals the current `runId`; for anonymous\n * invocations it carries the per-batch synthetic scope minted by\n * ToolNode (`\\0anon-<n>`), which `runId` from config cannot\n * recover. Falling back to `runId` keeps backward compatibility\n * with messages stamped before this field existed.\n */\n const lookupScope = readRefScope(meta) ?? runId;\n const liveRef =\n refKey != null && registry.has(lookupScope, refKey) ? refKey : undefined;\n const annotates = liveRef != null || unresolved.length > 0;\n\n const tm = m as ToolMessage;\n let nextContent: ToolMessage['content'] = tm.content;\n\n if (annotates && typeof tm.content === 'string') {\n nextContent = annotateToolOutputWithReference(\n tm.content,\n liveRef,\n unresolved\n );\n } else if (annotates && Array.isArray(tm.content)) {\n /**\n * Array tool content. The string annotator can't run — this notably\n * includes a tail tool result that prompt caching rewrote from a string\n * into a text-block array to host its `cache_control` / `cachePoint`\n * marker (the `_refKey` survives on `additional_kwargs`). Project the\n * same markers the string path would, as leading text blocks: the live\n * `[ref: …]` prefix and/or the unresolved-refs warning. Without this the\n * common tool-result tail loses its reference marker once cached.\n *\n * `as unknown as ToolMessage['content']` is unavoidable: LangChain's\n * content union does not accept a freshly built mixed array literal even\n * though the structural shape is valid at runtime. The double-cast is\n * structurally safe — every original block is preserved and only\n * `{ type: 'text', text }` blocks (which all providers accept) are\n * prepended.\n */\n const prefixBlocks: Array<{ type: 'text'; text: string }> = [];\n if (liveRef != null) {\n prefixBlocks.push({\n type: 'text',\n text: buildReferencePrefix(liveRef),\n });\n }\n if (unresolved.length > 0) {\n prefixBlocks.push({\n type: 'text',\n text: `[unresolved refs: ${unresolved.join(', ')}]`,\n });\n }\n if (prefixBlocks.length > 0) {\n nextContent = [\n ...prefixBlocks,\n ...tm.content,\n ] as unknown as ToolMessage['content'];\n }\n }\n\n /**\n * Project unconditionally: even when no annotation applies (stale\n * `_refKey` or non-annotatable content), `cloneToolMessageWithContent`\n * runs `stripFrameworkRefMetadata` on `additional_kwargs` so the\n * framework-owned keys never reach the wire.\n */\n out ??= messages.slice();\n out[i] = cloneToolMessageWithContent(tm, nextContent);\n }\n\n return out ?? messages;\n}\n\n/**\n * Reads `_refKey` defensively from untyped `additional_kwargs`. Returns\n * undefined for non-string values so a malformed field cannot poison\n * the registry lookup or downstream string operations.\n */\nfunction readRefKey(\n meta: Record<string, unknown> | undefined\n): string | undefined {\n const v = meta?._refKey;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * Reads `_refScope` defensively from untyped `additional_kwargs`.\n * Mirrors {@link readRefKey} — non-string scopes are dropped (the\n * caller falls back to the run-derived scope) rather than passed into\n * the registry as a malformed key.\n */\nfunction readRefScope(\n meta: Record<string, unknown> | undefined\n): string | undefined {\n const v = meta?._refScope;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * Reads `_unresolvedRefs` defensively from untyped `additional_kwargs`.\n * Returns an empty array for any non-array value, and filters out\n * non-string entries from a real array. Without this guard, a hydrated\n * ToolMessage carrying e.g. `_unresolvedRefs: 'tool0turn0'` would crash\n * `attemptInvoke` on the eventual `.length` / `.join(...)` call.\n */\nfunction readUnresolvedRefs(\n meta: Record<string, unknown> | undefined\n): string[] {\n const v = meta?._unresolvedRefs;\n if (!Array.isArray(v)) return [];\n const out: string[] = [];\n for (const item of v) {\n if (typeof item === 'string') out.push(item);\n }\n return out;\n}\n\n/**\n * Builds a fresh `ToolMessage` that mirrors `tm`'s identity fields with\n * the supplied `content`. Every `ToolMessage` field but `content` is\n * carried over so the projection is structurally identical to the\n * original from a LangChain serializer's perspective.\n *\n * `additional_kwargs` is rebuilt with the framework-owned ref keys\n * stripped. Defensive: LangChain's standard provider serializers do not\n * transmit `additional_kwargs` to provider HTTP APIs, but a custom\n * adapter or future LangChain change could. Stripping keeps the\n * implementation correct under any serializer behavior at the cost of a\n * shallow object spread per annotated message.\n */\nfunction cloneToolMessageWithContent(\n tm: ToolMessage,\n content: ToolMessage['content']\n): ToolMessage {\n return new ToolMessage({\n id: tm.id,\n name: tm.name,\n status: tm.status,\n artifact: tm.artifact,\n tool_call_id: tm.tool_call_id,\n response_metadata: tm.response_metadata,\n additional_kwargs: stripFrameworkRefMetadata(tm.additional_kwargs),\n content,\n });\n}\n\n/**\n * Returns a copy of `kwargs` with `_refKey`, `_refScope`, and\n * `_unresolvedRefs` removed. Returns the input reference-equal when\n * none of those keys are present so the no-strip path stays cheap;\n * returns `undefined` when stripping leaves the object empty so the\n * caller can drop the field entirely.\n */\nfunction stripFrameworkRefMetadata(\n kwargs: Record<string, unknown> | undefined\n): Record<string, unknown> | undefined {\n if (kwargs == null) return undefined;\n if (\n !('_refKey' in kwargs) &&\n !('_refScope' in kwargs) &&\n !('_unresolvedRefs' in kwargs)\n ) {\n return kwargs;\n }\n const { _refKey, _refScope, _unresolvedRefs, ...rest } = kwargs as Record<\n string,\n unknown\n > & {\n _refKey?: unknown;\n _refScope?: unknown;\n _unresolvedRefs?: unknown;\n };\n void _refKey;\n void _refScope;\n void _unresolvedRefs;\n return Object.keys(rest).length === 0 ? undefined : rest;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;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MAAM,QAAQ,GACjB,IAAI,OAAO,SAAS,UAAU,IAAI,KAAK,IAAI;CAE7C,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAS,4BACP,IACA,SACa;CACb,OAAO,IAAIC,yBAAAA,YAAY;EACrB,IAAI,GAAG;EACP,MAAM,GAAG;EACT,QAAQ,GAAG;EACX,UAAU,GAAG;EACb,cAAc,GAAG;EACjB,mBAAmB,GAAG;EACtB,mBAAmB,0BAA0B,GAAG,iBAAiB;EACjE;CACF,CAAC;AACH;;;;;;;;AASA,SAAS,0BACP,QACqC;CACrC,IAAI,UAAU,MAAM,OAAO,KAAA;CAC3B,IACE,EAAE,aAAa,WACf,EAAE,eAAe,WACjB,EAAE,qBAAqB,SAEvB,OAAO;CAET,MAAM,EAAE,SAAS,WAAW,iBAAiB,GAAG,SAAS;CAWzD,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,WAAW,IAAI,KAAA,IAAY;AACtD"}
1
+ {"version":3,"file":"toolOutputReferences.cjs","names":["HARD_MAX_TOOL_RESULT_CHARS","HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE","calculateMaxTotalToolOutputSize","isComputerCallOutputMessage","ToolMessage"],"sources":["../../../src/tools/toolOutputReferences.ts"],"sourcesContent":["/**\n * Tool output reference registry.\n *\n * When enabled via `RunConfig.toolOutputReferences.enabled`, ToolNode\n * stores each successful tool output under a stable key\n * (`tool<idx>turn<turn>`) where `idx` is the tool's position within a\n * ToolNode batch and `turn` is the batch index within the run\n * (incremented once per ToolNode invocation).\n *\n * Subsequent tool calls can pipe a previous output into their args by\n * embedding `{{tool<idx>turn<turn>}}` inside any string argument;\n * {@link ToolOutputReferenceRegistry.resolve} walks the args and\n * substitutes the placeholders immediately before invocation.\n *\n * The registry stores the *raw, untruncated* tool output so a later\n * `{{…}}` substitution pipes the full payload into the next tool —\n * even when the LLM only saw a head+tail-truncated preview in\n * `ToolMessage.content`. Outputs are stored without any annotation\n * (the `_ref` key or the `[ref: ...]` prefix seen by the LLM is\n * strictly a UX signal attached to `ToolMessage.content`). Keeping the\n * registry pristine means downstream bash/jq piping receives the\n * complete, verbatim output with no injected fields.\n */\n\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport {\n calculateMaxTotalToolOutputSize,\n HARD_MAX_TOOL_RESULT_CHARS,\n HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE,\n} from '@/utils/truncation';\nimport { isComputerCallOutputMessage } from '@/utils/toolContent';\nimport { INTENT_ARG } from '@/tools/intentArg';\n\n/** Parses a stringified JSON object arg; undefined for anything else. */\nfunction parseStringifiedArgsObject(\n value: string\n): Record<string, unknown> | undefined {\n if (!value.trim().startsWith('{')) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(value) as unknown;\n if (\n parsed != null &&\n typeof parsed === 'object' &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\n/**\n * Non-global matcher for a single `{{tool<i>turn<n>}}` placeholder.\n * Exported for consumers that want to detect references (e.g., syntax\n * highlighting, docs). The stateful `g` variant lives inside the\n * registry so nobody trips on `lastIndex`.\n */\nexport const TOOL_OUTPUT_REF_PATTERN = /\\{\\{(tool\\d+turn\\d+)\\}\\}/;\n\n/** Object key used when a parsed-object output has `_ref` injected. */\nexport const TOOL_OUTPUT_REF_KEY = '_ref';\n\n/**\n * Object key used to carry unresolved reference warnings on a parsed-\n * object output. Using a dedicated field instead of a trailing text\n * line keeps the annotated `ToolMessage.content` parseable as JSON for\n * downstream consumers that rely on the object shape.\n */\nexport const TOOL_OUTPUT_UNRESOLVED_KEY = '_unresolved_refs';\n\n/** Single-line prefix prepended to non-object tool outputs so the LLM sees the reference key. */\nexport function buildReferencePrefix(key: string): string {\n return `[ref: ${key}]`;\n}\n\n/** Stable registry key for a tool output. */\nexport function buildReferenceKey(toolIndex: number, turn: number): string {\n return `tool${toolIndex}turn${turn}`;\n}\n\nexport type ToolOutputReferenceRegistryOptions = {\n /** Maximum characters stored per registered output. */\n maxOutputSize?: number;\n /** Maximum total characters retained across all registered outputs. */\n maxTotalSize?: number;\n /**\n * Upper bound on the number of concurrently-tracked runs. When\n * exceeded, the oldest run bucket is evicted (FIFO). Defaults to 32.\n */\n maxActiveRuns?: number;\n};\n\nexport interface ToolOutputReferenceState {\n entries: Array<{ key: string; value: string }>;\n turnCounter: number;\n warnedNonStringTools: string[];\n}\n\n/**\n * Result of resolving placeholders in tool args.\n */\nexport type ResolveResult<T> = {\n /** Arguments with placeholders replaced. Same shape as the input. */\n resolved: T;\n /** Reference keys that were referenced but had no stored value. */\n unresolved: string[];\n};\n\n/**\n * Read-only view over a frozen registry snapshot. Returned by\n * {@link ToolOutputReferenceRegistry.snapshot} for callers that need\n * to resolve placeholders against the registry state at a specific\n * point in time, ignoring any subsequent registrations.\n */\nexport interface ToolOutputResolveView {\n resolve<T>(args: T, options?: ResolveOptions): ResolveResult<T>;\n}\n\n/**\n * Per-call resolution options. `substituteIntentKey` opts the top-level\n * `intent` key back INTO placeholder substitution: the exemption protects\n * the injected display label, but a tool whose own schema declares a\n * business parameter named `intent` (the injectors skip such tools) still\n * needs references piped into it like any other argument.\n */\nexport type ResolveOptions = {\n substituteIntentKey?: boolean;\n};\n\n/**\n * Pre-resolved arg map keyed by `toolCallId`. Used by the mixed\n * direct+event dispatch path to feed event calls' resolved args\n * (captured pre-batch) into the dispatcher without re-resolving\n * against the now-stale live registry.\n */\nexport type PreResolvedArgsMap = Map<\n string,\n { resolved: Record<string, unknown>; unresolved: string[] }\n>;\n\n/**\n * Per-call sink for resolved args, keyed by `toolCallId`. Threaded\n * as a per-batch local map so concurrent `ToolNode.run()` calls do\n * not race on shared sink state.\n */\nexport type ResolvedArgsByCallId = Map<string, Record<string, unknown>>;\n\nconst EMPTY_ENTRIES: ReadonlyMap<string, string> = new Map<string, string>();\n\n/**\n * Per-run state bucket held inside the registry. Each distinct\n * `run_id` gets its own bucket so overlapping concurrent runs on a\n * shared registry cannot leak outputs, turn counters, or warn-memos\n * into one another.\n */\nclass RunStateBucket {\n entries: Map<string, string> = new Map();\n totalSize: number = 0;\n turnCounter: number = 0;\n warnedNonStringTools: Set<string> = new Set();\n}\n\n/**\n * Anonymous (`run_id` absent) bucket key. Anonymous batches are\n * treated as fresh runs on every invocation — see `nextTurn`.\n */\nconst ANON_RUN_KEY = '\\0anon';\n\n/**\n * Default upper bound on the number of concurrently-tracked runs per\n * registry. When exceeded, the oldest run's bucket (by insertion\n * order) is evicted. Keeps memory bounded when a ToolNode is reused\n * across many runs without explicit `releaseRun` calls.\n */\nconst DEFAULT_MAX_ACTIVE_RUNS = 32;\n\n/**\n * Ordered map of reference-key → stored output, partitioned by run so\n * concurrent / interleaved runs sharing one registry cannot leak\n * outputs between each other.\n *\n * Each public method takes a `runId` which selects the run's bucket.\n * Hosts typically get one registry per run via `Graph`, in which\n * case only a single bucket is ever populated; the partitioning\n * exists so the registry also behaves correctly when a single\n * instance is reused directly.\n */\nexport class ToolOutputReferenceRegistry {\n private runStates: Map<string, RunStateBucket> = new Map();\n private readonly maxOutputSize: number;\n private readonly maxTotalSize: number;\n private readonly maxActiveRuns: number;\n /**\n * Local stateful matcher used only by `replaceInString`. Kept\n * off-module so callers of the exported `TOOL_OUTPUT_REF_PATTERN`\n * never see a stale `lastIndex`.\n */\n private static readonly PLACEHOLDER_MATCHER = /\\{\\{(tool\\d+turn\\d+)\\}\\}/g;\n\n constructor(options: ToolOutputReferenceRegistryOptions = {}) {\n /**\n * Per-output default is the same ~400 KB budget as the standard\n * tool-result truncation (`HARD_MAX_TOOL_RESULT_CHARS`). This\n * keeps a single `{{…}}` substitution at a size that is safe to\n * pass through typical shell `ARG_MAX` limits and matches what\n * the LLM would otherwise have seen. Hosts that want larger per-\n * output payloads (API consumers, long JSON streams) can raise\n * the cap explicitly up to the 5 MB total budget.\n */\n const perOutput =\n options.maxOutputSize != null && options.maxOutputSize > 0\n ? options.maxOutputSize\n : HARD_MAX_TOOL_RESULT_CHARS;\n /**\n * Clamp a caller-supplied `maxTotalSize` to\n * `HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE` (5 MB) so the documented\n * absolute cap is enforced regardless of host config —\n * `calculateMaxTotalToolOutputSize` already applies the same\n * upper bound on its computed default, but the user-provided\n * branch was bypassing it.\n */\n const totalRaw =\n options.maxTotalSize != null && options.maxTotalSize > 0\n ? Math.min(options.maxTotalSize, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE)\n : calculateMaxTotalToolOutputSize(perOutput);\n this.maxTotalSize = totalRaw;\n /**\n * The per-output cap can never exceed the per-run aggregate cap:\n * if a single entry were allowed to be larger than `maxTotalSize`,\n * the eviction loop would either blow the cap (to keep the entry)\n * or self-evict a just-stored value. Clamping here turns\n * `maxTotalSize` into a hard upper bound on *any* state the\n * registry retains per run.\n */\n this.maxOutputSize = Math.min(perOutput, totalRaw);\n this.maxActiveRuns =\n options.maxActiveRuns != null && options.maxActiveRuns > 0\n ? options.maxActiveRuns\n : DEFAULT_MAX_ACTIVE_RUNS;\n }\n\n private keyFor(runId: string | undefined): string {\n return runId ?? ANON_RUN_KEY;\n }\n\n private getOrCreate(runId: string | undefined): RunStateBucket {\n const key = this.keyFor(runId);\n let state = this.runStates.get(key);\n if (state == null) {\n state = new RunStateBucket();\n this.runStates.set(key, state);\n if (this.runStates.size > this.maxActiveRuns) {\n const oldest = this.runStates.keys().next().value;\n if (oldest != null && oldest !== key) {\n this.runStates.delete(oldest);\n }\n }\n }\n return state;\n }\n\n /** Registers (or replaces) the output stored under `key` for `runId`. */\n set(runId: string | undefined, key: string, value: string): void {\n const bucket = this.getOrCreate(runId);\n const clipped =\n value.length > this.maxOutputSize\n ? value.slice(0, this.maxOutputSize)\n : value;\n const existing = bucket.entries.get(key);\n if (existing != null) {\n bucket.totalSize -= existing.length;\n bucket.entries.delete(key);\n }\n bucket.entries.set(key, clipped);\n bucket.totalSize += clipped.length;\n this.evictWithinBucket(bucket);\n }\n\n /** Returns the stored value for `key` in `runId`'s bucket, or `undefined`. */\n get(runId: string | undefined, key: string): string | undefined {\n return this.runStates.get(this.keyFor(runId))?.entries.get(key);\n }\n\n /**\n * Returns `true` when `key` is currently stored in `runId`'s bucket.\n * Used by {@link annotateMessagesForLLM} to gate transient annotation\n * on whether the registry still owns the referenced output (a stale\n * `_refKey` from a prior run silently no-ops here).\n */\n has(runId: string | undefined, key: string): boolean {\n return this.runStates.get(this.keyFor(runId))?.entries.has(key) ?? false;\n }\n\n /** Total number of registered outputs across every run bucket. */\n get size(): number {\n let n = 0;\n for (const bucket of this.runStates.values()) {\n n += bucket.entries.size;\n }\n return n;\n }\n\n /** Maximum characters retained per output (post-clip). */\n get perOutputLimit(): number {\n return this.maxOutputSize;\n }\n\n /** Maximum total characters retained *per run*. */\n get totalLimit(): number {\n return this.maxTotalSize;\n }\n\n /** Drops every run's state. */\n clear(): void {\n this.runStates.clear();\n }\n\n /**\n * Explicitly release `runId`'s state. Safe to call when a run has\n * finished. Hosts sharing one registry across runs should call this\n * to reclaim memory deterministically; otherwise LRU eviction kicks\n * in when `maxActiveRuns` runs accumulate.\n */\n releaseRun(runId: string | undefined): void {\n this.runStates.delete(this.keyFor(runId));\n }\n\n /**\n * Claims the next batch turn synchronously from `runId`'s bucket.\n *\n * Must be called once at the start of each ToolNode batch before\n * any `await`, so concurrent invocations within the same run see\n * distinct turn values (reads are effectively atomic by JS's\n * single-threaded execution of the sync prefix).\n *\n * If `runId` is missing the anonymous bucket is dropped and a\n * fresh one created so each anonymous call behaves as its own run.\n */\n nextTurn(runId: string | undefined): number {\n if (runId == null) {\n this.runStates.delete(ANON_RUN_KEY);\n }\n const bucket = this.getOrCreate(runId);\n return bucket.turnCounter++;\n }\n\n /**\n * Records that `toolName` has been warned about in `runId` (returns\n * `true` on the first call per run, `false` after). Used by\n * ToolNode to emit one log line per offending tool per run when a\n * `ToolMessage.content` isn't a string.\n */\n claimWarnOnce(runId: string | undefined, toolName: string): boolean {\n const bucket = this.getOrCreate(runId);\n if (bucket.warnedNonStringTools.has(toolName)) {\n return false;\n }\n bucket.warnedNonStringTools.add(toolName);\n return true;\n }\n\n /**\n * Walks `args` and replaces every `{{tool<i>turn<n>}}` placeholder in\n * string values with the stored output *from `runId`'s bucket*. Non-\n * string values and object keys are left untouched. Unresolved\n * references are left in-place and reported so the caller can\n * surface them to the LLM. When no placeholder appears anywhere in\n * the serialized args, the original input is returned without\n * walking the tree.\n */\n resolve<T>(\n runId: string | undefined,\n args: T,\n options?: ResolveOptions\n ): ResolveResult<T> {\n if (!hasAnyPlaceholder(args)) {\n return { resolved: args, unresolved: [] };\n }\n const bucket = this.runStates.get(this.keyFor(runId));\n return this.resolveAgainst(bucket?.entries ?? EMPTY_ENTRIES, args, options);\n }\n\n /**\n * Captures a frozen snapshot of `runId`'s current entries and\n * returns a view that resolves placeholders against *only* that\n * snapshot. The snapshot is decoupled from the live registry, so\n * subsequent `set()` calls (for example, same-turn direct outputs\n * registering while an event branch is still in flight) are\n * invisible to the snapshot's `resolve`. Used by the mixed\n * direct+event dispatch path to preserve same-turn isolation when\n * a `PreToolUse` hook rewrites event args after directs have\n * completed.\n */\n snapshot(runId: string | undefined): ToolOutputResolveView {\n const bucket = this.runStates.get(this.keyFor(runId));\n const entries: ReadonlyMap<string, string> = bucket\n ? new Map(bucket.entries)\n : EMPTY_ENTRIES;\n return {\n resolve: <T>(args: T, options?: ResolveOptions): ResolveResult<T> =>\n this.resolveAgainst(entries, args, options),\n };\n }\n\n /** Captures the checkpoint-safe state needed to resume one run bucket. */\n snapshotState(runId: string | undefined): ToolOutputReferenceState {\n const bucket = this.runStates.get(this.keyFor(runId));\n return {\n entries: [...(bucket?.entries ?? EMPTY_ENTRIES)].map(([key, value]) => ({\n key,\n value,\n })),\n turnCounter: bucket?.turnCounter ?? 0,\n warnedNonStringTools: [...(bucket?.warnedNonStringTools ?? [])],\n };\n }\n\n /** Restores a checkpointed run bucket under the current resume scope. */\n restoreState(\n runId: string | undefined,\n state: ToolOutputReferenceState\n ): void {\n this.releaseRun(runId);\n const bucket = this.getOrCreate(runId);\n for (const { key, value } of state.entries) {\n this.set(runId, key, value);\n }\n bucket.turnCounter = state.turnCounter;\n for (const toolName of state.warnedNonStringTools) {\n bucket.warnedNonStringTools.add(toolName);\n }\n }\n\n private resolveAgainst<T>(\n entries: ReadonlyMap<string, string>,\n args: T,\n options?: ResolveOptions\n ): ResolveResult<T> {\n if (!hasAnyPlaceholder(args)) {\n return { resolved: args, unresolved: [] };\n }\n const exemptIntentKey = options?.substituteIntentKey !== true;\n const unresolved = new Set<string>();\n /**\n * Providers may deliver the args OBJECT as a JSON string. A plain\n * string-root transform would expand placeholders inside the `intent`\n * label too, bypassing the top-level exclusion below — parse, transform\n * key-aware, and re-serialize so the label stays verbatim while every\n * other field still substitutes. Only taken when an `intent` key is\n * actually present; other strings keep the fast raw-string path.\n */\n if (exemptIntentKey && typeof args === 'string') {\n const parsedRoot = parseStringifiedArgsObject(args);\n if (parsedRoot != null && INTENT_ARG in parsedRoot) {\n const resolved = JSON.stringify(\n this.transform(entries, parsedRoot, unresolved, true)\n ) as T;\n return { resolved, unresolved: Array.from(unresolved) };\n }\n }\n const resolved = this.transform(\n entries,\n args,\n unresolved,\n exemptIntentKey\n ) as T;\n return { resolved, unresolved: Array.from(unresolved) };\n }\n\n private transform(\n entries: ReadonlyMap<string, string>,\n value: unknown,\n unresolved: Set<string>,\n exemptRootIntent = false\n ): unknown {\n if (typeof value === 'string') {\n return this.replaceInString(entries, value, unresolved);\n }\n if (Array.isArray(value)) {\n return value.map((item) => this.transform(entries, item, unresolved));\n }\n if (value !== null && typeof value === 'object') {\n const source = value as Record<string, unknown>;\n const next: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(source)) {\n /**\n * The top-level `intent` arg is a display label, never a data\n * channel: expanding a `{{tool<i>turn<n>}}` placeholder there would\n * dump a stored output (up to the registry cap) into a single-line\n * UI label and persist it with the message. Left verbatim instead.\n */\n next[key] =\n exemptRootIntent && key === INTENT_ARG\n ? item\n : this.transform(entries, item, unresolved);\n }\n return next;\n }\n return value;\n }\n\n private replaceInString(\n entries: ReadonlyMap<string, string>,\n input: string,\n unresolved: Set<string>\n ): string {\n if (input.indexOf('{{tool') === -1) {\n return input;\n }\n return input.replace(\n ToolOutputReferenceRegistry.PLACEHOLDER_MATCHER,\n (match, key: string) => {\n const stored = entries.get(key);\n if (stored == null) {\n unresolved.add(key);\n return match;\n }\n return stored;\n }\n );\n }\n\n private evictWithinBucket(bucket: RunStateBucket): void {\n if (bucket.totalSize <= this.maxTotalSize) {\n return;\n }\n for (const key of bucket.entries.keys()) {\n if (bucket.totalSize <= this.maxTotalSize) {\n return;\n }\n const entry = bucket.entries.get(key);\n if (entry == null) {\n continue;\n }\n bucket.totalSize -= entry.length;\n bucket.entries.delete(key);\n }\n }\n}\n\n/**\n * Cheap pre-check: returns true if any string value in `args` contains\n * the `{{tool` substring. Lets `resolve()` skip the deep tree walk (and\n * its object allocations) for the common case of plain args.\n */\nfunction hasAnyPlaceholder(value: unknown): boolean {\n if (typeof value === 'string') {\n return value.indexOf('{{tool') !== -1;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n if (hasAnyPlaceholder(item)) {\n return true;\n }\n }\n return false;\n }\n if (value !== null && typeof value === 'object') {\n for (const item of Object.values(value as Record<string, unknown>)) {\n if (hasAnyPlaceholder(item)) {\n return true;\n }\n }\n return false;\n }\n return false;\n}\n\n/**\n * Annotates `content` with a reference key and/or unresolved-ref\n * warnings so the LLM sees both alongside the tool output.\n *\n * Behavior:\n * - If `content` parses as a plain (non-array, non-null) JSON object\n * and the object does not already have a conflicting `_ref` key,\n * the reference key and (when present) `_unresolved_refs` array\n * are injected as object fields, preserving JSON validity for\n * downstream consumers that parse the output.\n * - Otherwise (string output, JSON array/primitive, parse failure,\n * or `_ref` collision), a `[ref: <key>]\\n` prefix line is\n * prepended and unresolved refs are appended as a trailing\n * `[unresolved refs: …]` line.\n *\n * The annotated string is what the LLM sees as `ToolMessage.content`.\n * The *original* (un-annotated) value is what gets stored in the\n * registry, so downstream piping remains pristine.\n *\n * @param content Raw (post-truncation) tool output.\n * @param key Reference key for this output, or undefined when\n * there is nothing to register (errors etc.).\n * @param unresolved Reference keys that failed to resolve during\n * argument substitution. Surfaced so the LLM can\n * self-correct its next tool call.\n */\nexport function annotateToolOutputWithReference(\n content: string,\n key: string | undefined,\n unresolved: string[] = []\n): string {\n const hasRefKey = key != null;\n const hasUnresolved = unresolved.length > 0;\n if (!hasRefKey && !hasUnresolved) {\n return content;\n }\n const trimmed = content.trimStart();\n if (trimmed.startsWith('{')) {\n const annotated = tryInjectRefIntoJsonObject(content, key, unresolved);\n if (annotated != null) {\n return annotated;\n }\n }\n const prefix = hasRefKey ? `${buildReferencePrefix(key!)}\\n` : '';\n const trailer = hasUnresolved\n ? `\\n[unresolved refs: ${unresolved.join(', ')}]`\n : '';\n return `${prefix}${content}${trailer}`;\n}\n\nfunction tryInjectRefIntoJsonObject(\n content: string,\n key: string | undefined,\n unresolved: string[]\n): string | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n return null;\n }\n\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return null;\n }\n\n const obj = parsed as Record<string, unknown>;\n const injectingRef = key != null;\n const injectingUnresolved = unresolved.length > 0;\n\n /**\n * Reject the JSON-injection path (fall back to prefix form) when\n * either of our keys collides with real payload data:\n * - `_ref` collision: existing value is non-null and differs from\n * the key we're about to inject.\n * - `_unresolved_refs` collision: existing value is non-null and\n * is not a deep-equal match for the array we'd inject.\n * This keeps us from silently overwriting legitimate tool output.\n */\n if (\n injectingRef &&\n TOOL_OUTPUT_REF_KEY in obj &&\n obj[TOOL_OUTPUT_REF_KEY] !== key &&\n obj[TOOL_OUTPUT_REF_KEY] != null\n ) {\n return null;\n }\n if (\n injectingUnresolved &&\n TOOL_OUTPUT_UNRESOLVED_KEY in obj &&\n obj[TOOL_OUTPUT_UNRESOLVED_KEY] != null &&\n !arraysShallowEqual(obj[TOOL_OUTPUT_UNRESOLVED_KEY], unresolved)\n ) {\n return null;\n }\n\n /**\n * Only strip the framework-owned key we're actually injecting —\n * leave everything else (including a pre-existing `_ref` on the\n * unresolved-only path, or a pre-existing `_unresolved_refs` on a\n * plain-annotation path) untouched so we annotate rather than\n * mutate downstream payload data. Our injected keys land first in\n * the serialized JSON so the LLM sees them before the body.\n */\n const omitKeys = new Set<string>();\n if (injectingRef) omitKeys.add(TOOL_OUTPUT_REF_KEY);\n if (injectingUnresolved) omitKeys.add(TOOL_OUTPUT_UNRESOLVED_KEY);\n const rest: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (!omitKeys.has(k)) {\n rest[k] = v;\n }\n }\n const injected: Record<string, unknown> = {};\n if (injectingRef) {\n injected[TOOL_OUTPUT_REF_KEY] = key;\n }\n if (injectingUnresolved) {\n injected[TOOL_OUTPUT_UNRESOLVED_KEY] = unresolved;\n }\n Object.assign(injected, rest);\n\n const pretty = /^\\{\\s*\\n/.test(content);\n return pretty ? JSON.stringify(injected, null, 2) : JSON.stringify(injected);\n}\n\nfunction arraysShallowEqual(a: unknown, b: readonly string[]): boolean {\n if (!Array.isArray(a) || a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Lazy projection that, given a registry and a runId, returns a new\n * `messages` array where each `ToolMessage` carrying ref metadata is\n * projected into a transient copy with annotated content (when the ref\n * is live in the registry) and with the framework-owned `additional_\n * kwargs` keys (`_refKey`, `_refScope`, `_unresolvedRefs`) stripped\n * regardless of whether annotation applied. The original input array\n * and its messages are never mutated.\n *\n * Annotation is gated on registry presence: a stale `_refKey` from a\n * prior run (e.g. one that survived in persisted history) silently\n * no-ops on the *content* side. The strip-metadata side still runs so\n * stale framework keys never leak onto the wire under any custom or\n * future provider serializer that might transmit `additional_kwargs`.\n * `_unresolvedRefs` is always meaningful and is not gated.\n *\n * **Feature-disabled fast path:** when the host hasn't enabled the\n * tool-output-reference feature, the registry is `undefined` and this\n * function returns the input array reference-equal *without iterating\n * a single message*. The loop is exclusive to the feature-enabled\n * code path.\n */\nexport function annotateMessagesForLLM(\n messages: BaseMessage[],\n registry: ToolOutputReferenceRegistry | undefined,\n runId: string | undefined\n): BaseMessage[] {\n if (registry == null) return messages;\n\n /**\n * Lazy-allocate the output array so the common case (no ToolMessage\n * carries framework metadata) returns the input reference-equal with\n * zero allocations beyond the per-message predicate checks.\n */\n let out: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n if (m._getType() !== 'tool') continue;\n /**\n * `additional_kwargs` is untyped at the LangChain layer\n * (`Record<string, unknown>`), so persisted or client-supplied\n * ToolMessages can carry arbitrary shapes — including primitives\n * (a malformed serializer might write a string, or `null`).\n * Guard with a runtime object check before the `in` probes\n * because the `in` operator throws `TypeError` on primitives.\n * A single malformed message must never crash the provider call\n * path; skip its annotation/strip and continue.\n */\n const rawMeta = m.additional_kwargs as unknown;\n if (rawMeta == null || typeof rawMeta !== 'object') continue;\n const meta = rawMeta as Record<string, unknown>;\n const hasRefKey = '_refKey' in meta;\n const hasRefScope = '_refScope' in meta;\n const hasUnresolvedField = '_unresolvedRefs' in meta;\n if (!hasRefKey && !hasRefScope && !hasUnresolvedField) continue;\n if (isComputerCallOutputMessage(m)) {\n out ??= messages.slice();\n out[i] = cloneToolMessageWithContent(m as ToolMessage, m.content);\n continue;\n }\n\n const refKey = readRefKey(meta);\n const unresolved = readUnresolvedRefs(meta);\n\n /**\n * Prefer the message-stamped `_refScope` for the registry lookup.\n * For named runs it equals the current `runId`; for anonymous\n * invocations it carries the per-batch synthetic scope minted by\n * ToolNode (`\\0anon-<n>`), which `runId` from config cannot\n * recover. Falling back to `runId` keeps backward compatibility\n * with messages stamped before this field existed.\n */\n const lookupScope = readRefScope(meta) ?? runId;\n const liveRef =\n refKey != null && registry.has(lookupScope, refKey) ? refKey : undefined;\n const annotates = liveRef != null || unresolved.length > 0;\n\n const tm = m as ToolMessage;\n let nextContent: ToolMessage['content'] = tm.content;\n\n if (annotates && typeof tm.content === 'string') {\n nextContent = annotateToolOutputWithReference(\n tm.content,\n liveRef,\n unresolved\n );\n } else if (annotates && Array.isArray(tm.content)) {\n /**\n * Array tool content. The string annotator can't run — this notably\n * includes a tail tool result that prompt caching rewrote from a string\n * into a text-block array to host its `cache_control` / `cachePoint`\n * marker (the `_refKey` survives on `additional_kwargs`). Project the\n * same markers the string path would, as leading text blocks: the live\n * `[ref: …]` prefix and/or the unresolved-refs warning. Without this the\n * common tool-result tail loses its reference marker once cached.\n *\n * `as unknown as ToolMessage['content']` is unavoidable: LangChain's\n * content union does not accept a freshly built mixed array literal even\n * though the structural shape is valid at runtime. The double-cast is\n * structurally safe — every original block is preserved and only\n * `{ type: 'text', text }` blocks (which all providers accept) are\n * prepended.\n */\n const prefixBlocks: Array<{ type: 'text'; text: string }> = [];\n if (liveRef != null) {\n prefixBlocks.push({\n type: 'text',\n text: buildReferencePrefix(liveRef),\n });\n }\n if (unresolved.length > 0) {\n prefixBlocks.push({\n type: 'text',\n text: `[unresolved refs: ${unresolved.join(', ')}]`,\n });\n }\n if (prefixBlocks.length > 0) {\n nextContent = [\n ...prefixBlocks,\n ...tm.content,\n ] as unknown as ToolMessage['content'];\n }\n }\n\n /**\n * Project unconditionally: even when no annotation applies (stale\n * `_refKey` or non-annotatable content), `cloneToolMessageWithContent`\n * runs `stripFrameworkRefMetadata` on `additional_kwargs` so the\n * framework-owned keys never reach the wire.\n */\n out ??= messages.slice();\n out[i] = cloneToolMessageWithContent(tm, nextContent);\n }\n\n return out ?? messages;\n}\n\n/**\n * Reads `_refKey` defensively from untyped `additional_kwargs`. Returns\n * undefined for non-string values so a malformed field cannot poison\n * the registry lookup or downstream string operations.\n */\nfunction readRefKey(\n meta: Record<string, unknown> | undefined\n): string | undefined {\n const v = meta?._refKey;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * Reads `_refScope` defensively from untyped `additional_kwargs`.\n * Mirrors {@link readRefKey} — non-string scopes are dropped (the\n * caller falls back to the run-derived scope) rather than passed into\n * the registry as a malformed key.\n */\nfunction readRefScope(\n meta: Record<string, unknown> | undefined\n): string | undefined {\n const v = meta?._refScope;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * Reads `_unresolvedRefs` defensively from untyped `additional_kwargs`.\n * Returns an empty array for any non-array value, and filters out\n * non-string entries from a real array. Without this guard, a hydrated\n * ToolMessage carrying e.g. `_unresolvedRefs: 'tool0turn0'` would crash\n * `attemptInvoke` on the eventual `.length` / `.join(...)` call.\n */\nfunction readUnresolvedRefs(\n meta: Record<string, unknown> | undefined\n): string[] {\n const v = meta?._unresolvedRefs;\n if (!Array.isArray(v)) return [];\n const out: string[] = [];\n for (const item of v) {\n if (typeof item === 'string') out.push(item);\n }\n return out;\n}\n\n/**\n * Builds a fresh `ToolMessage` that mirrors `tm`'s identity fields with\n * the supplied `content`. Every `ToolMessage` field but `content` is\n * carried over so the projection is structurally identical to the\n * original from a LangChain serializer's perspective.\n *\n * `additional_kwargs` is rebuilt with the framework-owned ref keys\n * stripped. Defensive: LangChain's standard provider serializers do not\n * transmit `additional_kwargs` to provider HTTP APIs, but a custom\n * adapter or future LangChain change could. Stripping keeps the\n * implementation correct under any serializer behavior at the cost of a\n * shallow object spread per annotated message.\n */\nfunction cloneToolMessageWithContent(\n tm: ToolMessage,\n content: ToolMessage['content']\n): ToolMessage {\n return new ToolMessage({\n id: tm.id,\n name: tm.name,\n status: tm.status,\n artifact: tm.artifact,\n tool_call_id: tm.tool_call_id,\n response_metadata: tm.response_metadata,\n additional_kwargs: stripFrameworkRefMetadata(tm.additional_kwargs),\n content,\n });\n}\n\n/**\n * Returns a copy of `kwargs` with `_refKey`, `_refScope`, and\n * `_unresolvedRefs` removed. Returns the input reference-equal when\n * none of those keys are present so the no-strip path stays cheap;\n * returns `undefined` when stripping leaves the object empty so the\n * caller can drop the field entirely.\n */\nfunction stripFrameworkRefMetadata(\n kwargs: Record<string, unknown> | undefined\n): Record<string, unknown> | undefined {\n if (kwargs == null) return undefined;\n if (\n !('_refKey' in kwargs) &&\n !('_refScope' in kwargs) &&\n !('_unresolvedRefs' in kwargs)\n ) {\n return kwargs;\n }\n const { _refKey, _refScope, _unresolvedRefs, ...rest } = kwargs as Record<\n string,\n unknown\n > & {\n _refKey?: unknown;\n _refScope?: unknown;\n _unresolvedRefs?: unknown;\n };\n void _refKey;\n void _refScope;\n void _unresolvedRefs;\n return Object.keys(rest).length === 0 ? undefined : rest;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAS,2BACP,OACqC;CACrC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,WAAW,GAAG,GAC9B;CAEF,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,KAAK;EAC/B,IACE,UAAU,QACV,OAAO,WAAW,YAClB,CAAC,MAAM,QAAQ,MAAM,GAErB,OAAO;CAEX,QAAQ;EACN;CACF;AAEF;;;;;;;AAQA,MAAa,0BAA0B;;AAGvC,MAAa,sBAAsB;;;;;;;AAQnC,MAAa,6BAA6B;;AAG1C,SAAgB,qBAAqB,KAAqB;CACxD,OAAO,SAAS,IAAI;AACtB;;AAGA,SAAgB,kBAAkB,WAAmB,MAAsB;CACzE,OAAO,OAAO,UAAU,MAAM;AAChC;AAqEA,MAAM,gCAA6C,IAAI,IAAoB;;;;;;;AAQ3E,IAAM,iBAAN,MAAqB;CACnB,0BAA+B,IAAI,IAAI;CACvC,YAAoB;CACpB,cAAsB;CACtB,uCAAoC,IAAI,IAAI;AAC9C;;;;;AAMA,MAAM,eAAe;;;;;;;AAQrB,MAAM,0BAA0B;;;;;;;;;;;;AAahC,IAAa,8BAAb,MAAa,4BAA4B;CACvC,4BAAiD,IAAI,IAAI;CACzD;CACA;CACA;;;;;;CAMA,OAAwB,sBAAsB;CAE9C,YAAY,UAA8C,CAAC,GAA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G,iBAAiB;EACjE;CACF,CAAC;AACH;;;;;;;;AASA,SAAS,0BACP,QACqC;CACrC,IAAI,UAAU,MAAM,OAAO,KAAA;CAC3B,IACE,EAAE,aAAa,WACf,EAAE,eAAe,WACjB,EAAE,qBAAqB,SAEvB,OAAO;CAET,MAAM,EAAE,SAAS,WAAW,iBAAiB,GAAG,SAAS;CAWzD,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,WAAW,IAAI,KAAA,IAAY;AACtD"}
@@ -1,10 +1,10 @@
1
1
  require("./misc.cjs");
2
2
  require("./truncation.cjs");
3
3
  require("./tokens.cjs");
4
- require("./llm.cjs");
5
- require("./errors.cjs");
6
4
  require("./graph.cjs");
5
+ require("./llm.cjs");
7
6
  require("./proxy.cjs");
8
7
  require("./handlers.cjs");
9
8
  require("./run.cjs");
10
9
  require("./schema.cjs");
10
+ require("./errors.cjs");