@librechat/agents 3.1.67-dev.4 → 3.1.68

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 (162) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +3 -23
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +0 -16
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +0 -91
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/graphs/MultiAgentGraph.cjs +36 -0
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  9. package/dist/cjs/main.cjs +1 -53
  10. package/dist/cjs/main.cjs.map +1 -1
  11. package/dist/cjs/messages/format.cjs +12 -74
  12. package/dist/cjs/messages/format.cjs.map +1 -1
  13. package/dist/cjs/run.cjs +0 -111
  14. package/dist/cjs/run.cjs.map +1 -1
  15. package/dist/cjs/summarization/index.cjs +41 -0
  16. package/dist/cjs/summarization/index.cjs.map +1 -1
  17. package/dist/cjs/summarization/node.cjs +121 -63
  18. package/dist/cjs/summarization/node.cjs.map +1 -1
  19. package/dist/cjs/tools/ToolNode.cjs +140 -304
  20. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  21. package/dist/esm/agents/AgentContext.mjs +3 -23
  22. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  23. package/dist/esm/common/enum.mjs +1 -15
  24. package/dist/esm/common/enum.mjs.map +1 -1
  25. package/dist/esm/graphs/Graph.mjs +0 -91
  26. package/dist/esm/graphs/Graph.mjs.map +1 -1
  27. package/dist/esm/graphs/MultiAgentGraph.mjs +36 -0
  28. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  29. package/dist/esm/main.mjs +2 -13
  30. package/dist/esm/main.mjs.map +1 -1
  31. package/dist/esm/messages/format.mjs +4 -66
  32. package/dist/esm/messages/format.mjs.map +1 -1
  33. package/dist/esm/run.mjs +0 -111
  34. package/dist/esm/run.mjs.map +1 -1
  35. package/dist/esm/summarization/index.mjs +41 -1
  36. package/dist/esm/summarization/index.mjs.map +1 -1
  37. package/dist/esm/summarization/node.mjs +121 -63
  38. package/dist/esm/summarization/node.mjs.map +1 -1
  39. package/dist/esm/tools/ToolNode.mjs +142 -306
  40. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  41. package/dist/types/agents/AgentContext.d.ts +0 -6
  42. package/dist/types/common/enum.d.ts +1 -10
  43. package/dist/types/graphs/Graph.d.ts +0 -2
  44. package/dist/types/graphs/MultiAgentGraph.d.ts +12 -0
  45. package/dist/types/index.d.ts +0 -8
  46. package/dist/types/messages/format.d.ts +1 -2
  47. package/dist/types/run.d.ts +0 -1
  48. package/dist/types/summarization/index.d.ts +2 -0
  49. package/dist/types/summarization/node.d.ts +0 -2
  50. package/dist/types/tools/ToolNode.d.ts +2 -24
  51. package/dist/types/types/graph.d.ts +2 -61
  52. package/dist/types/types/index.d.ts +0 -1
  53. package/dist/types/types/run.d.ts +0 -20
  54. package/dist/types/types/tools.d.ts +1 -38
  55. package/package.json +1 -5
  56. package/src/agents/AgentContext.ts +2 -26
  57. package/src/common/enum.ts +0 -15
  58. package/src/graphs/Graph.ts +0 -113
  59. package/src/graphs/MultiAgentGraph.ts +39 -0
  60. package/src/graphs/__tests__/MultiAgentGraph.test.ts +91 -0
  61. package/src/index.ts +0 -10
  62. package/src/messages/format.ts +4 -74
  63. package/src/run.ts +0 -126
  64. package/src/summarization/__tests__/node.test.ts +42 -0
  65. package/src/summarization/__tests__/trigger.test.ts +100 -1
  66. package/src/summarization/index.ts +47 -0
  67. package/src/summarization/node.ts +149 -77
  68. package/src/tools/ToolNode.ts +169 -391
  69. package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
  70. package/src/types/graph.ts +1 -80
  71. package/src/types/index.ts +0 -1
  72. package/src/types/run.ts +0 -20
  73. package/src/types/tools.ts +1 -41
  74. package/dist/cjs/hooks/HookRegistry.cjs +0 -162
  75. package/dist/cjs/hooks/HookRegistry.cjs.map +0 -1
  76. package/dist/cjs/hooks/executeHooks.cjs +0 -276
  77. package/dist/cjs/hooks/executeHooks.cjs.map +0 -1
  78. package/dist/cjs/hooks/matchers.cjs +0 -256
  79. package/dist/cjs/hooks/matchers.cjs.map +0 -1
  80. package/dist/cjs/hooks/types.cjs +0 -27
  81. package/dist/cjs/hooks/types.cjs.map +0 -1
  82. package/dist/cjs/tools/BashExecutor.cjs +0 -175
  83. package/dist/cjs/tools/BashExecutor.cjs.map +0 -1
  84. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +0 -296
  85. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +0 -1
  86. package/dist/cjs/tools/ReadFile.cjs +0 -43
  87. package/dist/cjs/tools/ReadFile.cjs.map +0 -1
  88. package/dist/cjs/tools/SkillTool.cjs +0 -50
  89. package/dist/cjs/tools/SkillTool.cjs.map +0 -1
  90. package/dist/cjs/tools/SubagentTool.cjs +0 -92
  91. package/dist/cjs/tools/SubagentTool.cjs.map +0 -1
  92. package/dist/cjs/tools/skillCatalog.cjs +0 -84
  93. package/dist/cjs/tools/skillCatalog.cjs.map +0 -1
  94. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +0 -511
  95. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +0 -1
  96. package/dist/esm/hooks/HookRegistry.mjs +0 -160
  97. package/dist/esm/hooks/HookRegistry.mjs.map +0 -1
  98. package/dist/esm/hooks/executeHooks.mjs +0 -273
  99. package/dist/esm/hooks/executeHooks.mjs.map +0 -1
  100. package/dist/esm/hooks/matchers.mjs +0 -251
  101. package/dist/esm/hooks/matchers.mjs.map +0 -1
  102. package/dist/esm/hooks/types.mjs +0 -25
  103. package/dist/esm/hooks/types.mjs.map +0 -1
  104. package/dist/esm/tools/BashExecutor.mjs +0 -169
  105. package/dist/esm/tools/BashExecutor.mjs.map +0 -1
  106. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +0 -287
  107. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +0 -1
  108. package/dist/esm/tools/ReadFile.mjs +0 -38
  109. package/dist/esm/tools/ReadFile.mjs.map +0 -1
  110. package/dist/esm/tools/SkillTool.mjs +0 -45
  111. package/dist/esm/tools/SkillTool.mjs.map +0 -1
  112. package/dist/esm/tools/SubagentTool.mjs +0 -85
  113. package/dist/esm/tools/SubagentTool.mjs.map +0 -1
  114. package/dist/esm/tools/skillCatalog.mjs +0 -82
  115. package/dist/esm/tools/skillCatalog.mjs.map +0 -1
  116. package/dist/esm/tools/subagent/SubagentExecutor.mjs +0 -505
  117. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +0 -1
  118. package/dist/types/hooks/HookRegistry.d.ts +0 -56
  119. package/dist/types/hooks/executeHooks.d.ts +0 -79
  120. package/dist/types/hooks/index.d.ts +0 -6
  121. package/dist/types/hooks/matchers.d.ts +0 -95
  122. package/dist/types/hooks/types.d.ts +0 -320
  123. package/dist/types/tools/BashExecutor.d.ts +0 -45
  124. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +0 -72
  125. package/dist/types/tools/ReadFile.d.ts +0 -28
  126. package/dist/types/tools/SkillTool.d.ts +0 -40
  127. package/dist/types/tools/SubagentTool.d.ts +0 -36
  128. package/dist/types/tools/skillCatalog.d.ts +0 -19
  129. package/dist/types/tools/subagent/SubagentExecutor.d.ts +0 -137
  130. package/dist/types/tools/subagent/index.d.ts +0 -2
  131. package/dist/types/types/skill.d.ts +0 -9
  132. package/src/hooks/HookRegistry.ts +0 -208
  133. package/src/hooks/__tests__/HookRegistry.test.ts +0 -190
  134. package/src/hooks/__tests__/compactHooks.test.ts +0 -214
  135. package/src/hooks/__tests__/executeHooks.test.ts +0 -1013
  136. package/src/hooks/__tests__/integration.test.ts +0 -337
  137. package/src/hooks/__tests__/matchers.test.ts +0 -238
  138. package/src/hooks/__tests__/toolHooks.test.ts +0 -669
  139. package/src/hooks/executeHooks.ts +0 -375
  140. package/src/hooks/index.ts +0 -57
  141. package/src/hooks/matchers.ts +0 -280
  142. package/src/hooks/types.ts +0 -404
  143. package/src/messages/formatAgentMessages.skills.test.ts +0 -334
  144. package/src/scripts/multi-agent-subagent.ts +0 -246
  145. package/src/scripts/subagent-event-driven-debug.ts +0 -190
  146. package/src/scripts/subagent-tools-debug.ts +0 -160
  147. package/src/specs/subagent.test.ts +0 -305
  148. package/src/tools/BashExecutor.ts +0 -205
  149. package/src/tools/BashProgrammaticToolCalling.ts +0 -397
  150. package/src/tools/ReadFile.ts +0 -39
  151. package/src/tools/SkillTool.ts +0 -46
  152. package/src/tools/SubagentTool.ts +0 -100
  153. package/src/tools/__tests__/ReadFile.test.ts +0 -44
  154. package/src/tools/__tests__/SkillTool.test.ts +0 -442
  155. package/src/tools/__tests__/SubagentExecutor.test.ts +0 -1148
  156. package/src/tools/__tests__/SubagentTool.test.ts +0 -149
  157. package/src/tools/__tests__/skillCatalog.test.ts +0 -161
  158. package/src/tools/__tests__/subagentHooks.test.ts +0 -215
  159. package/src/tools/skillCatalog.ts +0 -126
  160. package/src/tools/subagent/SubagentExecutor.ts +0 -676
  161. package/src/tools/subagent/index.ts +0 -13
  162. package/src/types/skill.ts +0 -11
@@ -1,40 +0,0 @@
1
- import { Constants } from '@/common';
2
- export declare const SkillToolName = Constants.SKILL_TOOL;
3
- export declare const SkillToolDescription = "Invoke a skill from the user's library. Skills provide domain-specific instructions loaded into the conversation context, and may also provide files accessible via available tools depending on the runtime environment.\n\nWHEN TO USE:\n- The user's request matches a skill listed in the \"Available Skills\" section of the system prompt.\n- You MUST invoke the matching skill BEFORE attempting the task yourself.\n\nWHAT HAPPENS:\n- The skill's full instructions are loaded into the conversation as context.\n- Files bundled with the skill may become accessible via available tools.\n- Follow the skill's instructions to complete the task.\n\nCONSTRAINTS:\n- Do not invoke a skill that is already active in this conversation.\n- Skill names come from the catalog only. Do not guess names.";
4
- /**
5
- * JSON Schema for the SkillTool parameters.
6
- * Single source of truth used by both SkillToolDefinition (LCTool registry)
7
- * and createSkillTool() (DynamicStructuredTool instance).
8
- */
9
- export declare const SkillToolSchema: {
10
- readonly type: "object";
11
- readonly properties: {
12
- readonly skillName: {
13
- readonly type: "string";
14
- readonly description: "The kebab-case identifier of the skill to invoke (e.g. \"financial-analyzer\", \"meeting-notes\"). Must match a name from the \"Available Skills\" section.";
15
- };
16
- readonly args: {
17
- readonly type: "string";
18
- readonly description: "Optional freeform arguments string passed to the skill.";
19
- };
20
- };
21
- readonly required: readonly ["skillName"];
22
- };
23
- export declare const SkillToolDefinition: {
24
- readonly name: Constants.SKILL_TOOL;
25
- readonly description: "Invoke a skill from the user's library. Skills provide domain-specific instructions loaded into the conversation context, and may also provide files accessible via available tools depending on the runtime environment.\n\nWHEN TO USE:\n- The user's request matches a skill listed in the \"Available Skills\" section of the system prompt.\n- You MUST invoke the matching skill BEFORE attempting the task yourself.\n\nWHAT HAPPENS:\n- The skill's full instructions are loaded into the conversation as context.\n- Files bundled with the skill may become accessible via available tools.\n- Follow the skill's instructions to complete the task.\n\nCONSTRAINTS:\n- Do not invoke a skill that is already active in this conversation.\n- Skill names come from the catalog only. Do not guess names.";
26
- readonly parameters: {
27
- readonly type: "object";
28
- readonly properties: {
29
- readonly skillName: {
30
- readonly type: "string";
31
- readonly description: "The kebab-case identifier of the skill to invoke (e.g. \"financial-analyzer\", \"meeting-notes\"). Must match a name from the \"Available Skills\" section.";
32
- };
33
- readonly args: {
34
- readonly type: "string";
35
- readonly description: "Optional freeform arguments string passed to the skill.";
36
- };
37
- };
38
- readonly required: readonly ["skillName"];
39
- };
40
- };
@@ -1,36 +0,0 @@
1
- import { Constants } from '@/common';
2
- import type { SubagentConfig } from '@/types';
3
- import type { JsonSchemaType, LCTool } from '@/types/tools';
4
- export declare const SubagentToolName = Constants.SUBAGENT;
5
- export declare const SubagentToolDescription = "Delegate a task to a specialized subagent that runs in an isolated context window. The subagent executes independently and returns only its final text result \u2014 all intermediate tool calls, reasoning, and context stay isolated.\n\nWHEN TO USE:\n- The task is self-contained and can be described in a single prompt.\n- You want to offload verbose or exploratory work without bloating your own context.\n- A specialized subagent is available for the task domain.\n\nWHAT HAPPENS:\n- A fresh agent is created with the task description as its only input.\n- The subagent runs to completion using its own tools and context.\n- Only the final text response is returned to you.\n\nCONSTRAINTS:\n- subagent_type must match one of the available types listed below.\n- The subagent cannot see your conversation history.";
6
- export declare const SubagentToolSchema: {
7
- readonly type: "object";
8
- readonly properties: {
9
- readonly description: {
10
- readonly type: "string";
11
- readonly description: "Complete task description for the subagent. This is the ONLY information it receives — include all necessary context, requirements, and constraints.";
12
- };
13
- readonly subagent_type: {
14
- readonly type: "string";
15
- readonly description: "Which subagent type to delegate to. Must be one of the available types.";
16
- };
17
- };
18
- readonly required: string[];
19
- };
20
- export declare const SubagentToolDefinition: LCTool;
21
- /**
22
- * Build the name, schema, and description params for `tool()` from available configs.
23
- * Used by `Graph.createAgentNode()` when constructing the runtime tool instance.
24
- * Extends `SubagentToolSchema` by populating `subagent_type.enum` dynamically.
25
- */
26
- export declare function buildSubagentToolParams(configs: SubagentConfig[]): {
27
- name: string;
28
- schema: JsonSchemaType;
29
- description: string;
30
- };
31
- /**
32
- * Create a SubagentTool LCTool definition with dynamic enum and description
33
- * populated from the available subagent configs.
34
- * Used for the tool registry in event-driven mode.
35
- */
36
- export declare function createSubagentToolDefinition(configs: SubagentConfig[]): LCTool;
@@ -1,19 +0,0 @@
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;
@@ -1,137 +0,0 @@
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;
@@ -1,2 +0,0 @@
1
- export { SubagentExecutor, filterSubagentResult, resolveSubagentConfigs, buildChildInputs, summarizeEvent, } from './SubagentExecutor';
2
- export type { SubagentExecuteParams, SubagentExecuteResult, SubagentExecutorOptions, ChildGraphFactory, } from './SubagentExecutor';
@@ -1,9 +0,0 @@
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,208 +0,0 @@
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
- }
@@ -1,190 +0,0 @@
1
- // src/hooks/__tests__/HookRegistry.test.ts
2
- import { HookRegistry } from '../HookRegistry';
3
- import type {
4
- HookMatcher,
5
- HookCallback,
6
- PreToolUseHookOutput,
7
- PostToolUseHookOutput,
8
- } from '../types';
9
-
10
- const noop: HookCallback<
11
- 'PreToolUse'
12
- > = async (): Promise<PreToolUseHookOutput> => ({});
13
- const noopPost: HookCallback<
14
- 'PostToolUse'
15
- > = async (): Promise<PostToolUseHookOutput> => ({});
16
-
17
- function makePreToolUseMatcher(pattern?: string): HookMatcher<'PreToolUse'> {
18
- return {
19
- pattern,
20
- hooks: [noop],
21
- };
22
- }
23
-
24
- function makePostToolUseMatcher(): HookMatcher<'PostToolUse'> {
25
- return {
26
- hooks: [noopPost],
27
- };
28
- }
29
-
30
- describe('HookRegistry', () => {
31
- describe('global registration', () => {
32
- it('stores a matcher and returns it via getMatchers', () => {
33
- const registry = new HookRegistry();
34
- const matcher = makePreToolUseMatcher('Bash');
35
- registry.register('PreToolUse', matcher);
36
- const matchers = registry.getMatchers('PreToolUse');
37
- expect(matchers).toHaveLength(1);
38
- expect(matchers[0]).toBe(matcher);
39
- });
40
-
41
- it('keeps registrations isolated across events', () => {
42
- const registry = new HookRegistry();
43
- const pre = makePreToolUseMatcher('Bash');
44
- const post = makePostToolUseMatcher();
45
- registry.register('PreToolUse', pre);
46
- registry.register('PostToolUse', post);
47
- expect(registry.getMatchers('PreToolUse')).toEqual([pre]);
48
- expect(registry.getMatchers('PostToolUse')).toEqual([post]);
49
- expect(registry.getMatchers('Stop')).toEqual([]);
50
- });
51
-
52
- it('unregister removes the matcher from the registry', () => {
53
- const registry = new HookRegistry();
54
- const matcher = makePreToolUseMatcher();
55
- const unregister = registry.register('PreToolUse', matcher);
56
- expect(registry.getMatchers('PreToolUse')).toHaveLength(1);
57
- unregister();
58
- expect(registry.getMatchers('PreToolUse')).toHaveLength(0);
59
- });
60
-
61
- it('hasHookFor reflects registration state', () => {
62
- const registry = new HookRegistry();
63
- expect(registry.hasHookFor('PreToolUse')).toBe(false);
64
- registry.register('PreToolUse', makePreToolUseMatcher());
65
- expect(registry.hasHookFor('PreToolUse')).toBe(true);
66
- expect(registry.hasHookFor('PostToolUse')).toBe(false);
67
- });
68
-
69
- it('supports multiple matchers on the same event', () => {
70
- const registry = new HookRegistry();
71
- const a = makePreToolUseMatcher('Bash');
72
- const b = makePreToolUseMatcher('Edit');
73
- registry.register('PreToolUse', a);
74
- registry.register('PreToolUse', b);
75
- const matchers = registry.getMatchers('PreToolUse');
76
- expect(matchers).toHaveLength(2);
77
- expect(matchers).toContain(a);
78
- expect(matchers).toContain(b);
79
- });
80
-
81
- it('returns a fresh array on each getMatchers call', () => {
82
- const registry = new HookRegistry();
83
- registry.register('PreToolUse', makePreToolUseMatcher());
84
- const first = registry.getMatchers('PreToolUse');
85
- const second = registry.getMatchers('PreToolUse');
86
- expect(first).not.toBe(second);
87
- first.length = 0;
88
- expect(registry.getMatchers('PreToolUse')).toHaveLength(1);
89
- });
90
- });
91
-
92
- describe('session registration', () => {
93
- it('scopes matchers to a single session', () => {
94
- const registry = new HookRegistry();
95
- const sessionA = makePreToolUseMatcher('Bash');
96
- const sessionB = makePreToolUseMatcher('Edit');
97
- registry.registerSession('run-a', 'PreToolUse', sessionA);
98
- registry.registerSession('run-b', 'PreToolUse', sessionB);
99
-
100
- expect(registry.getMatchers('PreToolUse', 'run-a')).toEqual([sessionA]);
101
- expect(registry.getMatchers('PreToolUse', 'run-b')).toEqual([sessionB]);
102
- expect(registry.getMatchers('PreToolUse')).toEqual([]);
103
- });
104
-
105
- it('merges global matchers in front of session matchers', () => {
106
- const registry = new HookRegistry();
107
- const global = makePreToolUseMatcher('global');
108
- const session = makePreToolUseMatcher('session');
109
- registry.register('PreToolUse', global);
110
- registry.registerSession('run-a', 'PreToolUse', session);
111
-
112
- const matchers = registry.getMatchers('PreToolUse', 'run-a');
113
- expect(matchers).toEqual([global, session]);
114
- });
115
-
116
- it('clearSession drops only the given session', () => {
117
- const registry = new HookRegistry();
118
- const a = makePreToolUseMatcher('a');
119
- const b = makePreToolUseMatcher('b');
120
- registry.registerSession('run-a', 'PreToolUse', a);
121
- registry.registerSession('run-b', 'PreToolUse', b);
122
-
123
- registry.clearSession('run-a');
124
- expect(registry.getMatchers('PreToolUse', 'run-a')).toEqual([]);
125
- expect(registry.getMatchers('PreToolUse', 'run-b')).toEqual([b]);
126
- });
127
-
128
- it('removeMatcher removes from the correct scope', () => {
129
- const registry = new HookRegistry();
130
- const global = makePreToolUseMatcher('global');
131
- const session = makePreToolUseMatcher('session');
132
- registry.register('PreToolUse', global);
133
- registry.registerSession('run-a', 'PreToolUse', session);
134
-
135
- expect(registry.removeMatcher('PreToolUse', session, 'run-a')).toBe(true);
136
- expect(registry.getMatchers('PreToolUse', 'run-a')).toEqual([global]);
137
-
138
- expect(registry.removeMatcher('PreToolUse', global)).toBe(true);
139
- expect(registry.getMatchers('PreToolUse', 'run-a')).toEqual([]);
140
- });
141
-
142
- it('removeMatcher returns false when the matcher is not found', () => {
143
- const registry = new HookRegistry();
144
- const orphan = makePreToolUseMatcher('orphan');
145
- expect(registry.removeMatcher('PreToolUse', orphan)).toBe(false);
146
- expect(registry.removeMatcher('PreToolUse', orphan, 'run-a')).toBe(false);
147
- });
148
-
149
- it('session unregister function removes only that matcher', () => {
150
- const registry = new HookRegistry();
151
- const a = makePreToolUseMatcher('a');
152
- const b = makePreToolUseMatcher('b');
153
- const unregisterA = registry.registerSession('run-a', 'PreToolUse', a);
154
- registry.registerSession('run-a', 'PreToolUse', b);
155
-
156
- unregisterA();
157
- expect(registry.getMatchers('PreToolUse', 'run-a')).toEqual([b]);
158
- });
159
-
160
- it('hasHookFor honours the sessionId parameter', () => {
161
- const registry = new HookRegistry();
162
- registry.registerSession('run-a', 'PreToolUse', makePreToolUseMatcher());
163
- expect(registry.hasHookFor('PreToolUse')).toBe(false);
164
- expect(registry.hasHookFor('PreToolUse', 'run-a')).toBe(true);
165
- expect(registry.hasHookFor('PreToolUse', 'run-b')).toBe(false);
166
- });
167
- });
168
-
169
- describe('session isolation under parallel registration', () => {
170
- it('does not leak matchers between sessions registered in parallel', async () => {
171
- const registry = new HookRegistry();
172
- const sessions = Array.from({ length: 50 }, (_, i) => `run-${i}`);
173
- await Promise.all(
174
- sessions.map(async (sid): Promise<void> => {
175
- registry.registerSession(
176
- sid,
177
- 'PreToolUse',
178
- makePreToolUseMatcher(sid)
179
- );
180
- })
181
- );
182
-
183
- for (const sid of sessions) {
184
- const matchers = registry.getMatchers('PreToolUse', sid);
185
- expect(matchers).toHaveLength(1);
186
- expect(matchers[0]?.pattern).toBe(sid);
187
- }
188
- });
189
- });
190
- });