@librechat/agents 3.1.66 → 3.1.67-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +23 -3
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +14 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +72 -0
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs +162 -0
- package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
- package/dist/cjs/hooks/executeHooks.cjs +276 -0
- package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
- package/dist/cjs/hooks/matchers.cjs +256 -0
- package/dist/cjs/hooks/matchers.cjs.map +1 -0
- package/dist/cjs/hooks/types.cjs +27 -0
- package/dist/cjs/hooks/types.cjs.map +1 -0
- package/dist/cjs/main.cjs +52 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +74 -12
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/run.cjs +111 -0
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +44 -0
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +175 -0
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +296 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/ReadFile.cjs +43 -0
- package/dist/cjs/tools/ReadFile.cjs.map +1 -0
- package/dist/cjs/tools/SkillTool.cjs +50 -0
- package/dist/cjs/tools/SkillTool.cjs.map +1 -0
- package/dist/cjs/tools/SubagentTool.cjs +92 -0
- package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +304 -140
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/skillCatalog.cjs +84 -0
- package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +261 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +23 -3
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +13 -1
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +72 -0
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/hooks/HookRegistry.mjs +160 -0
- package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
- package/dist/esm/hooks/executeHooks.mjs +273 -0
- package/dist/esm/hooks/executeHooks.mjs.map +1 -0
- package/dist/esm/hooks/matchers.mjs +251 -0
- package/dist/esm/hooks/matchers.mjs.map +1 -0
- package/dist/esm/hooks/types.mjs +25 -0
- package/dist/esm/hooks/types.mjs.map +1 -0
- package/dist/esm/main.mjs +12 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +66 -4
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/run.mjs +111 -0
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +44 -0
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +169 -0
- package/dist/esm/tools/BashExecutor.mjs.map +1 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +287 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/ReadFile.mjs +38 -0
- package/dist/esm/tools/ReadFile.mjs.map +1 -0
- package/dist/esm/tools/SkillTool.mjs +45 -0
- package/dist/esm/tools/SkillTool.mjs.map +1 -0
- package/dist/esm/tools/SubagentTool.mjs +85 -0
- package/dist/esm/tools/SubagentTool.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +306 -142
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/skillCatalog.mjs +82 -0
- package/dist/esm/tools/skillCatalog.mjs.map +1 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +256 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +6 -0
- package/dist/types/common/enum.d.ts +8 -1
- package/dist/types/graphs/Graph.d.ts +2 -0
- package/dist/types/hooks/HookRegistry.d.ts +56 -0
- package/dist/types/hooks/executeHooks.d.ts +79 -0
- package/dist/types/hooks/index.d.ts +6 -0
- package/dist/types/hooks/matchers.d.ts +95 -0
- package/dist/types/hooks/types.d.ts +320 -0
- package/dist/types/index.d.ts +8 -0
- package/dist/types/messages/format.d.ts +2 -1
- package/dist/types/run.d.ts +1 -0
- package/dist/types/summarization/node.d.ts +2 -0
- package/dist/types/tools/BashExecutor.d.ts +45 -0
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
- package/dist/types/tools/ReadFile.d.ts +28 -0
- package/dist/types/tools/SkillTool.d.ts +40 -0
- package/dist/types/tools/SubagentTool.d.ts +36 -0
- package/dist/types/tools/ToolNode.d.ts +24 -2
- package/dist/types/tools/skillCatalog.d.ts +19 -0
- package/dist/types/tools/subagent/SubagentExecutor.d.ts +83 -0
- package/dist/types/tools/subagent/index.d.ts +2 -0
- package/dist/types/types/graph.d.ts +25 -0
- package/dist/types/types/index.d.ts +1 -0
- package/dist/types/types/llm.d.ts +14 -2
- package/dist/types/types/run.d.ts +20 -0
- package/dist/types/types/skill.d.ts +9 -0
- package/dist/types/types/tools.d.ts +38 -1
- package/package.json +2 -1
- package/src/agents/AgentContext.ts +26 -2
- package/src/common/enum.ts +13 -0
- package/src/graphs/Graph.ts +92 -0
- package/src/hooks/HookRegistry.ts +208 -0
- package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
- package/src/hooks/__tests__/compactHooks.test.ts +214 -0
- package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
- package/src/hooks/__tests__/integration.test.ts +337 -0
- package/src/hooks/__tests__/matchers.test.ts +238 -0
- package/src/hooks/__tests__/toolHooks.test.ts +669 -0
- package/src/hooks/executeHooks.ts +375 -0
- package/src/hooks/index.ts +57 -0
- package/src/hooks/matchers.ts +280 -0
- package/src/hooks/types.ts +404 -0
- package/src/index.ts +10 -0
- package/src/messages/format.ts +74 -4
- package/src/messages/formatAgentMessages.skills.test.ts +334 -0
- package/src/run.ts +126 -0
- package/src/scripts/multi-agent-subagent.ts +246 -0
- package/src/specs/subagent.test.ts +305 -0
- package/src/summarization/node.ts +53 -0
- package/src/tools/BashExecutor.ts +205 -0
- package/src/tools/BashProgrammaticToolCalling.ts +397 -0
- package/src/tools/ReadFile.ts +39 -0
- package/src/tools/SkillTool.ts +46 -0
- package/src/tools/SubagentTool.ts +100 -0
- package/src/tools/ToolNode.ts +391 -169
- package/src/tools/__tests__/ReadFile.test.ts +44 -0
- package/src/tools/__tests__/SkillTool.test.ts +442 -0
- package/src/tools/__tests__/SubagentExecutor.test.ts +615 -0
- package/src/tools/__tests__/SubagentTool.test.ts +149 -0
- package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
- package/src/tools/__tests__/skillCatalog.test.ts +161 -0
- package/src/tools/__tests__/subagentHooks.test.ts +215 -0
- package/src/tools/skillCatalog.ts +126 -0
- package/src/tools/subagent/SubagentExecutor.ts +344 -0
- package/src/tools/subagent/index.ts +12 -0
- package/src/types/graph.ts +27 -0
- package/src/types/index.ts +1 -0
- package/src/types/llm.ts +16 -2
- package/src/types/run.ts +20 -0
- package/src/types/skill.ts +11 -0
- package/src/types/tools.ts +41 -1
|
@@ -1,7 +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 {
|
|
4
|
+
import type { HookRegistry } from '@/hooks';
|
|
5
|
+
import type { MessageContentComplex, ToolErrorData } from './stream';
|
|
5
6
|
import { EnvVar } from '@/common';
|
|
6
7
|
/** Replacement type for `import type { ToolCall } from '@langchain/core/messages/tool'` in order to have stringified args typed */
|
|
7
8
|
export type CustomToolCall = {
|
|
@@ -39,6 +40,12 @@ export type ToolNodeOptions = {
|
|
|
39
40
|
agentId?: string;
|
|
40
41
|
/** Tool names that must be executed directly (via runTool) even in event-driven mode (e.g., graph-managed handoff tools) */
|
|
41
42
|
directToolNames?: Set<string>;
|
|
43
|
+
/**
|
|
44
|
+
* Hook registry for PreToolUse/PostToolUse lifecycle hooks.
|
|
45
|
+
* Only fires for event-driven tool calls (`dispatchToolEvents`). Tools
|
|
46
|
+
* routed through `directToolNames` bypass hook dispatch entirely.
|
|
47
|
+
*/
|
|
48
|
+
hookRegistry?: HookRegistry;
|
|
42
49
|
/** Max context tokens for the agent — used to compute tool result truncation limits. */
|
|
43
50
|
maxContextTokens?: number;
|
|
44
51
|
/**
|
|
@@ -154,6 +161,25 @@ export type ToolExecuteBatchRequest = {
|
|
|
154
161
|
/** Promise rejector - handler calls this on fatal error */
|
|
155
162
|
reject: (error: Error) => void;
|
|
156
163
|
};
|
|
164
|
+
/**
|
|
165
|
+
* A message injected into graph state by any tool execution handler.
|
|
166
|
+
* Generic mechanism: any tool returning `injectedMessages` in its `ToolExecuteResult`
|
|
167
|
+
* will have these appended to state after the ToolMessage for this call.
|
|
168
|
+
*/
|
|
169
|
+
export type InjectedMessage = {
|
|
170
|
+
/** 'user' for skill body injection, 'system' for context hints.
|
|
171
|
+
* Both are converted to HumanMessage at runtime; the original role
|
|
172
|
+
* is preserved in additional_kwargs.role. */
|
|
173
|
+
role: 'user' | 'system';
|
|
174
|
+
/** Message content: string for simple text, array for complex multi-part content */
|
|
175
|
+
content: string | MessageContentComplex[];
|
|
176
|
+
/** When true, the message is framework-internal: not shown in UI, not counted as a user turn */
|
|
177
|
+
isMeta?: boolean;
|
|
178
|
+
/** Origin tag for downstream consumers (UI, pruner, compaction) */
|
|
179
|
+
source?: 'skill' | 'hook' | 'system';
|
|
180
|
+
/** Only set when source is 'skill', for compaction preservation */
|
|
181
|
+
skillName?: string;
|
|
182
|
+
};
|
|
157
183
|
/** Result for a single tool call in event-driven execution */
|
|
158
184
|
export type ToolExecuteResult = {
|
|
159
185
|
/** Matches ToolCallRequest.id */
|
|
@@ -166,6 +192,13 @@ export type ToolExecuteResult = {
|
|
|
166
192
|
status: 'success' | 'error';
|
|
167
193
|
/** Error message if status is 'error' */
|
|
168
194
|
errorMessage?: string;
|
|
195
|
+
/**
|
|
196
|
+
* Messages to inject into graph state after the ToolMessage for this call.
|
|
197
|
+
* Placed after tool results to respect provider message ordering (tool_call -> tool_result adjacency).
|
|
198
|
+
* The host's message formatter may merge injected user messages with the preceding tool_result turn.
|
|
199
|
+
* Generic mechanism: any tool execution handler can use this.
|
|
200
|
+
*/
|
|
201
|
+
injectedMessages?: InjectedMessage[];
|
|
169
202
|
};
|
|
170
203
|
/** Map of tool names to tool definitions */
|
|
171
204
|
export type LCToolRegistry = Map<string, LCTool>;
|
|
@@ -266,6 +299,10 @@ export type ProgrammaticExecutionArtifact = {
|
|
|
266
299
|
session_id?: string;
|
|
267
300
|
files?: FileRefs;
|
|
268
301
|
};
|
|
302
|
+
/** Parameters for creating a bash execution tool (same API as CodeExecutor, bash-only) */
|
|
303
|
+
export type BashExecutionToolParams = CodeExecutionToolParams;
|
|
304
|
+
/** Parameters for creating a bash programmatic tool calling tool (same API as PTC, bash-only) */
|
|
305
|
+
export type BashProgrammaticToolCallingParams = ProgrammaticToolCallingParams;
|
|
269
306
|
/**
|
|
270
307
|
* Initialization parameters for the PTC tool
|
|
271
308
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@librechat/agents",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.67-dev.0",
|
|
4
4
|
"main": "./dist/cjs/main.cjs",
|
|
5
5
|
"module": "./dist/esm/main.mjs",
|
|
6
6
|
"types": "./dist/types/index.d.ts",
|
|
@@ -77,6 +77,7 @@
|
|
|
77
77
|
"multi-agent-chain": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-chain.ts",
|
|
78
78
|
"multi-agent-sequence": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-sequence.ts",
|
|
79
79
|
"multi-agent-conditional": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-conditional.ts",
|
|
80
|
+
"multi-agent-subagent": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-subagent.ts",
|
|
80
81
|
"multi-agent-supervisor": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-supervisor.ts",
|
|
81
82
|
"test-handoff-preamble": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/test-handoff-preamble.ts",
|
|
82
83
|
"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
|
-
|
|
689
|
-
|
|
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 &&
|
package/src/common/enum.ts
CHANGED
|
@@ -182,8 +182,21 @@ export enum Constants {
|
|
|
182
182
|
MCP_DELIMITER = '_mcp_',
|
|
183
183
|
/** Anthropic server tool ID prefix (web_search, code_execution, etc.) */
|
|
184
184
|
ANTHROPIC_SERVER_TOOL_PREFIX = 'srvtoolu_',
|
|
185
|
+
SKILL_TOOL = 'skill',
|
|
186
|
+
READ_FILE = 'read_file',
|
|
187
|
+
BASH_TOOL = 'bash_tool',
|
|
188
|
+
BASH_PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_bash',
|
|
189
|
+
SUBAGENT = 'subagent',
|
|
185
190
|
}
|
|
186
191
|
|
|
192
|
+
/** Tool names that use the code execution environment (shared session, file tracking). */
|
|
193
|
+
export const CODE_EXECUTION_TOOLS: ReadonlySet<string> = new Set([
|
|
194
|
+
Constants.EXECUTE_CODE,
|
|
195
|
+
Constants.BASH_TOOL,
|
|
196
|
+
Constants.PROGRAMMATIC_TOOL_CALLING,
|
|
197
|
+
Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
|
|
198
|
+
]);
|
|
199
|
+
|
|
187
200
|
export enum TitleMethod {
|
|
188
201
|
STRUCTURED = 'structured',
|
|
189
202
|
FUNCTIONS = 'functions',
|
package/src/graphs/Graph.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/* eslint-disable no-console */
|
|
2
2
|
import { nanoid } from 'nanoid';
|
|
3
|
+
import { tool } from '@langchain/core/tools';
|
|
3
4
|
import { ToolNode } from '@langchain/langgraph/prebuilt';
|
|
4
5
|
import { Runnable, RunnableConfig } from '@langchain/core/runnables';
|
|
5
6
|
import { ToolMessage, AIMessageChunk } from '@langchain/core/messages';
|
|
@@ -39,6 +40,8 @@ import {
|
|
|
39
40
|
joinKeys,
|
|
40
41
|
sleep,
|
|
41
42
|
} from '@/utils';
|
|
43
|
+
import { SubagentExecutor, resolveSubagentConfigs } from '@/tools/subagent';
|
|
44
|
+
import { buildSubagentToolParams } from '@/tools/SubagentTool';
|
|
42
45
|
import { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';
|
|
43
46
|
import { safeDispatchCustomEvent, emitAgentLog } from '@/utils/events';
|
|
44
47
|
import { attemptInvoke, tryFallbackProviders } from '@/llm/invoke';
|
|
@@ -53,6 +56,7 @@ import { isThinkingEnabled } from '@/llm/request';
|
|
|
53
56
|
import { initializeModel } from '@/llm/init';
|
|
54
57
|
import { HandlerRegistry } from '@/events';
|
|
55
58
|
import { ChatOpenAI } from '@/llm/openai';
|
|
59
|
+
import type { HookRegistry } from '@/hooks';
|
|
56
60
|
|
|
57
61
|
const { AGENT, TOOLS, SUMMARIZE } = GraphNodeKeys;
|
|
58
62
|
|
|
@@ -123,6 +127,7 @@ export abstract class Graph<
|
|
|
123
127
|
/** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */
|
|
124
128
|
invokedToolIds?: Set<string>;
|
|
125
129
|
handlerRegistry: HandlerRegistry | undefined;
|
|
130
|
+
hookRegistry: HookRegistry | undefined;
|
|
126
131
|
/**
|
|
127
132
|
* Tool session contexts for automatic state persistence across tool invocations.
|
|
128
133
|
* Keyed by tool name (e.g., Constants.EXECUTE_CODE).
|
|
@@ -147,6 +152,7 @@ export abstract class Graph<
|
|
|
147
152
|
this.prelimMessageIdsByStepKey = new Map();
|
|
148
153
|
this.invokedToolIds = undefined;
|
|
149
154
|
this.handlerRegistry = undefined;
|
|
155
|
+
this.hookRegistry = undefined;
|
|
150
156
|
this.sessions.clear();
|
|
151
157
|
}
|
|
152
158
|
}
|
|
@@ -506,6 +512,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
|
|
|
506
512
|
agentId: agentContext?.agentId,
|
|
507
513
|
toolCallStepIds: this.toolCallStepIds,
|
|
508
514
|
toolRegistry: agentContext?.toolRegistry,
|
|
515
|
+
hookRegistry: this.hookRegistry,
|
|
509
516
|
directToolNames: directToolNames.size > 0 ? directToolNames : undefined,
|
|
510
517
|
maxContextTokens: agentContext?.maxContextTokens,
|
|
511
518
|
maxToolResultChars: agentContext?.maxToolResultChars,
|
|
@@ -1148,6 +1155,90 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
|
|
|
1148
1155
|
throw new Error(`Agent context not found for agentId: ${agentId}`);
|
|
1149
1156
|
}
|
|
1150
1157
|
|
|
1158
|
+
/**
|
|
1159
|
+
* Depth countdown across graph boundaries: the parent's `maxSubagentDepth`
|
|
1160
|
+
* becomes this executor's `maxDepth`. When the child graph is constructed,
|
|
1161
|
+
* `buildChildInputs()` decrements `maxSubagentDepth` on the child's
|
|
1162
|
+
* `AgentInputs` (only when `allowNested: true`; otherwise subagentConfigs
|
|
1163
|
+
* are stripped entirely). The child graph's own `createAgentNode()` then
|
|
1164
|
+
* reads the decremented value here and creates a narrower executor —
|
|
1165
|
+
* recursion is bounded even though each graph has its own separate
|
|
1166
|
+
* executor instance.
|
|
1167
|
+
*/
|
|
1168
|
+
const effectiveSubagentDepth = agentContext.maxSubagentDepth ?? 1;
|
|
1169
|
+
if (
|
|
1170
|
+
agentContext.subagentConfigs != null &&
|
|
1171
|
+
agentContext.subagentConfigs.length > 0 &&
|
|
1172
|
+
effectiveSubagentDepth > 0
|
|
1173
|
+
) {
|
|
1174
|
+
const resolvedConfigs = resolveSubagentConfigs(
|
|
1175
|
+
agentContext.subagentConfigs,
|
|
1176
|
+
agentContext
|
|
1177
|
+
);
|
|
1178
|
+
if (resolvedConfigs.length > 0) {
|
|
1179
|
+
const executor = new SubagentExecutor({
|
|
1180
|
+
configs: new Map(resolvedConfigs.map((c) => [c.type, c])),
|
|
1181
|
+
parentSignal: this.signal,
|
|
1182
|
+
hookRegistry: this.hookRegistry,
|
|
1183
|
+
parentRunId: this.runId ?? '',
|
|
1184
|
+
parentAgentId: agentContext.agentId,
|
|
1185
|
+
tokenCounter: agentContext.tokenCounter,
|
|
1186
|
+
maxDepth: effectiveSubagentDepth,
|
|
1187
|
+
createChildGraph: (input): StandardGraph => new StandardGraph(input),
|
|
1188
|
+
});
|
|
1189
|
+
|
|
1190
|
+
const subagentTool = tool(async (rawInput, config) => {
|
|
1191
|
+
const input = rawInput as {
|
|
1192
|
+
description?: string;
|
|
1193
|
+
subagent_type?: string;
|
|
1194
|
+
};
|
|
1195
|
+
const description =
|
|
1196
|
+
typeof input.description === 'string' &&
|
|
1197
|
+
input.description.trim().length > 0
|
|
1198
|
+
? input.description
|
|
1199
|
+
: 'No task description provided';
|
|
1200
|
+
const subagentType =
|
|
1201
|
+
typeof input.subagent_type === 'string' ? input.subagent_type : '';
|
|
1202
|
+
const threadId = config.configurable?.thread_id as string | undefined;
|
|
1203
|
+
const result = await executor.execute({
|
|
1204
|
+
description,
|
|
1205
|
+
subagentType,
|
|
1206
|
+
threadId,
|
|
1207
|
+
});
|
|
1208
|
+
return result.content;
|
|
1209
|
+
}, buildSubagentToolParams(resolvedConfigs));
|
|
1210
|
+
|
|
1211
|
+
if (!agentContext.graphTools) {
|
|
1212
|
+
agentContext.graphTools = [];
|
|
1213
|
+
}
|
|
1214
|
+
(agentContext.graphTools as t.GenericTool[]).push(subagentTool);
|
|
1215
|
+
|
|
1216
|
+
/**
|
|
1217
|
+
* Refresh toolSchemaTokens to include the subagent tool's schema.
|
|
1218
|
+
* `calculateInstructionTokens()` was kicked off in `fromConfig()`
|
|
1219
|
+
* before graphTools was populated, so its result did not count this
|
|
1220
|
+
* tool. Without this retrigger, token-budget/pruning logic
|
|
1221
|
+
* underestimates prompt overhead.
|
|
1222
|
+
*/
|
|
1223
|
+
if (agentContext.tokenCounter) {
|
|
1224
|
+
const { tokenCounter, baseIndexTokenCountMap } = agentContext;
|
|
1225
|
+
agentContext.tokenCalculationPromise = agentContext
|
|
1226
|
+
.calculateInstructionTokens(tokenCounter)
|
|
1227
|
+
.then(() => {
|
|
1228
|
+
agentContext.updateTokenMapWithInstructions(
|
|
1229
|
+
baseIndexTokenCountMap
|
|
1230
|
+
);
|
|
1231
|
+
})
|
|
1232
|
+
.catch((err) => {
|
|
1233
|
+
console.error(
|
|
1234
|
+
'Error recalculating instruction tokens after subagent tool injection:',
|
|
1235
|
+
err
|
|
1236
|
+
);
|
|
1237
|
+
});
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1151
1242
|
const agentNode = `${AGENT}${agentId}` as const;
|
|
1152
1243
|
const toolNode = `${TOOLS}${agentId}` as const;
|
|
1153
1244
|
const summarizeNode = `${SUMMARIZE}${agentId}` as const;
|
|
@@ -1203,6 +1294,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
|
|
|
1203
1294
|
},
|
|
1204
1295
|
runId: this.runId,
|
|
1205
1296
|
isMultiAgent: this.isMultiAgentGraph(),
|
|
1297
|
+
hookRegistry: this.hookRegistry,
|
|
1206
1298
|
dispatchRunStep: async (runStep, nodeConfig) => {
|
|
1207
1299
|
this.contentData.push(runStep);
|
|
1208
1300
|
this.contentIndexMap.set(runStep.id, runStep.index);
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// src/hooks/HookRegistry.ts
|
|
2
|
+
import type { HookEvent, HookMatcher } from './types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Internal matcher storage type.
|
|
6
|
+
*
|
|
7
|
+
* Matchers registered via the public `register<E>` API are strictly typed
|
|
8
|
+
* to a single `E`, but the storage needs one uniform slot type per event.
|
|
9
|
+
* We store them as `HookMatcher<HookEvent>` and cast once at the variance
|
|
10
|
+
* boundary — see `ensureList` and `snapshot` below. The invariant (every
|
|
11
|
+
* matcher in `bucket[event]` was registered with that exact event) is
|
|
12
|
+
* enforced by the public API; breaking it requires bypassing the types.
|
|
13
|
+
*/
|
|
14
|
+
type MatcherBucket = Partial<Record<HookEvent, HookMatcher<HookEvent>[]>>;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Run-scoped storage for hook matchers with an additional layer for
|
|
18
|
+
* session-scoped matchers that should be cleaned up between sessions.
|
|
19
|
+
*
|
|
20
|
+
* Hosts construct one registry per `Run` (mirroring how `HandlerRegistry` is
|
|
21
|
+
* scoped) and register global matchers + per-session matchers against it.
|
|
22
|
+
* Registration is strictly additive — nothing in this class mutates a
|
|
23
|
+
* matcher's callbacks or flags after insertion.
|
|
24
|
+
*
|
|
25
|
+
* ## Why `Map<sessionId, MatcherBucket>` and not `Record`
|
|
26
|
+
*
|
|
27
|
+
* LibreChat runs thousands of parallel sessions in one Node process, and
|
|
28
|
+
* hook registration happens inside hot paths (tool loading, agent spawning).
|
|
29
|
+
* A `Record<sessionId, ...>` has to be spread on every insertion, which is
|
|
30
|
+
* O(n) per call and O(n²) total for a batch of parallel registrations. A
|
|
31
|
+
* Map mutates in place, keeping insertions O(1). This mirrors the reasoning
|
|
32
|
+
* Claude Code documents at `utils/hooks/sessionHooks.ts:62`.
|
|
33
|
+
*/
|
|
34
|
+
export class HookRegistry {
|
|
35
|
+
private readonly global: MatcherBucket = {};
|
|
36
|
+
private readonly sessions: Map<string, MatcherBucket> = new Map();
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Register a matcher for the lifetime of this registry (= one Run).
|
|
40
|
+
* Returns an unregister function that removes the matcher by reference.
|
|
41
|
+
*/
|
|
42
|
+
register<E extends HookEvent>(event: E, matcher: HookMatcher<E>): () => void {
|
|
43
|
+
const list = ensureList(this.global, event);
|
|
44
|
+
list.push(widen(matcher));
|
|
45
|
+
return () => {
|
|
46
|
+
removeFromList(list, matcher);
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Register a matcher for a specific session. Cleared automatically when
|
|
52
|
+
* `clearSession(sessionId)` is called, or can be removed directly via the
|
|
53
|
+
* returned unregister function.
|
|
54
|
+
*/
|
|
55
|
+
registerSession<E extends HookEvent>(
|
|
56
|
+
sessionId: string,
|
|
57
|
+
event: E,
|
|
58
|
+
matcher: HookMatcher<E>
|
|
59
|
+
): () => void {
|
|
60
|
+
const bucket = this.ensureSessionBucket(sessionId);
|
|
61
|
+
const list = ensureList(bucket, event);
|
|
62
|
+
list.push(widen(matcher));
|
|
63
|
+
return () => {
|
|
64
|
+
removeFromList(list, matcher);
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Returns all matchers registered for `event`, concatenating global first
|
|
70
|
+
* and then session-specific (when `sessionId` is supplied). The caller
|
|
71
|
+
* receives a fresh array, so iterating it is safe even if a matcher is
|
|
72
|
+
* removed mid-iteration (e.g. via `once: true`).
|
|
73
|
+
*/
|
|
74
|
+
getMatchers<E extends HookEvent>(
|
|
75
|
+
event: E,
|
|
76
|
+
sessionId?: string
|
|
77
|
+
): HookMatcher<E>[] {
|
|
78
|
+
const globalList = readList(this.global, event);
|
|
79
|
+
if (sessionId === undefined) {
|
|
80
|
+
return snapshot<E>(globalList);
|
|
81
|
+
}
|
|
82
|
+
const bucket = this.sessions.get(sessionId);
|
|
83
|
+
if (bucket === undefined) {
|
|
84
|
+
return snapshot<E>(globalList);
|
|
85
|
+
}
|
|
86
|
+
const sessionList = readList(bucket, event);
|
|
87
|
+
if (globalList.length === 0) {
|
|
88
|
+
return snapshot<E>(sessionList);
|
|
89
|
+
}
|
|
90
|
+
if (sessionList.length === 0) {
|
|
91
|
+
return snapshot<E>(globalList);
|
|
92
|
+
}
|
|
93
|
+
return snapshot<E>([...globalList, ...sessionList]);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Removes `matcher` by reference from global storage first, falling back
|
|
98
|
+
* to the session bucket when `sessionId` is supplied. Used by
|
|
99
|
+
* `executeHooks` to drop `once: true` matchers after they fire.
|
|
100
|
+
*/
|
|
101
|
+
removeMatcher<E extends HookEvent>(
|
|
102
|
+
event: E,
|
|
103
|
+
matcher: HookMatcher<E>,
|
|
104
|
+
sessionId?: string
|
|
105
|
+
): boolean {
|
|
106
|
+
if (removeFromList(readList(this.global, event), matcher)) {
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
if (sessionId === undefined) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
const bucket = this.sessions.get(sessionId);
|
|
113
|
+
if (bucket === undefined) {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
return removeFromList(readList(bucket, event), matcher);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Drops every session-scoped matcher for `sessionId`. Call this in the
|
|
121
|
+
* `finally` block around a Run so a `once: true` hook that never fired
|
|
122
|
+
* cannot leak into the next session on the same registry.
|
|
123
|
+
*/
|
|
124
|
+
clearSession(sessionId: string): void {
|
|
125
|
+
this.sessions.delete(sessionId);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** True if at least one matcher exists for `event` (global + session). */
|
|
129
|
+
hasHookFor(event: HookEvent, sessionId?: string): boolean {
|
|
130
|
+
if (readList(this.global, event).length > 0) {
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
if (sessionId === undefined) {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
const bucket = this.sessions.get(sessionId);
|
|
137
|
+
if (bucket === undefined) {
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
return readList(bucket, event).length > 0;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private ensureSessionBucket(sessionId: string): MatcherBucket {
|
|
144
|
+
const existing = this.sessions.get(sessionId);
|
|
145
|
+
if (existing !== undefined) {
|
|
146
|
+
return existing;
|
|
147
|
+
}
|
|
148
|
+
const fresh: MatcherBucket = {};
|
|
149
|
+
this.sessions.set(sessionId, fresh);
|
|
150
|
+
return fresh;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function ensureList(
|
|
155
|
+
bucket: MatcherBucket,
|
|
156
|
+
event: HookEvent
|
|
157
|
+
): HookMatcher<HookEvent>[] {
|
|
158
|
+
const existing = bucket[event];
|
|
159
|
+
if (existing !== undefined) {
|
|
160
|
+
return existing;
|
|
161
|
+
}
|
|
162
|
+
const fresh: HookMatcher<HookEvent>[] = [];
|
|
163
|
+
bucket[event] = fresh;
|
|
164
|
+
return fresh;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function readList(
|
|
168
|
+
bucket: MatcherBucket,
|
|
169
|
+
event: HookEvent
|
|
170
|
+
): HookMatcher<HookEvent>[] {
|
|
171
|
+
return bucket[event] ?? [];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function removeFromList<E extends HookEvent>(
|
|
175
|
+
list: HookMatcher<HookEvent>[],
|
|
176
|
+
matcher: HookMatcher<E>
|
|
177
|
+
): boolean {
|
|
178
|
+
const idx = list.indexOf(widen(matcher));
|
|
179
|
+
if (idx < 0) {
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
list.splice(idx, 1);
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Widen a per-event matcher to the storage's uniform slot type. Unsound at
|
|
188
|
+
* the type level (function parameters are contravariant) but safe by
|
|
189
|
+
* construction: `HookRegistry.register<E>` only ever puts matchers into the
|
|
190
|
+
* bucket slot for their own event, and reads go through `snapshot<E>`
|
|
191
|
+
* which is only called with the same `E`.
|
|
192
|
+
*/
|
|
193
|
+
function widen<E extends HookEvent>(
|
|
194
|
+
matcher: HookMatcher<E>
|
|
195
|
+
): HookMatcher<HookEvent> {
|
|
196
|
+
return matcher as unknown as HookMatcher<HookEvent>;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Narrow a storage list back to a per-event matcher list on the way out.
|
|
201
|
+
* Sound counterpart to `widen`: the list only contains matchers that were
|
|
202
|
+
* registered against `E`, because the public API enforces it on insert.
|
|
203
|
+
*/
|
|
204
|
+
function snapshot<E extends HookEvent>(
|
|
205
|
+
list: readonly HookMatcher<HookEvent>[]
|
|
206
|
+
): HookMatcher<E>[] {
|
|
207
|
+
return list.slice() as unknown as HookMatcher<E>[];
|
|
208
|
+
}
|