@librechat/agents 4.1.0 → 4.2.0

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 (204) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +9 -1
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/constants.cjs +2 -0
  4. package/dist/cjs/common/constants.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +15 -12
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/graphs/MultiAgentGraph.cjs +1 -1
  8. package/dist/cjs/hitl/approvalReview.cjs +10 -2
  9. package/dist/cjs/hitl/approvalReview.cjs.map +1 -1
  10. package/dist/cjs/llm/anthropic/defaults.cjs +12 -0
  11. package/dist/cjs/llm/anthropic/defaults.cjs.map +1 -0
  12. package/dist/cjs/llm/anthropic/index.cjs +6 -0
  13. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  14. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +1 -1
  15. package/dist/cjs/llm/google/utils/common.cjs +1 -1
  16. package/dist/cjs/llm/init.cjs +5 -2
  17. package/dist/cjs/llm/init.cjs.map +1 -1
  18. package/dist/cjs/llm/invoke.cjs +17 -15
  19. package/dist/cjs/llm/invoke.cjs.map +1 -1
  20. package/dist/cjs/llm/openai/index.cjs +1 -1
  21. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  22. package/dist/cjs/llm/request.cjs +13 -0
  23. package/dist/cjs/llm/request.cjs.map +1 -1
  24. package/dist/cjs/llm/stream/chunkAdapters.cjs +2 -3
  25. package/dist/cjs/llm/stream/chunkAdapters.cjs.map +1 -1
  26. package/dist/cjs/llm/truncation.cjs +12 -2
  27. package/dist/cjs/llm/truncation.cjs.map +1 -1
  28. package/dist/cjs/main.cjs +7 -4
  29. package/dist/cjs/messages/core.cjs +1 -1
  30. package/dist/cjs/messages/format.cjs +1 -1
  31. package/dist/cjs/messages/index.cjs +1 -1
  32. package/dist/cjs/messages/prune.cjs +2 -2
  33. package/dist/cjs/messages/reasoningTypes.cjs +20 -0
  34. package/dist/cjs/messages/reasoningTypes.cjs.map +1 -1
  35. package/dist/cjs/messages/recency.cjs +68 -7
  36. package/dist/cjs/messages/recency.cjs.map +1 -1
  37. package/dist/cjs/run.cjs +135 -54
  38. package/dist/cjs/run.cjs.map +1 -1
  39. package/dist/cjs/session/AgentSession.cjs +7 -10
  40. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  41. package/dist/cjs/stream.cjs +3 -2
  42. package/dist/cjs/stream.cjs.map +1 -1
  43. package/dist/cjs/summarization/input.cjs +87 -0
  44. package/dist/cjs/summarization/input.cjs.map +1 -0
  45. package/dist/cjs/summarization/node.cjs +470 -135
  46. package/dist/cjs/summarization/node.cjs.map +1 -1
  47. package/dist/cjs/summarization/retry.cjs +172 -0
  48. package/dist/cjs/summarization/retry.cjs.map +1 -0
  49. package/dist/cjs/summarization/shared.cjs +6 -2
  50. package/dist/cjs/summarization/shared.cjs.map +1 -1
  51. package/dist/cjs/summarization/toolBudget.cjs +45 -0
  52. package/dist/cjs/summarization/toolBudget.cjs.map +1 -0
  53. package/dist/cjs/summarization/usage.cjs +70 -0
  54. package/dist/cjs/summarization/usage.cjs.map +1 -0
  55. package/dist/cjs/tools/ToolNode.cjs +46 -16
  56. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  57. package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs.map +1 -1
  58. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +155 -18
  59. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  60. package/dist/cjs/tools/subagent/SubagentReplay.cjs +6 -1
  61. package/dist/cjs/tools/subagent/SubagentReplay.cjs.map +1 -1
  62. package/dist/cjs/tools/subagent/childGraphConfig.cjs +2 -1
  63. package/dist/cjs/tools/subagent/childGraphConfig.cjs.map +1 -1
  64. package/dist/cjs/tools/toolBatchReplay.cjs +182 -6
  65. package/dist/cjs/tools/toolBatchReplay.cjs.map +1 -1
  66. package/dist/cjs/utils/errors.cjs +21 -0
  67. package/dist/cjs/utils/errors.cjs.map +1 -1
  68. package/dist/cjs/utils/index.cjs +1 -1
  69. package/dist/cjs/utils/schema.cjs +17 -0
  70. package/dist/cjs/utils/schema.cjs.map +1 -1
  71. package/dist/esm/agents/AgentContext.mjs +9 -1
  72. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  73. package/dist/esm/common/constants.mjs +2 -1
  74. package/dist/esm/common/constants.mjs.map +1 -1
  75. package/dist/esm/graphs/Graph.mjs +16 -13
  76. package/dist/esm/graphs/Graph.mjs.map +1 -1
  77. package/dist/esm/graphs/MultiAgentGraph.mjs +1 -1
  78. package/dist/esm/hitl/approvalReview.mjs +10 -2
  79. package/dist/esm/hitl/approvalReview.mjs.map +1 -1
  80. package/dist/esm/llm/anthropic/defaults.mjs +12 -0
  81. package/dist/esm/llm/anthropic/defaults.mjs.map +1 -0
  82. package/dist/esm/llm/anthropic/index.mjs +6 -0
  83. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  84. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +1 -1
  85. package/dist/esm/llm/google/utils/common.mjs +1 -1
  86. package/dist/esm/llm/init.mjs +5 -2
  87. package/dist/esm/llm/init.mjs.map +1 -1
  88. package/dist/esm/llm/invoke.mjs +18 -16
  89. package/dist/esm/llm/invoke.mjs.map +1 -1
  90. package/dist/esm/llm/openai/index.mjs +1 -1
  91. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  92. package/dist/esm/llm/request.mjs +13 -1
  93. package/dist/esm/llm/request.mjs.map +1 -1
  94. package/dist/esm/llm/stream/chunkAdapters.mjs +2 -3
  95. package/dist/esm/llm/stream/chunkAdapters.mjs.map +1 -1
  96. package/dist/esm/llm/truncation.mjs +12 -3
  97. package/dist/esm/llm/truncation.mjs.map +1 -1
  98. package/dist/esm/main.mjs +8 -8
  99. package/dist/esm/messages/core.mjs +1 -1
  100. package/dist/esm/messages/format.mjs +1 -1
  101. package/dist/esm/messages/index.mjs +1 -1
  102. package/dist/esm/messages/prune.mjs +2 -2
  103. package/dist/esm/messages/reasoningTypes.mjs +19 -1
  104. package/dist/esm/messages/reasoningTypes.mjs.map +1 -1
  105. package/dist/esm/messages/recency.mjs +68 -8
  106. package/dist/esm/messages/recency.mjs.map +1 -1
  107. package/dist/esm/run.mjs +135 -54
  108. package/dist/esm/run.mjs.map +1 -1
  109. package/dist/esm/session/AgentSession.mjs +7 -10
  110. package/dist/esm/session/AgentSession.mjs.map +1 -1
  111. package/dist/esm/stream.mjs +3 -2
  112. package/dist/esm/stream.mjs.map +1 -1
  113. package/dist/esm/summarization/input.mjs +84 -0
  114. package/dist/esm/summarization/input.mjs.map +1 -0
  115. package/dist/esm/summarization/node.mjs +469 -133
  116. package/dist/esm/summarization/node.mjs.map +1 -1
  117. package/dist/esm/summarization/retry.mjs +169 -0
  118. package/dist/esm/summarization/retry.mjs.map +1 -0
  119. package/dist/esm/summarization/shared.mjs +6 -2
  120. package/dist/esm/summarization/shared.mjs.map +1 -1
  121. package/dist/esm/summarization/toolBudget.mjs +45 -0
  122. package/dist/esm/summarization/toolBudget.mjs.map +1 -0
  123. package/dist/esm/summarization/usage.mjs +69 -0
  124. package/dist/esm/summarization/usage.mjs.map +1 -0
  125. package/dist/esm/tools/ToolNode.mjs +46 -16
  126. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  127. package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs.map +1 -1
  128. package/dist/esm/tools/subagent/SubagentExecutor.mjs +156 -19
  129. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  130. package/dist/esm/tools/subagent/SubagentReplay.mjs +6 -1
  131. package/dist/esm/tools/subagent/SubagentReplay.mjs.map +1 -1
  132. package/dist/esm/tools/subagent/childGraphConfig.mjs +2 -1
  133. package/dist/esm/tools/subagent/childGraphConfig.mjs.map +1 -1
  134. package/dist/esm/tools/toolBatchReplay.mjs +178 -7
  135. package/dist/esm/tools/toolBatchReplay.mjs.map +1 -1
  136. package/dist/esm/utils/errors.mjs +21 -1
  137. package/dist/esm/utils/errors.mjs.map +1 -1
  138. package/dist/esm/utils/index.mjs +1 -1
  139. package/dist/esm/utils/schema.mjs +17 -0
  140. package/dist/esm/utils/schema.mjs.map +1 -1
  141. package/dist/types/agents/AgentContext.d.ts +2 -0
  142. package/dist/types/common/constants.d.ts +2 -0
  143. package/dist/types/hitl/approvalReview.d.ts +1 -1
  144. package/dist/types/llm/anthropic/defaults.d.ts +11 -0
  145. package/dist/types/llm/init.d.ts +2 -1
  146. package/dist/types/llm/invoke.d.ts +8 -1
  147. package/dist/types/llm/request.d.ts +12 -0
  148. package/dist/types/llm/stream/chunkAdapters.d.ts +1 -1
  149. package/dist/types/llm/truncation.d.ts +2 -0
  150. package/dist/types/messages/reasoningTypes.d.ts +6 -0
  151. package/dist/types/messages/recency.d.ts +2 -0
  152. package/dist/types/run.d.ts +3 -0
  153. package/dist/types/summarization/input.d.ts +16 -0
  154. package/dist/types/summarization/node.d.ts +2 -1
  155. package/dist/types/summarization/retry.d.ts +22 -0
  156. package/dist/types/summarization/shared.d.ts +3 -3
  157. package/dist/types/summarization/toolBudget.d.ts +8 -0
  158. package/dist/types/summarization/usage.d.ts +9 -0
  159. package/dist/types/tools/subagent/SubagentReplay.d.ts +3 -1
  160. package/dist/types/tools/toolBatchReplay.d.ts +14 -1
  161. package/dist/types/types/graph.d.ts +2 -1
  162. package/dist/types/types/hitl.d.ts +2 -0
  163. package/dist/types/types/llm.d.ts +3 -0
  164. package/dist/types/types/run.d.ts +1 -1
  165. package/dist/types/types/summarize.d.ts +15 -3
  166. package/dist/types/utils/errors.d.ts +2 -0
  167. package/dist/types/utils/schema.d.ts +1 -1
  168. package/package.json +13 -4
  169. package/src/agents/AgentContext.ts +7 -0
  170. package/src/common/constants.ts +3 -0
  171. package/src/graphs/Graph.ts +16 -21
  172. package/src/hitl/approvalReview.ts +10 -2
  173. package/src/llm/anthropic/defaults.ts +22 -0
  174. package/src/llm/anthropic/index.ts +15 -2
  175. package/src/llm/init.ts +16 -2
  176. package/src/llm/invoke.ts +33 -14
  177. package/src/llm/openai/utils/index.ts +2 -4
  178. package/src/llm/request.ts +44 -0
  179. package/src/llm/stream/chunkAdapters.ts +14 -18
  180. package/src/llm/truncation.ts +33 -17
  181. package/src/messages/reasoningTypes.ts +71 -0
  182. package/src/messages/recency.ts +78 -0
  183. package/src/run.ts +190 -81
  184. package/src/session/AgentSession.ts +8 -11
  185. package/src/stream.ts +1 -0
  186. package/src/summarization/input.ts +98 -0
  187. package/src/summarization/node.ts +749 -356
  188. package/src/summarization/retry.ts +294 -0
  189. package/src/summarization/shared.ts +9 -2
  190. package/src/summarization/toolBudget.ts +87 -0
  191. package/src/summarization/usage.ts +117 -0
  192. package/src/tools/ToolNode.ts +84 -23
  193. package/src/tools/cloudflare/CloudflareBridgeRuntime.ts +2 -2
  194. package/src/tools/subagent/SubagentExecutor.ts +227 -32
  195. package/src/tools/subagent/SubagentReplay.ts +30 -1
  196. package/src/tools/subagent/childGraphConfig.ts +9 -2
  197. package/src/tools/toolBatchReplay.ts +237 -7
  198. package/src/types/graph.ts +2 -1
  199. package/src/types/hitl.ts +4 -0
  200. package/src/types/llm.ts +4 -0
  201. package/src/types/run.ts +6 -3
  202. package/src/types/summarize.ts +22 -3
  203. package/src/utils/errors.ts +45 -0
  204. package/src/utils/schema.ts +26 -2
@@ -154,15 +154,22 @@ function assertGraphSubagentConfigShape(
154
154
  `Graph subagent "${configType}" maxTurns must be a positive safe integer.`
155
155
  );
156
156
  }
157
+ if (
158
+ candidate.configId !== undefined &&
159
+ !isNonEmptyString(candidate.configId)
160
+ ) {
161
+ throw new Error(
162
+ `Graph subagent "${configType}" configId must be a non-empty revision.`
163
+ );
164
+ }
157
165
  if (
158
166
  candidate.agentInputs !== undefined ||
159
167
  candidate.resolveAgentInputs !== undefined ||
160
- candidate.configId !== undefined ||
161
168
  candidate.hostArgs !== undefined ||
162
169
  candidate.self !== undefined
163
170
  ) {
164
171
  throw new Error(
165
- `Graph subagent "${configType}" cannot define agentInputs or self, or lazy fields configId/resolveAgentInputs/hostArgs.`
172
+ `Graph subagent "${configType}" cannot define agentInputs or self, or lazy fields resolveAgentInputs/hostArgs.`
166
173
  );
167
174
  }
168
175
  }
@@ -1,17 +1,18 @@
1
- import { Command, MemorySaver, isCommand } from '@langchain/langgraph';
2
1
  import { isBaseMessage } from '@langchain/core/messages';
3
- import type { BaseMessage } from '@langchain/core/messages';
2
+ import { Command, MemorySaver, isCommand } from '@langchain/langgraph';
4
3
  import type { RunnableConfig } from '@langchain/core/runnables';
5
- import type { SubagentToolNodeResumeState } from '@/tools/subagent/SubagentReplay';
4
+ import type { BaseMessage } from '@langchain/core/messages';
5
+ import type { Interrupt } from '@langchain/langgraph';
6
+ import type { SubagentResumeManifest, SubagentToolNodeResumeState } from '@/tools/subagent/SubagentReplay';
6
7
  import type { ToolOutputReferenceState } from '@/tools/toolOutputReferences';
8
+ import type { ToolApprovalReviewEvidence } from '@/hitl/approvalReview';
7
9
  import {
8
10
  isToolNodeResumeState,
9
11
  isToolOutputReferenceState,
10
12
  stripSubagentResumeManifest,
11
13
  requireValidSubagentResumeManifest,
14
+ SUBAGENT_RESUME_MANIFEST_CONFIG_KEY,
12
15
  } from '@/tools/subagent/SubagentReplay';
13
- import { isToolApprovalInterrupt } from '@/types/hitl';
14
- import { TOOL_APPROVAL_EXECUTION_SCOPE_CONFIG_KEY } from '@/hooks/types';
15
16
  import {
16
17
  TOOL_APPROVAL_REVIEW_CONFIG_KEY,
17
18
  getToolApprovalReviewEvidence,
@@ -22,8 +23,13 @@ import {
22
23
  getRunStepResumeState,
23
24
  stripRunStepResumeState,
24
25
  } from '@/tools/runStepResume';
26
+ import { TOOL_APPROVAL_EXECUTION_SCOPE_CONFIG_KEY } from '@/hooks/types';
27
+ import { stableStringify } from '@/tools/eagerEventExecution';
28
+ import { isToolApprovalInterrupt } from '@/types/hitl';
25
29
 
26
30
  export const TOOL_BATCH_REPLAY_KEY = '__librechat_tool_batch_replay';
31
+ export const TOOL_REPLAY_CONFIGS_KEY = '__librechat_tool_replay_configs';
32
+ export const TOOL_PENDING_APPROVAL_KEY = '__librechat_tool_pending_approval';
27
33
  const TOOL_BATCH_PAYLOAD_KEY = '__librechat_tool_batch_payload';
28
34
  const TOOL_BATCH_WRAPPER_KEY = '__librechat_tool_batch_wrapper';
29
35
 
@@ -59,6 +65,21 @@ interface ToolBatchReplayState {
59
65
  wrappedPayload?: boolean;
60
66
  }
61
67
 
68
+ interface CheckpointPendingApproval extends ToolApprovalReviewEvidence {
69
+ value: Interrupt['value'];
70
+ }
71
+
72
+ export function getCheckpointPendingApproval(config: RunnableConfig): CheckpointPendingApproval | undefined {
73
+ return config.configurable?.[TOOL_PENDING_APPROVAL_KEY] as CheckpointPendingApproval | undefined;
74
+ }
75
+
76
+ type ToolReplayConfig = {
77
+ [TOOL_PENDING_APPROVAL_KEY]?: CheckpointPendingApproval;
78
+ [TOOL_BATCH_REPLAY_KEY]?: ToolBatchReplayState;
79
+ [TOOL_APPROVAL_REVIEW_CONFIG_KEY]?: ToolApprovalReviewEvidence;
80
+ [SUBAGENT_RESUME_MANIFEST_CONFIG_KEY]?: SubagentResumeManifest;
81
+ };
82
+
62
83
  /** Use the same message/Command codec as LangGraph checkpoints. */
63
84
  const serializer = new MemorySaver().serde;
64
85
 
@@ -112,6 +133,7 @@ export function restoreToolReplayConfig(
112
133
  ): void {
113
134
  delete configurable[TOOL_BATCH_REPLAY_KEY];
114
135
  delete configurable[TOOL_APPROVAL_REVIEW_CONFIG_KEY];
136
+ delete configurable[TOOL_PENDING_APPROVAL_KEY];
115
137
  const state = bindLegacyReplayState(
116
138
  getToolBatchReplayState(payload),
117
139
  configurable
@@ -131,7 +153,204 @@ export function restoreToolReplayConfig(
131
153
  }
132
154
  if (review != null) {
133
155
  configurable[TOOL_APPROVAL_REVIEW_CONFIG_KEY] = review;
156
+ configurable[TOOL_PENDING_APPROVAL_KEY] = { ...review, value: payload } satisfies CheckpointPendingApproval;
157
+ }
158
+ }
159
+
160
+ /** Several child proposals can carry the same parent's checkpointed batch. */
161
+ function mergeParentReplayConfig(
162
+ left: ToolReplayConfig,
163
+ right: ToolReplayConfig
164
+ ): ToolReplayConfig {
165
+ const leftState = left[TOOL_BATCH_REPLAY_KEY];
166
+ const rightState = right[TOOL_BATCH_REPLAY_KEY];
167
+ const records = new Map<string, ToolBatchReplayRecord>();
168
+ for (const record of [...(leftState?.records ?? []), ...(rightState?.records ?? [])]) {
169
+ const key = JSON.stringify([record.owner, record.batch]);
170
+ const previous = records.get(key);
171
+ if (previous != null && stableStringify(previous) !== stableStringify(record)) {
172
+ throw new Error('Conflicting parent tool replay checkpoint records');
173
+ }
174
+ records.set(key, record);
175
+ }
176
+ const manifest = left[SUBAGENT_RESUME_MANIFEST_CONFIG_KEY];
177
+ const other = right[SUBAGENT_RESUME_MANIFEST_CONFIG_KEY];
178
+ const executions = new Map<string, SubagentResumeManifest['executions'][number]>();
179
+ for (const execution of [...(manifest?.executions ?? []), ...(other?.executions ?? [])]) {
180
+ const key = JSON.stringify([execution.parentToolCallId, execution.childRunId]);
181
+ const previous = executions.get(key);
182
+ if (previous != null && stableStringify(previous) !== stableStringify(execution)) {
183
+ throw new Error('Conflicting parent subagent checkpoint manifests');
184
+ }
185
+ executions.set(key, execution);
134
186
  }
187
+ const review = left[TOOL_APPROVAL_REVIEW_CONFIG_KEY] ?? right[TOOL_APPROVAL_REVIEW_CONFIG_KEY];
188
+ return {
189
+ [TOOL_APPROVAL_REVIEW_CONFIG_KEY]: review,
190
+ [TOOL_BATCH_REPLAY_KEY]: {
191
+ ...(leftState ?? rightState),
192
+ version: 1,
193
+ records: [...records.values()],
194
+ approvalOwner: review?.owner,
195
+ interruptId: review?.interruptId ?? leftState?.interruptId ?? rightState?.interruptId,
196
+ },
197
+ [SUBAGENT_RESUME_MANIFEST_CONFIG_KEY]: executions.size === 0
198
+ ? undefined : { version: 1, executions: [...executions.values()] },
199
+ };
200
+ }
201
+
202
+ /** Restore each checkpointed interrupt without sharing member authorization. */
203
+ export function restoreToolReplayConfigs(
204
+ configurable: NonNullable<RunnableConfig['configurable']>,
205
+ interrupts: readonly Interrupt[],
206
+ sourceScope: string,
207
+ destinationScope: string,
208
+ destinationThreadId: string,
209
+ resumedInterruptIds: ReadonlySet<string>
210
+ ): void {
211
+ delete configurable[TOOL_REPLAY_CONFIGS_KEY];
212
+ delete configurable[TOOL_PENDING_APPROVAL_KEY];
213
+ const configs = new Map<string, ToolReplayConfig>();
214
+ const parents = new Map<string, ToolReplayConfig>();
215
+ let first: ToolReplayConfig | undefined;
216
+ for (const pending of interrupts) {
217
+ const restored: ToolReplayConfig &
218
+ NonNullable<RunnableConfig['configurable']> = {
219
+ user_id: configurable.user_id,
220
+ thread_id: configurable.thread_id,
221
+ };
222
+ restoreToolReplayConfig(restored, pending.id, pending.value);
223
+ rebindToolBatchReplayScope(
224
+ restored,
225
+ sourceScope,
226
+ destinationScope,
227
+ destinationThreadId
228
+ );
229
+ const replay = restored[TOOL_BATCH_REPLAY_KEY];
230
+ const review = restored[TOOL_APPROVAL_REVIEW_CONFIG_KEY];
231
+ const resumed = pending.id != null && resumedInterruptIds.has(pending.id);
232
+ const payload = stripRunStepResumeState(pending.value);
233
+ const manifest =
234
+ requireValidSubagentResumeManifest(payload) ??
235
+ requireValidSubagentResumeManifest(stripToolBatchReplayState(payload));
236
+ const evidence: ToolReplayConfig = {
237
+ [TOOL_PENDING_APPROVAL_KEY]: getCheckpointPendingApproval({ configurable: restored }),
238
+ [SUBAGENT_RESUME_MANIFEST_CONFIG_KEY]: manifest,
239
+ [TOOL_BATCH_REPLAY_KEY]: resumed || replay == null
240
+ ? replay
241
+ : { ...replay, approvalOwner: undefined },
242
+ [TOOL_APPROVAL_REVIEW_CONFIG_KEY]: resumed ? review : undefined,
243
+ };
244
+ if (resumed) first ??= evidence;
245
+ const childScopes = new Set<string>();
246
+ const executions = [...(manifest?.executions ?? [])];
247
+ while (executions.length > 0) {
248
+ const execution = executions.pop()!;
249
+ if (execution.descendant == null) {
250
+ childScopes.add(execution.approvalExecutionScope);
251
+ } else executions.push(...execution.descendant.executions);
252
+ }
253
+ const memberRecords = manifest == null
254
+ ? replay?.records ?? []
255
+ : (replay?.records ?? []).filter((record) => {
256
+ const identity: unknown = JSON.parse(record.owner);
257
+ return Array.isArray(identity) && childScopes.has(identity[0]);
258
+ });
259
+ const owner = review?.owner ?? replay?.approvalOwner;
260
+ if (owner == null && memberRecords.length === 0) configs.set('', {
261
+ [TOOL_PENDING_APPROVAL_KEY]: undefined,
262
+ [SUBAGENT_RESUME_MANIFEST_CONFIG_KEY]: undefined,
263
+ [TOOL_BATCH_REPLAY_KEY]: undefined,
264
+ [TOOL_APPROVAL_REVIEW_CONFIG_KEY]: undefined,
265
+ });
266
+ const owners = owner == null
267
+ ? new Set(memberRecords.map(record => record.owner))
268
+ : new Set([owner]);
269
+ for (const owner of owners) {
270
+ if (configs.has(owner)) {
271
+ throw new Error('Ambiguous tool replay checkpoint owner');
272
+ }
273
+ configs.set(owner, evidence);
274
+ }
275
+ if (manifest != null) {
276
+ for (const record of replay?.records ?? []) {
277
+ if (owners.has(record.owner)) continue;
278
+ const previous = parents.get(record.owner);
279
+ parents.set(
280
+ record.owner,
281
+ previous == null ? evidence : mergeParentReplayConfig(previous, evidence)
282
+ );
283
+ }
284
+ }
285
+ }
286
+ for (const [owner, evidence] of parents) {
287
+ if (!configs.has(owner)) configs.set(owner, evidence);
288
+ }
289
+ delete configurable[TOOL_BATCH_REPLAY_KEY];
290
+ delete configurable[TOOL_APPROVAL_REVIEW_CONFIG_KEY];
291
+ Object.assign(configurable, first);
292
+ if (first != null && first[SUBAGENT_RESUME_MANIFEST_CONFIG_KEY] === undefined) {
293
+ delete configurable[SUBAGENT_RESUME_MANIFEST_CONFIG_KEY];
294
+ }
295
+ if (configs.size > 1) configurable[TOOL_REPLAY_CONFIGS_KEY] = configs;
296
+ }
297
+
298
+ export function matchesToolReplayBatch(saved: string, current: string | undefined, messageId?: string): boolean {
299
+ if (saved === current) return true;
300
+ if (messageId == null || messageId === '') return false;
301
+ const identity: unknown = JSON.parse(saved);
302
+ return Array.isArray(identity) && identity[1] === messageId;
303
+ }
304
+
305
+ /** Select a member's evidence before the unchanged owner/proposal safeguards. */
306
+ export function getToolReplayConfig(
307
+ config: RunnableConfig,
308
+ owner: string,
309
+ batch?: string,
310
+ messageId?: string
311
+ ): RunnableConfig {
312
+ const candidate = config.configurable?.[TOOL_REPLAY_CONFIGS_KEY];
313
+ if (!(candidate instanceof Map)) return config;
314
+ const configs = candidate as ReadonlyMap<string, ToolReplayConfig>;
315
+ let evidence = configs.get(owner);
316
+ if (evidence == null && configs.has('')) {
317
+ const identity: unknown = JSON.parse(owner);
318
+ if (Array.isArray(identity)) {
319
+ const execution = JSON.stringify(identity.map((part, index) => index === 2 ? '' : part));
320
+ for (const key of configs.keys()) {
321
+ if (key === '') continue;
322
+ const sibling: unknown = JSON.parse(key);
323
+ if (Array.isArray(sibling) && execution === JSON.stringify(sibling.map((part, index) => index === 2 ? '' : part))) {
324
+ evidence = configs.get('');
325
+ break;
326
+ }
327
+ }
328
+ }
329
+ if (evidence == null) throw new Error('Tool replay execution identity changed before resume');
330
+ }
331
+ if (evidence == null) {
332
+ let hasApproval = false;
333
+ let hasCheckpointBatch = false;
334
+ for (const pending of configs.values()) {
335
+ const replay = pending[TOOL_BATCH_REPLAY_KEY];
336
+ hasApproval ||= pending[TOOL_PENDING_APPROVAL_KEY] != null || pending[TOOL_APPROVAL_REVIEW_CONFIG_KEY] != null || replay?.approvalOwner != null;
337
+ hasCheckpointBatch ||= batch != null && replay?.records.some((record) => matchesToolReplayBatch(record.batch, batch, messageId)) === true;
338
+ }
339
+ if (hasApproval && (hasCheckpointBatch || getToolReplayResumeStatus(config, undefined, false) !== 'stale')) {
340
+ throw new Error('Tool approval execution owner changed before resume — failing closed');
341
+ }
342
+ }
343
+ const configurable: NonNullable<RunnableConfig['configurable']> = { ...config.configurable };
344
+ delete configurable[TOOL_REPLAY_CONFIGS_KEY];
345
+ delete configurable[TOOL_PENDING_APPROVAL_KEY];
346
+ delete configurable[TOOL_BATCH_REPLAY_KEY];
347
+ delete configurable[TOOL_APPROVAL_REVIEW_CONFIG_KEY];
348
+ delete configurable[SUBAGENT_RESUME_MANIFEST_CONFIG_KEY];
349
+ Object.assign(configurable, evidence);
350
+ if (configurable[SUBAGENT_RESUME_MANIFEST_CONFIG_KEY] === undefined) {
351
+ delete configurable[SUBAGENT_RESUME_MANIFEST_CONFIG_KEY];
352
+ }
353
+ return { ...config, configurable };
135
354
  }
136
355
 
137
356
  /**
@@ -202,6 +421,8 @@ export function clearStaleToolApprovalConfig(
202
421
  batch: string | undefined
203
422
  ): void {
204
423
  delete configurable[TOOL_APPROVAL_REVIEW_CONFIG_KEY];
424
+ delete configurable[TOOL_PENDING_APPROVAL_KEY];
425
+ delete configurable[TOOL_REPLAY_CONFIGS_KEY];
205
426
  const state = getToolBatchReplayState(configurable);
206
427
  const records = batch == null
207
428
  ? []
@@ -275,6 +496,13 @@ export function rebindToolBatchReplayScope(
275
496
  owner: rebind(review.owner),
276
497
  };
277
498
  }
499
+ const pending = getCheckpointPendingApproval(config);
500
+ if (pending?.owner != null) {
501
+ configurable[TOOL_PENDING_APPROVAL_KEY] = {
502
+ ...pending, owner: rebind(pending.owner),
503
+ value: rebindToolBatchReplayPayload(pending.value, sourceScope, destinationScope, destinationThreadId),
504
+ };
505
+ }
278
506
  const state = getToolBatchReplayState(configurable);
279
507
  if (state != null) {
280
508
  configurable[TOOL_BATCH_REPLAY_KEY] = {
@@ -418,8 +646,10 @@ export async function attachToolBatchReplayState(
418
646
  if (records.length === 0 && approvalOwner == null) {
419
647
  return payload;
420
648
  }
649
+ const inline = isRecord(publicPayload) &&
650
+ Object.getPrototypeOf(publicPayload) === Object.prototype;
421
651
  const result = {
422
- ...(isRecord(publicPayload)
652
+ ...(inline
423
653
  ? publicPayload
424
654
  : {
425
655
  [TOOL_BATCH_WRAPPER_KEY]: 1,
@@ -429,7 +659,7 @@ export async function attachToolBatchReplayState(
429
659
  version: 1,
430
660
  approvalOwner,
431
661
  records,
432
- wrappedPayload: previous?.wrappedPayload ?? !isRecord(publicPayload),
662
+ wrappedPayload: previous?.wrappedPayload ?? !inline,
433
663
  } satisfies ToolBatchReplayState,
434
664
  };
435
665
  const runStepState = getRunStepResumeState(payload);
@@ -677,7 +677,8 @@ export interface SingleAgentSubagentConfig extends SubagentConfig {
677
677
 
678
678
  export interface GraphSubagentConfig extends SubagentConfigBase {
679
679
  kind: 'graph';
680
- configId?: never;
680
+ /** Host revision for executable implementations. Required for HITL executable tools, functional prompts, and opaque member options. */
681
+ configId?: string;
681
682
  resolveAgentInputs?: never;
682
683
  hostArgs?: never;
683
684
  allowNested?: false;
package/src/types/hitl.ts CHANGED
@@ -457,4 +457,8 @@ export interface RunInterruptResult<TPayload = HumanInterruptPayload> {
457
457
  checkpointNs?: string;
458
458
  /** Structured payload describing what needs human input. */
459
459
  payload: TPayload;
460
+ /** All pending proposals keyed by the interrupt IDs accepted by `Run.resume()`. */
461
+ pendingInterrupts?: Array<
462
+ Pick<RunInterruptResult<TPayload>, 'interruptId' | 'payload'>
463
+ >;
460
464
  }
package/src/types/llm.ts CHANGED
@@ -226,9 +226,13 @@ export type ProviderClientOptionsConfig =
226
226
  clientOptions: ClientOptions;
227
227
  };
228
228
 
229
+ export type ContextBudgetMode = 'input' | 'window';
230
+
229
231
  export type FallbackConfig = ProviderClientOptionsConfig & {
230
232
  /** Context window used to corroborate ambiguous fallback overflow errors. */
231
233
  maxContextTokens?: number;
234
+ /** Applies to an explicit maxContextTokens; inherited ceilings retain their source units. */
235
+ contextBudgetMode?: ContextBudgetMode;
232
236
  };
233
237
 
234
238
  type LLMConfigFor<P extends CustomProviderName> = SharedLLMConfig<P> &
package/src/types/run.ts CHANGED
@@ -18,8 +18,7 @@ import type * as e from '@/common/enum';
18
18
  import type * as g from '@/types/graph';
19
19
  import type * as l from '@/types/llm';
20
20
 
21
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
22
- export type ZodObjectAny = z.ZodObject<any, any, any, any>;
21
+ export type ZodObjectAny = z.ZodObject;
23
22
  export type BaseGraphConfig = {
24
23
  llmConfig: l.LLMConfig;
25
24
  provider?: l.ProviderName;
@@ -35,7 +34,11 @@ export type LegacyGraphConfig = BaseGraphConfig & {
35
34
  * via the top-level `RunConfig.streamLimits`; accepting the field here
36
35
  * would type-check but be silently ignored by `createLegacyGraph`.
37
36
  * Required provider-text protection also belongs only to RunConfig. */
38
- 'provider' | 'clientOptions' | 'agents' | 'streamLimits' | 'providerTextProtection'
37
+ | 'provider'
38
+ | 'clientOptions'
39
+ | 'agents'
40
+ | 'streamLimits'
41
+ | 'providerTextProtection'
39
42
  > &
40
43
  Omit<g.AgentInputs, 'provider' | 'clientOptions' | 'agentId'>;
41
44
 
@@ -1,5 +1,6 @@
1
+ import type { UsageMetadata, BaseMessage } from '@langchain/core/messages';
2
+ import type { ProviderName, ContextBudgetMode } from '@/types/llm';
1
3
  import type { SummaryContentBlock } from '@/types/stream';
2
- import type { ProviderName } from '@/types/llm';
3
4
 
4
5
  export type SummarizationTrigger = {
5
6
  type:
@@ -97,6 +98,8 @@ export type SummarizationConfig = {
97
98
  updatePrompt?: string;
98
99
  trigger?: SummarizationTrigger;
99
100
  maxSummaryTokens?: number;
101
+ /** maxContextTokens is an input ceiling by default; use window for a full model window. */
102
+ contextBudgetMode?: ContextBudgetMode;
100
103
  /** Fraction of the token budget reserved as headroom (0–1). Defaults to 0.05. */
101
104
  reserveRatio?: number;
102
105
  /**
@@ -118,6 +121,8 @@ export interface SummarizeResult {
118
121
  export interface SummarizationNodeInput {
119
122
  remainingContextTokens: number;
120
123
  agentId: string;
124
+ /** Pruned, masked provider history from the turn requesting compaction. */
125
+ windowMessages?: BaseMessage[];
121
126
  /**
122
127
  * Why the detour was requested.
123
128
  *
@@ -128,8 +133,7 @@ export interface SummarizationNodeInput {
128
133
  * variant performs no model call — the corrected budget alone is what the
129
134
  * retry needs.
130
135
  * - `manual`: the host asked for a summary outright (a summarize-only run).
131
- * The recency window is not applied unless the host configured
132
- * `retainRecent` explicitly, so the summary replaces the whole history.
136
+ * Uses the same bounded recent-tail policy as automatic compaction.
133
137
  */
134
138
  reason?: 'trigger' | 'overflow' | 'manual';
135
139
  /**
@@ -165,9 +169,24 @@ export interface SummarizeDeltaEvent {
165
169
  };
166
170
  }
167
171
 
172
+ export type SummarizationErrorCode =
173
+ | 'provider_overloaded'
174
+ | 'rate_limited'
175
+ | 'context_exceeded'
176
+ | 'timeout'
177
+ | 'unknown';
178
+
179
+ export interface SummarizationAttemptUsage {
180
+ provider: ProviderName;
181
+ model?: string;
182
+ usage: Partial<UsageMetadata>;
183
+ }
184
+
168
185
  export interface SummarizeCompleteEvent {
169
186
  id: string;
170
187
  agentId: string;
171
188
  summary?: SummaryContentBlock;
172
189
  error?: string;
190
+ errorCode?: SummarizationErrorCode;
191
+ attemptUsage?: readonly SummarizationAttemptUsage[];
173
192
  }
@@ -242,6 +242,7 @@ const CONTEXT_OVERFLOW_HINT_RE =
242
242
  const MAX_CAUSE_DEPTH = 4;
243
243
 
244
244
  interface NestedErrorShape {
245
+ name?: string;
245
246
  message?: unknown;
246
247
  code?: unknown;
247
248
  type?: unknown;
@@ -249,6 +250,7 @@ interface NestedErrorShape {
249
250
  reason?: unknown;
250
251
  error?: unknown;
251
252
  cause?: unknown;
253
+ $metadata?: unknown;
252
254
  body?: unknown;
253
255
  response?: unknown;
254
256
  /** gaxios-style clients (Vertex AI) put the API error document here. */
@@ -427,6 +429,49 @@ export function extractErrorMessage(error: unknown): string {
427
429
  }
428
430
  }
429
431
 
432
+ function hasProviderCancellation(error: unknown, depth: number): boolean {
433
+ if (error == null || depth > MAX_CAUSE_DEPTH) {
434
+ return false;
435
+ }
436
+ const record = asRecord(error);
437
+ const message = record == null ? extractErrorMessage(error) : record.message;
438
+ const text = `${record?.name ?? ''} ${record?.code ?? ''} ${record?.type ?? ''} ${typeof message === 'string' ? message : ''}`;
439
+ if (
440
+ /^(?:AbortError|APIUserAbortError|CanceledError|CancelledError)$/.test(
441
+ record?.name ?? ''
442
+ ) ||
443
+ /^(?:ABORT_ERR|ERR_CANCELED)$/.test(String(record?.code ?? '')) ||
444
+ /\buser (?:aborted|cancelled|canceled)\b/i.test(text) ||
445
+ (!/timed?[_ -]?out/i.test(text) &&
446
+ /\bAbortError\b|\b(?:request|operation) (?:was )?(?:aborted|cancelled|canceled)\b/i.test(
447
+ text
448
+ ))
449
+ ) {
450
+ return true;
451
+ }
452
+ if (record == null) {
453
+ return false;
454
+ }
455
+ for (const nested of [
456
+ record.cause,
457
+ record.error,
458
+ record.body,
459
+ record.data,
460
+ record.response,
461
+ record.$metadata,
462
+ ]) {
463
+ if (hasProviderCancellation(nested, depth + 1)) {
464
+ return true;
465
+ }
466
+ }
467
+ return false;
468
+ }
469
+
470
+ /** Recognizes cancellation names, codes, and messages in bounded error chains. */
471
+ export function isProviderCancellation(error: unknown): boolean {
472
+ return hasProviderCancellation(error, 0);
473
+ }
474
+
430
475
  /**
431
476
  * Classifies a provider error as a recoverable context overflow, returning
432
477
  * whatever the provider disclosed about the limit and the request size.
@@ -1,6 +1,18 @@
1
- // src/utils/schema.ts
2
1
  import { zodToJsonSchema } from 'zod-to-json-schema';
3
- import type { ZodTypeAny } from 'zod';
2
+ import { isZodSchemaV4 } from '@langchain/core/utils/types';
3
+ import { globalRegistry, registry, toJSONSchema } from 'zod';
4
+ import type { $ZodType, GlobalMeta } from 'zod/v4/core';
5
+ import type { ZodTypeAny } from 'zod/v3';
6
+ import type { ZodType } from 'zod';
7
+
8
+ /** Schemas from another Zod installation keep their metadata in that installation's registry. */
9
+ const schemaMetadata = registry<GlobalMeta>();
10
+ schemaMetadata.get = (schema): GlobalMeta | undefined => {
11
+ const annotated = schema as $ZodType & Partial<Pick<ZodType, 'meta'>>;
12
+ return typeof annotated.meta === 'function'
13
+ ? annotated.meta()
14
+ : globalRegistry.get(schema);
15
+ };
4
16
 
5
17
  /** Checks if a schema is a Zod schema by looking for the _def property */
6
18
  export function isZodSchema(schema: unknown): schema is ZodTypeAny {
@@ -18,6 +30,18 @@ export function toJsonSchema(
18
30
  name?: string,
19
31
  description?: string
20
32
  ): Record<string, unknown> {
33
+ if (isZodSchemaV4(schema)) {
34
+ return {
35
+ ...toJSONSchema(schema as $ZodType, {
36
+ target: 'draft-7',
37
+ io: 'input',
38
+ unrepresentable: 'any',
39
+ metadata: schemaMetadata,
40
+ }),
41
+ ...(name != null && name !== '' ? { title: name } : {}),
42
+ ...(description != null && description !== '' ? { description } : {}),
43
+ };
44
+ }
21
45
  if (isZodSchema(schema)) {
22
46
  const zodSchema = schema as ZodTypeAny & {
23
47
  describe: (desc: string) => ZodTypeAny;