@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.
Files changed (147) 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 +14 -0
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +72 -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 +52 -0
  16. package/dist/cjs/main.cjs.map +1 -1
  17. package/dist/cjs/messages/format.cjs +74 -12
  18. package/dist/cjs/messages/format.cjs.map +1 -1
  19. package/dist/cjs/run.cjs +111 -0
  20. package/dist/cjs/run.cjs.map +1 -1
  21. package/dist/cjs/summarization/node.cjs +44 -0
  22. package/dist/cjs/summarization/node.cjs.map +1 -1
  23. package/dist/cjs/tools/BashExecutor.cjs +175 -0
  24. package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
  25. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +296 -0
  26. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
  27. package/dist/cjs/tools/ReadFile.cjs +43 -0
  28. package/dist/cjs/tools/ReadFile.cjs.map +1 -0
  29. package/dist/cjs/tools/SkillTool.cjs +50 -0
  30. package/dist/cjs/tools/SkillTool.cjs.map +1 -0
  31. package/dist/cjs/tools/SubagentTool.cjs +92 -0
  32. package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
  33. package/dist/cjs/tools/ToolNode.cjs +304 -140
  34. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  35. package/dist/cjs/tools/skillCatalog.cjs +84 -0
  36. package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
  37. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +261 -0
  38. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
  39. package/dist/esm/agents/AgentContext.mjs +23 -3
  40. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  41. package/dist/esm/common/enum.mjs +13 -1
  42. package/dist/esm/common/enum.mjs.map +1 -1
  43. package/dist/esm/graphs/Graph.mjs +72 -0
  44. package/dist/esm/graphs/Graph.mjs.map +1 -1
  45. package/dist/esm/hooks/HookRegistry.mjs +160 -0
  46. package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
  47. package/dist/esm/hooks/executeHooks.mjs +273 -0
  48. package/dist/esm/hooks/executeHooks.mjs.map +1 -0
  49. package/dist/esm/hooks/matchers.mjs +251 -0
  50. package/dist/esm/hooks/matchers.mjs.map +1 -0
  51. package/dist/esm/hooks/types.mjs +25 -0
  52. package/dist/esm/hooks/types.mjs.map +1 -0
  53. package/dist/esm/main.mjs +12 -1
  54. package/dist/esm/main.mjs.map +1 -1
  55. package/dist/esm/messages/format.mjs +66 -4
  56. package/dist/esm/messages/format.mjs.map +1 -1
  57. package/dist/esm/run.mjs +111 -0
  58. package/dist/esm/run.mjs.map +1 -1
  59. package/dist/esm/summarization/node.mjs +44 -0
  60. package/dist/esm/summarization/node.mjs.map +1 -1
  61. package/dist/esm/tools/BashExecutor.mjs +169 -0
  62. package/dist/esm/tools/BashExecutor.mjs.map +1 -0
  63. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +287 -0
  64. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
  65. package/dist/esm/tools/ReadFile.mjs +38 -0
  66. package/dist/esm/tools/ReadFile.mjs.map +1 -0
  67. package/dist/esm/tools/SkillTool.mjs +45 -0
  68. package/dist/esm/tools/SkillTool.mjs.map +1 -0
  69. package/dist/esm/tools/SubagentTool.mjs +85 -0
  70. package/dist/esm/tools/SubagentTool.mjs.map +1 -0
  71. package/dist/esm/tools/ToolNode.mjs +306 -142
  72. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  73. package/dist/esm/tools/skillCatalog.mjs +82 -0
  74. package/dist/esm/tools/skillCatalog.mjs.map +1 -0
  75. package/dist/esm/tools/subagent/SubagentExecutor.mjs +256 -0
  76. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
  77. package/dist/types/agents/AgentContext.d.ts +6 -0
  78. package/dist/types/common/enum.d.ts +8 -1
  79. package/dist/types/graphs/Graph.d.ts +2 -0
  80. package/dist/types/hooks/HookRegistry.d.ts +56 -0
  81. package/dist/types/hooks/executeHooks.d.ts +79 -0
  82. package/dist/types/hooks/index.d.ts +6 -0
  83. package/dist/types/hooks/matchers.d.ts +95 -0
  84. package/dist/types/hooks/types.d.ts +320 -0
  85. package/dist/types/index.d.ts +8 -0
  86. package/dist/types/messages/format.d.ts +2 -1
  87. package/dist/types/run.d.ts +1 -0
  88. package/dist/types/summarization/node.d.ts +2 -0
  89. package/dist/types/tools/BashExecutor.d.ts +45 -0
  90. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
  91. package/dist/types/tools/ReadFile.d.ts +28 -0
  92. package/dist/types/tools/SkillTool.d.ts +40 -0
  93. package/dist/types/tools/SubagentTool.d.ts +36 -0
  94. package/dist/types/tools/ToolNode.d.ts +24 -2
  95. package/dist/types/tools/skillCatalog.d.ts +19 -0
  96. package/dist/types/tools/subagent/SubagentExecutor.d.ts +83 -0
  97. package/dist/types/tools/subagent/index.d.ts +2 -0
  98. package/dist/types/types/graph.d.ts +25 -0
  99. package/dist/types/types/index.d.ts +1 -0
  100. package/dist/types/types/llm.d.ts +14 -2
  101. package/dist/types/types/run.d.ts +20 -0
  102. package/dist/types/types/skill.d.ts +9 -0
  103. package/dist/types/types/tools.d.ts +38 -1
  104. package/package.json +2 -1
  105. package/src/agents/AgentContext.ts +26 -2
  106. package/src/common/enum.ts +13 -0
  107. package/src/graphs/Graph.ts +92 -0
  108. package/src/hooks/HookRegistry.ts +208 -0
  109. package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
  110. package/src/hooks/__tests__/compactHooks.test.ts +214 -0
  111. package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
  112. package/src/hooks/__tests__/integration.test.ts +337 -0
  113. package/src/hooks/__tests__/matchers.test.ts +238 -0
  114. package/src/hooks/__tests__/toolHooks.test.ts +669 -0
  115. package/src/hooks/executeHooks.ts +375 -0
  116. package/src/hooks/index.ts +57 -0
  117. package/src/hooks/matchers.ts +280 -0
  118. package/src/hooks/types.ts +404 -0
  119. package/src/index.ts +10 -0
  120. package/src/messages/format.ts +74 -4
  121. package/src/messages/formatAgentMessages.skills.test.ts +334 -0
  122. package/src/run.ts +126 -0
  123. package/src/scripts/multi-agent-subagent.ts +246 -0
  124. package/src/specs/subagent.test.ts +305 -0
  125. package/src/summarization/node.ts +53 -0
  126. package/src/tools/BashExecutor.ts +205 -0
  127. package/src/tools/BashProgrammaticToolCalling.ts +397 -0
  128. package/src/tools/ReadFile.ts +39 -0
  129. package/src/tools/SkillTool.ts +46 -0
  130. package/src/tools/SubagentTool.ts +100 -0
  131. package/src/tools/ToolNode.ts +391 -169
  132. package/src/tools/__tests__/ReadFile.test.ts +44 -0
  133. package/src/tools/__tests__/SkillTool.test.ts +442 -0
  134. package/src/tools/__tests__/SubagentExecutor.test.ts +615 -0
  135. package/src/tools/__tests__/SubagentTool.test.ts +149 -0
  136. package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
  137. package/src/tools/__tests__/skillCatalog.test.ts +161 -0
  138. package/src/tools/__tests__/subagentHooks.test.ts +215 -0
  139. package/src/tools/skillCatalog.ts +126 -0
  140. package/src/tools/subagent/SubagentExecutor.ts +344 -0
  141. package/src/tools/subagent/index.ts +12 -0
  142. package/src/types/graph.ts +27 -0
  143. package/src/types/index.ts +1 -0
  144. package/src/types/llm.ts +16 -2
  145. package/src/types/run.ts +20 -0
  146. package/src/types/skill.ts +11 -0
  147. package/src/types/tools.ts +41 -1
@@ -0,0 +1,334 @@
1
+ import { HumanMessage } from '@langchain/core/messages';
2
+ import type { TPayload } from '@/types';
3
+ import { formatAgentMessages } from './format';
4
+ import { ContentTypes, Constants } from '@/common';
5
+
6
+ /** Helper to build a skill tool_call content part */
7
+ function skillToolCall(
8
+ id: string,
9
+ skillName: string,
10
+ output = 'Skill loaded.',
11
+ ): Record<string, unknown> {
12
+ return {
13
+ type: ContentTypes.TOOL_CALL,
14
+ tool_call: {
15
+ id,
16
+ name: Constants.SKILL_TOOL,
17
+ args: JSON.stringify({ skillName }),
18
+ output,
19
+ },
20
+ };
21
+ }
22
+
23
+ describe('formatAgentMessages skill body reconstruction', () => {
24
+ const skillBodies = new Map([
25
+ ['pdf-analyzer', '# PDF Analyzer\nAnalyze PDF files step by step.'],
26
+ ['code-review', '# Code Review\nReview the code for issues.'],
27
+ ]);
28
+
29
+ describe('with discoveredTools (tools filtering active)', () => {
30
+ const tools = new Set([Constants.SKILL_TOOL, 'web_search']);
31
+
32
+ it('reconstructs HumanMessage after skill ToolMessage', () => {
33
+ const payload: TPayload = [
34
+ { role: 'user', content: 'Analyze this PDF' },
35
+ {
36
+ role: 'assistant',
37
+ content: [
38
+ {
39
+ type: ContentTypes.TEXT,
40
+ [ContentTypes.TEXT]: 'I\'ll invoke the skill.',
41
+ tool_call_ids: ['call_1'],
42
+ },
43
+ skillToolCall('call_1', 'pdf-analyzer'),
44
+ ],
45
+ },
46
+ ];
47
+
48
+ const { messages } = formatAgentMessages(payload, undefined, tools, skillBodies);
49
+
50
+ // user, AI, ToolMessage, injected HumanMessage
51
+ expect(messages.length).toBeGreaterThanOrEqual(4);
52
+ const last = messages[messages.length - 1];
53
+ expect(last).toBeInstanceOf(HumanMessage);
54
+ expect(last.content).toBe('# PDF Analyzer\nAnalyze PDF files step by step.');
55
+ expect((last as HumanMessage).additional_kwargs.source).toBe('skill');
56
+ expect((last as HumanMessage).additional_kwargs.skillName).toBe('pdf-analyzer');
57
+ expect((last as HumanMessage).additional_kwargs.isMeta).toBe(true);
58
+ });
59
+
60
+ it('does NOT inject body when skill tool is not in discoveredTools', () => {
61
+ const restrictedTools = new Set(['web_search']); // skill NOT allowed
62
+ const payload: TPayload = [
63
+ { role: 'user', content: 'Analyze this' },
64
+ {
65
+ role: 'assistant',
66
+ content: [skillToolCall('call_1', 'pdf-analyzer')],
67
+ },
68
+ ];
69
+
70
+ const { messages } = formatAgentMessages(payload, undefined, restrictedTools, skillBodies);
71
+
72
+ const humanMessages = messages.filter((m) => m instanceof HumanMessage);
73
+ // Only the user message, no injected skill body
74
+ expect(humanMessages).toHaveLength(1);
75
+ });
76
+
77
+ it('does not inject when skill name is not in skills Map', () => {
78
+ const payload: TPayload = [
79
+ { role: 'user', content: 'Hello' },
80
+ {
81
+ role: 'assistant',
82
+ content: [skillToolCall('call_1', 'unknown-skill')],
83
+ },
84
+ ];
85
+
86
+ const { messages } = formatAgentMessages(payload, undefined, tools, skillBodies);
87
+
88
+ const humanMessages = messages.filter((m) => m instanceof HumanMessage);
89
+ expect(humanMessages).toHaveLength(1); // only the user message
90
+ });
91
+ });
92
+
93
+ describe('without discoveredTools (no tools filtering)', () => {
94
+ it('reconstructs HumanMessage when skills Map provided', () => {
95
+ const payload: TPayload = [
96
+ { role: 'user', content: 'Review my code' },
97
+ {
98
+ role: 'assistant',
99
+ content: [skillToolCall('call_1', 'code-review')],
100
+ },
101
+ ];
102
+
103
+ const { messages } = formatAgentMessages(payload, undefined, undefined, skillBodies);
104
+
105
+ const injected = messages.filter(
106
+ (m) => m instanceof HumanMessage && (m as HumanMessage).additional_kwargs?.source === 'skill',
107
+ );
108
+ expect(injected).toHaveLength(1);
109
+ expect(injected[0].content).toBe('# Code Review\nReview the code for issues.');
110
+ });
111
+
112
+ it('no injection when skills Map is undefined', () => {
113
+ const payload: TPayload = [
114
+ { role: 'user', content: 'Hello' },
115
+ {
116
+ role: 'assistant',
117
+ content: [skillToolCall('call_1', 'pdf-analyzer')],
118
+ },
119
+ ];
120
+
121
+ const { messages } = formatAgentMessages(payload, undefined, undefined, undefined);
122
+
123
+ const injected = messages.filter(
124
+ (m) => m instanceof HumanMessage && (m as HumanMessage).additional_kwargs?.source === 'skill',
125
+ );
126
+ expect(injected).toHaveLength(0);
127
+ });
128
+
129
+ it('no injection when skills Map is empty', () => {
130
+ const payload: TPayload = [
131
+ { role: 'user', content: 'Hello' },
132
+ {
133
+ role: 'assistant',
134
+ content: [skillToolCall('call_1', 'pdf-analyzer')],
135
+ },
136
+ ];
137
+
138
+ const { messages } = formatAgentMessages(payload, undefined, undefined, new Map());
139
+
140
+ const injected = messages.filter(
141
+ (m) => m instanceof HumanMessage && (m as HumanMessage).additional_kwargs?.source === 'skill',
142
+ );
143
+ expect(injected).toHaveLength(0);
144
+ });
145
+ });
146
+
147
+ describe('extractSkillName edge cases', () => {
148
+ const tools = new Set([Constants.SKILL_TOOL]);
149
+
150
+ it('handles object args (not stringified)', () => {
151
+ const payload: TPayload = [
152
+ { role: 'user', content: 'Go' },
153
+ {
154
+ role: 'assistant',
155
+ content: [
156
+ {
157
+ type: ContentTypes.TOOL_CALL,
158
+ tool_call: {
159
+ id: 'call_1',
160
+ name: Constants.SKILL_TOOL,
161
+ args: { skillName: 'pdf-analyzer' }, // object, not string
162
+ output: 'Loaded.',
163
+ },
164
+ },
165
+ ],
166
+ },
167
+ ];
168
+
169
+ const { messages } = formatAgentMessages(payload, undefined, tools, skillBodies);
170
+
171
+ const injected = messages.filter(
172
+ (m) => m instanceof HumanMessage && (m as HumanMessage).additional_kwargs?.source === 'skill',
173
+ );
174
+ expect(injected).toHaveLength(1);
175
+ });
176
+
177
+ it('gracefully skips malformed JSON args', () => {
178
+ const payload: TPayload = [
179
+ { role: 'user', content: 'Go' },
180
+ {
181
+ role: 'assistant',
182
+ content: [
183
+ {
184
+ type: ContentTypes.TOOL_CALL,
185
+ tool_call: {
186
+ id: 'call_1',
187
+ name: Constants.SKILL_TOOL,
188
+ args: '{bad json',
189
+ output: 'Loaded.',
190
+ },
191
+ },
192
+ ],
193
+ },
194
+ ];
195
+
196
+ const { messages } = formatAgentMessages(payload, undefined, tools, skillBodies);
197
+
198
+ const injected = messages.filter(
199
+ (m) => m instanceof HumanMessage && (m as HumanMessage).additional_kwargs?.source === 'skill',
200
+ );
201
+ expect(injected).toHaveLength(0); // gracefully skipped
202
+ });
203
+
204
+ it('skips empty skillName', () => {
205
+ const payload: TPayload = [
206
+ { role: 'user', content: 'Go' },
207
+ {
208
+ role: 'assistant',
209
+ content: [
210
+ {
211
+ type: ContentTypes.TOOL_CALL,
212
+ tool_call: {
213
+ id: 'call_1',
214
+ name: Constants.SKILL_TOOL,
215
+ args: JSON.stringify({ skillName: '' }),
216
+ output: 'Loaded.',
217
+ },
218
+ },
219
+ ],
220
+ },
221
+ ];
222
+
223
+ const { messages } = formatAgentMessages(payload, undefined, tools, skillBodies);
224
+
225
+ const injected = messages.filter(
226
+ (m) => m instanceof HumanMessage && (m as HumanMessage).additional_kwargs?.source === 'skill',
227
+ );
228
+ expect(injected).toHaveLength(0);
229
+ });
230
+ });
231
+
232
+ describe('deduplication', () => {
233
+ const tools = new Set([Constants.SKILL_TOOL]);
234
+
235
+ it('injects body only once when same skill invoked twice in one message', () => {
236
+ const payload: TPayload = [
237
+ { role: 'user', content: 'Go' },
238
+ {
239
+ role: 'assistant',
240
+ content: [
241
+ skillToolCall('call_1', 'pdf-analyzer'),
242
+ skillToolCall('call_2', 'pdf-analyzer'),
243
+ ],
244
+ },
245
+ ];
246
+
247
+ const { messages } = formatAgentMessages(payload, undefined, tools, skillBodies);
248
+
249
+ const injected = messages.filter(
250
+ (m) => m instanceof HumanMessage && (m as HumanMessage).additional_kwargs?.source === 'skill',
251
+ );
252
+ expect(injected).toHaveLength(1);
253
+ });
254
+
255
+ it('injects body for each distinct skill invoked', () => {
256
+ const payload: TPayload = [
257
+ { role: 'user', content: 'Go' },
258
+ {
259
+ role: 'assistant',
260
+ content: [
261
+ skillToolCall('call_1', 'pdf-analyzer'),
262
+ skillToolCall('call_2', 'code-review'),
263
+ ],
264
+ },
265
+ ];
266
+
267
+ const { messages } = formatAgentMessages(payload, undefined, tools, skillBodies);
268
+
269
+ const injected = messages.filter(
270
+ (m) => m instanceof HumanMessage && (m as HumanMessage).additional_kwargs?.source === 'skill',
271
+ );
272
+ expect(injected).toHaveLength(2);
273
+ const names = injected.map((m) => (m as HumanMessage).additional_kwargs.skillName);
274
+ expect(names).toContain('pdf-analyzer');
275
+ expect(names).toContain('code-review');
276
+ });
277
+ });
278
+
279
+ describe('indexTokenCountMap distribution', () => {
280
+ const tools = new Set([Constants.SKILL_TOOL]);
281
+
282
+ it('excludes injected HumanMessages from assistant token distribution', () => {
283
+ const payload: TPayload = [
284
+ { role: 'user', content: 'Analyze this' },
285
+ {
286
+ role: 'assistant',
287
+ content: [
288
+ {
289
+ type: ContentTypes.TEXT,
290
+ [ContentTypes.TEXT]: 'Invoking skill.',
291
+ tool_call_ids: ['call_1'],
292
+ },
293
+ skillToolCall('call_1', 'pdf-analyzer'),
294
+ ],
295
+ },
296
+ ];
297
+
298
+ const inputTokenMap: Record<number, number | undefined> = {
299
+ 0: 100, // user message
300
+ 1: 500, // assistant message
301
+ };
302
+
303
+ const { messages, indexTokenCountMap } = formatAgentMessages(
304
+ payload,
305
+ inputTokenMap,
306
+ tools,
307
+ skillBodies,
308
+ );
309
+
310
+ // There should be messages: user, AI, ToolMessage, injected HumanMessage
311
+ expect(messages.length).toBeGreaterThanOrEqual(4);
312
+ const lastMsg = messages[messages.length - 1];
313
+ expect(lastMsg).toBeInstanceOf(HumanMessage);
314
+ expect((lastMsg as HumanMessage).additional_kwargs.source).toBe('skill');
315
+
316
+ // Token map must be defined when input was provided
317
+ expect(indexTokenCountMap).toBeDefined();
318
+
319
+ // The injected HumanMessage's index should NOT be in the token map
320
+ const injectedIndex = messages.length - 1;
321
+ expect(indexTokenCountMap![injectedIndex]).toBeUndefined();
322
+
323
+ // The assistant's 500 tokens should be distributed only across
324
+ // the AI + ToolMessage, NOT the injected HumanMessage
325
+ let assistantTotal = 0;
326
+ for (const [idx, count] of Object.entries(indexTokenCountMap!)) {
327
+ if (Number(idx) > 0 && Number(idx) < injectedIndex) {
328
+ assistantTotal += count ?? 0;
329
+ }
330
+ }
331
+ expect(assistantTotal).toBe(500);
332
+ });
333
+ });
334
+ });
package/src/run.ts CHANGED
@@ -22,8 +22,10 @@ import { MultiAgentGraph } from '@/graphs/MultiAgentGraph';
22
22
  import { StandardGraph } from '@/graphs/Graph';
23
23
  import { initializeModel } from '@/llm/init';
24
24
  import { HandlerRegistry } from '@/events';
25
+ import { executeHooks } from '@/hooks';
25
26
  import { isOpenAILike } from '@/utils/llm';
26
27
  import { isPresent } from '@/utils/misc';
28
+ import type { HookRegistry } from '@/hooks';
27
29
 
28
30
  export const defaultOmitOptions = new Set([
29
31
  'stream',
@@ -42,6 +44,7 @@ export class Run<_T extends t.BaseGraphState> {
42
44
  id: string;
43
45
  private tokenCounter?: t.TokenCounter;
44
46
  private handlerRegistry?: HandlerRegistry;
47
+ private hookRegistry?: HookRegistry;
45
48
  private indexTokenCountMap?: Record<string, number>;
46
49
  calibrationRatio: number = 1;
47
50
  graphRunnable?: t.CompiledStateWorkflow;
@@ -74,6 +77,7 @@ export class Run<_T extends t.BaseGraphState> {
74
77
  }
75
78
 
76
79
  this.handlerRegistry = handlerRegistry;
80
+ this.hookRegistry = config.hooks;
77
81
 
78
82
  if (!config.graphConfig) {
79
83
  throw new Error('Graph config not provided');
@@ -95,6 +99,12 @@ export class Run<_T extends t.BaseGraphState> {
95
99
  }
96
100
  }
97
101
 
102
+ if (config.initialSessions && this.Graph) {
103
+ for (const [key, value] of config.initialSessions) {
104
+ this.Graph.sessions.set(key, value);
105
+ }
106
+ }
107
+
98
108
  this.returnContent = config.returnContent ?? false;
99
109
  this.skipCleanup = config.skipCleanup ?? false;
100
110
  }
@@ -143,6 +153,7 @@ export class Run<_T extends t.BaseGraphState> {
143
153
  });
144
154
  /** Propagate compile options from graph config */
145
155
  standardGraph.compileOptions = config.compileOptions;
156
+ standardGraph.hookRegistry = this.hookRegistry;
146
157
  this.Graph = standardGraph;
147
158
  return standardGraph.createWorkflow();
148
159
  }
@@ -165,6 +176,7 @@ export class Run<_T extends t.BaseGraphState> {
165
176
  multiAgentGraph.compileOptions = compileOptions;
166
177
  }
167
178
 
179
+ multiAgentGraph.hookRegistry = this.hookRegistry;
168
180
  this.Graph = multiAgentGraph;
169
181
  return multiAgentGraph.createWorkflow();
170
182
  }
@@ -332,6 +344,47 @@ export class Run<_T extends t.BaseGraphState> {
332
344
  run_id: this.id,
333
345
  });
334
346
 
347
+ const threadId = config.configurable.thread_id as string | undefined;
348
+
349
+ if (this.hookRegistry != null) {
350
+ await executeHooks({
351
+ registry: this.hookRegistry,
352
+ input: {
353
+ hook_event_name: 'RunStart',
354
+ runId: this.id,
355
+ threadId,
356
+ agentId: this.Graph.defaultAgentId,
357
+ messages: inputs.messages,
358
+ },
359
+ sessionId: this.id,
360
+ });
361
+
362
+ const lastHuman = findLastMessageOfType(inputs.messages, 'human');
363
+ if (lastHuman != null) {
364
+ const promptResult = await executeHooks({
365
+ registry: this.hookRegistry,
366
+ input: {
367
+ hook_event_name: 'UserPromptSubmit',
368
+ runId: this.id,
369
+ threadId,
370
+ agentId: this.Graph.defaultAgentId,
371
+ prompt: extractPromptText(lastHuman),
372
+ // attachments: not yet wired — Phase 2 will extract
373
+ // non-text content blocks (images, files) from messages
374
+ },
375
+ sessionId: this.id,
376
+ });
377
+ if (
378
+ promptResult.decision === 'deny' ||
379
+ promptResult.decision === 'ask'
380
+ ) {
381
+ this.hookRegistry.clearSession(this.id);
382
+ config.callbacks = undefined;
383
+ return undefined;
384
+ }
385
+ }
386
+ }
387
+
335
388
  const stream = this.graphRunnable.streamEvents(inputs, config, {
336
389
  raiseError: true,
337
390
  /**
@@ -361,7 +414,45 @@ export class Run<_T extends t.BaseGraphState> {
361
414
  await handler.handle(eventName, data, metadata, this.Graph);
362
415
  }
363
416
  }
417
+
418
+ if (this.hookRegistry?.hasHookFor('Stop', this.id) === true) {
419
+ await executeHooks({
420
+ registry: this.hookRegistry,
421
+ input: {
422
+ hook_event_name: 'Stop',
423
+ runId: this.id,
424
+ threadId,
425
+ agentId: this.Graph.defaultAgentId,
426
+ messages: this.Graph.getRunMessages() ?? inputs.messages,
427
+ stopHookActive: false, // will be true when stop is triggered by a hook (Phase 2)
428
+ },
429
+ sessionId: this.id,
430
+ }).catch(() => {
431
+ /* Stop hook errors must not masquerade as stream failures */
432
+ });
433
+ }
434
+ } catch (err) {
435
+ if (this.hookRegistry?.hasHookFor('StopFailure', this.id) === true) {
436
+ const runMessages = this.Graph.getRunMessages() ?? [];
437
+ await executeHooks({
438
+ registry: this.hookRegistry,
439
+ input: {
440
+ hook_event_name: 'StopFailure',
441
+ runId: this.id,
442
+ threadId,
443
+ agentId: this.Graph.defaultAgentId,
444
+ error: err instanceof Error ? err.message : String(err),
445
+ lastAssistantMessage: findLastMessageOfType(runMessages, 'ai'),
446
+ },
447
+ sessionId: this.id,
448
+ }).catch(() => {
449
+ /* swallow hook errors — the original error must propagate */
450
+ });
451
+ }
452
+ throw err;
364
453
  } finally {
454
+ this.hookRegistry?.clearSession(this.id);
455
+
365
456
  /**
366
457
  * Break the reference chain that keeps heavy data alive via
367
458
  * LangGraph's internal `__pregel_scratchpad.currentTaskInput` →
@@ -557,3 +648,38 @@ export class Run<_T extends t.BaseGraphState> {
557
648
  }
558
649
  }
559
650
  }
651
+
652
+ function findLastMessageOfType(
653
+ messages: BaseMessage[],
654
+ type: string
655
+ ): BaseMessage | undefined {
656
+ for (let i = messages.length - 1; i >= 0; i--) {
657
+ if (messages[i].getType() === type) {
658
+ return messages[i];
659
+ }
660
+ }
661
+ return undefined;
662
+ }
663
+
664
+ function extractPromptText(message: BaseMessage): string {
665
+ const content = message.content;
666
+ if (typeof content === 'string') {
667
+ return content;
668
+ }
669
+ if (!Array.isArray(content)) {
670
+ return String(content);
671
+ }
672
+ const parts: string[] = [];
673
+ for (const block of content) {
674
+ if (
675
+ typeof block === 'object' &&
676
+ 'type' in block &&
677
+ block.type === 'text' &&
678
+ 'text' in block &&
679
+ typeof block.text === 'string'
680
+ ) {
681
+ parts.push(block.text);
682
+ }
683
+ }
684
+ return parts.join('\n');
685
+ }