@librechat/agents 3.1.66 → 3.1.67-dev.4

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 (149) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +23 -3
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +16 -0
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +91 -0
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/hooks/HookRegistry.cjs +162 -0
  8. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
  9. package/dist/cjs/hooks/executeHooks.cjs +276 -0
  10. package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
  11. package/dist/cjs/hooks/matchers.cjs +256 -0
  12. package/dist/cjs/hooks/matchers.cjs.map +1 -0
  13. package/dist/cjs/hooks/types.cjs +27 -0
  14. package/dist/cjs/hooks/types.cjs.map +1 -0
  15. package/dist/cjs/main.cjs +53 -0
  16. package/dist/cjs/main.cjs.map +1 -1
  17. package/dist/cjs/messages/format.cjs +74 -12
  18. package/dist/cjs/messages/format.cjs.map +1 -1
  19. package/dist/cjs/run.cjs +111 -0
  20. package/dist/cjs/run.cjs.map +1 -1
  21. package/dist/cjs/summarization/node.cjs +44 -0
  22. package/dist/cjs/summarization/node.cjs.map +1 -1
  23. package/dist/cjs/tools/BashExecutor.cjs +175 -0
  24. package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
  25. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +296 -0
  26. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
  27. package/dist/cjs/tools/ReadFile.cjs +43 -0
  28. package/dist/cjs/tools/ReadFile.cjs.map +1 -0
  29. package/dist/cjs/tools/SkillTool.cjs +50 -0
  30. package/dist/cjs/tools/SkillTool.cjs.map +1 -0
  31. package/dist/cjs/tools/SubagentTool.cjs +92 -0
  32. package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
  33. package/dist/cjs/tools/ToolNode.cjs +304 -140
  34. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  35. package/dist/cjs/tools/skillCatalog.cjs +84 -0
  36. package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
  37. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +511 -0
  38. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
  39. package/dist/esm/agents/AgentContext.mjs +23 -3
  40. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  41. package/dist/esm/common/enum.mjs +15 -1
  42. package/dist/esm/common/enum.mjs.map +1 -1
  43. package/dist/esm/graphs/Graph.mjs +91 -0
  44. package/dist/esm/graphs/Graph.mjs.map +1 -1
  45. package/dist/esm/hooks/HookRegistry.mjs +160 -0
  46. package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
  47. package/dist/esm/hooks/executeHooks.mjs +273 -0
  48. package/dist/esm/hooks/executeHooks.mjs.map +1 -0
  49. package/dist/esm/hooks/matchers.mjs +251 -0
  50. package/dist/esm/hooks/matchers.mjs.map +1 -0
  51. package/dist/esm/hooks/types.mjs +25 -0
  52. package/dist/esm/hooks/types.mjs.map +1 -0
  53. package/dist/esm/main.mjs +12 -1
  54. package/dist/esm/main.mjs.map +1 -1
  55. package/dist/esm/messages/format.mjs +66 -4
  56. package/dist/esm/messages/format.mjs.map +1 -1
  57. package/dist/esm/run.mjs +111 -0
  58. package/dist/esm/run.mjs.map +1 -1
  59. package/dist/esm/summarization/node.mjs +44 -0
  60. package/dist/esm/summarization/node.mjs.map +1 -1
  61. package/dist/esm/tools/BashExecutor.mjs +169 -0
  62. package/dist/esm/tools/BashExecutor.mjs.map +1 -0
  63. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +287 -0
  64. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
  65. package/dist/esm/tools/ReadFile.mjs +38 -0
  66. package/dist/esm/tools/ReadFile.mjs.map +1 -0
  67. package/dist/esm/tools/SkillTool.mjs +45 -0
  68. package/dist/esm/tools/SkillTool.mjs.map +1 -0
  69. package/dist/esm/tools/SubagentTool.mjs +85 -0
  70. package/dist/esm/tools/SubagentTool.mjs.map +1 -0
  71. package/dist/esm/tools/ToolNode.mjs +306 -142
  72. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  73. package/dist/esm/tools/skillCatalog.mjs +82 -0
  74. package/dist/esm/tools/skillCatalog.mjs.map +1 -0
  75. package/dist/esm/tools/subagent/SubagentExecutor.mjs +505 -0
  76. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
  77. package/dist/types/agents/AgentContext.d.ts +6 -0
  78. package/dist/types/common/enum.d.ts +10 -1
  79. package/dist/types/graphs/Graph.d.ts +2 -0
  80. package/dist/types/hooks/HookRegistry.d.ts +56 -0
  81. package/dist/types/hooks/executeHooks.d.ts +79 -0
  82. package/dist/types/hooks/index.d.ts +6 -0
  83. package/dist/types/hooks/matchers.d.ts +95 -0
  84. package/dist/types/hooks/types.d.ts +320 -0
  85. package/dist/types/index.d.ts +8 -0
  86. package/dist/types/messages/format.d.ts +2 -1
  87. package/dist/types/run.d.ts +1 -0
  88. package/dist/types/summarization/node.d.ts +2 -0
  89. package/dist/types/tools/BashExecutor.d.ts +45 -0
  90. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
  91. package/dist/types/tools/ReadFile.d.ts +28 -0
  92. package/dist/types/tools/SkillTool.d.ts +40 -0
  93. package/dist/types/tools/SubagentTool.d.ts +36 -0
  94. package/dist/types/tools/ToolNode.d.ts +24 -2
  95. package/dist/types/tools/skillCatalog.d.ts +19 -0
  96. package/dist/types/tools/subagent/SubagentExecutor.d.ts +137 -0
  97. package/dist/types/tools/subagent/index.d.ts +2 -0
  98. package/dist/types/types/graph.d.ts +61 -2
  99. package/dist/types/types/index.d.ts +1 -0
  100. package/dist/types/types/llm.d.ts +14 -2
  101. package/dist/types/types/run.d.ts +20 -0
  102. package/dist/types/types/skill.d.ts +9 -0
  103. package/dist/types/types/tools.d.ts +38 -1
  104. package/package.json +5 -1
  105. package/src/agents/AgentContext.ts +26 -2
  106. package/src/common/enum.ts +15 -0
  107. package/src/graphs/Graph.ts +113 -0
  108. package/src/hooks/HookRegistry.ts +208 -0
  109. package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
  110. package/src/hooks/__tests__/compactHooks.test.ts +214 -0
  111. package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
  112. package/src/hooks/__tests__/integration.test.ts +337 -0
  113. package/src/hooks/__tests__/matchers.test.ts +238 -0
  114. package/src/hooks/__tests__/toolHooks.test.ts +669 -0
  115. package/src/hooks/executeHooks.ts +375 -0
  116. package/src/hooks/index.ts +57 -0
  117. package/src/hooks/matchers.ts +280 -0
  118. package/src/hooks/types.ts +404 -0
  119. package/src/index.ts +10 -0
  120. package/src/messages/format.ts +74 -4
  121. package/src/messages/formatAgentMessages.skills.test.ts +334 -0
  122. package/src/run.ts +126 -0
  123. package/src/scripts/multi-agent-subagent.ts +246 -0
  124. package/src/scripts/subagent-event-driven-debug.ts +190 -0
  125. package/src/scripts/subagent-tools-debug.ts +160 -0
  126. package/src/specs/subagent.test.ts +305 -0
  127. package/src/summarization/node.ts +53 -0
  128. package/src/tools/BashExecutor.ts +205 -0
  129. package/src/tools/BashProgrammaticToolCalling.ts +397 -0
  130. package/src/tools/ReadFile.ts +39 -0
  131. package/src/tools/SkillTool.ts +46 -0
  132. package/src/tools/SubagentTool.ts +100 -0
  133. package/src/tools/ToolNode.ts +391 -169
  134. package/src/tools/__tests__/ReadFile.test.ts +44 -0
  135. package/src/tools/__tests__/SkillTool.test.ts +442 -0
  136. package/src/tools/__tests__/SubagentExecutor.test.ts +1148 -0
  137. package/src/tools/__tests__/SubagentTool.test.ts +149 -0
  138. package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
  139. package/src/tools/__tests__/skillCatalog.test.ts +161 -0
  140. package/src/tools/__tests__/subagentHooks.test.ts +215 -0
  141. package/src/tools/skillCatalog.ts +126 -0
  142. package/src/tools/subagent/SubagentExecutor.ts +676 -0
  143. package/src/tools/subagent/index.ts +13 -0
  144. package/src/types/graph.ts +80 -1
  145. package/src/types/index.ts +1 -0
  146. package/src/types/llm.ts +16 -2
  147. package/src/types/run.ts +20 -0
  148. package/src/types/skill.ts +11 -0
  149. package/src/types/tools.ts +41 -1
@@ -0,0 +1,511 @@
1
+ 'use strict';
2
+
3
+ var nanoid = require('nanoid');
4
+ var base = require('@langchain/core/callbacks/base');
5
+ var messages = require('@langchain/core/messages');
6
+ var _enum = require('../../common/enum.cjs');
7
+ var executeHooks = require('../../hooks/executeHooks.cjs');
8
+
9
+ const DEFAULT_MAX_TURNS = 25;
10
+ const RECURSION_MULTIPLIER = 3;
11
+ const ERROR_MESSAGE_MAX_CHARS = 200;
12
+ const HOOK_FALLBACK = Object.freeze({
13
+ additionalContexts: [],
14
+ errors: [],
15
+ });
16
+ class SubagentExecutor {
17
+ configs;
18
+ parentSignal;
19
+ hookRegistry;
20
+ parentRunId;
21
+ parentAgentId;
22
+ tokenCounter;
23
+ maxDepth;
24
+ createChildGraph;
25
+ resolveParentHandlerRegistry;
26
+ constructor(options) {
27
+ this.configs = options.configs;
28
+ this.parentSignal = options.parentSignal;
29
+ this.hookRegistry = options.hookRegistry;
30
+ this.parentRunId = options.parentRunId;
31
+ this.parentAgentId = options.parentAgentId;
32
+ this.tokenCounter = options.tokenCounter;
33
+ this.maxDepth = options.maxDepth ?? 1;
34
+ this.createChildGraph = options.createChildGraph;
35
+ const rawRegistry = options.parentHandlerRegistry;
36
+ if (typeof rawRegistry === 'function') {
37
+ this.resolveParentHandlerRegistry = rawRegistry;
38
+ }
39
+ else if (rawRegistry != null) {
40
+ this.resolveParentHandlerRegistry = () => rawRegistry;
41
+ }
42
+ }
43
+ /** Snapshot of the parent's registry at the moment a subagent is dispatched. */
44
+ getParentHandlerRegistry() {
45
+ return this.resolveParentHandlerRegistry?.();
46
+ }
47
+ async execute(params) {
48
+ const { description, subagentType, threadId, parentToolCallId } = params;
49
+ const config = this.configs.get(subagentType);
50
+ if (!config) {
51
+ const available = [...this.configs.keys()].join(', ');
52
+ return {
53
+ content: `Error: Unknown subagent type "${subagentType}". Available types: ${available}`,
54
+ messages: [],
55
+ };
56
+ }
57
+ if (this.maxDepth <= 0) {
58
+ return {
59
+ content: 'Error: Maximum subagent nesting depth exceeded.',
60
+ messages: [],
61
+ };
62
+ }
63
+ const childAgentId = config.agentInputs.agentId ||
64
+ `${this.parentAgentId ?? 'agent'}_sub_${nanoid.nanoid(8)}`;
65
+ if (this.hookRegistry?.hasHookFor('SubagentStart', this.parentRunId) === true) {
66
+ const hookResult = await executeHooks.executeHooks({
67
+ registry: this.hookRegistry,
68
+ input: {
69
+ hook_event_name: 'SubagentStart',
70
+ runId: this.parentRunId,
71
+ threadId,
72
+ parentAgentId: this.parentAgentId,
73
+ agentId: childAgentId,
74
+ agentType: subagentType,
75
+ inputs: [new messages.HumanMessage(description)],
76
+ },
77
+ sessionId: this.parentRunId,
78
+ matchQuery: subagentType,
79
+ }).catch(() => HOOK_FALLBACK);
80
+ /**
81
+ * `ask` is treated identically to `deny` in the subagent context:
82
+ * subagents are non-interactive, so there is no prompt path for `ask`.
83
+ * Both decisions block execution and return a "Blocked" tool result.
84
+ */
85
+ if (hookResult.decision === 'deny' || hookResult.decision === 'ask') {
86
+ return {
87
+ content: `Blocked: ${hookResult.reason ?? 'Blocked by hook'}`,
88
+ messages: [],
89
+ };
90
+ }
91
+ }
92
+ const parentRegistry = this.getParentHandlerRegistry();
93
+ const forwardingEnabled = parentRegistry != null;
94
+ /**
95
+ * Keep `toolDefinitions` only when the host has actually wired an
96
+ * `ON_TOOL_EXECUTE` handler. `Run` always constructs a `HandlerRegistry`,
97
+ * so treating any registry as "forwarding enabled" would leak
98
+ * `toolDefinitions` into children whose hosts cannot execute them — the
99
+ * child's `ToolNode` batch promise would hang forever with no handler to
100
+ * resolve/reject. Gating on the tool-execute handler preserves the
101
+ * recoverable "no tools" path for registry-but-no-handler configs.
102
+ */
103
+ const hasToolExecuteHandler = parentRegistry?.getHandler(_enum.GraphEvents.ON_TOOL_EXECUTE) != null;
104
+ const childInputs = buildChildInputs(config, childAgentId, this.maxDepth,
105
+ /* keepToolDefinitions */ hasToolExecuteHandler);
106
+ const childRunId = `${this.parentRunId}_sub_${nanoid.nanoid(8)}`;
107
+ const maxTurns = config.maxTurns ?? DEFAULT_MAX_TURNS;
108
+ const childGraph = this.createChildGraph({
109
+ runId: childRunId,
110
+ signal: this.parentSignal,
111
+ agents: [childInputs],
112
+ tokenCounter: this.tokenCounter,
113
+ });
114
+ const forwarder = forwardingEnabled
115
+ ? this.createForwarderCallback({
116
+ parentRegistry: parentRegistry,
117
+ subagentType,
118
+ subagentAgentId: childAgentId,
119
+ childRunId,
120
+ parentToolCallId,
121
+ })
122
+ : undefined;
123
+ if (forwarder) {
124
+ await this.emitSubagentUpdate(parentRegistry, {
125
+ childRunId,
126
+ subagentType,
127
+ subagentAgentId: childAgentId,
128
+ parentToolCallId,
129
+ phase: 'start',
130
+ label: `Subagent "${subagentType}" started`,
131
+ });
132
+ }
133
+ let result;
134
+ try {
135
+ const workflow = childGraph.createWorkflow();
136
+ /**
137
+ * When `parentHandlerRegistry` is provided (forwarding mode), attach a
138
+ * lightweight callback that intercepts the child's `on_custom_event`
139
+ * dispatches and routes them to the parent's registry — either as
140
+ * operational events (ON_TOOL_EXECUTE) or wrapped ON_SUBAGENT_UPDATE
141
+ * envelopes. Native LangChain streaming events (on_chat_model_stream,
142
+ * etc.) still do NOT propagate to the parent's outer streamEvents
143
+ * iterator — the `callbacks` array REPLACES the inherited chain, so
144
+ * parent handlers won't receive child stream chunks and raise "No
145
+ * agent context found" lookups on the parent's agentContexts map.
146
+ *
147
+ * When no registry is provided (legacy isolation), `callbacks: []`
148
+ * fully detaches the child.
149
+ *
150
+ * `runName` gives the child a distinct LangSmith trace root (avoids
151
+ * nested trace pollution).
152
+ */
153
+ const callbacks = forwarder ? [forwarder] : [];
154
+ result = await workflow.invoke({ messages: [new messages.HumanMessage(description)] }, {
155
+ recursionLimit: maxTurns * RECURSION_MULTIPLIER,
156
+ signal: this.parentSignal,
157
+ callbacks,
158
+ runName: `subagent:${subagentType}`,
159
+ configurable: {
160
+ thread_id: childRunId,
161
+ },
162
+ });
163
+ }
164
+ catch (error) {
165
+ const errorMessage = truncateErrorMessage(error);
166
+ if (forwarder) {
167
+ await this.emitSubagentUpdate(parentRegistry, {
168
+ childRunId,
169
+ subagentType,
170
+ subagentAgentId: childAgentId,
171
+ parentToolCallId,
172
+ phase: 'error',
173
+ label: `Subagent "${subagentType}" errored: ${errorMessage}`,
174
+ data: { message: errorMessage },
175
+ });
176
+ }
177
+ childGraph.clearHeavyState();
178
+ return {
179
+ content: `Subagent error: ${errorMessage}`,
180
+ messages: [],
181
+ };
182
+ }
183
+ const filteredContent = filterSubagentResult(result.messages);
184
+ if (this.hookRegistry?.hasHookFor('SubagentStop', this.parentRunId) === true) {
185
+ /**
186
+ * Awaited (not fire-and-forget) for deterministic test synchronization
187
+ * and consistency with PostCompact. The parent is already waiting on the
188
+ * tool result, so the small extra latency is acceptable. Errors are
189
+ * swallowed — SubagentStop is observational.
190
+ */
191
+ await executeHooks.executeHooks({
192
+ registry: this.hookRegistry,
193
+ input: {
194
+ hook_event_name: 'SubagentStop',
195
+ runId: this.parentRunId,
196
+ threadId,
197
+ agentId: childAgentId,
198
+ agentType: subagentType,
199
+ messages: result.messages,
200
+ },
201
+ sessionId: this.parentRunId,
202
+ matchQuery: subagentType,
203
+ }).catch(() => {
204
+ /* SubagentStop is observational — swallow errors */
205
+ });
206
+ }
207
+ if (forwarder) {
208
+ await this.emitSubagentUpdate(parentRegistry, {
209
+ childRunId,
210
+ subagentType,
211
+ subagentAgentId: childAgentId,
212
+ parentToolCallId,
213
+ phase: 'stop',
214
+ label: `Subagent "${subagentType}" finished`,
215
+ });
216
+ }
217
+ childGraph.clearHeavyState();
218
+ return { content: filteredContent, messages: result.messages };
219
+ }
220
+ /**
221
+ * Emits a single {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope through the
222
+ * parent's handler registry. Silent no-op when no parent registry is set.
223
+ * Errors are swallowed — update events are observational.
224
+ */
225
+ async emitSubagentUpdate(parentRegistry, args) {
226
+ const handler = parentRegistry.getHandler(_enum.GraphEvents.ON_SUBAGENT_UPDATE);
227
+ if (!handler) {
228
+ return;
229
+ }
230
+ const event = {
231
+ runId: this.parentRunId,
232
+ subagentRunId: args.childRunId,
233
+ subagentType: args.subagentType,
234
+ subagentAgentId: args.subagentAgentId,
235
+ parentAgentId: this.parentAgentId,
236
+ parentToolCallId: args.parentToolCallId,
237
+ phase: args.phase,
238
+ data: args.data,
239
+ label: args.label,
240
+ timestamp: new Date().toISOString(),
241
+ };
242
+ try {
243
+ await handler.handle(_enum.GraphEvents.ON_SUBAGENT_UPDATE, event);
244
+ }
245
+ catch {
246
+ /* observational — swallow */
247
+ }
248
+ }
249
+ /**
250
+ * Builds a BaseCallbackHandler that intercepts the child graph's custom
251
+ * events. Routing rules:
252
+ * - `ON_TOOL_EXECUTE` → forwarded as-is to the parent's ON_TOOL_EXECUTE
253
+ * handler (so event-driven tools work identically for child and parent).
254
+ * - `ON_RUN_STEP` / `ON_RUN_STEP_DELTA` / `ON_RUN_STEP_COMPLETED` /
255
+ * `ON_MESSAGE_DELTA` / `ON_REASONING_DELTA` → wrapped in a
256
+ * {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope with a human-readable
257
+ * label, delivered to the parent's subagent-update handler.
258
+ * - Everything else → ignored (keeps parent's UI scoped to the events it
259
+ * cares about; host apps can extend by registering more phases).
260
+ */
261
+ createForwarderCallback(args) {
262
+ const { parentRegistry, subagentType, subagentAgentId, childRunId, parentToolCallId, } = args;
263
+ const parentRunId = this.parentRunId;
264
+ const parentAgentId = this.parentAgentId;
265
+ const wrap = async (eventName, phase, data) => {
266
+ const handler = parentRegistry.getHandler(_enum.GraphEvents.ON_SUBAGENT_UPDATE);
267
+ if (!handler) {
268
+ return;
269
+ }
270
+ const event = {
271
+ runId: parentRunId,
272
+ subagentRunId: childRunId,
273
+ subagentType,
274
+ subagentAgentId,
275
+ parentAgentId,
276
+ parentToolCallId,
277
+ phase,
278
+ data,
279
+ label: summarizeEvent(eventName, data),
280
+ timestamp: new Date().toISOString(),
281
+ };
282
+ try {
283
+ await handler.handle(_enum.GraphEvents.ON_SUBAGENT_UPDATE, event);
284
+ }
285
+ catch {
286
+ /* observational — swallow */
287
+ }
288
+ };
289
+ const handler = base.BaseCallbackHandler.fromMethods({
290
+ [_enum.Callback.CUSTOM_EVENT]: async (eventName, data) => {
291
+ if (eventName === _enum.GraphEvents.ON_TOOL_EXECUTE) {
292
+ const toolHandler = parentRegistry.getHandler(_enum.GraphEvents.ON_TOOL_EXECUTE);
293
+ if (toolHandler) {
294
+ await toolHandler.handle(_enum.GraphEvents.ON_TOOL_EXECUTE, data);
295
+ }
296
+ /**
297
+ * We also surface a short notice in the subagent-update stream so
298
+ * the UI can show "calling <tool>" for each tool the child spawns.
299
+ */
300
+ await wrap(eventName, 'run_step', data);
301
+ return;
302
+ }
303
+ if (eventName === _enum.GraphEvents.ON_RUN_STEP) {
304
+ await wrap(eventName, 'run_step', data);
305
+ return;
306
+ }
307
+ if (eventName === _enum.GraphEvents.ON_RUN_STEP_DELTA) {
308
+ await wrap(eventName, 'run_step_delta', data);
309
+ return;
310
+ }
311
+ if (eventName === _enum.GraphEvents.ON_RUN_STEP_COMPLETED) {
312
+ await wrap(eventName, 'run_step_completed', data);
313
+ return;
314
+ }
315
+ if (eventName === _enum.GraphEvents.ON_MESSAGE_DELTA) {
316
+ await wrap(eventName, 'message_delta', data);
317
+ return;
318
+ }
319
+ if (eventName === _enum.GraphEvents.ON_REASONING_DELTA) {
320
+ await wrap(eventName, 'reasoning_delta', data);
321
+ return;
322
+ }
323
+ },
324
+ });
325
+ /**
326
+ * `awaitHandlers = true` is required so the child's `ToolNode` actually
327
+ * blocks on the parent's `ON_TOOL_EXECUTE` handler until it resolves
328
+ * the batch request. The same flag applies to observational events
329
+ * (message_delta, run_step, …), which means a slow
330
+ * `ON_SUBAGENT_UPDATE` handler on the host serializes the child
331
+ * stream. If host-side latency becomes a concern, a future
332
+ * refinement could split operational and observational events into
333
+ * separate callback handlers with distinct await semantics.
334
+ */
335
+ handler.awaitHandlers = true;
336
+ return handler;
337
+ }
338
+ }
339
+ /**
340
+ * Produces a short single-line label for an arbitrary forwarded child event.
341
+ * Used to populate {@link SubagentUpdateEvent.label} so the host UI can show
342
+ * a compact status ticker without parsing the raw payload.
343
+ */
344
+ function summarizeEvent(eventName, data) {
345
+ if (eventName === _enum.GraphEvents.ON_TOOL_EXECUTE) {
346
+ const req = data;
347
+ const names = (req.toolCalls ?? [])
348
+ .map((c) => c.name)
349
+ .filter((n) => typeof n === 'string');
350
+ return names.length > 0 ? `Calling ${names.join(', ')}` : 'Calling tool';
351
+ }
352
+ if (eventName === _enum.GraphEvents.ON_RUN_STEP) {
353
+ const step = data;
354
+ const detailType = step.stepDetails?.type ?? step.type ?? 'step';
355
+ if (detailType === 'tool_calls') {
356
+ const names = (step.stepDetails?.tool_calls ?? [])
357
+ .map((c) => c.name)
358
+ .filter((n) => typeof n === 'string');
359
+ return names.length > 0
360
+ ? `Using tool: ${names.join(', ')}`
361
+ : 'Planning tool call';
362
+ }
363
+ if (detailType === 'message_creation') {
364
+ return 'Thinking…';
365
+ }
366
+ return `Step: ${detailType}`;
367
+ }
368
+ if (eventName === _enum.GraphEvents.ON_RUN_STEP_COMPLETED) {
369
+ const step = data;
370
+ const tool = step.result?.tool_call;
371
+ if (tool?.name != null && tool.name !== '') {
372
+ return `Tool ${tool.name} complete`;
373
+ }
374
+ return 'Step complete';
375
+ }
376
+ if (eventName === _enum.GraphEvents.ON_MESSAGE_DELTA) {
377
+ return 'Streaming…';
378
+ }
379
+ return eventName;
380
+ }
381
+ /**
382
+ * Walk messages from last to first, returning the text content of the most
383
+ * recent AIMessage that has any. Non-text blocks (tool_use, thinking,
384
+ * redacted_thinking, tool_result) are stripped. If the last AIMessage is
385
+ * pure tool_use (e.g. the subagent hit `maxTurns` mid-tool-call), the walk
386
+ * continues to earlier AIMessages so partial progress is salvaged — this
387
+ * matches Claude Code's behavior in `agentToolUtils.finalizeAgentTool`.
388
+ * Returns "Task completed" only when no AIMessage in the history contains
389
+ * any text.
390
+ */
391
+ function filterSubagentResult(messages) {
392
+ for (let i = messages.length - 1; i >= 0; i--) {
393
+ if (messages[i]._getType() !== 'ai') {
394
+ continue;
395
+ }
396
+ const content = messages[i].content;
397
+ if (typeof content === 'string') {
398
+ if (content)
399
+ return content;
400
+ continue;
401
+ }
402
+ if (!Array.isArray(content)) {
403
+ continue;
404
+ }
405
+ const textParts = [];
406
+ for (const block of content) {
407
+ if (typeof block === 'string') {
408
+ textParts.push(block);
409
+ }
410
+ else if ('type' in block && block.type === 'text' && 'text' in block) {
411
+ textParts.push(block.text);
412
+ }
413
+ }
414
+ if (textParts.length > 0) {
415
+ return textParts.join('\n');
416
+ }
417
+ }
418
+ return 'Task completed';
419
+ }
420
+ /**
421
+ * Resolve self-spawn configs by filling in agentInputs from the parent context.
422
+ * Returns configs with agentInputs guaranteed present. Throws on duplicate
423
+ * `type` values to prevent silent config shadowing.
424
+ */
425
+ function resolveSubagentConfigs(configs, parentContext) {
426
+ const resolved = configs
427
+ .map((config) => {
428
+ if (config.agentInputs != null) {
429
+ return config;
430
+ }
431
+ if (config.self !== true || parentContext._sourceInputs == null) {
432
+ return null;
433
+ }
434
+ return {
435
+ ...config,
436
+ agentInputs: { ...parentContext._sourceInputs },
437
+ };
438
+ })
439
+ .filter((c) => c != null);
440
+ const seenTypes = new Set();
441
+ for (const config of resolved) {
442
+ if (seenTypes.has(config.type)) {
443
+ throw new Error(`Duplicate subagent type "${config.type}". Each SubagentConfig must have a unique "type" field.`);
444
+ }
445
+ seenTypes.add(config.type);
446
+ }
447
+ return resolved;
448
+ }
449
+ /**
450
+ * Build child AgentInputs from a resolved config, stripping nesting and
451
+ * (optionally) event-driven fields. When `allowNested: true`, the child's
452
+ * `maxSubagentDepth` is decremented so that depth is consumed as the call
453
+ * chain deepens across graph boundaries — the parent's executor-level check
454
+ * alone cannot see into the child graph's separate executor.
455
+ *
456
+ * When `keepToolDefinitions` is `true`, the child retains the parent's
457
+ * `toolDefinitions` so event-driven tools remain usable. This is only safe
458
+ * when the caller has wired a forwarder for `ON_TOOL_EXECUTE` to a
459
+ * registered handler — otherwise the child will hang on tool dispatch.
460
+ *
461
+ * @remarks Advanced utility: exported primarily for testing and by
462
+ * {@link SubagentExecutor}. Host applications configuring subagents should
463
+ * not need to call this directly — it is invoked internally when a subagent
464
+ * tool is dispatched. The depth-countdown contract (parent's `maxDepth` in,
465
+ * child's decremented `maxSubagentDepth` on the returned inputs) is the
466
+ * mechanism that bounds nesting across graph boundaries; callers must
467
+ * respect it.
468
+ */
469
+ function buildChildInputs(config, childAgentId, parentMaxDepth, keepToolDefinitions = false) {
470
+ const { agentInputs } = config;
471
+ const childInputs = {
472
+ ...agentInputs,
473
+ agentId: childAgentId,
474
+ toolDefinitions: keepToolDefinitions
475
+ ? agentInputs.toolDefinitions
476
+ : undefined,
477
+ /**
478
+ * Subagents run in an isolated context by contract. Parent-run-scoped
479
+ * fields that would otherwise survive the shallow-spread clone — the
480
+ * cross-run conversation summary and the prior-turn tool-discovery
481
+ * set — are cleared here so the child starts fresh. Host applications
482
+ * that want a subagent to see parent context must thread it in
483
+ * explicitly (e.g. via the `description` argument to the subagent
484
+ * tool), not via inherited state.
485
+ */
486
+ initialSummary: undefined,
487
+ discoveredTools: undefined,
488
+ };
489
+ if (config.allowNested === true) {
490
+ childInputs.maxSubagentDepth = Math.max(0, parentMaxDepth - 1);
491
+ }
492
+ else {
493
+ childInputs.subagentConfigs = undefined;
494
+ childInputs.maxSubagentDepth = undefined;
495
+ }
496
+ return childInputs;
497
+ }
498
+ function truncateErrorMessage(error) {
499
+ const message = error instanceof Error ? error.message : String(error);
500
+ if (message.length <= ERROR_MESSAGE_MAX_CHARS) {
501
+ return message;
502
+ }
503
+ return `${message.slice(0, ERROR_MESSAGE_MAX_CHARS)}...`;
504
+ }
505
+
506
+ exports.SubagentExecutor = SubagentExecutor;
507
+ exports.buildChildInputs = buildChildInputs;
508
+ exports.filterSubagentResult = filterSubagentResult;
509
+ exports.resolveSubagentConfigs = resolveSubagentConfigs;
510
+ exports.summarizeEvent = summarizeEvent;
511
+ //# sourceMappingURL=SubagentExecutor.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SubagentExecutor.cjs","sources":["../../../../src/tools/subagent/SubagentExecutor.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport { BaseCallbackHandler } from '@langchain/core/callbacks/base';\nimport { HumanMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport type { Callbacks } from '@langchain/core/callbacks/manager';\nimport type {\n AgentInputs,\n StandardGraphInput,\n ResolvedSubagentConfig,\n SubagentConfig,\n SubagentUpdateEvent,\n SubagentUpdatePhase,\n ToolExecuteBatchRequest,\n TokenCounter,\n} from '@/types';\nimport type { AggregatedHookResult, HookRegistry } from '@/hooks';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs/Graph';\nimport { GraphEvents, Callback } from '@/common';\nimport type { HandlerRegistry } from '@/events';\nimport { executeHooks } from '@/hooks';\n\nconst DEFAULT_MAX_TURNS = 25;\nconst RECURSION_MULTIPLIER = 3;\nconst ERROR_MESSAGE_MAX_CHARS = 200;\n\nconst HOOK_FALLBACK: AggregatedHookResult = Object.freeze({\n additionalContexts: [] as string[],\n errors: [] as string[],\n});\n\nexport type SubagentExecuteParams = {\n description: string;\n subagentType: string;\n threadId?: string;\n /**\n * Parent-side `tool_call_id` of the `subagent` tool invocation that\n * triggered this execution. Surfaced on {@link SubagentUpdateEvent} so\n * hosts can correlate child updates back to the originating tool call\n * without relying on event ordering heuristics.\n */\n parentToolCallId?: string;\n};\n\nexport type SubagentExecuteResult = {\n content: string;\n messages: BaseMessage[];\n};\n\n/**\n * Factory that constructs a child graph for subagent execution. Injected\n * rather than imported so that `SubagentExecutor` does not have a runtime\n * dependency on `StandardGraph` — this avoids a circular dependency between\n * `src/graphs/Graph.ts` and `src/tools/subagent/` that would otherwise break\n * Rollup's chunking under `preserveModules`.\n */\nexport type ChildGraphFactory = (input: StandardGraphInput) => StandardGraph;\n\nexport type SubagentExecutorOptions = {\n configs: Map<string, ResolvedSubagentConfig>;\n parentSignal?: AbortSignal;\n hookRegistry?: HookRegistry;\n parentRunId: string;\n parentAgentId?: string;\n tokenCounter?: TokenCounter;\n /** Remaining nesting budget. 0 or negative blocks execution. */\n maxDepth?: number;\n /**\n * Factory for constructing the isolated child graph. Callers pass\n * `(input) => new StandardGraph(input)` — injected to break a circular\n * module dependency.\n */\n createChildGraph: ChildGraphFactory;\n /**\n * Parent's event handler registry. When provided, child-graph events are\n * forwarded through this registry so hosts can:\n * (a) execute event-driven tools (`ON_TOOL_EXECUTE` routed to parent's handler),\n * (b) surface child activity to a UI via wrapped {@link GraphEvents.ON_SUBAGENT_UPDATE}.\n * When omitted, the child runs fully isolated (legacy behavior).\n *\n * Can be a direct `HandlerRegistry` or a zero-arg getter — use the getter\n * form when the registry is assigned to the graph AFTER the executor is\n * constructed (the current `Run.create` flow sets `handlerRegistry`\n * post-`createWorkflow`, so `createAgentNode` must capture lazily).\n */\n parentHandlerRegistry?: HandlerRegistry | (() => HandlerRegistry | undefined);\n};\n\nexport class SubagentExecutor {\n private readonly configs: Map<string, ResolvedSubagentConfig>;\n private readonly parentSignal?: AbortSignal;\n private readonly hookRegistry?: HookRegistry;\n private readonly parentRunId: string;\n private readonly parentAgentId?: string;\n private readonly tokenCounter?: TokenCounter;\n private readonly maxDepth: number;\n private readonly createChildGraph: ChildGraphFactory;\n private readonly resolveParentHandlerRegistry?: () =>\n | HandlerRegistry\n | undefined;\n\n constructor(options: SubagentExecutorOptions) {\n this.configs = options.configs;\n this.parentSignal = options.parentSignal;\n this.hookRegistry = options.hookRegistry;\n this.parentRunId = options.parentRunId;\n this.parentAgentId = options.parentAgentId;\n this.tokenCounter = options.tokenCounter;\n this.maxDepth = options.maxDepth ?? 1;\n this.createChildGraph = options.createChildGraph;\n const rawRegistry = options.parentHandlerRegistry;\n if (typeof rawRegistry === 'function') {\n this.resolveParentHandlerRegistry = rawRegistry;\n } else if (rawRegistry != null) {\n this.resolveParentHandlerRegistry = (): HandlerRegistry => rawRegistry;\n }\n }\n\n /** Snapshot of the parent's registry at the moment a subagent is dispatched. */\n private getParentHandlerRegistry(): HandlerRegistry | undefined {\n return this.resolveParentHandlerRegistry?.();\n }\n\n async execute(params: SubagentExecuteParams): Promise<SubagentExecuteResult> {\n const { description, subagentType, threadId, parentToolCallId } = params;\n const config = this.configs.get(subagentType);\n\n if (!config) {\n const available = [...this.configs.keys()].join(', ');\n return {\n content: `Error: Unknown subagent type \"${subagentType}\". Available types: ${available}`,\n messages: [],\n };\n }\n\n if (this.maxDepth <= 0) {\n return {\n content: 'Error: Maximum subagent nesting depth exceeded.',\n messages: [],\n };\n }\n\n const childAgentId =\n config.agentInputs.agentId ||\n `${this.parentAgentId ?? 'agent'}_sub_${nanoid(8)}`;\n\n if (\n this.hookRegistry?.hasHookFor('SubagentStart', this.parentRunId) === true\n ) {\n const hookResult = await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'SubagentStart',\n runId: this.parentRunId,\n threadId,\n parentAgentId: this.parentAgentId,\n agentId: childAgentId,\n agentType: subagentType,\n inputs: [new HumanMessage(description)],\n },\n sessionId: this.parentRunId,\n matchQuery: subagentType,\n }).catch((): AggregatedHookResult => HOOK_FALLBACK);\n\n /**\n * `ask` is treated identically to `deny` in the subagent context:\n * subagents are non-interactive, so there is no prompt path for `ask`.\n * Both decisions block execution and return a \"Blocked\" tool result.\n */\n if (hookResult.decision === 'deny' || hookResult.decision === 'ask') {\n return {\n content: `Blocked: ${hookResult.reason ?? 'Blocked by hook'}`,\n messages: [],\n };\n }\n }\n\n const parentRegistry = this.getParentHandlerRegistry();\n const forwardingEnabled = parentRegistry != null;\n /**\n * Keep `toolDefinitions` only when the host has actually wired an\n * `ON_TOOL_EXECUTE` handler. `Run` always constructs a `HandlerRegistry`,\n * so treating any registry as \"forwarding enabled\" would leak\n * `toolDefinitions` into children whose hosts cannot execute them — the\n * child's `ToolNode` batch promise would hang forever with no handler to\n * resolve/reject. Gating on the tool-execute handler preserves the\n * recoverable \"no tools\" path for registry-but-no-handler configs.\n */\n const hasToolExecuteHandler =\n parentRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) != null;\n const childInputs = buildChildInputs(\n config,\n childAgentId,\n this.maxDepth,\n /* keepToolDefinitions */ hasToolExecuteHandler\n );\n const childRunId = `${this.parentRunId}_sub_${nanoid(8)}`;\n const maxTurns = config.maxTurns ?? DEFAULT_MAX_TURNS;\n\n const childGraph = this.createChildGraph({\n runId: childRunId,\n signal: this.parentSignal,\n agents: [childInputs],\n tokenCounter: this.tokenCounter,\n });\n\n const forwarder = forwardingEnabled\n ? this.createForwarderCallback({\n parentRegistry: parentRegistry!,\n subagentType,\n subagentAgentId: childAgentId,\n childRunId,\n parentToolCallId,\n })\n : undefined;\n\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'start',\n label: `Subagent \"${subagentType}\" started`,\n });\n }\n\n let result: { messages: BaseMessage[] };\n try {\n const workflow = childGraph.createWorkflow();\n /**\n * When `parentHandlerRegistry` is provided (forwarding mode), attach a\n * lightweight callback that intercepts the child's `on_custom_event`\n * dispatches and routes them to the parent's registry — either as\n * operational events (ON_TOOL_EXECUTE) or wrapped ON_SUBAGENT_UPDATE\n * envelopes. Native LangChain streaming events (on_chat_model_stream,\n * etc.) still do NOT propagate to the parent's outer streamEvents\n * iterator — the `callbacks` array REPLACES the inherited chain, so\n * parent handlers won't receive child stream chunks and raise \"No\n * agent context found\" lookups on the parent's agentContexts map.\n *\n * When no registry is provided (legacy isolation), `callbacks: []`\n * fully detaches the child.\n *\n * `runName` gives the child a distinct LangSmith trace root (avoids\n * nested trace pollution).\n */\n const callbacks: Callbacks = forwarder ? [forwarder] : [];\n result = await workflow.invoke(\n { messages: [new HumanMessage(description)] },\n {\n recursionLimit: maxTurns * RECURSION_MULTIPLIER,\n signal: this.parentSignal,\n callbacks,\n runName: `subagent:${subagentType}`,\n configurable: {\n thread_id: childRunId,\n },\n }\n );\n } catch (error) {\n const errorMessage = truncateErrorMessage(error);\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'error',\n label: `Subagent \"${subagentType}\" errored: ${errorMessage}`,\n data: { message: errorMessage },\n });\n }\n childGraph.clearHeavyState();\n return {\n content: `Subagent error: ${errorMessage}`,\n messages: [],\n };\n }\n\n const filteredContent = filterSubagentResult(result.messages);\n\n if (\n this.hookRegistry?.hasHookFor('SubagentStop', this.parentRunId) === true\n ) {\n /**\n * Awaited (not fire-and-forget) for deterministic test synchronization\n * and consistency with PostCompact. The parent is already waiting on the\n * tool result, so the small extra latency is acceptable. Errors are\n * swallowed — SubagentStop is observational.\n */\n await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'SubagentStop',\n runId: this.parentRunId,\n threadId,\n agentId: childAgentId,\n agentType: subagentType,\n messages: result.messages,\n },\n sessionId: this.parentRunId,\n matchQuery: subagentType,\n }).catch(() => {\n /* SubagentStop is observational — swallow errors */\n });\n }\n\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'stop',\n label: `Subagent \"${subagentType}\" finished`,\n });\n }\n\n childGraph.clearHeavyState();\n\n return { content: filteredContent, messages: result.messages };\n }\n\n /**\n * Emits a single {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope through the\n * parent's handler registry. Silent no-op when no parent registry is set.\n * Errors are swallowed — update events are observational.\n */\n private async emitSubagentUpdate(\n parentRegistry: HandlerRegistry,\n args: {\n childRunId: string;\n subagentType: string;\n subagentAgentId: string;\n parentToolCallId?: string;\n phase: SubagentUpdatePhase;\n data?: unknown;\n label?: string;\n }\n ): Promise<void> {\n const handler = parentRegistry.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (!handler) {\n return;\n }\n const event: SubagentUpdateEvent = {\n runId: this.parentRunId,\n subagentRunId: args.childRunId,\n subagentType: args.subagentType,\n subagentAgentId: args.subagentAgentId,\n parentAgentId: this.parentAgentId,\n parentToolCallId: args.parentToolCallId,\n phase: args.phase,\n data: args.data,\n label: args.label,\n timestamp: new Date().toISOString(),\n };\n try {\n await handler.handle(GraphEvents.ON_SUBAGENT_UPDATE, event);\n } catch {\n /* observational — swallow */\n }\n }\n\n /**\n * Builds a BaseCallbackHandler that intercepts the child graph's custom\n * events. Routing rules:\n * - `ON_TOOL_EXECUTE` → forwarded as-is to the parent's ON_TOOL_EXECUTE\n * handler (so event-driven tools work identically for child and parent).\n * - `ON_RUN_STEP` / `ON_RUN_STEP_DELTA` / `ON_RUN_STEP_COMPLETED` /\n * `ON_MESSAGE_DELTA` / `ON_REASONING_DELTA` → wrapped in a\n * {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope with a human-readable\n * label, delivered to the parent's subagent-update handler.\n * - Everything else → ignored (keeps parent's UI scoped to the events it\n * cares about; host apps can extend by registering more phases).\n */\n private createForwarderCallback(args: {\n parentRegistry: HandlerRegistry;\n subagentType: string;\n subagentAgentId: string;\n childRunId: string;\n parentToolCallId?: string;\n }): BaseCallbackHandler {\n const {\n parentRegistry,\n subagentType,\n subagentAgentId,\n childRunId,\n parentToolCallId,\n } = args;\n const parentRunId = this.parentRunId;\n const parentAgentId = this.parentAgentId;\n\n const wrap = async (\n eventName: string,\n phase: SubagentUpdatePhase,\n data: unknown\n ): Promise<void> => {\n const handler = parentRegistry.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (!handler) {\n return;\n }\n const event: SubagentUpdateEvent = {\n runId: parentRunId,\n subagentRunId: childRunId,\n subagentType,\n subagentAgentId,\n parentAgentId,\n parentToolCallId,\n phase,\n data,\n label: summarizeEvent(eventName, data),\n timestamp: new Date().toISOString(),\n };\n try {\n await handler.handle(GraphEvents.ON_SUBAGENT_UPDATE, event);\n } catch {\n /* observational — swallow */\n }\n };\n\n const handler = BaseCallbackHandler.fromMethods({\n [Callback.CUSTOM_EVENT]: async (\n eventName: string,\n data: unknown\n ): Promise<void> => {\n if (eventName === GraphEvents.ON_TOOL_EXECUTE) {\n const toolHandler = parentRegistry.getHandler(\n GraphEvents.ON_TOOL_EXECUTE\n );\n if (toolHandler) {\n await toolHandler.handle(\n GraphEvents.ON_TOOL_EXECUTE,\n data as ToolExecuteBatchRequest\n );\n }\n /**\n * We also surface a short notice in the subagent-update stream so\n * the UI can show \"calling <tool>\" for each tool the child spawns.\n */\n await wrap(eventName, 'run_step', data);\n return;\n }\n\n if (eventName === GraphEvents.ON_RUN_STEP) {\n await wrap(eventName, 'run_step', data);\n return;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_DELTA) {\n await wrap(eventName, 'run_step_delta', data);\n return;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_COMPLETED) {\n await wrap(eventName, 'run_step_completed', data);\n return;\n }\n if (eventName === GraphEvents.ON_MESSAGE_DELTA) {\n await wrap(eventName, 'message_delta', data);\n return;\n }\n if (eventName === GraphEvents.ON_REASONING_DELTA) {\n await wrap(eventName, 'reasoning_delta', data);\n return;\n }\n },\n });\n /**\n * `awaitHandlers = true` is required so the child's `ToolNode` actually\n * blocks on the parent's `ON_TOOL_EXECUTE` handler until it resolves\n * the batch request. The same flag applies to observational events\n * (message_delta, run_step, …), which means a slow\n * `ON_SUBAGENT_UPDATE` handler on the host serializes the child\n * stream. If host-side latency becomes a concern, a future\n * refinement could split operational and observational events into\n * separate callback handlers with distinct await semantics.\n */\n handler.awaitHandlers = true;\n return handler;\n }\n}\n\n/**\n * Produces a short single-line label for an arbitrary forwarded child event.\n * Used to populate {@link SubagentUpdateEvent.label} so the host UI can show\n * a compact status ticker without parsing the raw payload.\n */\nexport function summarizeEvent(eventName: string, data: unknown): string {\n if (eventName === GraphEvents.ON_TOOL_EXECUTE) {\n const req = data as { toolCalls?: Array<{ name?: string }> };\n const names = (req.toolCalls ?? [])\n .map((c) => c.name)\n .filter((n): n is string => typeof n === 'string');\n return names.length > 0 ? `Calling ${names.join(', ')}` : 'Calling tool';\n }\n if (eventName === GraphEvents.ON_RUN_STEP) {\n const step = data as {\n type?: string;\n stepDetails?: { type?: string; tool_calls?: Array<{ name?: string }> };\n };\n const detailType = step.stepDetails?.type ?? step.type ?? 'step';\n if (detailType === 'tool_calls') {\n const names = (step.stepDetails?.tool_calls ?? [])\n .map((c) => c.name)\n .filter((n): n is string => typeof n === 'string');\n return names.length > 0\n ? `Using tool: ${names.join(', ')}`\n : 'Planning tool call';\n }\n if (detailType === 'message_creation') {\n return 'Thinking…';\n }\n return `Step: ${detailType}`;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const step = data as {\n result?: {\n type?: string;\n tool_call?: { name?: string; output?: string };\n };\n };\n const tool = step.result?.tool_call;\n if (tool?.name != null && tool.name !== '') {\n return `Tool ${tool.name} complete`;\n }\n return 'Step complete';\n }\n if (eventName === GraphEvents.ON_MESSAGE_DELTA) {\n return 'Streaming…';\n }\n return eventName;\n}\n\n/**\n * Walk messages from last to first, returning the text content of the most\n * recent AIMessage that has any. Non-text blocks (tool_use, thinking,\n * redacted_thinking, tool_result) are stripped. If the last AIMessage is\n * pure tool_use (e.g. the subagent hit `maxTurns` mid-tool-call), the walk\n * continues to earlier AIMessages so partial progress is salvaged — this\n * matches Claude Code's behavior in `agentToolUtils.finalizeAgentTool`.\n * Returns \"Task completed\" only when no AIMessage in the history contains\n * any text.\n */\nexport function filterSubagentResult(messages: BaseMessage[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]._getType() !== 'ai') {\n continue;\n }\n\n const content = messages[i].content;\n\n if (typeof content === 'string') {\n if (content) return content;\n continue;\n }\n\n if (!Array.isArray(content)) {\n continue;\n }\n\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n textParts.push(block);\n } else if ('type' in block && block.type === 'text' && 'text' in block) {\n textParts.push(block.text as string);\n }\n }\n\n if (textParts.length > 0) {\n return textParts.join('\\n');\n }\n }\n\n return 'Task completed';\n}\n\n/**\n * Resolve self-spawn configs by filling in agentInputs from the parent context.\n * Returns configs with agentInputs guaranteed present. Throws on duplicate\n * `type` values to prevent silent config shadowing.\n */\nexport function resolveSubagentConfigs(\n configs: SubagentConfig[],\n parentContext: AgentContext\n): ResolvedSubagentConfig[] {\n const resolved = configs\n .map((config) => {\n if (config.agentInputs != null) {\n return config as ResolvedSubagentConfig;\n }\n if (config.self !== true || parentContext._sourceInputs == null) {\n return null;\n }\n return {\n ...config,\n agentInputs: { ...parentContext._sourceInputs },\n } as ResolvedSubagentConfig;\n })\n .filter((c): c is ResolvedSubagentConfig => c != null);\n\n const seenTypes = new Set<string>();\n for (const config of resolved) {\n if (seenTypes.has(config.type)) {\n throw new Error(\n `Duplicate subagent type \"${config.type}\". Each SubagentConfig must have a unique \"type\" field.`\n );\n }\n seenTypes.add(config.type);\n }\n\n return resolved;\n}\n\n/**\n * Build child AgentInputs from a resolved config, stripping nesting and\n * (optionally) event-driven fields. When `allowNested: true`, the child's\n * `maxSubagentDepth` is decremented so that depth is consumed as the call\n * chain deepens across graph boundaries — the parent's executor-level check\n * alone cannot see into the child graph's separate executor.\n *\n * When `keepToolDefinitions` is `true`, the child retains the parent's\n * `toolDefinitions` so event-driven tools remain usable. This is only safe\n * when the caller has wired a forwarder for `ON_TOOL_EXECUTE` to a\n * registered handler — otherwise the child will hang on tool dispatch.\n *\n * @remarks Advanced utility: exported primarily for testing and by\n * {@link SubagentExecutor}. Host applications configuring subagents should\n * not need to call this directly — it is invoked internally when a subagent\n * tool is dispatched. The depth-countdown contract (parent's `maxDepth` in,\n * child's decremented `maxSubagentDepth` on the returned inputs) is the\n * mechanism that bounds nesting across graph boundaries; callers must\n * respect it.\n */\nexport function buildChildInputs(\n config: ResolvedSubagentConfig,\n childAgentId: string,\n parentMaxDepth: number,\n keepToolDefinitions: boolean = false\n): AgentInputs {\n const { agentInputs } = config;\n const childInputs: AgentInputs = {\n ...agentInputs,\n agentId: childAgentId,\n toolDefinitions: keepToolDefinitions\n ? agentInputs.toolDefinitions\n : undefined,\n /**\n * Subagents run in an isolated context by contract. Parent-run-scoped\n * fields that would otherwise survive the shallow-spread clone — the\n * cross-run conversation summary and the prior-turn tool-discovery\n * set — are cleared here so the child starts fresh. Host applications\n * that want a subagent to see parent context must thread it in\n * explicitly (e.g. via the `description` argument to the subagent\n * tool), not via inherited state.\n */\n initialSummary: undefined,\n discoveredTools: undefined,\n };\n\n if (config.allowNested === true) {\n childInputs.maxSubagentDepth = Math.max(0, parentMaxDepth - 1);\n } else {\n childInputs.subagentConfigs = undefined;\n childInputs.maxSubagentDepth = undefined;\n }\n\n return childInputs;\n}\n\nfunction truncateErrorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n if (message.length <= ERROR_MESSAGE_MAX_CHARS) {\n return message;\n }\n return `${message.slice(0, ERROR_MESSAGE_MAX_CHARS)}...`;\n}\n"],"names":["nanoid","executeHooks","HumanMessage","GraphEvents","BaseCallbackHandler","Callback"],"mappings":";;;;;;;;AAsBA,MAAM,iBAAiB,GAAG,EAAE;AAC5B,MAAM,oBAAoB,GAAG,CAAC;AAC9B,MAAM,uBAAuB,GAAG,GAAG;AAEnC,MAAM,aAAa,GAAyB,MAAM,CAAC,MAAM,CAAC;AACxD,IAAA,kBAAkB,EAAE,EAAc;AAClC,IAAA,MAAM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AG,CAAC,MAAM,CAAC,IAAI,CAAC;IAC5B;AAEA,IAAA,OAAO,QAAQ;AACjB;AAEA;;;;;;;;;;;;;;;;;;;AAmBG;AACG,SAAU,gBAAgB,CAC9B,MAA8B,EAC9B,YAAoB,EACpB,cAAsB,EACtB,mBAAA,GAA+B,KAAK,EAAA;AAEpC,IAAA,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM;AAC9B,IAAA,MAAM,WAAW,GAAgB;AAC/B,QAAA,GAAG,WAAW;AACd,QAAA,OAAO,EAAE,YAAY;AACrB,QAAA,eAAe,EAAE;cACb,WAAW,CAAC;AACd,cAAE,SAAS;AACb;;;;;;;;AAQG;AACH,QAAA,cAAc,EAAE,SAAS;AACzB,QAAA,eAAe,EAAE,SAAS;KAC3B;AAED,IAAA,IAAI,MAAM,CAAC,WAAW,KAAK,IAAI,EAAE;AAC/B,QAAA,WAAW,CAAC,gBAAgB,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,cAAc,GAAG,CAAC,CAAC;IAChE;SAAO;AACL,QAAA,WAAW,CAAC,eAAe,GAAG,SAAS;AACvC,QAAA,WAAW,CAAC,gBAAgB,GAAG,SAAS;IAC1C;AAEA,IAAA,OAAO,WAAW;AACpB;AAEA,SAAS,oBAAoB,CAAC,KAAc,EAAA;AAC1C,IAAA,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC;AACtE,IAAA,IAAI,OAAO,CAAC,MAAM,IAAI,uBAAuB,EAAE;AAC7C,QAAA,OAAO,OAAO;IAChB;IACA,OAAO,CAAA,EAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,uBAAuB,CAAC,CAAA,GAAA,CAAK;AAC1D;;;;;;;;"}
@@ -20,7 +20,7 @@ class AgentContext {
20
20
  * Create an AgentContext from configuration with token accounting initialization
21
21
  */
22
22
  static fromConfig(agentConfig, tokenCounter, indexTokenCountMap) {
23
- const { agentId, name, provider, clientOptions, tools, toolMap, toolEnd, toolRegistry, toolDefinitions, instructions, additional_instructions, streamBuffer, maxContextTokens, reasoningKey, useLegacyContent, discoveredTools, summarizationEnabled, summarizationConfig, initialSummary, contextPruningConfig, maxToolResultChars, toolSchemaTokens, } = agentConfig;
23
+ const { agentId, name, provider, clientOptions, tools, toolMap, toolEnd, toolRegistry, toolDefinitions, instructions, additional_instructions, streamBuffer, maxContextTokens, reasoningKey, useLegacyContent, discoveredTools, summarizationEnabled, summarizationConfig, initialSummary, contextPruningConfig, maxToolResultChars, toolSchemaTokens, subagentConfigs, maxSubagentDepth, } = agentConfig;
24
24
  const agentContext = new AgentContext({
25
25
  agentId,
26
26
  name: name ?? agentId,
@@ -45,6 +45,9 @@ class AgentContext {
45
45
  contextPruningConfig,
46
46
  maxToolResultChars,
47
47
  });
48
+ agentContext._sourceInputs = agentConfig;
49
+ agentContext.subagentConfigs = subagentConfigs;
50
+ agentContext.maxSubagentDepth = maxSubagentDepth;
48
51
  if (initialSummary?.text != null && initialSummary.text !== '') {
49
52
  agentContext.setInitialSummary(initialSummary.text, initialSummary.tokenCount);
50
53
  }
@@ -147,6 +150,12 @@ class AgentContext {
147
150
  toolDefinitions;
148
151
  /** Set of tool names discovered via tool search (to be loaded) */
149
152
  discoveredToolNames = new Set();
153
+ /** Original AgentInputs used to create this context — used for self-spawn subagent resolution. */
154
+ _sourceInputs;
155
+ /** Subagent configurations for hierarchical delegation. */
156
+ subagentConfigs;
157
+ /** Maximum subagent nesting depth. */
158
+ maxSubagentDepth;
150
159
  /** Instructions for this agent */
151
160
  instructions;
152
161
  /** Additional instructions for this agent */
@@ -503,8 +512,19 @@ class AgentContext {
503
512
  async calculateInstructionTokens(tokenCounter) {
504
513
  let toolTokens = 0;
505
514
  const countedToolNames = new Set();
506
- if (this.tools && this.tools.length > 0) {
507
- for (const tool of this.tools) {
515
+ /**
516
+ * Iterate both `tools` (user-provided instance tools) and `graphTools`
517
+ * (graph-managed tools like handoff + subagent). `graphTools` is often
518
+ * populated after `fromConfig()` kicks off the initial calculation, so
519
+ * callers that mutate `graphTools` must re-trigger this method to
520
+ * refresh `toolSchemaTokens`.
521
+ */
522
+ const instanceTools = [
523
+ ...(this.tools ?? []),
524
+ ...(this.graphTools ?? []),
525
+ ];
526
+ if (instanceTools.length > 0) {
527
+ for (const tool of instanceTools) {
508
528
  const genericTool = tool;
509
529
  if (genericTool.schema != null &&
510
530
  typeof genericTool.schema === 'object') {