@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,251 +0,0 @@
1
- // src/hooks/matchers.ts
2
- /**
3
- * Upper bound on hook-matcher pattern length. Patterns longer than this
4
- * are rejected outright — the goal is a cheap cap on pathological inputs
5
- * (repeated quantifiers, huge alternation groups) without pulling in a
6
- * safe-regex dependency.
7
- *
8
- * Legitimate matchers are almost always under 50 characters (tool names,
9
- * short alternations, simple prefix anchors); 512 leaves generous
10
- * headroom while preventing 10KB regexes.
11
- */
12
- const MAX_PATTERN_LENGTH = 512;
13
- /**
14
- * Upper bound on the compilation cache. Chosen to comfortably hold every
15
- * distinct pattern a single multi-tenant run is likely to see (tools,
16
- * agent types, basename filters) without growing without bound.
17
- *
18
- * Under hosts that register unique patterns per tenant, LRU eviction
19
- * keeps the working set bounded — cold patterns are re-compiled on next
20
- * use, which is the correct cost trade-off for long-running processes
21
- * that must not leak memory.
22
- */
23
- const MAX_CACHE_SIZE = 256;
24
- /**
25
- * Module-level LRU cache keyed by pattern string. Map iteration order is
26
- * insertion order in ECMAScript, so refreshing an entry's position means
27
- * "delete then re-set". On overflow we evict the first key (least
28
- * recently used).
29
- *
30
- * Failed compiles are cached as `{ regex: null }` so a malformed pattern
31
- * does not re-enter the compiler — and so a tenant spamming bad patterns
32
- * doesn't burn CPU on every call.
33
- */
34
- const patternCache = new Map();
35
- /**
36
- * Threshold above which `touchCacheEntry` actually performs the LRU
37
- * refresh. Below this watermark the cache has zero eviction pressure, so
38
- * the delete+set on every hit would be pure overhead. Above it we refresh
39
- * properly so hot patterns survive evictions. 75% of capacity is the
40
- * standard sweet spot.
41
- */
42
- const LRU_REFRESH_THRESHOLD = Math.floor((MAX_CACHE_SIZE * 3) / 4);
43
- function touchCacheEntry(pattern, entry) {
44
- if (patternCache.size < LRU_REFRESH_THRESHOLD) {
45
- return;
46
- }
47
- patternCache.delete(pattern);
48
- patternCache.set(pattern, entry);
49
- }
50
- function setCacheEntry(pattern, entry) {
51
- if (patternCache.size >= MAX_CACHE_SIZE) {
52
- const oldestKey = patternCache.keys().next().value;
53
- if (oldestKey !== undefined) {
54
- patternCache.delete(oldestKey);
55
- }
56
- }
57
- patternCache.set(pattern, entry);
58
- }
59
- function skipGroupSyntaxPrefix(pattern, start) {
60
- if (start >= pattern.length || pattern[start] !== '?') {
61
- return start;
62
- }
63
- let i = start + 1;
64
- if (i >= pattern.length) {
65
- return i;
66
- }
67
- const modifier = pattern[i];
68
- if (modifier === ':' || modifier === '=' || modifier === '!') {
69
- return i + 1;
70
- }
71
- if (modifier !== '<') {
72
- return i;
73
- }
74
- i++;
75
- if (i < pattern.length && (pattern[i] === '=' || pattern[i] === '!')) {
76
- return i + 1;
77
- }
78
- while (i < pattern.length && pattern[i] !== '>') {
79
- i++;
80
- }
81
- if (i < pattern.length) {
82
- i++;
83
- }
84
- return i;
85
- }
86
- /**
87
- * Cheap syntactic detector for the most common catastrophic-backtracking
88
- * shape: a quantified group that contains another quantifier (e.g.
89
- * `(a+)+`, `(.*)*`, `(\w+)+$`, `(?:(a+))+`). This is the "nested
90
- * quantifier" class of ReDoS — runs in polynomial-or-worse time on
91
- * adversarial inputs.
92
- *
93
- * The scan walks the pattern linearly using an explicit stack of group
94
- * frames. For each group it tracks whether the group's contents include
95
- * "backtrack risk" — meaning a direct quantifier OR a nested group that
96
- * carries risk up. When a group closes with a trailing quantifier AND its
97
- * frame carries backtrack risk, the pattern is flagged. Risk propagates
98
- * to the enclosing frame when a child group closes (whether the child
99
- * itself was quantified or not), so `(?:(a+))+` — equivalent to `(a+)+`
100
- * — is flagged correctly even though the outer non-capturing wrapper is
101
- * one level removed from the inner quantifier.
102
- *
103
- * ## Group-syntax prefixes
104
- *
105
- * Non-capturing groups (`(?:`), lookaheads (`(?=`, `(?!`), lookbehinds
106
- * (`(?<=`, `(?<!`), and named groups (`(?<name>`) are skipped over at
107
- * the `(` so their `?` is not misread as a quantifier. Without this,
108
- * `(?:pre_)?tool_name` would be incorrectly rejected because the scanner
109
- * would see the group-syntax `?` as a quantifier at depth 1.
110
- *
111
- * ## Heuristic, not a proof
112
- *
113
- * This catches the common forms but not all. Ambiguous-alternation ReDoS
114
- * like `(a|a)+` is not detected. Pathologically long patterns are also
115
- * caught by {@link MAX_PATTERN_LENGTH}. Hosts that accept user-supplied
116
- * patterns must still validate upstream.
117
- */
118
- function hasNestedQuantifier(pattern) {
119
- const stack = [];
120
- let i = 0;
121
- while (i < pattern.length) {
122
- const ch = pattern[i];
123
- if (ch === '\\') {
124
- i += 2;
125
- continue;
126
- }
127
- if (ch === '[') {
128
- i = findCharClassEnd(pattern, i) + 1;
129
- continue;
130
- }
131
- if (ch === '(') {
132
- stack.push({ hasBacktrackRisk: false });
133
- i = skipGroupSyntaxPrefix(pattern, i + 1);
134
- continue;
135
- }
136
- if (ch === ')') {
137
- const frame = stack.pop();
138
- if (frame === undefined) {
139
- i++;
140
- continue;
141
- }
142
- const next = pattern[i + 1];
143
- const isQuantifier = next === '*' || next === '+' || next === '?' || next === '{';
144
- if (isQuantifier && frame.hasBacktrackRisk) {
145
- return true;
146
- }
147
- if (stack.length > 0 && (frame.hasBacktrackRisk || isQuantifier)) {
148
- stack[stack.length - 1].hasBacktrackRisk = true;
149
- }
150
- i++;
151
- continue;
152
- }
153
- if (ch === '*' || ch === '+' || ch === '?' || ch === '{') {
154
- if (stack.length > 0) {
155
- stack[stack.length - 1].hasBacktrackRisk = true;
156
- }
157
- }
158
- i++;
159
- }
160
- return false;
161
- }
162
- function findCharClassEnd(pattern, start) {
163
- let i = start + 1;
164
- while (i < pattern.length) {
165
- const ch = pattern[i];
166
- if (ch === '\\') {
167
- i += 2;
168
- continue;
169
- }
170
- if (ch === ']') {
171
- return i;
172
- }
173
- i++;
174
- }
175
- return pattern.length - 1;
176
- }
177
- function compile(pattern) {
178
- const cached = patternCache.get(pattern);
179
- if (cached !== undefined) {
180
- touchCacheEntry(pattern, cached);
181
- return cached.regex;
182
- }
183
- if (pattern.length > MAX_PATTERN_LENGTH) {
184
- setCacheEntry(pattern, { regex: null });
185
- return null;
186
- }
187
- if (hasNestedQuantifier(pattern)) {
188
- setCacheEntry(pattern, { regex: null });
189
- return null;
190
- }
191
- try {
192
- const regex = new RegExp(pattern);
193
- setCacheEntry(pattern, { regex });
194
- return regex;
195
- }
196
- catch {
197
- setCacheEntry(pattern, { regex: null });
198
- return null;
199
- }
200
- }
201
- /**
202
- * Tests whether a hook matcher pattern matches the given query string.
203
- *
204
- * ## Semantics
205
- *
206
- * - `undefined` or empty `pattern` matches any query (wildcard). This is
207
- * the intended shape for events that do not supply a query string at
208
- * all (`RunStart`, `Stop`, etc.) — register such matchers without a
209
- * pattern.
210
- * - `undefined` or empty `query` with a non-empty `pattern` never matches.
211
- * Setting a pattern on a query-less event is therefore inert: the
212
- * matcher will simply never fire. This is intentional — it keeps
213
- * query-based filtering out of event types where "query" has no meaning,
214
- * and is documented on `HookMatcher.pattern`.
215
- * - Otherwise, the pattern is compiled once (via a bounded LRU cache) and
216
- * tested against the query.
217
- * - Invalid regex patterns never throw — a failed compile is cached as
218
- * "never matches" so a single malformed pattern cannot take out a whole
219
- * `executeHooks` batch.
220
- *
221
- * ## ReDoS mitigations
222
- *
223
- * Patterns compile through three cheap gates before reaching `new RegExp`:
224
- *
225
- * 1. {@link MAX_PATTERN_LENGTH} length cap rejects oversized inputs.
226
- * 2. {@link hasNestedQuantifier} rejects the most common catastrophic-
227
- * backtracking shape (quantified group containing a quantifier).
228
- * 3. Successful compiles are cached in a bounded LRU so repeated calls
229
- * never re-enter the regex compiler.
230
- *
231
- * These are a floor, not a ceiling. Hosts that accept user-supplied
232
- * patterns should still validate upstream. The design report §3.8 routes
233
- * persistable hooks through a host-side compiler before they reach this
234
- * module.
235
- */
236
- function matchesQuery(pattern, query) {
237
- if (pattern === undefined || pattern === '') {
238
- return true;
239
- }
240
- if (query === undefined || query === '') {
241
- return false;
242
- }
243
- const regex = compile(pattern);
244
- if (regex === null) {
245
- return false;
246
- }
247
- return regex.test(query);
248
- }
249
-
250
- export { MAX_CACHE_SIZE, MAX_PATTERN_LENGTH, hasNestedQuantifier, matchesQuery };
251
- //# sourceMappingURL=matchers.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"matchers.mjs","sources":["../../../src/hooks/matchers.ts"],"sourcesContent":["// src/hooks/matchers.ts\n\n/**\n * Upper bound on hook-matcher pattern length. Patterns longer than this\n * are rejected outright — the goal is a cheap cap on pathological inputs\n * (repeated quantifiers, huge alternation groups) without pulling in a\n * safe-regex dependency.\n *\n * Legitimate matchers are almost always under 50 characters (tool names,\n * short alternations, simple prefix anchors); 512 leaves generous\n * headroom while preventing 10KB regexes.\n */\nexport const MAX_PATTERN_LENGTH = 512;\n\n/**\n * Upper bound on the compilation cache. Chosen to comfortably hold every\n * distinct pattern a single multi-tenant run is likely to see (tools,\n * agent types, basename filters) without growing without bound.\n *\n * Under hosts that register unique patterns per tenant, LRU eviction\n * keeps the working set bounded — cold patterns are re-compiled on next\n * use, which is the correct cost trade-off for long-running processes\n * that must not leak memory.\n */\nexport const MAX_CACHE_SIZE = 256;\n\ninterface CacheEntry {\n regex: RegExp | null;\n}\n\n/**\n * Module-level LRU cache keyed by pattern string. Map iteration order is\n * insertion order in ECMAScript, so refreshing an entry's position means\n * \"delete then re-set\". On overflow we evict the first key (least\n * recently used).\n *\n * Failed compiles are cached as `{ regex: null }` so a malformed pattern\n * does not re-enter the compiler — and so a tenant spamming bad patterns\n * doesn't burn CPU on every call.\n */\nconst patternCache: Map<string, CacheEntry> = new Map();\n\n/**\n * Threshold above which `touchCacheEntry` actually performs the LRU\n * refresh. Below this watermark the cache has zero eviction pressure, so\n * the delete+set on every hit would be pure overhead. Above it we refresh\n * properly so hot patterns survive evictions. 75% of capacity is the\n * standard sweet spot.\n */\nconst LRU_REFRESH_THRESHOLD = Math.floor((MAX_CACHE_SIZE * 3) / 4);\n\nfunction touchCacheEntry(pattern: string, entry: CacheEntry): void {\n if (patternCache.size < LRU_REFRESH_THRESHOLD) {\n return;\n }\n patternCache.delete(pattern);\n patternCache.set(pattern, entry);\n}\n\nfunction setCacheEntry(pattern: string, entry: CacheEntry): void {\n if (patternCache.size >= MAX_CACHE_SIZE) {\n const oldestKey = patternCache.keys().next().value;\n if (oldestKey !== undefined) {\n patternCache.delete(oldestKey);\n }\n }\n patternCache.set(pattern, entry);\n}\n\ninterface QuantifierFrame {\n hasBacktrackRisk: boolean;\n}\n\nfunction skipGroupSyntaxPrefix(pattern: string, start: number): number {\n if (start >= pattern.length || pattern[start] !== '?') {\n return start;\n }\n let i = start + 1;\n if (i >= pattern.length) {\n return i;\n }\n const modifier = pattern[i];\n if (modifier === ':' || modifier === '=' || modifier === '!') {\n return i + 1;\n }\n if (modifier !== '<') {\n return i;\n }\n i++;\n if (i < pattern.length && (pattern[i] === '=' || pattern[i] === '!')) {\n return i + 1;\n }\n while (i < pattern.length && pattern[i] !== '>') {\n i++;\n }\n if (i < pattern.length) {\n i++;\n }\n return i;\n}\n\n/**\n * Cheap syntactic detector for the most common catastrophic-backtracking\n * shape: a quantified group that contains another quantifier (e.g.\n * `(a+)+`, `(.*)*`, `(\\w+)+$`, `(?:(a+))+`). This is the \"nested\n * quantifier\" class of ReDoS — runs in polynomial-or-worse time on\n * adversarial inputs.\n *\n * The scan walks the pattern linearly using an explicit stack of group\n * frames. For each group it tracks whether the group's contents include\n * \"backtrack risk\" — meaning a direct quantifier OR a nested group that\n * carries risk up. When a group closes with a trailing quantifier AND its\n * frame carries backtrack risk, the pattern is flagged. Risk propagates\n * to the enclosing frame when a child group closes (whether the child\n * itself was quantified or not), so `(?:(a+))+` — equivalent to `(a+)+`\n * — is flagged correctly even though the outer non-capturing wrapper is\n * one level removed from the inner quantifier.\n *\n * ## Group-syntax prefixes\n *\n * Non-capturing groups (`(?:`), lookaheads (`(?=`, `(?!`), lookbehinds\n * (`(?<=`, `(?<!`), and named groups (`(?<name>`) are skipped over at\n * the `(` so their `?` is not misread as a quantifier. Without this,\n * `(?:pre_)?tool_name` would be incorrectly rejected because the scanner\n * would see the group-syntax `?` as a quantifier at depth 1.\n *\n * ## Heuristic, not a proof\n *\n * This catches the common forms but not all. Ambiguous-alternation ReDoS\n * like `(a|a)+` is not detected. Pathologically long patterns are also\n * caught by {@link MAX_PATTERN_LENGTH}. Hosts that accept user-supplied\n * patterns must still validate upstream.\n */\nexport function hasNestedQuantifier(pattern: string): boolean {\n const stack: QuantifierFrame[] = [];\n let i = 0;\n while (i < pattern.length) {\n const ch = pattern[i];\n if (ch === '\\\\') {\n i += 2;\n continue;\n }\n if (ch === '[') {\n i = findCharClassEnd(pattern, i) + 1;\n continue;\n }\n if (ch === '(') {\n stack.push({ hasBacktrackRisk: false });\n i = skipGroupSyntaxPrefix(pattern, i + 1);\n continue;\n }\n if (ch === ')') {\n const frame = stack.pop();\n if (frame === undefined) {\n i++;\n continue;\n }\n const next = pattern[i + 1];\n const isQuantifier =\n next === '*' || next === '+' || next === '?' || next === '{';\n if (isQuantifier && frame.hasBacktrackRisk) {\n return true;\n }\n if (stack.length > 0 && (frame.hasBacktrackRisk || isQuantifier)) {\n stack[stack.length - 1].hasBacktrackRisk = true;\n }\n i++;\n continue;\n }\n if (ch === '*' || ch === '+' || ch === '?' || ch === '{') {\n if (stack.length > 0) {\n stack[stack.length - 1].hasBacktrackRisk = true;\n }\n }\n i++;\n }\n return false;\n}\n\nfunction findCharClassEnd(pattern: string, start: number): number {\n let i = start + 1;\n while (i < pattern.length) {\n const ch = pattern[i];\n if (ch === '\\\\') {\n i += 2;\n continue;\n }\n if (ch === ']') {\n return i;\n }\n i++;\n }\n return pattern.length - 1;\n}\n\nfunction compile(pattern: string): RegExp | null {\n const cached = patternCache.get(pattern);\n if (cached !== undefined) {\n touchCacheEntry(pattern, cached);\n return cached.regex;\n }\n if (pattern.length > MAX_PATTERN_LENGTH) {\n setCacheEntry(pattern, { regex: null });\n return null;\n }\n if (hasNestedQuantifier(pattern)) {\n setCacheEntry(pattern, { regex: null });\n return null;\n }\n try {\n const regex = new RegExp(pattern);\n setCacheEntry(pattern, { regex });\n return regex;\n } catch {\n setCacheEntry(pattern, { regex: null });\n return null;\n }\n}\n\n/**\n * Tests whether a hook matcher pattern matches the given query string.\n *\n * ## Semantics\n *\n * - `undefined` or empty `pattern` matches any query (wildcard). This is\n * the intended shape for events that do not supply a query string at\n * all (`RunStart`, `Stop`, etc.) — register such matchers without a\n * pattern.\n * - `undefined` or empty `query` with a non-empty `pattern` never matches.\n * Setting a pattern on a query-less event is therefore inert: the\n * matcher will simply never fire. This is intentional — it keeps\n * query-based filtering out of event types where \"query\" has no meaning,\n * and is documented on `HookMatcher.pattern`.\n * - Otherwise, the pattern is compiled once (via a bounded LRU cache) and\n * tested against the query.\n * - Invalid regex patterns never throw — a failed compile is cached as\n * \"never matches\" so a single malformed pattern cannot take out a whole\n * `executeHooks` batch.\n *\n * ## ReDoS mitigations\n *\n * Patterns compile through three cheap gates before reaching `new RegExp`:\n *\n * 1. {@link MAX_PATTERN_LENGTH} length cap rejects oversized inputs.\n * 2. {@link hasNestedQuantifier} rejects the most common catastrophic-\n * backtracking shape (quantified group containing a quantifier).\n * 3. Successful compiles are cached in a bounded LRU so repeated calls\n * never re-enter the regex compiler.\n *\n * These are a floor, not a ceiling. Hosts that accept user-supplied\n * patterns should still validate upstream. The design report §3.8 routes\n * persistable hooks through a host-side compiler before they reach this\n * module.\n */\nexport function matchesQuery(\n pattern: string | undefined,\n query: string | undefined\n): boolean {\n if (pattern === undefined || pattern === '') {\n return true;\n }\n if (query === undefined || query === '') {\n return false;\n }\n const regex = compile(pattern);\n if (regex === null) {\n return false;\n }\n return regex.test(query);\n}\n\n/** Clears the regex compilation cache. Intended for test isolation. */\nexport function clearMatcherCache(): void {\n patternCache.clear();\n}\n\n/** Returns the current size of the compilation cache. Intended for tests. */\nexport function getMatcherCacheSize(): number {\n return patternCache.size;\n}\n"],"names":[],"mappings":"AAAA;AAEA;;;;;;;;;AASG;AACI,MAAM,kBAAkB,GAAG;AAElC;;;;;;;;;AASG;AACI,MAAM,cAAc,GAAG;AAM9B;;;;;;;;;AASG;AACH,MAAM,YAAY,GAA4B,IAAI,GAAG,EAAE;AAEvD;;;;;;AAMG;AACH,MAAM,qBAAqB,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,cAAc,GAAG,CAAC,IAAI,CAAC,CAAC;AAElE,SAAS,eAAe,CAAC,OAAe,EAAE,KAAiB,EAAA;AACzD,IAAA,IAAI,YAAY,CAAC,IAAI,GAAG,qBAAqB,EAAE;QAC7C;IACF;AACA,IAAA,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC;AAC5B,IAAA,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC;AAClC;AAEA,SAAS,aAAa,CAAC,OAAe,EAAE,KAAiB,EAAA;AACvD,IAAA,IAAI,YAAY,CAAC,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mBAAmB,CAAC,OAAO,CAAC,EAAE;QAChC,aAAa,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AACvC,QAAA,OAAO,IAAI;IACb;AACA,IAAA,IAAI;AACF,QAAA,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC;AACjC,QAAA,aAAa,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC;AACjC,QAAA,OAAO,KAAK;IACd;AAAE,IAAA,MAAM;QACN,aAAa,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AACvC,QAAA,OAAO,IAAI;IACb;AACF;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCG;AACG,SAAU,YAAY,CAC1B,OAA2B,EAC3B,KAAyB,EAAA;IAEzB,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,EAAE,EAAE;AAC3C,QAAA,OAAO,IAAI;IACb;IACA,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,EAAE,EAAE;AACvC,QAAA,OAAO,KAAK;IACd;AACA,IAAA,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC;AAC9B,IAAA,IAAI,KAAK,KAAK,IAAI,EAAE;AAClB,QAAA,OAAO,KAAK;IACd;AACA,IAAA,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;AAC1B;;;;"}
@@ -1,25 +0,0 @@
1
- /**
2
- * Closed set of hook lifecycle events supported by the hooks system.
3
- *
4
- * These mirror the subset of Claude Code's event surface that makes sense
5
- * for a library context (no filesystem/CLI-specific events). See
6
- * `docs/hooks-design-report.md` §3.2 for the mapping to existing
7
- * `@librechat/agents` emission points.
8
- */
9
- const HOOK_EVENTS = [
10
- 'RunStart',
11
- 'UserPromptSubmit',
12
- 'PreToolUse',
13
- 'PostToolUse',
14
- 'PostToolUseFailure',
15
- 'PermissionDenied',
16
- 'SubagentStart',
17
- 'SubagentStop',
18
- 'Stop',
19
- 'StopFailure',
20
- 'PreCompact',
21
- 'PostCompact',
22
- ];
23
-
24
- export { HOOK_EVENTS };
25
- //# sourceMappingURL=types.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.mjs","sources":["../../../src/hooks/types.ts"],"sourcesContent":["// src/hooks/types.ts\nimport type { BaseMessage } from '@langchain/core/messages';\n\n/**\n * Closed set of hook lifecycle events supported by the hooks system.\n *\n * These mirror the subset of Claude Code's event surface that makes sense\n * for a library context (no filesystem/CLI-specific events). See\n * `docs/hooks-design-report.md` §3.2 for the mapping to existing\n * `@librechat/agents` emission points.\n */\nexport const HOOK_EVENTS = [\n 'RunStart',\n 'UserPromptSubmit',\n 'PreToolUse',\n 'PostToolUse',\n 'PostToolUseFailure',\n 'PermissionDenied',\n 'SubagentStart',\n 'SubagentStop',\n 'Stop',\n 'StopFailure',\n 'PreCompact',\n 'PostCompact',\n] as const;\n\nexport type HookEvent = (typeof HOOK_EVENTS)[number];\n\n/** Tool-gating decision; executeHooks folds with `deny > ask > allow` precedence. */\nexport type ToolDecision = 'allow' | 'deny' | 'ask';\n\n/** Stop-loop decision; `block` means \"do not stop, run another turn\". Any `block` wins. */\nexport type StopDecision = 'continue' | 'block';\n\n/**\n * Fields shared by every `HookInput`. Discriminated by `hook_event_name`.\n *\n * - `runId` identifies the current agent run and is always present.\n * - `threadId` identifies the conversation thread when the host has one.\n * - `agentId` is only set when the hook fires inside a subagent scope.\n */\nexport interface BaseHookInput {\n runId: string;\n threadId?: string;\n agentId?: string;\n}\n\nexport interface RunStartHookInput extends BaseHookInput {\n hook_event_name: 'RunStart';\n messages: BaseMessage[];\n}\n\nexport interface UserPromptSubmitHookInput extends BaseHookInput {\n hook_event_name: 'UserPromptSubmit';\n prompt: string;\n attachments?: BaseMessage[];\n}\n\n/**\n * Fires before a tool is invoked. Hook may return `deny`/`ask`/`allow` and/or\n * an `updatedInput` that replaces the tool arguments before invocation.\n *\n * `toolInput` is intentionally typed as `Record<string, unknown>` because the\n * SDK is tool-agnostic — concrete tool argument shapes are only known at the\n * call site and are narrowed by the host. This is the one escape hatch in\n * the hook type system.\n */\nexport interface PreToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PreToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n stepId?: string;\n /**\n * Number of times this tool has been invoked in prior batches within the\n * current run. Within a single batch of parallel calls, all calls to the\n * same tool share the same turn value — per-call discrimination within a\n * batch is not supported in v1.\n */\n turn?: number;\n}\n\nexport interface PostToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolOutput: unknown;\n toolUseId: string;\n stepId?: string;\n turn?: number;\n}\n\nexport interface PostToolUseFailureHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUseFailure';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n error: string;\n stepId?: string;\n turn?: number;\n}\n\nexport interface PermissionDeniedHookInput extends BaseHookInput {\n hook_event_name: 'PermissionDenied';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n reason: string;\n}\n\nexport interface SubagentStartHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStart';\n parentAgentId?: string;\n agentId: string;\n agentType: string;\n inputs: BaseMessage[];\n}\n\nexport interface SubagentStopHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStop';\n agentId: string;\n agentType: string;\n messages: BaseMessage[];\n}\n\nexport interface StopHookInput extends BaseHookInput {\n hook_event_name: 'Stop';\n messages: BaseMessage[];\n stopReason?: string;\n stopHookActive: boolean;\n}\n\nexport interface StopFailureHookInput extends BaseHookInput {\n hook_event_name: 'StopFailure';\n error: string;\n lastAssistantMessage?: BaseMessage;\n}\n\nexport interface PreCompactHookInput extends BaseHookInput {\n hook_event_name: 'PreCompact';\n messagesBeforeCount: number;\n /**\n * What triggered compaction. Matches `SummarizationTrigger.type` from the\n * agent's summarization config. `'default'` means no trigger was\n * configured and compaction fired because messages were pruned.\n */\n trigger:\n | 'token_ratio'\n | 'remaining_tokens'\n | 'messages_to_refine'\n | 'default'\n | (string & {});\n}\n\nexport interface PostCompactHookInput extends BaseHookInput {\n hook_event_name: 'PostCompact';\n summary: string;\n /**\n * Number of messages remaining after compaction. The summarize node\n * returns a `removeAll` signal that clears all messages from state;\n * the summary itself is injected into the system prompt, not as a\n * message. This is `0` at the point of hook dispatch.\n */\n messagesAfterCount: number;\n}\n\n/** Discriminated union of every hook input shape. */\nexport type HookInput =\n | RunStartHookInput\n | UserPromptSubmitHookInput\n | PreToolUseHookInput\n | PostToolUseHookInput\n | PostToolUseFailureHookInput\n | PermissionDeniedHookInput\n | SubagentStartHookInput\n | SubagentStopHookInput\n | StopHookInput\n | StopFailureHookInput\n | PreCompactHookInput\n | PostCompactHookInput;\n\n/** Compile-time map from event name to its input shape. */\nexport type HookInputByEvent = {\n RunStart: RunStartHookInput;\n UserPromptSubmit: UserPromptSubmitHookInput;\n PreToolUse: PreToolUseHookInput;\n PostToolUse: PostToolUseHookInput;\n PostToolUseFailure: PostToolUseFailureHookInput;\n PermissionDenied: PermissionDeniedHookInput;\n SubagentStart: SubagentStartHookInput;\n SubagentStop: SubagentStopHookInput;\n Stop: StopHookInput;\n StopFailure: StopFailureHookInput;\n PreCompact: PreCompactHookInput;\n PostCompact: PostCompactHookInput;\n};\n\n/**\n * Fields common to every hook output. Hooks that have nothing to say simply\n * return `{}` (or omit the fields below).\n */\nexport interface BaseHookOutput {\n /** Context string to inject into the conversation. Accumulated across hooks. */\n additionalContext?: string;\n /** True to prevent the next model turn. Any hook can set this. */\n preventContinuation?: boolean;\n /** Reason reported alongside `preventContinuation`. */\n stopReason?: string;\n}\n\nexport type RunStartHookOutput = BaseHookOutput;\n\nexport interface UserPromptSubmitHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport interface PreToolUseHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n /**\n * Replacement tool input. Merged into the pending tool call by the host.\n *\n * When multiple hooks set `updatedInput` within a single `executeHooks`\n * call, the last writer in registration order wins (outer loop: matcher\n * registration order; inner loop: hook position within the matcher). The\n * winner is deterministic — `Promise.all` preserves input-array order.\n * Consumers that need a single authoritative rewrite should still scope\n * `updatedInput` to one hook per matcher to avoid confusing precedence.\n */\n updatedInput?: Record<string, unknown>;\n}\n\nexport interface PostToolUseHookOutput extends BaseHookOutput {\n /**\n * Replacement tool output. Flows through the aggregated result so the\n * host can substitute it before appending the tool result message.\n * Ordering semantics match `PreToolUseHookOutput.updatedInput`:\n * last-writer-wins in registration order.\n */\n updatedOutput?: unknown;\n}\n\nexport type PostToolUseFailureHookOutput = BaseHookOutput;\n\nexport type PermissionDeniedHookOutput = BaseHookOutput;\n\nexport interface SubagentStartHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport type SubagentStopHookOutput = BaseHookOutput;\n\nexport interface StopHookOutput extends BaseHookOutput {\n decision?: StopDecision;\n reason?: string;\n}\n\nexport type StopFailureHookOutput = BaseHookOutput;\n\nexport type PreCompactHookOutput = BaseHookOutput;\n\nexport type PostCompactHookOutput = BaseHookOutput;\n\n/** Compile-time map from event name to its output shape. */\nexport type HookOutputByEvent = {\n RunStart: RunStartHookOutput;\n UserPromptSubmit: UserPromptSubmitHookOutput;\n PreToolUse: PreToolUseHookOutput;\n PostToolUse: PostToolUseHookOutput;\n PostToolUseFailure: PostToolUseFailureHookOutput;\n PermissionDenied: PermissionDeniedHookOutput;\n SubagentStart: SubagentStartHookOutput;\n SubagentStop: SubagentStopHookOutput;\n Stop: StopHookOutput;\n StopFailure: StopFailureHookOutput;\n PreCompact: PreCompactHookOutput;\n PostCompact: PostCompactHookOutput;\n};\n\n/** Superset output shape used by the executor's fold loop. */\nexport type HookOutput =\n | RunStartHookOutput\n | UserPromptSubmitHookOutput\n | PreToolUseHookOutput\n | PostToolUseHookOutput\n | PostToolUseFailureHookOutput\n | PermissionDeniedHookOutput\n | SubagentStartHookOutput\n | SubagentStopHookOutput\n | StopHookOutput\n | StopFailureHookOutput\n | PreCompactHookOutput\n | PostCompactHookOutput;\n\n/**\n * A hook callback is a plain async function registered against a specific\n * event. The `signal` is always supplied by `executeHooks` and combines the\n * batch's parent signal with the per-hook timeout — callbacks that perform\n * long-running work should observe it.\n */\nexport type HookCallback<E extends HookEvent = HookEvent> = (\n input: HookInputByEvent[E],\n signal: AbortSignal\n) => HookOutputByEvent[E] | Promise<HookOutputByEvent[E]>;\n\n/**\n * A matcher groups one or more callbacks under a shared regex filter and\n * shared timeout/once/internal flags. The generic `E` ties the callback\n * types to the event the matcher is registered against.\n */\nexport interface HookMatcher<E extends HookEvent = HookEvent> {\n /**\n * Regex pattern matched against the event's primary query string (e.g.\n * the tool name for `PreToolUse`, the agent type for `SubagentStart`).\n *\n * Omitted or empty means \"always match\". For events that do not supply a\n * query string (`RunStart`, `Stop`, etc.), only wildcard matchers fire —\n * a non-empty pattern on such events will never match.\n *\n * Patterns are treated as trusted input: `executeHooks` compiles them\n * with `new RegExp(pattern)` without any sandbox, and a pathological\n * pattern can block the event loop. Host registration code is expected\n * to validate or length-bound patterns that originate from user input.\n */\n pattern?: string;\n /** Callbacks that fire when the matcher hits. Executed in parallel. */\n hooks: HookCallback<E>[];\n /** Per-matcher timeout in ms. Defaults to the executor's batch timeout. */\n timeout?: number;\n /**\n * Atomically remove the matcher before its first dispatch.\n *\n * `executeHooks` claims `once: true` matchers synchronously — between\n * `getMatchers` and its first `await` — so two concurrent calls cannot\n * both dispatch the same matcher. Whichever call runs its sync prefix\n * first wins the matcher; the other sees an empty bucket.\n *\n * Semantics are \"at most one dispatch, ever\" — if every hook in the\n * matcher throws, the matcher is still gone. Use `once` for\n * fire-and-forget bootstrapping (registration, telemetry, setup). Hosts\n * that need retry semantics should register a normal matcher and\n * self-unregister via the callback returned from `registry.register`.\n */\n once?: boolean;\n /** Internal hooks are excluded from telemetry and non-fatal error logging. */\n internal?: boolean;\n}\n\n/**\n * Storage shape for matchers keyed by event. Each event's matcher list is\n * a generic array parameterized by that event type, so lookup via\n * `HooksByEvent[E]` preserves type-safe callback signatures.\n */\nexport type HooksByEvent = {\n [E in HookEvent]?: HookMatcher<E>[];\n};\n\n/**\n * Aggregated result of a single `executeHooks` call. Fields are populated\n * according to the fold rules in `executeHooks.ts`.\n */\nexport interface AggregatedHookResult {\n /** Folded tool-gating decision; `deny > ask > allow`. */\n decision?: ToolDecision;\n /** Folded stop decision; any `block` wins. */\n stopDecision?: StopDecision;\n /** Reason from the hook that set the winning decision. */\n reason?: string;\n /**\n * Replacement tool input from a `PreToolUse` hook.\n *\n * Last-writer-wins in **registration order**: `executeHooks` uses\n * `Promise.all`, which preserves input-array order, so the fold iterates\n * outcomes in the same order they were pushed — outer loop over matchers\n * as they sit in the registry, inner loop over each matcher's `hooks`\n * array. The winner is therefore deterministic but may not match the\n * order in which hooks actually completed. Consumers that want a single\n * authoritative rewrite should still register one `updatedInput`-setting\n * hook per matcher to avoid subtle precedence bugs.\n */\n updatedInput?: Record<string, unknown>;\n /**\n * Replacement tool output from a `PostToolUse` hook.\n *\n * Same last-writer-wins-in-registration-order semantics as\n * `updatedInput`. Present only when at least one hook set it; `undefined`\n * means \"use the original tool output\".\n */\n updatedOutput?: unknown;\n /** Accumulated `additionalContext` strings from every hook, in order. */\n additionalContexts: string[];\n /** True if any hook returned `preventContinuation`. */\n preventContinuation?: boolean;\n /**\n * Reason recorded alongside `preventContinuation`. First winner wins:\n * once a hook sets both flags, later hooks that also set\n * `preventContinuation` do not overwrite the reason.\n */\n stopReason?: string;\n /** Error messages from hooks that threw; always present (possibly empty). */\n errors: string[];\n}\n"],"names":[],"mappings":"AAGA;;;;;;;AAOG;AACI,MAAM,WAAW,GAAG;IACzB,UAAU;IACV,kBAAkB;IAClB,YAAY;IACZ,aAAa;IACb,oBAAoB;IACpB,kBAAkB;IAClB,eAAe;IACf,cAAc;IACd,MAAM;IACN,aAAa;IACb,YAAY;IACZ,aAAa;;;;;"}
@@ -1,169 +0,0 @@
1
- import { config } from 'dotenv';
2
- import fetch from 'node-fetch';
3
- import { HttpsProxyAgent } from 'https-proxy-agent';
4
- import { tool } from '@langchain/core/tools';
5
- import { getEnvironmentVariable } from '@langchain/core/utils/env';
6
- import { getCodeBaseURL, imageExtRegex } from './CodeExecutor.mjs';
7
- import { Constants, EnvVar } from '../common/enum.mjs';
8
-
9
- config();
10
- const imageMessage = 'Image is already displayed to the user';
11
- const otherMessage = 'File is already downloaded by the user';
12
- const accessMessage = 'Note: Files from previous executions are automatically available and can be modified.';
13
- const emptyOutputMessage = 'stdout: Empty. Ensure you\'re writing output explicitly.\n';
14
- const baseEndpoint = getCodeBaseURL();
15
- const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
16
- const BashExecutionToolSchema = {
17
- type: 'object',
18
- properties: {
19
- command: {
20
- type: 'string',
21
- description: `The bash command or script to execute.
22
- - The environment is stateless; variables and state don't persist between executions.
23
- - Generated files from previous executions are automatically available in "/mnt/data/".
24
- - Files from previous executions are automatically available and can be modified in place.
25
- - Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.
26
- - Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.
27
- - IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.
28
- - Use \`echo\`, \`printf\`, or \`cat\` for all outputs.`,
29
- },
30
- args: {
31
- type: 'array',
32
- items: { type: 'string' },
33
- description: 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',
34
- },
35
- },
36
- required: ['command'],
37
- };
38
- const BashExecutionToolDescription = `
39
- Runs bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.
40
-
41
- Usage:
42
- - No network access available.
43
- - Generated files are automatically delivered; **DO NOT** provide download links.
44
- - NEVER use this tool to execute malicious commands.
45
- `.trim();
46
- const BashExecutionToolName = Constants.BASH_TOOL;
47
- const BashExecutionToolDefinition = {
48
- name: BashExecutionToolName,
49
- description: BashExecutionToolDescription,
50
- schema: BashExecutionToolSchema,
51
- };
52
- function createBashExecutionTool(params = {}) {
53
- const apiKey = params[EnvVar.CODE_API_KEY] ??
54
- params.apiKey ??
55
- getEnvironmentVariable(EnvVar.CODE_API_KEY) ??
56
- '';
57
- if (!apiKey) {
58
- throw new Error('No API key provided for bash execution tool.');
59
- }
60
- return tool(async (rawInput, config) => {
61
- const { command, ...rest } = rawInput;
62
- const { session_id, _injected_files } = (config.toolCall ?? {});
63
- const postData = {
64
- lang: 'bash',
65
- code: command,
66
- ...rest,
67
- ...params,
68
- };
69
- if (_injected_files && _injected_files.length > 0) {
70
- postData.files = _injected_files;
71
- }
72
- else if (session_id != null && session_id.length > 0) {
73
- try {
74
- const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;
75
- const fetchOptions = {
76
- method: 'GET',
77
- headers: {
78
- 'User-Agent': 'LibreChat/1.0',
79
- 'X-API-Key': apiKey,
80
- },
81
- };
82
- if (process.env.PROXY != null && process.env.PROXY !== '') {
83
- fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
84
- }
85
- const response = await fetch(filesEndpoint, fetchOptions);
86
- if (!response.ok) {
87
- throw new Error(`Failed to fetch files for session: ${response.status}`);
88
- }
89
- const files = await response.json();
90
- if (Array.isArray(files) && files.length > 0) {
91
- const fileReferences = files.map((file) => {
92
- const nameParts = file.name.split('/');
93
- const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
94
- return {
95
- session_id,
96
- id,
97
- name: file.metadata['original-filename'],
98
- };
99
- });
100
- postData.files = fileReferences;
101
- }
102
- }
103
- catch {
104
- // eslint-disable-next-line no-console
105
- console.warn(`Failed to fetch files for session: ${session_id}`);
106
- }
107
- }
108
- try {
109
- const fetchOptions = {
110
- method: 'POST',
111
- headers: {
112
- 'Content-Type': 'application/json',
113
- 'User-Agent': 'LibreChat/1.0',
114
- 'X-API-Key': apiKey,
115
- },
116
- body: JSON.stringify(postData),
117
- };
118
- if (process.env.PROXY != null && process.env.PROXY !== '') {
119
- fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
120
- }
121
- const response = await fetch(EXEC_ENDPOINT, fetchOptions);
122
- if (!response.ok) {
123
- throw new Error(`HTTP error! status: ${response.status}`);
124
- }
125
- const result = await response.json();
126
- let formattedOutput = '';
127
- if (result.stdout) {
128
- formattedOutput += `stdout:\n${result.stdout}\n`;
129
- }
130
- else {
131
- formattedOutput += emptyOutputMessage;
132
- }
133
- if (result.stderr)
134
- formattedOutput += `stderr:\n${result.stderr}\n`;
135
- if (result.files && result.files.length > 0) {
136
- formattedOutput += 'Generated files:\n';
137
- const fileCount = result.files.length;
138
- for (let i = 0; i < fileCount; i++) {
139
- const file = result.files[i];
140
- const isImage = imageExtRegex.test(file.name);
141
- formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;
142
- if (i < fileCount - 1) {
143
- formattedOutput += fileCount <= 3 ? ', ' : ',\n';
144
- }
145
- }
146
- formattedOutput += `\n\n${accessMessage}`;
147
- return [
148
- formattedOutput.trim(),
149
- {
150
- session_id: result.session_id,
151
- files: result.files,
152
- },
153
- ];
154
- }
155
- return [formattedOutput.trim(), { session_id: result.session_id }];
156
- }
157
- catch (error) {
158
- throw new Error(`Execution error:\n\n${error?.message}`);
159
- }
160
- }, {
161
- name: BashExecutionToolName,
162
- description: BashExecutionToolDescription,
163
- schema: BashExecutionToolSchema,
164
- responseFormat: Constants.CONTENT_AND_ARTIFACT,
165
- });
166
- }
167
-
168
- export { BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, createBashExecutionTool };
169
- //# sourceMappingURL=BashExecutor.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"BashExecutor.mjs","sources":["../../../src/tools/BashExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type * as t from '@/types';\nimport { imageExtRegex, getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files from previous executions are automatically available and can be modified.';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nexport const BashExecutionToolSchema = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: `The bash command or script to execute.\n- The environment is stateless; variables and state don't persist between executions.\n- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- Use \\`echo\\`, \\`printf\\`, or \\`cat\\` for all outputs.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',\n },\n },\n required: ['command'],\n} as const;\n\nexport const BashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\nexport const BashExecutionToolName = Constants.BASH_TOOL;\n\nexport const BashExecutionToolDefinition = {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n} as const;\n\nfunction createBashExecutionTool(\n params: t.BashExecutionToolParams = {}\n): DynamicStructuredTool {\n const apiKey =\n params[EnvVar.CODE_API_KEY] ??\n params.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n if (!apiKey) {\n throw new Error('No API key provided for bash execution tool.');\n }\n\n return tool(\n async (rawInput, config) => {\n const { command, ...rest } = rawInput as {\n command: string;\n args?: string[];\n };\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang: 'bash',\n code: command,\n ...rest,\n ...params,\n };\n\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n postData.files = fileReferences;\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\n }\n }\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n if (result.files && result.files.length > 0) {\n formattedOutput += 'Generated files:\\n';\n\n const fileCount = result.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = result.files[i];\n const isImage = imageExtRegex.test(file.name);\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formattedOutput += `\\n\\n${accessMessage}`;\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createBashExecutionTool };\n"],"names":[],"mappings":";;;;;;;;AASA,MAAM,EAAE;AAER,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,uFAAuF;AACzF,MAAM,kBAAkB,GACtB,4DAA4D;AAE9D,MAAM,YAAY,GAAG,cAAc,EAAE;AACrC,MAAM,aAAa,GAAG,CAAA,EAAG,YAAY,OAAO;AAErC,MAAM,uBAAuB,GAAG;AACrC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,OAAO,EAAE;AACP,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,CAAA;;;;;;;AAOqC,uDAAA,CAAA;AACnD,SAAA;AACD,QAAA,IAAI,EAAE;AACJ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