@librechat/agents 3.1.68 → 3.1.70

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 (170) 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 -1
  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 +165 -0
  24. package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
  25. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +287 -0
  26. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
  27. package/dist/cjs/tools/CodeExecutor.cjs +0 -9
  28. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  29. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +7 -23
  30. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  31. package/dist/cjs/tools/ReadFile.cjs +43 -0
  32. package/dist/cjs/tools/ReadFile.cjs.map +1 -0
  33. package/dist/cjs/tools/SkillTool.cjs +50 -0
  34. package/dist/cjs/tools/SkillTool.cjs.map +1 -0
  35. package/dist/cjs/tools/SubagentTool.cjs +92 -0
  36. package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
  37. package/dist/cjs/tools/ToolNode.cjs +304 -140
  38. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  39. package/dist/cjs/tools/ToolSearch.cjs +2 -13
  40. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  41. package/dist/cjs/tools/skillCatalog.cjs +84 -0
  42. package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
  43. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +511 -0
  44. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
  45. package/dist/esm/agents/AgentContext.mjs +23 -3
  46. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  47. package/dist/esm/common/enum.mjs +15 -2
  48. package/dist/esm/common/enum.mjs.map +1 -1
  49. package/dist/esm/graphs/Graph.mjs +91 -0
  50. package/dist/esm/graphs/Graph.mjs.map +1 -1
  51. package/dist/esm/hooks/HookRegistry.mjs +160 -0
  52. package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
  53. package/dist/esm/hooks/executeHooks.mjs +273 -0
  54. package/dist/esm/hooks/executeHooks.mjs.map +1 -0
  55. package/dist/esm/hooks/matchers.mjs +251 -0
  56. package/dist/esm/hooks/matchers.mjs.map +1 -0
  57. package/dist/esm/hooks/types.mjs +25 -0
  58. package/dist/esm/hooks/types.mjs.map +1 -0
  59. package/dist/esm/main.mjs +12 -1
  60. package/dist/esm/main.mjs.map +1 -1
  61. package/dist/esm/messages/format.mjs +66 -4
  62. package/dist/esm/messages/format.mjs.map +1 -1
  63. package/dist/esm/run.mjs +111 -0
  64. package/dist/esm/run.mjs.map +1 -1
  65. package/dist/esm/summarization/node.mjs +44 -0
  66. package/dist/esm/summarization/node.mjs.map +1 -1
  67. package/dist/esm/tools/BashExecutor.mjs +159 -0
  68. package/dist/esm/tools/BashExecutor.mjs.map +1 -0
  69. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +278 -0
  70. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
  71. package/dist/esm/tools/CodeExecutor.mjs +0 -9
  72. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  73. package/dist/esm/tools/ProgrammaticToolCalling.mjs +8 -24
  74. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  75. package/dist/esm/tools/ReadFile.mjs +38 -0
  76. package/dist/esm/tools/ReadFile.mjs.map +1 -0
  77. package/dist/esm/tools/SkillTool.mjs +45 -0
  78. package/dist/esm/tools/SkillTool.mjs.map +1 -0
  79. package/dist/esm/tools/SubagentTool.mjs +85 -0
  80. package/dist/esm/tools/SubagentTool.mjs.map +1 -0
  81. package/dist/esm/tools/ToolNode.mjs +306 -142
  82. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  83. package/dist/esm/tools/ToolSearch.mjs +3 -14
  84. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  85. package/dist/esm/tools/skillCatalog.mjs +82 -0
  86. package/dist/esm/tools/skillCatalog.mjs.map +1 -0
  87. package/dist/esm/tools/subagent/SubagentExecutor.mjs +505 -0
  88. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
  89. package/dist/types/agents/AgentContext.d.ts +6 -0
  90. package/dist/types/common/enum.d.ts +10 -2
  91. package/dist/types/graphs/Graph.d.ts +2 -0
  92. package/dist/types/hooks/HookRegistry.d.ts +56 -0
  93. package/dist/types/hooks/executeHooks.d.ts +79 -0
  94. package/dist/types/hooks/index.d.ts +6 -0
  95. package/dist/types/hooks/matchers.d.ts +95 -0
  96. package/dist/types/hooks/types.d.ts +320 -0
  97. package/dist/types/index.d.ts +8 -0
  98. package/dist/types/messages/format.d.ts +2 -1
  99. package/dist/types/run.d.ts +1 -0
  100. package/dist/types/summarization/node.d.ts +2 -0
  101. package/dist/types/tools/BashExecutor.d.ts +45 -0
  102. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
  103. package/dist/types/tools/ProgrammaticToolCalling.d.ts +4 -9
  104. package/dist/types/tools/ReadFile.d.ts +28 -0
  105. package/dist/types/tools/SkillTool.d.ts +40 -0
  106. package/dist/types/tools/SubagentTool.d.ts +36 -0
  107. package/dist/types/tools/ToolNode.d.ts +24 -2
  108. package/dist/types/tools/ToolSearch.d.ts +2 -2
  109. package/dist/types/tools/skillCatalog.d.ts +19 -0
  110. package/dist/types/tools/subagent/SubagentExecutor.d.ts +137 -0
  111. package/dist/types/tools/subagent/index.d.ts +2 -0
  112. package/dist/types/types/graph.d.ts +61 -2
  113. package/dist/types/types/index.d.ts +1 -0
  114. package/dist/types/types/run.d.ts +20 -0
  115. package/dist/types/types/skill.d.ts +9 -0
  116. package/dist/types/types/tools.d.ts +38 -10
  117. package/package.json +5 -1
  118. package/src/agents/AgentContext.ts +26 -2
  119. package/src/common/enum.ts +15 -1
  120. package/src/graphs/Graph.ts +113 -0
  121. package/src/hooks/HookRegistry.ts +208 -0
  122. package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
  123. package/src/hooks/__tests__/compactHooks.test.ts +214 -0
  124. package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
  125. package/src/hooks/__tests__/integration.test.ts +337 -0
  126. package/src/hooks/__tests__/matchers.test.ts +238 -0
  127. package/src/hooks/__tests__/toolHooks.test.ts +669 -0
  128. package/src/hooks/executeHooks.ts +375 -0
  129. package/src/hooks/index.ts +57 -0
  130. package/src/hooks/matchers.ts +280 -0
  131. package/src/hooks/types.ts +404 -0
  132. package/src/index.ts +10 -0
  133. package/src/messages/format.ts +74 -4
  134. package/src/messages/formatAgentMessages.skills.test.ts +334 -0
  135. package/src/run.ts +126 -0
  136. package/src/scripts/multi-agent-subagent.ts +246 -0
  137. package/src/scripts/programmatic_exec.ts +1 -10
  138. package/src/scripts/subagent-event-driven-debug.ts +190 -0
  139. package/src/scripts/subagent-tools-debug.ts +160 -0
  140. package/src/scripts/test_code_api.ts +0 -7
  141. package/src/scripts/tool_search.ts +1 -10
  142. package/src/specs/subagent.test.ts +305 -0
  143. package/src/summarization/node.ts +53 -0
  144. package/src/tools/BashExecutor.ts +193 -0
  145. package/src/tools/BashProgrammaticToolCalling.ts +381 -0
  146. package/src/tools/CodeExecutor.ts +0 -11
  147. package/src/tools/ProgrammaticToolCalling.ts +4 -29
  148. package/src/tools/ReadFile.ts +39 -0
  149. package/src/tools/SkillTool.ts +46 -0
  150. package/src/tools/SubagentTool.ts +100 -0
  151. package/src/tools/ToolNode.ts +391 -169
  152. package/src/tools/ToolSearch.ts +3 -19
  153. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +7 -8
  154. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -1
  155. package/src/tools/__tests__/ReadFile.test.ts +44 -0
  156. package/src/tools/__tests__/SkillTool.test.ts +442 -0
  157. package/src/tools/__tests__/SubagentExecutor.test.ts +1148 -0
  158. package/src/tools/__tests__/SubagentTool.test.ts +149 -0
  159. package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
  160. package/src/tools/__tests__/ToolSearch.integration.test.ts +7 -8
  161. package/src/tools/__tests__/skillCatalog.test.ts +161 -0
  162. package/src/tools/__tests__/subagentHooks.test.ts +215 -0
  163. package/src/tools/skillCatalog.ts +126 -0
  164. package/src/tools/subagent/SubagentExecutor.ts +676 -0
  165. package/src/tools/subagent/index.ts +13 -0
  166. package/src/types/graph.ts +80 -1
  167. package/src/types/index.ts +1 -0
  168. package/src/types/run.ts +20 -0
  169. package/src/types/skill.ts +11 -0
  170. package/src/types/tools.ts +41 -10
@@ -28,7 +28,9 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
28
28
  private directToolNames?;
29
29
  /** Maximum characters allowed in a single tool result before truncation. */
30
30
  private maxToolResultChars;
31
- constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, agentId, directToolNames, maxContextTokens, maxToolResultChars, }: t.ToolNodeConstructorParams);
31
+ /** Hook registry for PreToolUse/PostToolUse lifecycle hooks */
32
+ private hookRegistry?;
33
+ constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, agentId, directToolNames, maxContextTokens, maxToolResultChars, hookRegistry, }: t.ToolNodeConstructorParams);
32
34
  /**
33
35
  * Returns cached programmatic tools, computing once on first access.
34
36
  * Single iteration builds both toolMap and toolDefs simultaneously.
@@ -66,11 +68,31 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
66
68
  /**
67
69
  * Dispatches tool calls to the host via ON_TOOL_EXECUTE event and returns raw ToolMessages.
68
70
  * Core logic for event-driven execution, separated from output shaping.
71
+ *
72
+ * Hook lifecycle (when `hookRegistry` is set):
73
+ * 1. **PreToolUse** fires per call in parallel before dispatch. Denied
74
+ * calls produce error ToolMessages and fire **PermissionDenied**;
75
+ * surviving calls proceed with optional `updatedInput`.
76
+ * 2. Surviving calls are dispatched to the host via `ON_TOOL_EXECUTE`.
77
+ * 3. **PostToolUse** / **PostToolUseFailure** fire per result. Post hooks
78
+ * can replace tool output via `updatedOutput`.
79
+ * 4. Injected messages from results are collected and returned alongside
80
+ * ToolMessages (appended AFTER to respect provider ordering).
69
81
  */
70
82
  private dispatchToolEvents;
83
+ private dispatchStepCompleted;
84
+ /**
85
+ * Converts InjectedMessage instances to LangChain HumanMessage objects.
86
+ * Both 'user' and 'system' roles become HumanMessage to avoid provider
87
+ * rejections (Anthropic/Google reject non-leading SystemMessages).
88
+ * The original role is preserved in additional_kwargs for downstream consumers.
89
+ */
90
+ private convertInjectedMessages;
71
91
  /**
72
92
  * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.
73
- * Used in event-driven mode where the host handles actual tool execution.
93
+ * Injected messages are placed AFTER ToolMessages to respect provider
94
+ * message ordering (AIMessage tool_calls must be immediately followed
95
+ * by their ToolMessage results).
74
96
  */
75
97
  private executeViaEvent;
76
98
  protected run(input: any, config: RunnableConfig): Promise<T>;
@@ -211,11 +211,11 @@ declare function formatServerListing(tools: t.ToolMetadata[], serverNames: strin
211
211
  *
212
212
  * @example
213
213
  * // Option 1: Code interpreter mode (regex via sandbox)
214
- * const tool = createToolSearch({ apiKey, toolRegistry });
214
+ * const tool = createToolSearch({ toolRegistry });
215
215
  * await tool.invoke({ query: 'expense.*report' });
216
216
  *
217
217
  * @example
218
- * // Option 2: Local mode (safe substring search, no API key needed)
218
+ * // Option 2: Local mode (safe substring search)
219
219
  * const tool = createToolSearch({ mode: 'local', toolRegistry });
220
220
  * await tool.invoke({ query: 'expense' });
221
221
  */
@@ -0,0 +1,19 @@
1
+ import type { SkillCatalogEntry } from '@/types';
2
+ export type SkillCatalogOptions = {
3
+ /** Total context window in tokens. Default: 200_000 */
4
+ contextWindowTokens?: number;
5
+ /** Fraction of context budget for catalog. Default: 0.01 (1%) */
6
+ budgetPercent?: number;
7
+ /** Max chars per entry description. Default: 250 */
8
+ maxEntryChars?: number;
9
+ /** Descriptions below this length trigger names-only fallback. Default: 20 */
10
+ minDescLength?: number;
11
+ /** Approximate chars per token for budget calculation. Default: 4 */
12
+ charsPerToken?: number;
13
+ };
14
+ /**
15
+ * Formats a skill catalog for injection into agent context.
16
+ * Uses a truncation ladder: full descriptions, proportional truncation, names-only.
17
+ * Returns empty string for empty input.
18
+ */
19
+ export declare function formatSkillCatalog(skills: SkillCatalogEntry[], opts?: SkillCatalogOptions): string;
@@ -0,0 +1,137 @@
1
+ import type { BaseMessage } from '@langchain/core/messages';
2
+ import type { AgentInputs, StandardGraphInput, ResolvedSubagentConfig, SubagentConfig, TokenCounter } from '@/types';
3
+ import type { HookRegistry } from '@/hooks';
4
+ import type { AgentContext } from '@/agents/AgentContext';
5
+ import type { StandardGraph } from '@/graphs/Graph';
6
+ import type { HandlerRegistry } from '@/events';
7
+ export type SubagentExecuteParams = {
8
+ description: string;
9
+ subagentType: string;
10
+ threadId?: string;
11
+ /**
12
+ * Parent-side `tool_call_id` of the `subagent` tool invocation that
13
+ * triggered this execution. Surfaced on {@link SubagentUpdateEvent} so
14
+ * hosts can correlate child updates back to the originating tool call
15
+ * without relying on event ordering heuristics.
16
+ */
17
+ parentToolCallId?: string;
18
+ };
19
+ export type SubagentExecuteResult = {
20
+ content: string;
21
+ messages: BaseMessage[];
22
+ };
23
+ /**
24
+ * Factory that constructs a child graph for subagent execution. Injected
25
+ * rather than imported so that `SubagentExecutor` does not have a runtime
26
+ * dependency on `StandardGraph` — this avoids a circular dependency between
27
+ * `src/graphs/Graph.ts` and `src/tools/subagent/` that would otherwise break
28
+ * Rollup's chunking under `preserveModules`.
29
+ */
30
+ export type ChildGraphFactory = (input: StandardGraphInput) => StandardGraph;
31
+ export type SubagentExecutorOptions = {
32
+ configs: Map<string, ResolvedSubagentConfig>;
33
+ parentSignal?: AbortSignal;
34
+ hookRegistry?: HookRegistry;
35
+ parentRunId: string;
36
+ parentAgentId?: string;
37
+ tokenCounter?: TokenCounter;
38
+ /** Remaining nesting budget. 0 or negative blocks execution. */
39
+ maxDepth?: number;
40
+ /**
41
+ * Factory for constructing the isolated child graph. Callers pass
42
+ * `(input) => new StandardGraph(input)` — injected to break a circular
43
+ * module dependency.
44
+ */
45
+ createChildGraph: ChildGraphFactory;
46
+ /**
47
+ * Parent's event handler registry. When provided, child-graph events are
48
+ * forwarded through this registry so hosts can:
49
+ * (a) execute event-driven tools (`ON_TOOL_EXECUTE` routed to parent's handler),
50
+ * (b) surface child activity to a UI via wrapped {@link GraphEvents.ON_SUBAGENT_UPDATE}.
51
+ * When omitted, the child runs fully isolated (legacy behavior).
52
+ *
53
+ * Can be a direct `HandlerRegistry` or a zero-arg getter — use the getter
54
+ * form when the registry is assigned to the graph AFTER the executor is
55
+ * constructed (the current `Run.create` flow sets `handlerRegistry`
56
+ * post-`createWorkflow`, so `createAgentNode` must capture lazily).
57
+ */
58
+ parentHandlerRegistry?: HandlerRegistry | (() => HandlerRegistry | undefined);
59
+ };
60
+ export declare class SubagentExecutor {
61
+ private readonly configs;
62
+ private readonly parentSignal?;
63
+ private readonly hookRegistry?;
64
+ private readonly parentRunId;
65
+ private readonly parentAgentId?;
66
+ private readonly tokenCounter?;
67
+ private readonly maxDepth;
68
+ private readonly createChildGraph;
69
+ private readonly resolveParentHandlerRegistry?;
70
+ constructor(options: SubagentExecutorOptions);
71
+ /** Snapshot of the parent's registry at the moment a subagent is dispatched. */
72
+ private getParentHandlerRegistry;
73
+ execute(params: SubagentExecuteParams): Promise<SubagentExecuteResult>;
74
+ /**
75
+ * Emits a single {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope through the
76
+ * parent's handler registry. Silent no-op when no parent registry is set.
77
+ * Errors are swallowed — update events are observational.
78
+ */
79
+ private emitSubagentUpdate;
80
+ /**
81
+ * Builds a BaseCallbackHandler that intercepts the child graph's custom
82
+ * events. Routing rules:
83
+ * - `ON_TOOL_EXECUTE` → forwarded as-is to the parent's ON_TOOL_EXECUTE
84
+ * handler (so event-driven tools work identically for child and parent).
85
+ * - `ON_RUN_STEP` / `ON_RUN_STEP_DELTA` / `ON_RUN_STEP_COMPLETED` /
86
+ * `ON_MESSAGE_DELTA` / `ON_REASONING_DELTA` → wrapped in a
87
+ * {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope with a human-readable
88
+ * label, delivered to the parent's subagent-update handler.
89
+ * - Everything else → ignored (keeps parent's UI scoped to the events it
90
+ * cares about; host apps can extend by registering more phases).
91
+ */
92
+ private createForwarderCallback;
93
+ }
94
+ /**
95
+ * Produces a short single-line label for an arbitrary forwarded child event.
96
+ * Used to populate {@link SubagentUpdateEvent.label} so the host UI can show
97
+ * a compact status ticker without parsing the raw payload.
98
+ */
99
+ export declare function summarizeEvent(eventName: string, data: unknown): string;
100
+ /**
101
+ * Walk messages from last to first, returning the text content of the most
102
+ * recent AIMessage that has any. Non-text blocks (tool_use, thinking,
103
+ * redacted_thinking, tool_result) are stripped. If the last AIMessage is
104
+ * pure tool_use (e.g. the subagent hit `maxTurns` mid-tool-call), the walk
105
+ * continues to earlier AIMessages so partial progress is salvaged — this
106
+ * matches Claude Code's behavior in `agentToolUtils.finalizeAgentTool`.
107
+ * Returns "Task completed" only when no AIMessage in the history contains
108
+ * any text.
109
+ */
110
+ export declare function filterSubagentResult(messages: BaseMessage[]): string;
111
+ /**
112
+ * Resolve self-spawn configs by filling in agentInputs from the parent context.
113
+ * Returns configs with agentInputs guaranteed present. Throws on duplicate
114
+ * `type` values to prevent silent config shadowing.
115
+ */
116
+ export declare function resolveSubagentConfigs(configs: SubagentConfig[], parentContext: AgentContext): ResolvedSubagentConfig[];
117
+ /**
118
+ * Build child AgentInputs from a resolved config, stripping nesting and
119
+ * (optionally) event-driven fields. When `allowNested: true`, the child's
120
+ * `maxSubagentDepth` is decremented so that depth is consumed as the call
121
+ * chain deepens across graph boundaries — the parent's executor-level check
122
+ * alone cannot see into the child graph's separate executor.
123
+ *
124
+ * When `keepToolDefinitions` is `true`, the child retains the parent's
125
+ * `toolDefinitions` so event-driven tools remain usable. This is only safe
126
+ * when the caller has wired a forwarder for `ON_TOOL_EXECUTE` to a
127
+ * registered handler — otherwise the child will hang on tool dispatch.
128
+ *
129
+ * @remarks Advanced utility: exported primarily for testing and by
130
+ * {@link SubagentExecutor}. Host applications configuring subagents should
131
+ * not need to call this directly — it is invoked internally when a subagent
132
+ * tool is dispatched. The depth-countdown contract (parent's `maxDepth` in,
133
+ * child's decremented `maxSubagentDepth` on the returned inputs) is the
134
+ * mechanism that bounds nesting across graph boundaries; callers must
135
+ * respect it.
136
+ */
137
+ export declare function buildChildInputs(config: ResolvedSubagentConfig, childAgentId: string, parentMaxDepth: number, keepToolDefinitions?: boolean): AgentInputs;
@@ -0,0 +1,2 @@
1
+ export { SubagentExecutor, filterSubagentResult, resolveSubagentConfigs, buildChildInputs, summarizeEvent, } from './SubagentExecutor';
2
+ export type { SubagentExecuteParams, SubagentExecuteResult, SubagentExecutorOptions, ChildGraphFactory, } from './SubagentExecutor';
@@ -4,7 +4,7 @@ import type { BaseMessage, AIMessageChunk, SystemMessage } from '@langchain/core
4
4
  import type { RunnableConfig, Runnable } from '@langchain/core/runnables';
5
5
  import type { ChatGenerationChunk } from '@langchain/core/outputs';
6
6
  import type { GoogleAIToolType } from '@langchain/google-common';
7
- import type { ToolMap, ToolEndEvent, GenericTool, LCTool } from '@/types/tools';
7
+ import type { ToolMap, ToolEndEvent, GenericTool, LCTool, ToolExecuteBatchRequest } from '@/types/tools';
8
8
  import type { Providers, Callback, GraphNodeKeys } from '@/common';
9
9
  import type { StandardGraph, MultiAgentGraph } from '@/graphs';
10
10
  import type { ClientOptions } from '@/types/llm';
@@ -45,7 +45,7 @@ export interface AgentLogEvent {
45
45
  agentId?: string;
46
46
  }
47
47
  export interface EventHandler {
48
- handle(event: string, data: StreamEventData | ModelEndData | RunStep | RunStepDeltaEvent | MessageDeltaEvent | ReasoningDeltaEvent | SummarizeStartEvent | SummarizeDeltaEvent | SummarizeCompleteEvent | AgentLogEvent | {
48
+ handle(event: string, data: StreamEventData | ModelEndData | RunStep | RunStepDeltaEvent | MessageDeltaEvent | ReasoningDeltaEvent | SummarizeStartEvent | SummarizeDeltaEvent | SummarizeCompleteEvent | SubagentUpdateEvent | AgentLogEvent | ToolExecuteBatchRequest | {
49
49
  result: ToolEndEvent;
50
50
  }, metadata?: Record<string, unknown>, graph?: StandardGraph | MultiAgentGraph): void | Promise<void>;
51
51
  }
@@ -248,6 +248,61 @@ export type GraphEdge = {
248
248
  export type MultiAgentGraphInput = StandardGraphInput & {
249
249
  edges: GraphEdge[];
250
250
  };
251
+ /** Configuration for a subagent type that can be spawned by a parent agent. */
252
+ export type SubagentConfig = {
253
+ /** Identifier used in the tool's `subagent_type` enum (e.g. 'researcher', 'coder'). */
254
+ type: string;
255
+ /** Human-readable display name. */
256
+ name: string;
257
+ /** What this subagent specializes in — shown to the LLM. */
258
+ description: string;
259
+ /** Full agent config for the child graph. Omit when `self` is true. */
260
+ agentInputs?: AgentInputs;
261
+ /** When true, reuse the parent's AgentInputs (context isolation without separate config). */
262
+ self?: boolean;
263
+ /** Max AGENT→TOOLS cycles before forced stop (default: 25). */
264
+ maxTurns?: number;
265
+ /** Allow this subagent to spawn its own subagents (default: false). */
266
+ allowNested?: boolean;
267
+ };
268
+ /** SubagentConfig with agentInputs guaranteed present (self-spawn resolved). */
269
+ export type ResolvedSubagentConfig = SubagentConfig & {
270
+ agentInputs: AgentInputs;
271
+ };
272
+ /** Lifecycle phase carried on {@link SubagentUpdateEvent}. */
273
+ export type SubagentUpdatePhase = 'start' | 'run_step' | 'run_step_delta' | 'run_step_completed' | 'message_delta' | 'reasoning_delta' | 'stop' | 'error';
274
+ /**
275
+ * Wrapper event emitted when a subagent's child graph dispatches activity.
276
+ * Lets hosts show subagent progress in a UI surface separate from the parent
277
+ * conversation without having to untangle events by agent ID.
278
+ */
279
+ export interface SubagentUpdateEvent {
280
+ /** Parent run ID. */
281
+ runId: string;
282
+ /** Child run ID (unique per subagent execution). */
283
+ subagentRunId: string;
284
+ /**
285
+ * Parent-side `tool_call_id` for the `subagent` tool invocation that
286
+ * triggered this run. Stable for the duration of the child; lets hosts
287
+ * correlate updates deterministically instead of inferring by ordering.
288
+ * Omitted when the executor was invoked outside of a tool-call context.
289
+ */
290
+ parentToolCallId?: string;
291
+ /** Subagent `type` identifier from the SubagentConfig. */
292
+ subagentType: string;
293
+ /** Child agent ID assigned to this subagent execution. */
294
+ subagentAgentId: string;
295
+ /** Parent agent ID that spawned this subagent. */
296
+ parentAgentId?: string;
297
+ /** Lifecycle phase carried by this update. */
298
+ phase: SubagentUpdatePhase;
299
+ /** Underlying event payload (shape depends on phase). */
300
+ data?: unknown;
301
+ /** Short human-readable description. Hosts can render this directly. */
302
+ label?: string;
303
+ /** ISO timestamp for ordering / display. */
304
+ timestamp: string;
305
+ }
251
306
  export interface AgentInputs {
252
307
  agentId: string;
253
308
  /** Human-readable name for the agent (used in handoff context). Defaults to agentId if not provided. */
@@ -294,6 +349,10 @@ export interface AgentInputs {
294
349
  maxToolResultChars?: number;
295
350
  /** Pre-computed tool schema token count (from cache). Skips recalculation when provided. */
296
351
  toolSchemaTokens?: number;
352
+ /** Subagent configurations for hierarchical delegation. Each defines a child agent type. */
353
+ subagentConfigs?: SubagentConfig[];
354
+ /** Maximum subagent nesting depth. Default 1 means top-level agents can spawn subagents but subagents cannot nest further. */
355
+ maxSubagentDepth?: number;
297
356
  }
298
357
  export interface ContextPruningConfig {
299
358
  enabled?: boolean;
@@ -1,6 +1,7 @@
1
1
  export * from './graph';
2
2
  export * from './llm';
3
3
  export * from './run';
4
+ export * from './skill';
4
5
  export * from './stream';
5
6
  export * from './tools';
6
7
  export * from './summarize';
@@ -7,6 +7,8 @@ import type * as s from '@/types/stream';
7
7
  import type * as e from '@/common/enum';
8
8
  import type * as g from '@/types/graph';
9
9
  import type * as l from '@/types/llm';
10
+ import type { ToolSessionMap } from '@/types/tools';
11
+ import type { HookRegistry } from '@/hooks';
10
12
  export type ZodObjectAny = z.ZodObject<any, any, any, any>;
11
13
  export type BaseGraphConfig = {
12
14
  llmConfig: l.LLMConfig;
@@ -100,6 +102,18 @@ export type RunConfig = {
100
102
  runId: string;
101
103
  graphConfig: LegacyGraphConfig | StandardGraphConfig | MultiAgentGraphConfig;
102
104
  customHandlers?: Record<string, g.EventHandler>;
105
+ /**
106
+ * Pre-constructed hook registry for this run. Hooks fire at lifecycle
107
+ * points in `processStream` (RunStart, UserPromptSubmit, Stop,
108
+ * StopFailure) and around tool calls (PreToolUse, PostToolUse,
109
+ * PostToolUseFailure, PermissionDenied).
110
+ *
111
+ * Pass `undefined` (the default) to skip all hook dispatch. When a
112
+ * registry is provided, the run attaches it to the `Graph` so internal
113
+ * nodes can fire hooks too, and clears the session in the `finally`
114
+ * block to prevent leaks.
115
+ */
116
+ hooks?: HookRegistry;
103
117
  returnContent?: boolean;
104
118
  tokenCounter?: TokenCounter;
105
119
  indexTokenCountMap?: Record<string, number>;
@@ -114,6 +128,12 @@ export type RunConfig = {
114
128
  calibrationRatio?: number;
115
129
  /** Skip post-stream cleanup (clearHeavyState) — useful for tests that inspect graph state after processStream */
116
130
  skipCleanup?: boolean;
131
+ /**
132
+ * Initial session state to seed the Graph's ToolSessionMap.
133
+ * Used to carry over code environment sessions from skill file priming
134
+ * at run start, so ToolNode can inject session_id + files into tool calls.
135
+ */
136
+ initialSessions?: ToolSessionMap;
117
137
  };
118
138
  export type ProvidedCallbacks = (BaseCallbackHandler | CallbackHandlerMethods)[] | undefined;
119
139
  export type TokenCounter = (message: BaseMessage) => number;
@@ -0,0 +1,9 @@
1
+ /** Minimal skill metadata for catalog assembly. The host provides these from its own data layer. */
2
+ export type SkillCatalogEntry = {
3
+ /** Kebab-case identifier (what the model passes to SkillTool) */
4
+ name: string;
5
+ /** One-line description for the catalog listing */
6
+ description: string;
7
+ /** Optional human-readable label (UI only, not shown to model) */
8
+ displayTitle?: string;
9
+ };
@@ -1,8 +1,8 @@
1
1
  import type { StructuredToolInterface } from '@langchain/core/tools';
2
2
  import type { RunnableToolLike } from '@langchain/core/runnables';
3
3
  import type { ToolCall } from '@langchain/core/messages/tool';
4
- import type { ToolErrorData } from './stream';
5
- import { EnvVar } from '@/common';
4
+ import type { HookRegistry } from '@/hooks';
5
+ import type { MessageContentComplex, ToolErrorData } from './stream';
6
6
  /** Replacement type for `import type { ToolCall } from '@langchain/core/messages/tool'` in order to have stringified args typed */
7
7
  export type CustomToolCall = {
8
8
  name: string;
@@ -39,6 +39,12 @@ export type ToolNodeOptions = {
39
39
  agentId?: string;
40
40
  /** Tool names that must be executed directly (via runTool) even in event-driven mode (e.g., graph-managed handoff tools) */
41
41
  directToolNames?: Set<string>;
42
+ /**
43
+ * Hook registry for PreToolUse/PostToolUse lifecycle hooks.
44
+ * Only fires for event-driven tool calls (`dispatchToolEvents`). Tools
45
+ * routed through `directToolNames` bypass hook dispatch entirely.
46
+ */
47
+ hookRegistry?: HookRegistry;
42
48
  /** Max context tokens for the agent — used to compute tool result truncation limits. */
43
49
  maxContextTokens?: number;
44
50
  /**
@@ -65,9 +71,7 @@ export type CodeEnvFile = {
65
71
  export type CodeExecutionToolParams = undefined | {
66
72
  session_id?: string;
67
73
  user_id?: string;
68
- apiKey?: string;
69
74
  files?: CodeEnvFile[];
70
- [EnvVar.CODE_API_KEY]?: string;
71
75
  };
72
76
  export type FileRef = {
73
77
  id: string;
@@ -154,6 +158,25 @@ export type ToolExecuteBatchRequest = {
154
158
  /** Promise rejector - handler calls this on fatal error */
155
159
  reject: (error: Error) => void;
156
160
  };
161
+ /**
162
+ * A message injected into graph state by any tool execution handler.
163
+ * Generic mechanism: any tool returning `injectedMessages` in its `ToolExecuteResult`
164
+ * will have these appended to state after the ToolMessage for this call.
165
+ */
166
+ export type InjectedMessage = {
167
+ /** 'user' for skill body injection, 'system' for context hints.
168
+ * Both are converted to HumanMessage at runtime; the original role
169
+ * is preserved in additional_kwargs.role. */
170
+ role: 'user' | 'system';
171
+ /** Message content: string for simple text, array for complex multi-part content */
172
+ content: string | MessageContentComplex[];
173
+ /** When true, the message is framework-internal: not shown in UI, not counted as a user turn */
174
+ isMeta?: boolean;
175
+ /** Origin tag for downstream consumers (UI, pruner, compaction) */
176
+ source?: 'skill' | 'hook' | 'system';
177
+ /** Only set when source is 'skill', for compaction preservation */
178
+ skillName?: string;
179
+ };
157
180
  /** Result for a single tool call in event-driven execution */
158
181
  export type ToolExecuteResult = {
159
182
  /** Matches ToolCallRequest.id */
@@ -166,6 +189,13 @@ export type ToolExecuteResult = {
166
189
  status: 'success' | 'error';
167
190
  /** Error message if status is 'error' */
168
191
  errorMessage?: string;
192
+ /**
193
+ * Messages to inject into graph state after the ToolMessage for this call.
194
+ * Placed after tool results to respect provider message ordering (tool_call -> tool_result adjacency).
195
+ * The host's message formatter may merge injected user messages with the preceding tool_result turn.
196
+ * Generic mechanism: any tool execution handler can use this.
197
+ */
198
+ injectedMessages?: InjectedMessage[];
169
199
  };
170
200
  /** Map of tool names to tool definitions */
171
201
  export type LCToolRegistry = Map<string, LCTool>;
@@ -179,7 +209,6 @@ export type ToolSearchMode = 'code_interpreter' | 'local';
179
209
  export type McpNameFormat = 'full' | 'base';
180
210
  /** Parameters for creating a Tool Search tool */
181
211
  export type ToolSearchParams = {
182
- apiKey?: string;
183
212
  toolRegistry?: LCToolRegistry;
184
213
  onlyDeferred?: boolean;
185
214
  baseUrl?: string;
@@ -189,7 +218,6 @@ export type ToolSearchParams = {
189
218
  mcpServer?: string | string[];
190
219
  /** Format for MCP tool names: 'full' (tool_mcp_server) or 'base' (tool only). Default: 'full' */
191
220
  mcpNameFormat?: McpNameFormat;
192
- [key: string]: unknown;
193
221
  };
194
222
  /** Simplified tool metadata for search purposes */
195
223
  export type ToolMetadata = {
@@ -266,12 +294,14 @@ export type ProgrammaticExecutionArtifact = {
266
294
  session_id?: string;
267
295
  files?: FileRefs;
268
296
  };
297
+ /** Parameters for creating a bash execution tool (same API as CodeExecutor, bash-only) */
298
+ export type BashExecutionToolParams = CodeExecutionToolParams;
299
+ /** Parameters for creating a bash programmatic tool calling tool (same API as PTC, bash-only) */
300
+ export type BashProgrammaticToolCallingParams = ProgrammaticToolCallingParams;
269
301
  /**
270
302
  * Initialization parameters for the PTC tool
271
303
  */
272
304
  export type ProgrammaticToolCallingParams = {
273
- /** Code API key (or use CODE_API_KEY env var) */
274
- apiKey?: string;
275
305
  /** Code API base URL (or use CODE_BASEURL env var) */
276
306
  baseUrl?: string;
277
307
  /** Safety limit for round-trips (default: 20) */
@@ -280,8 +310,6 @@ export type ProgrammaticToolCallingParams = {
280
310
  proxy?: string;
281
311
  /** Enable debug logging (or set PTC_DEBUG=true env var) */
282
312
  debug?: boolean;
283
- /** Environment variable key for API key */
284
- [key: string]: unknown;
285
313
  };
286
314
  /**
287
315
  * Tracks code execution session state for automatic file persistence.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "3.1.68",
3
+ "version": "3.1.70",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -61,6 +61,9 @@
61
61
  "tool": "node --trace-warnings -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/tools.ts --provider 'bedrock' --name 'Jo' --location 'New York, NY'",
62
62
  "search": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/search.ts --provider 'bedrock' --name 'Jo' --location 'New York, NY'",
63
63
  "tool_search": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/tool_search.ts",
64
+ "subagent": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-subagent.ts",
65
+ "subagent:events": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/subagent-event-driven-debug.ts",
66
+ "subagent:tools": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/subagent-tools-debug.ts",
64
67
  "programmatic_exec": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/programmatic_exec.ts",
65
68
  "code_exec_ptc": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_ptc.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
66
69
  "programmatic_exec_agent": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/programmatic_exec_agent.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
@@ -77,6 +80,7 @@
77
80
  "multi-agent-chain": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-chain.ts",
78
81
  "multi-agent-sequence": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-sequence.ts",
79
82
  "multi-agent-conditional": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-conditional.ts",
83
+ "multi-agent-subagent": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-subagent.ts",
80
84
  "multi-agent-supervisor": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-supervisor.ts",
81
85
  "test-handoff-preamble": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/test-handoff-preamble.ts",
82
86
  "multi-agent-list-handoff": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/test-multi-agent-list-handoff.ts",
@@ -55,6 +55,8 @@ export class AgentContext {
55
55
  contextPruningConfig,
56
56
  maxToolResultChars,
57
57
  toolSchemaTokens,
58
+ subagentConfigs,
59
+ maxSubagentDepth,
58
60
  } = agentConfig;
59
61
 
60
62
  const agentContext = new AgentContext({
@@ -82,6 +84,10 @@ export class AgentContext {
82
84
  maxToolResultChars,
83
85
  });
84
86
 
87
+ agentContext._sourceInputs = agentConfig;
88
+ agentContext.subagentConfigs = subagentConfigs;
89
+ agentContext.maxSubagentDepth = maxSubagentDepth;
90
+
85
91
  if (initialSummary?.text != null && initialSummary.text !== '') {
86
92
  agentContext.setInitialSummary(
87
93
  initialSummary.text,
@@ -198,6 +204,12 @@ export class AgentContext {
198
204
  toolDefinitions?: t.LCTool[];
199
205
  /** Set of tool names discovered via tool search (to be loaded) */
200
206
  discoveredToolNames: Set<string> = new Set();
207
+ /** Original AgentInputs used to create this context — used for self-spawn subagent resolution. */
208
+ _sourceInputs?: t.AgentInputs;
209
+ /** Subagent configurations for hierarchical delegation. */
210
+ subagentConfigs?: t.SubagentConfig[];
211
+ /** Maximum subagent nesting depth. */
212
+ maxSubagentDepth?: number;
201
213
  /** Instructions for this agent */
202
214
  instructions?: string;
203
215
  /** Additional instructions for this agent */
@@ -685,8 +697,20 @@ export class AgentContext {
685
697
  let toolTokens = 0;
686
698
  const countedToolNames = new Set<string>();
687
699
 
688
- if (this.tools && this.tools.length > 0) {
689
- for (const tool of this.tools) {
700
+ /**
701
+ * Iterate both `tools` (user-provided instance tools) and `graphTools`
702
+ * (graph-managed tools like handoff + subagent). `graphTools` is often
703
+ * populated after `fromConfig()` kicks off the initial calculation, so
704
+ * callers that mutate `graphTools` must re-trigger this method to
705
+ * refresh `toolSchemaTokens`.
706
+ */
707
+ const instanceTools: t.GraphTools = [
708
+ ...((this.tools as t.GenericTool[] | undefined) ?? []),
709
+ ...((this.graphTools as t.GenericTool[] | undefined) ?? []),
710
+ ];
711
+
712
+ if (instanceTools.length > 0) {
713
+ for (const tool of instanceTools) {
690
714
  const genericTool = tool as Record<string, unknown>;
691
715
  if (
692
716
  genericTool.schema != null &&
@@ -27,6 +27,8 @@ export enum GraphEvents {
27
27
  ON_SUMMARIZE_DELTA = 'on_summarize_delta',
28
28
  /** [Custom] Emitted when the summarize node completes with the final summary */
29
29
  ON_SUMMARIZE_COMPLETE = 'on_summarize_complete',
30
+ /** [Custom] Progress update from a running subagent (wraps child-graph events so hosts can display activity separately from parent). */
31
+ ON_SUBAGENT_UPDATE = 'on_subagent_update',
30
32
  /** [Custom] Diagnostic logging event for context management observability */
31
33
  ON_AGENT_LOG = 'on_agent_log',
32
34
 
@@ -182,8 +184,21 @@ export enum Constants {
182
184
  MCP_DELIMITER = '_mcp_',
183
185
  /** Anthropic server tool ID prefix (web_search, code_execution, etc.) */
184
186
  ANTHROPIC_SERVER_TOOL_PREFIX = 'srvtoolu_',
187
+ SKILL_TOOL = 'skill',
188
+ READ_FILE = 'read_file',
189
+ BASH_TOOL = 'bash_tool',
190
+ BASH_PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_bash',
191
+ SUBAGENT = 'subagent',
185
192
  }
186
193
 
194
+ /** Tool names that use the code execution environment (shared session, file tracking). */
195
+ export const CODE_EXECUTION_TOOLS: ReadonlySet<string> = new Set([
196
+ Constants.EXECUTE_CODE,
197
+ Constants.BASH_TOOL,
198
+ Constants.PROGRAMMATIC_TOOL_CALLING,
199
+ Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
200
+ ]);
201
+
187
202
  export enum TitleMethod {
188
203
  STRUCTURED = 'structured',
189
204
  FUNCTIONS = 'functions',
@@ -191,6 +206,5 @@ export enum TitleMethod {
191
206
  }
192
207
 
193
208
  export enum EnvVar {
194
- CODE_API_KEY = 'LIBRECHAT_CODE_API_KEY',
195
209
  CODE_BASEURL = 'LIBRECHAT_CODE_BASEURL',
196
210
  }