@librechat/agents 3.1.64 → 3.1.66-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/common/enum.cjs +13 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +3 -0
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs +162 -0
- package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
- package/dist/cjs/hooks/executeHooks.cjs +276 -0
- package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
- package/dist/cjs/hooks/matchers.cjs +256 -0
- package/dist/cjs/hooks/matchers.cjs.map +1 -0
- package/dist/cjs/hooks/types.cjs +27 -0
- package/dist/cjs/hooks/types.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +69 -54
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/main.cjs +40 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +8 -1
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +74 -12
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/run.cjs +111 -0
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +175 -0
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +296 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/ReadFile.cjs +43 -0
- package/dist/cjs/tools/ReadFile.cjs.map +1 -0
- package/dist/cjs/tools/SkillTool.cjs +50 -0
- package/dist/cjs/tools/SkillTool.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +304 -140
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/skillCatalog.cjs +84 -0
- package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
- package/dist/esm/common/enum.mjs +12 -1
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +3 -0
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/hooks/HookRegistry.mjs +160 -0
- package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
- package/dist/esm/hooks/executeHooks.mjs +273 -0
- package/dist/esm/hooks/executeHooks.mjs.map +1 -0
- package/dist/esm/hooks/matchers.mjs +251 -0
- package/dist/esm/hooks/matchers.mjs.map +1 -0
- package/dist/esm/hooks/types.mjs +25 -0
- package/dist/esm/hooks/types.mjs.map +1 -0
- package/dist/esm/llm/anthropic/types.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +69 -54
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/main.mjs +10 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +8 -1
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +66 -4
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/run.mjs +111 -0
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +169 -0
- package/dist/esm/tools/BashExecutor.mjs.map +1 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +287 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/ReadFile.mjs +38 -0
- package/dist/esm/tools/ReadFile.mjs.map +1 -0
- package/dist/esm/tools/SkillTool.mjs +45 -0
- package/dist/esm/tools/SkillTool.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +306 -142
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/skillCatalog.mjs +82 -0
- package/dist/esm/tools/skillCatalog.mjs.map +1 -0
- package/dist/types/common/enum.d.ts +7 -1
- package/dist/types/graphs/Graph.d.ts +2 -0
- package/dist/types/hooks/HookRegistry.d.ts +56 -0
- package/dist/types/hooks/executeHooks.d.ts +79 -0
- package/dist/types/hooks/index.d.ts +6 -0
- package/dist/types/hooks/matchers.d.ts +95 -0
- package/dist/types/hooks/types.d.ts +309 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/llm/anthropic/types.d.ts +1 -1
- package/dist/types/messages/format.d.ts +2 -1
- package/dist/types/run.d.ts +1 -0
- package/dist/types/tools/BashExecutor.d.ts +45 -0
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
- package/dist/types/tools/ReadFile.d.ts +28 -0
- package/dist/types/tools/SkillTool.d.ts +40 -0
- package/dist/types/tools/ToolNode.d.ts +24 -2
- package/dist/types/tools/skillCatalog.d.ts +19 -0
- package/dist/types/types/index.d.ts +1 -0
- package/dist/types/types/run.d.ts +20 -0
- package/dist/types/types/skill.d.ts +9 -0
- package/dist/types/types/tools.d.ts +38 -1
- package/package.json +2 -2
- package/src/common/enum.ts +12 -0
- package/src/graphs/Graph.ts +4 -0
- package/src/hooks/HookRegistry.ts +208 -0
- package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
- package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
- package/src/hooks/__tests__/integration.test.ts +337 -0
- package/src/hooks/__tests__/matchers.test.ts +238 -0
- package/src/hooks/__tests__/toolHooks.test.ts +669 -0
- package/src/hooks/executeHooks.ts +375 -0
- package/src/hooks/index.ts +55 -0
- package/src/hooks/matchers.ts +280 -0
- package/src/hooks/types.ts +388 -0
- package/src/index.ts +8 -0
- package/src/llm/anthropic/types.ts +1 -1
- package/src/llm/anthropic/utils/message_inputs.ts +93 -68
- package/src/llm/anthropic/utils/server-tool-inputs.test.ts +349 -0
- package/src/messages/core.ts +8 -1
- package/src/messages/format.ts +74 -4
- package/src/messages/formatAgentMessages.skills.test.ts +334 -0
- package/src/run.ts +126 -0
- package/src/tools/BashExecutor.ts +205 -0
- package/src/tools/BashProgrammaticToolCalling.ts +397 -0
- package/src/tools/ReadFile.ts +39 -0
- package/src/tools/SkillTool.ts +46 -0
- package/src/tools/ToolNode.ts +391 -169
- package/src/tools/__tests__/ReadFile.test.ts +44 -0
- package/src/tools/__tests__/SkillTool.test.ts +442 -0
- package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
- package/src/tools/__tests__/skillCatalog.test.ts +161 -0
- package/src/tools/skillCatalog.ts +126 -0
- package/src/types/index.ts +1 -0
- package/src/types/run.ts +20 -0
- package/src/types/skill.ts +11 -0
- package/src/types/tools.ts +41 -1
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/hooks/matchers.ts
|
|
4
|
+
/**
|
|
5
|
+
* Upper bound on hook-matcher pattern length. Patterns longer than this
|
|
6
|
+
* are rejected outright — the goal is a cheap cap on pathological inputs
|
|
7
|
+
* (repeated quantifiers, huge alternation groups) without pulling in a
|
|
8
|
+
* safe-regex dependency.
|
|
9
|
+
*
|
|
10
|
+
* Legitimate matchers are almost always under 50 characters (tool names,
|
|
11
|
+
* short alternations, simple prefix anchors); 512 leaves generous
|
|
12
|
+
* headroom while preventing 10KB regexes.
|
|
13
|
+
*/
|
|
14
|
+
const MAX_PATTERN_LENGTH = 512;
|
|
15
|
+
/**
|
|
16
|
+
* Upper bound on the compilation cache. Chosen to comfortably hold every
|
|
17
|
+
* distinct pattern a single multi-tenant run is likely to see (tools,
|
|
18
|
+
* agent types, basename filters) without growing without bound.
|
|
19
|
+
*
|
|
20
|
+
* Under hosts that register unique patterns per tenant, LRU eviction
|
|
21
|
+
* keeps the working set bounded — cold patterns are re-compiled on next
|
|
22
|
+
* use, which is the correct cost trade-off for long-running processes
|
|
23
|
+
* that must not leak memory.
|
|
24
|
+
*/
|
|
25
|
+
const MAX_CACHE_SIZE = 256;
|
|
26
|
+
/**
|
|
27
|
+
* Module-level LRU cache keyed by pattern string. Map iteration order is
|
|
28
|
+
* insertion order in ECMAScript, so refreshing an entry's position means
|
|
29
|
+
* "delete then re-set". On overflow we evict the first key (least
|
|
30
|
+
* recently used).
|
|
31
|
+
*
|
|
32
|
+
* Failed compiles are cached as `{ regex: null }` so a malformed pattern
|
|
33
|
+
* does not re-enter the compiler — and so a tenant spamming bad patterns
|
|
34
|
+
* doesn't burn CPU on every call.
|
|
35
|
+
*/
|
|
36
|
+
const patternCache = new Map();
|
|
37
|
+
/**
|
|
38
|
+
* Threshold above which `touchCacheEntry` actually performs the LRU
|
|
39
|
+
* refresh. Below this watermark the cache has zero eviction pressure, so
|
|
40
|
+
* the delete+set on every hit would be pure overhead. Above it we refresh
|
|
41
|
+
* properly so hot patterns survive evictions. 75% of capacity is the
|
|
42
|
+
* standard sweet spot.
|
|
43
|
+
*/
|
|
44
|
+
const LRU_REFRESH_THRESHOLD = Math.floor((MAX_CACHE_SIZE * 3) / 4);
|
|
45
|
+
function touchCacheEntry(pattern, entry) {
|
|
46
|
+
if (patternCache.size < LRU_REFRESH_THRESHOLD) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
patternCache.delete(pattern);
|
|
50
|
+
patternCache.set(pattern, entry);
|
|
51
|
+
}
|
|
52
|
+
function setCacheEntry(pattern, entry) {
|
|
53
|
+
if (patternCache.size >= MAX_CACHE_SIZE) {
|
|
54
|
+
const oldestKey = patternCache.keys().next().value;
|
|
55
|
+
if (oldestKey !== undefined) {
|
|
56
|
+
patternCache.delete(oldestKey);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
patternCache.set(pattern, entry);
|
|
60
|
+
}
|
|
61
|
+
function skipGroupSyntaxPrefix(pattern, start) {
|
|
62
|
+
if (start >= pattern.length || pattern[start] !== '?') {
|
|
63
|
+
return start;
|
|
64
|
+
}
|
|
65
|
+
let i = start + 1;
|
|
66
|
+
if (i >= pattern.length) {
|
|
67
|
+
return i;
|
|
68
|
+
}
|
|
69
|
+
const modifier = pattern[i];
|
|
70
|
+
if (modifier === ':' || modifier === '=' || modifier === '!') {
|
|
71
|
+
return i + 1;
|
|
72
|
+
}
|
|
73
|
+
if (modifier !== '<') {
|
|
74
|
+
return i;
|
|
75
|
+
}
|
|
76
|
+
i++;
|
|
77
|
+
if (i < pattern.length && (pattern[i] === '=' || pattern[i] === '!')) {
|
|
78
|
+
return i + 1;
|
|
79
|
+
}
|
|
80
|
+
while (i < pattern.length && pattern[i] !== '>') {
|
|
81
|
+
i++;
|
|
82
|
+
}
|
|
83
|
+
if (i < pattern.length) {
|
|
84
|
+
i++;
|
|
85
|
+
}
|
|
86
|
+
return i;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Cheap syntactic detector for the most common catastrophic-backtracking
|
|
90
|
+
* shape: a quantified group that contains another quantifier (e.g.
|
|
91
|
+
* `(a+)+`, `(.*)*`, `(\w+)+$`, `(?:(a+))+`). This is the "nested
|
|
92
|
+
* quantifier" class of ReDoS — runs in polynomial-or-worse time on
|
|
93
|
+
* adversarial inputs.
|
|
94
|
+
*
|
|
95
|
+
* The scan walks the pattern linearly using an explicit stack of group
|
|
96
|
+
* frames. For each group it tracks whether the group's contents include
|
|
97
|
+
* "backtrack risk" — meaning a direct quantifier OR a nested group that
|
|
98
|
+
* carries risk up. When a group closes with a trailing quantifier AND its
|
|
99
|
+
* frame carries backtrack risk, the pattern is flagged. Risk propagates
|
|
100
|
+
* to the enclosing frame when a child group closes (whether the child
|
|
101
|
+
* itself was quantified or not), so `(?:(a+))+` — equivalent to `(a+)+`
|
|
102
|
+
* — is flagged correctly even though the outer non-capturing wrapper is
|
|
103
|
+
* one level removed from the inner quantifier.
|
|
104
|
+
*
|
|
105
|
+
* ## Group-syntax prefixes
|
|
106
|
+
*
|
|
107
|
+
* Non-capturing groups (`(?:`), lookaheads (`(?=`, `(?!`), lookbehinds
|
|
108
|
+
* (`(?<=`, `(?<!`), and named groups (`(?<name>`) are skipped over at
|
|
109
|
+
* the `(` so their `?` is not misread as a quantifier. Without this,
|
|
110
|
+
* `(?:pre_)?tool_name` would be incorrectly rejected because the scanner
|
|
111
|
+
* would see the group-syntax `?` as a quantifier at depth 1.
|
|
112
|
+
*
|
|
113
|
+
* ## Heuristic, not a proof
|
|
114
|
+
*
|
|
115
|
+
* This catches the common forms but not all. Ambiguous-alternation ReDoS
|
|
116
|
+
* like `(a|a)+` is not detected. Pathologically long patterns are also
|
|
117
|
+
* caught by {@link MAX_PATTERN_LENGTH}. Hosts that accept user-supplied
|
|
118
|
+
* patterns must still validate upstream.
|
|
119
|
+
*/
|
|
120
|
+
function hasNestedQuantifier(pattern) {
|
|
121
|
+
const stack = [];
|
|
122
|
+
let i = 0;
|
|
123
|
+
while (i < pattern.length) {
|
|
124
|
+
const ch = pattern[i];
|
|
125
|
+
if (ch === '\\') {
|
|
126
|
+
i += 2;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (ch === '[') {
|
|
130
|
+
i = findCharClassEnd(pattern, i) + 1;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (ch === '(') {
|
|
134
|
+
stack.push({ hasBacktrackRisk: false });
|
|
135
|
+
i = skipGroupSyntaxPrefix(pattern, i + 1);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (ch === ')') {
|
|
139
|
+
const frame = stack.pop();
|
|
140
|
+
if (frame === undefined) {
|
|
141
|
+
i++;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const next = pattern[i + 1];
|
|
145
|
+
const isQuantifier = next === '*' || next === '+' || next === '?' || next === '{';
|
|
146
|
+
if (isQuantifier && frame.hasBacktrackRisk) {
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
if (stack.length > 0 && (frame.hasBacktrackRisk || isQuantifier)) {
|
|
150
|
+
stack[stack.length - 1].hasBacktrackRisk = true;
|
|
151
|
+
}
|
|
152
|
+
i++;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (ch === '*' || ch === '+' || ch === '?' || ch === '{') {
|
|
156
|
+
if (stack.length > 0) {
|
|
157
|
+
stack[stack.length - 1].hasBacktrackRisk = true;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
i++;
|
|
161
|
+
}
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
function findCharClassEnd(pattern, start) {
|
|
165
|
+
let i = start + 1;
|
|
166
|
+
while (i < pattern.length) {
|
|
167
|
+
const ch = pattern[i];
|
|
168
|
+
if (ch === '\\') {
|
|
169
|
+
i += 2;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (ch === ']') {
|
|
173
|
+
return i;
|
|
174
|
+
}
|
|
175
|
+
i++;
|
|
176
|
+
}
|
|
177
|
+
return pattern.length - 1;
|
|
178
|
+
}
|
|
179
|
+
function compile(pattern) {
|
|
180
|
+
const cached = patternCache.get(pattern);
|
|
181
|
+
if (cached !== undefined) {
|
|
182
|
+
touchCacheEntry(pattern, cached);
|
|
183
|
+
return cached.regex;
|
|
184
|
+
}
|
|
185
|
+
if (pattern.length > MAX_PATTERN_LENGTH) {
|
|
186
|
+
setCacheEntry(pattern, { regex: null });
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
if (hasNestedQuantifier(pattern)) {
|
|
190
|
+
setCacheEntry(pattern, { regex: null });
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
try {
|
|
194
|
+
const regex = new RegExp(pattern);
|
|
195
|
+
setCacheEntry(pattern, { regex });
|
|
196
|
+
return regex;
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
setCacheEntry(pattern, { regex: null });
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Tests whether a hook matcher pattern matches the given query string.
|
|
205
|
+
*
|
|
206
|
+
* ## Semantics
|
|
207
|
+
*
|
|
208
|
+
* - `undefined` or empty `pattern` matches any query (wildcard). This is
|
|
209
|
+
* the intended shape for events that do not supply a query string at
|
|
210
|
+
* all (`RunStart`, `Stop`, etc.) — register such matchers without a
|
|
211
|
+
* pattern.
|
|
212
|
+
* - `undefined` or empty `query` with a non-empty `pattern` never matches.
|
|
213
|
+
* Setting a pattern on a query-less event is therefore inert: the
|
|
214
|
+
* matcher will simply never fire. This is intentional — it keeps
|
|
215
|
+
* query-based filtering out of event types where "query" has no meaning,
|
|
216
|
+
* and is documented on `HookMatcher.pattern`.
|
|
217
|
+
* - Otherwise, the pattern is compiled once (via a bounded LRU cache) and
|
|
218
|
+
* tested against the query.
|
|
219
|
+
* - Invalid regex patterns never throw — a failed compile is cached as
|
|
220
|
+
* "never matches" so a single malformed pattern cannot take out a whole
|
|
221
|
+
* `executeHooks` batch.
|
|
222
|
+
*
|
|
223
|
+
* ## ReDoS mitigations
|
|
224
|
+
*
|
|
225
|
+
* Patterns compile through three cheap gates before reaching `new RegExp`:
|
|
226
|
+
*
|
|
227
|
+
* 1. {@link MAX_PATTERN_LENGTH} length cap rejects oversized inputs.
|
|
228
|
+
* 2. {@link hasNestedQuantifier} rejects the most common catastrophic-
|
|
229
|
+
* backtracking shape (quantified group containing a quantifier).
|
|
230
|
+
* 3. Successful compiles are cached in a bounded LRU so repeated calls
|
|
231
|
+
* never re-enter the regex compiler.
|
|
232
|
+
*
|
|
233
|
+
* These are a floor, not a ceiling. Hosts that accept user-supplied
|
|
234
|
+
* patterns should still validate upstream. The design report §3.8 routes
|
|
235
|
+
* persistable hooks through a host-side compiler before they reach this
|
|
236
|
+
* module.
|
|
237
|
+
*/
|
|
238
|
+
function matchesQuery(pattern, query) {
|
|
239
|
+
if (pattern === undefined || pattern === '') {
|
|
240
|
+
return true;
|
|
241
|
+
}
|
|
242
|
+
if (query === undefined || query === '') {
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
const regex = compile(pattern);
|
|
246
|
+
if (regex === null) {
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
return regex.test(query);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE;
|
|
253
|
+
exports.MAX_PATTERN_LENGTH = MAX_PATTERN_LENGTH;
|
|
254
|
+
exports.hasNestedQuantifier = hasNestedQuantifier;
|
|
255
|
+
exports.matchesQuery = matchesQuery;
|
|
256
|
+
//# sourceMappingURL=matchers.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"matchers.cjs","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,IAAI,IAAI,cAAc,EAAE;QACvC,MAAM,SAAS,GAAG,YAAY,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK;AAClD,QAAA,IAAI,SAAS,KAAK,SAAS,EAAE;AAC3B,YAAA,YAAY,CAAC,MAAM,CAAC,SAAS,CAAC;QAChC;IACF;AACA,IAAA,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC;AAClC;AAMA,SAAS,qBAAqB,CAAC,OAAe,EAAE,KAAa,EAAA;AAC3D,IAAA,IAAI,KAAK,IAAI,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,EAAE;AACrD,QAAA,OAAO,KAAK;IACd;AACA,IAAA,IAAI,CAAC,GAAG,KAAK,GAAG,CAAC;AACjB,IAAA,IAAI,CAAC,IAAI,OAAO,CAAC,MAAM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AAS,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;;;;;;;"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Closed set of hook lifecycle events supported by the hooks system.
|
|
5
|
+
*
|
|
6
|
+
* These mirror the subset of Claude Code's event surface that makes sense
|
|
7
|
+
* for a library context (no filesystem/CLI-specific events). See
|
|
8
|
+
* `docs/hooks-design-report.md` §3.2 for the mapping to existing
|
|
9
|
+
* `@librechat/agents` emission points.
|
|
10
|
+
*/
|
|
11
|
+
const HOOK_EVENTS = [
|
|
12
|
+
'RunStart',
|
|
13
|
+
'UserPromptSubmit',
|
|
14
|
+
'PreToolUse',
|
|
15
|
+
'PostToolUse',
|
|
16
|
+
'PostToolUseFailure',
|
|
17
|
+
'PermissionDenied',
|
|
18
|
+
'SubagentStart',
|
|
19
|
+
'SubagentStop',
|
|
20
|
+
'Stop',
|
|
21
|
+
'StopFailure',
|
|
22
|
+
'PreCompact',
|
|
23
|
+
'PostCompact',
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
exports.HOOK_EVENTS = HOOK_EVENTS;
|
|
27
|
+
//# sourceMappingURL=types.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.cjs","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 trigger: 'threshold' | 'manual' | 'error';\n}\n\nexport interface PostCompactHookInput extends BaseHookInput {\n hook_event_name: 'PostCompact';\n summary: string;\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","sources":["../../../../src/llm/anthropic/types.ts"],"sourcesContent":["import Anthropic from '@anthropic-ai/sdk';\nimport { BindToolsInput } from '@langchain/core/language_models/chat_models';\n\nexport type AnthropicStreamUsage = Anthropic.Usage;\nexport type AnthropicMessageDeltaEvent = Anthropic.MessageDeltaEvent;\nexport type AnthropicMessageStartEvent = Anthropic.MessageStartEvent;\n\nexport type AnthropicToolResponse = {\n type: 'tool_use';\n id: string;\n name: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: Record<string, any>;\n};\n\nexport type AnthropicMessageParam = Anthropic.MessageParam;\nexport type AnthropicMessageResponse =\n | Anthropic.ContentBlock\n | AnthropicToolResponse;\nexport type AnthropicMessageCreateParams =\n Anthropic.MessageCreateParamsNonStreaming;\nexport type AnthropicStreamingMessageCreateParams =\n Anthropic.MessageCreateParamsStreaming;\nexport type AnthropicThinkingConfigParam = Anthropic.ThinkingConfigParam;\nexport type AnthropicMessageStreamEvent = Anthropic.MessageStreamEvent;\nexport type AnthropicRequestOptions = Anthropic.RequestOptions;\nexport type AnthropicToolChoice =\n | {\n type: 'tool';\n name: string;\n }\n | 'any'\n | 'auto'\n | 'none'\n | string;\nexport type ChatAnthropicToolType = Anthropic.Messages.Tool | BindToolsInput;\nexport type AnthropicTextBlockParam = Anthropic.Messages.TextBlockParam;\nexport type AnthropicImageBlockParam = Anthropic.Messages.ImageBlockParam;\nexport type AnthropicToolUseBlockParam = Anthropic.Messages.ToolUseBlockParam;\nexport type AnthropicToolResultBlockParam =\n Anthropic.Messages.ToolResultBlockParam;\nexport type AnthropicDocumentBlockParam = Anthropic.Messages.DocumentBlockParam;\nexport type AnthropicThinkingBlockParam = Anthropic.Messages.ThinkingBlockParam;\nexport type AnthropicRedactedThinkingBlockParam =\n Anthropic.Messages.RedactedThinkingBlockParam;\nexport type AnthropicServerToolUseBlockParam =\n Anthropic.Messages.ServerToolUseBlockParam;\nexport type AnthropicWebSearchToolResultBlockParam =\n Anthropic.Messages.WebSearchToolResultBlockParam;\nexport type AnthropicWebSearchResultBlockParam =\n Anthropic.Messages.WebSearchResultBlockParam;\nexport type AnthropicSearchResultBlockParam =\n Anthropic.Beta.BetaSearchResultBlockParam;\nexport type AnthropicCompactionBlockParam =\n Anthropic.Beta.BetaCompactionBlockParam;\nexport type AnthropicOutputConfig = Anthropic.Messages.OutputConfig;\nexport type ChatAnthropicOutputFormat = Anthropic.Messages.JSONOutputFormat;\n\n// Union of all possible content block types including server tool use\nexport type AnthropicContentBlock =\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicWebSearchResultBlockParam\n | AnthropicCompactionBlockParam;\n\n// Union of all possible content block types including server tool use\nexport type ChatAnthropicContentBlock =\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicWebSearchResultBlockParam\n | AnthropicSearchResultBlockParam\n | AnthropicCompactionBlockParam;\n\nexport function isAnthropicImageBlockParam(\n block: unknown\n): block is AnthropicImageBlockParam {\n if (block == null) {\n return false;\n }\n if (typeof block !== 'object') {\n return false;\n }\n if (!('type' in block) || block.type !== 'image') {\n return false;\n }\n\n if (!('source' in block) || typeof block.source !== 'object') {\n return false;\n }\n\n if (block.source == null) {\n return false;\n }\n\n if (!('type' in block.source)) {\n return false;\n }\n\n if (block.source.type === 'base64') {\n if (!('media_type' in block.source)) {\n return false;\n }\n\n if (typeof block.source.media_type !== 'string') {\n return false;\n }\n\n if (!('data' in block.source)) {\n return false;\n }\n\n if (typeof block.source.data !== 'string') {\n return false;\n }\n\n return true;\n }\n\n if (block.source.type === 'url') {\n if (!('url' in block.source)) {\n return false;\n }\n\n if (typeof block.source.url !== 'string') {\n return false;\n }\n\n return true;\n }\n\n return false;\n}\n"],"names":[],"mappings":";;AAuFM,SAAU,0BAA0B,CACxC,KAAc,EAAA;AAEd,IAAA,IAAI,KAAK,IAAI,IAAI,EAAE;AACjB,QAAA,OAAO,KAAK;IACd;AACA,IAAA,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AAC7B,QAAA,OAAO,KAAK;IACd;AACA,IAAA,IAAI,EAAE,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE;AAChD,QAAA,OAAO,KAAK;IACd;AAEA,IAAA,IAAI,EAAE,QAAQ,IAAI,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,EAAE;AAC5D,QAAA,OAAO,KAAK;IACd;AAEA,IAAA,IAAI,KAAK,CAAC,MAAM,IAAI,IAAI,EAAE;AACxB,QAAA,OAAO,KAAK;IACd;IAEA,IAAI,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE;AAC7B,QAAA,OAAO,KAAK;IACd;IAEA,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,KAAK,QAAQ,EAAE;QAClC,IAAI,EAAE,YAAY,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE;AACnC,YAAA,OAAO,KAAK;QACd;QAEA,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,UAAU,KAAK,QAAQ,EAAE;AAC/C,YAAA,OAAO,KAAK;QACd;QAEA,IAAI,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE;AAC7B,YAAA,OAAO,KAAK;QACd;QAEA,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,IAAI,KAAK,QAAQ,EAAE;AACzC,YAAA,OAAO,KAAK;QACd;AAEA,QAAA,OAAO,IAAI;IACb;IAEA,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,KAAK,KAAK,EAAE;QAC/B,IAAI,EAAE,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE;AAC5B,YAAA,OAAO,KAAK;QACd;QAEA,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,GAAG,KAAK,QAAQ,EAAE;AACxC,YAAA,OAAO,KAAK;QACd;AAEA,QAAA,OAAO,IAAI;IACb;AAEA,IAAA,OAAO,KAAK;AACd;;;;"}
|
|
1
|
+
{"version":3,"file":"types.cjs","sources":["../../../../src/llm/anthropic/types.ts"],"sourcesContent":["import Anthropic from '@anthropic-ai/sdk';\nimport { BindToolsInput } from '@langchain/core/language_models/chat_models';\n\nexport type AnthropicStreamUsage = Anthropic.Usage;\nexport type AnthropicMessageDeltaEvent = Anthropic.MessageDeltaEvent;\nexport type AnthropicMessageStartEvent = Anthropic.MessageStartEvent;\n\nexport type AnthropicToolResponse = {\n type: 'tool_use' | 'server_tool_use';\n id: string;\n name: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: Record<string, any>;\n};\n\nexport type AnthropicMessageParam = Anthropic.MessageParam;\nexport type AnthropicMessageResponse =\n | Anthropic.ContentBlock\n | AnthropicToolResponse;\nexport type AnthropicMessageCreateParams =\n Anthropic.MessageCreateParamsNonStreaming;\nexport type AnthropicStreamingMessageCreateParams =\n Anthropic.MessageCreateParamsStreaming;\nexport type AnthropicThinkingConfigParam = Anthropic.ThinkingConfigParam;\nexport type AnthropicMessageStreamEvent = Anthropic.MessageStreamEvent;\nexport type AnthropicRequestOptions = Anthropic.RequestOptions;\nexport type AnthropicToolChoice =\n | {\n type: 'tool';\n name: string;\n }\n | 'any'\n | 'auto'\n | 'none'\n | string;\nexport type ChatAnthropicToolType = Anthropic.Messages.Tool | BindToolsInput;\nexport type AnthropicTextBlockParam = Anthropic.Messages.TextBlockParam;\nexport type AnthropicImageBlockParam = Anthropic.Messages.ImageBlockParam;\nexport type AnthropicToolUseBlockParam = Anthropic.Messages.ToolUseBlockParam;\nexport type AnthropicToolResultBlockParam =\n Anthropic.Messages.ToolResultBlockParam;\nexport type AnthropicDocumentBlockParam = Anthropic.Messages.DocumentBlockParam;\nexport type AnthropicThinkingBlockParam = Anthropic.Messages.ThinkingBlockParam;\nexport type AnthropicRedactedThinkingBlockParam =\n Anthropic.Messages.RedactedThinkingBlockParam;\nexport type AnthropicServerToolUseBlockParam =\n Anthropic.Messages.ServerToolUseBlockParam;\nexport type AnthropicWebSearchToolResultBlockParam =\n Anthropic.Messages.WebSearchToolResultBlockParam;\nexport type AnthropicWebSearchResultBlockParam =\n Anthropic.Messages.WebSearchResultBlockParam;\nexport type AnthropicSearchResultBlockParam =\n Anthropic.Beta.BetaSearchResultBlockParam;\nexport type AnthropicCompactionBlockParam =\n Anthropic.Beta.BetaCompactionBlockParam;\nexport type AnthropicOutputConfig = Anthropic.Messages.OutputConfig;\nexport type ChatAnthropicOutputFormat = Anthropic.Messages.JSONOutputFormat;\n\n// Union of all possible content block types including server tool use\nexport type AnthropicContentBlock =\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicWebSearchResultBlockParam\n | AnthropicCompactionBlockParam;\n\n// Union of all possible content block types including server tool use\nexport type ChatAnthropicContentBlock =\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicWebSearchResultBlockParam\n | AnthropicSearchResultBlockParam\n | AnthropicCompactionBlockParam;\n\nexport function isAnthropicImageBlockParam(\n block: unknown\n): block is AnthropicImageBlockParam {\n if (block == null) {\n return false;\n }\n if (typeof block !== 'object') {\n return false;\n }\n if (!('type' in block) || block.type !== 'image') {\n return false;\n }\n\n if (!('source' in block) || typeof block.source !== 'object') {\n return false;\n }\n\n if (block.source == null) {\n return false;\n }\n\n if (!('type' in block.source)) {\n return false;\n }\n\n if (block.source.type === 'base64') {\n if (!('media_type' in block.source)) {\n return false;\n }\n\n if (typeof block.source.media_type !== 'string') {\n return false;\n }\n\n if (!('data' in block.source)) {\n return false;\n }\n\n if (typeof block.source.data !== 'string') {\n return false;\n }\n\n return true;\n }\n\n if (block.source.type === 'url') {\n if (!('url' in block.source)) {\n return false;\n }\n\n if (typeof block.source.url !== 'string') {\n return false;\n }\n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E;AAC5B,YAAA,OAAO,KAAK;QACd;QAEA,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,GAAG,KAAK,QAAQ,EAAE;AACxC,YAAA,OAAO,KAAK;QACd;AAEA,QAAA,OAAO,IAAI;IACb;AAEA,IAAA,OAAO,KAAK;AACd;;;;"}
|
|
@@ -98,7 +98,9 @@ function _convertLangChainToolCallToAnthropic(toolCall) {
|
|
|
98
98
|
throw new Error('Anthropic requires all tool calls to have an "id".');
|
|
99
99
|
}
|
|
100
100
|
return {
|
|
101
|
-
type:
|
|
101
|
+
type: toolCall.id.startsWith(_enum.Constants.ANTHROPIC_SERVER_TOOL_PREFIX)
|
|
102
|
+
? 'server_tool_use'
|
|
103
|
+
: 'tool_use',
|
|
102
104
|
id: toolCall.id,
|
|
103
105
|
name: toolCall.name,
|
|
104
106
|
input: toolCall.args,
|
|
@@ -303,71 +305,74 @@ function _formatContent(message) {
|
|
|
303
305
|
else {
|
|
304
306
|
const contentBlocks = content.map((contentPart) => {
|
|
305
307
|
/**
|
|
306
|
-
*
|
|
307
|
-
* These
|
|
308
|
-
*
|
|
309
|
-
*
|
|
308
|
+
* Normalize server_tool_use blocks into a clean shape the API accepts.
|
|
309
|
+
* These blocks may arrive with the correct type (server_tool_use) or mislabeled
|
|
310
|
+
* as text/tool_use after chunk concatenation or state serialization.
|
|
311
|
+
* Regardless of current type, if the id starts with 'srvtoolu_' we rebuild
|
|
312
|
+
* a clean block with only the properties the API expects.
|
|
310
313
|
*/
|
|
311
314
|
if ('id' in contentPart &&
|
|
312
|
-
'
|
|
313
|
-
|
|
314
|
-
|
|
315
|
+
typeof contentPart.id === 'string' &&
|
|
316
|
+
contentPart.id.startsWith(_enum.Constants.ANTHROPIC_SERVER_TOOL_PREFIX) &&
|
|
317
|
+
'name' in contentPart) {
|
|
315
318
|
const rawPart = contentPart;
|
|
316
|
-
|
|
317
|
-
if (
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
if (typeof input === 'string') {
|
|
321
|
-
try {
|
|
322
|
-
input = JSON.parse(input);
|
|
323
|
-
}
|
|
324
|
-
catch {
|
|
325
|
-
input = {};
|
|
326
|
-
}
|
|
319
|
+
let input = rawPart.input;
|
|
320
|
+
if (typeof input === 'string') {
|
|
321
|
+
try {
|
|
322
|
+
input = JSON.parse(input);
|
|
327
323
|
}
|
|
324
|
+
catch {
|
|
325
|
+
input = {};
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const corrected = {
|
|
329
|
+
type: 'server_tool_use',
|
|
330
|
+
id: rawPart.id,
|
|
331
|
+
name: (rawPart.name ?? 'web_search'),
|
|
332
|
+
input: (input ?? {}),
|
|
333
|
+
};
|
|
334
|
+
return corrected;
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Normalize web_search_tool_result blocks into a clean shape.
|
|
338
|
+
* Same rationale as above — the block may carry extra properties from
|
|
339
|
+
* streaming (input, index, etc.) that the API rejects. Rebuild cleanly.
|
|
340
|
+
*/
|
|
341
|
+
if ('tool_use_id' in contentPart &&
|
|
342
|
+
typeof contentPart.tool_use_id ===
|
|
343
|
+
'string' &&
|
|
344
|
+
contentPart.tool_use_id.startsWith(_enum.Constants.ANTHROPIC_SERVER_TOOL_PREFIX) &&
|
|
345
|
+
'content' in contentPart) {
|
|
346
|
+
const rawPart = contentPart;
|
|
347
|
+
const content = rawPart.content;
|
|
348
|
+
const isValidContent = Array.isArray(content) ||
|
|
349
|
+
(content != null &&
|
|
350
|
+
typeof content === 'object' &&
|
|
351
|
+
'type' in content &&
|
|
352
|
+
content.type ===
|
|
353
|
+
'web_search_tool_result_error');
|
|
354
|
+
if (isValidContent) {
|
|
328
355
|
const corrected = {
|
|
329
|
-
type: '
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
input: input,
|
|
356
|
+
type: 'web_search_tool_result',
|
|
357
|
+
tool_use_id: rawPart.tool_use_id,
|
|
358
|
+
content: content,
|
|
333
359
|
};
|
|
334
360
|
return corrected;
|
|
335
361
|
}
|
|
336
|
-
// If it's not a server tool, skip it (return null to filter it out)
|
|
337
362
|
return null;
|
|
338
363
|
}
|
|
339
364
|
/**
|
|
340
|
-
*
|
|
341
|
-
* These have tool_use_id and nested content - fix their type instead of filtering.
|
|
342
|
-
* Only correct if we can confirm it's a web search result by checking the tool_use_id prefix.
|
|
343
|
-
*
|
|
344
|
-
* Handles both success results (array content) and error results (object with error_code).
|
|
365
|
+
* Skip non-server malformed blocks that have tool fields mixed with text type.
|
|
345
366
|
*/
|
|
367
|
+
if ('id' in contentPart &&
|
|
368
|
+
'name' in contentPart &&
|
|
369
|
+
'input' in contentPart &&
|
|
370
|
+
contentPart.type === 'text') {
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
346
373
|
if ('tool_use_id' in contentPart &&
|
|
347
374
|
'content' in contentPart &&
|
|
348
375
|
contentPart.type === 'text') {
|
|
349
|
-
const rawPart = contentPart;
|
|
350
|
-
const toolUseId = rawPart.tool_use_id;
|
|
351
|
-
const content = rawPart.content;
|
|
352
|
-
if (toolUseId &&
|
|
353
|
-
toolUseId.startsWith(_enum.Constants.ANTHROPIC_SERVER_TOOL_PREFIX)) {
|
|
354
|
-
// Verify content is either an array (success) or error object
|
|
355
|
-
const isValidContent = Array.isArray(content) ||
|
|
356
|
-
(content != null &&
|
|
357
|
-
typeof content === 'object' &&
|
|
358
|
-
'type' in content &&
|
|
359
|
-
content.type ===
|
|
360
|
-
'web_search_tool_result_error');
|
|
361
|
-
if (isValidContent) {
|
|
362
|
-
const corrected = {
|
|
363
|
-
type: 'web_search_tool_result',
|
|
364
|
-
tool_use_id: toolUseId,
|
|
365
|
-
content: content,
|
|
366
|
-
};
|
|
367
|
-
return corrected;
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
// If it's not a recognized server tool result format, skip it (return null to filter it out)
|
|
371
376
|
return null;
|
|
372
377
|
}
|
|
373
378
|
if (messages.isDataContentBlock(contentPart)) {
|
|
@@ -461,6 +466,12 @@ function _formatContent(message) {
|
|
|
461
466
|
// and is not a valid type for Anthropic messages.
|
|
462
467
|
contentPartCopy.type = 'tool_use';
|
|
463
468
|
}
|
|
469
|
+
if (contentPartCopy.type === 'tool_use' &&
|
|
470
|
+
'id' in contentPartCopy &&
|
|
471
|
+
typeof contentPartCopy.id === 'string' &&
|
|
472
|
+
contentPartCopy.id.startsWith(_enum.Constants.ANTHROPIC_SERVER_TOOL_PREFIX)) {
|
|
473
|
+
contentPartCopy.type = 'server_tool_use';
|
|
474
|
+
}
|
|
464
475
|
if ('input' in contentPartCopy) {
|
|
465
476
|
// Anthropic tool use inputs should be valid objects, when applicable.
|
|
466
477
|
if (typeof contentPartCopy.input === 'string') {
|
|
@@ -507,7 +518,8 @@ function _formatContent(message) {
|
|
|
507
518
|
throw new Error('Unsupported message content format');
|
|
508
519
|
}
|
|
509
520
|
});
|
|
510
|
-
return contentBlocks.filter((block) => block !== null
|
|
521
|
+
return contentBlocks.filter((block) => block !== null &&
|
|
522
|
+
!(block.type === 'text' && 'text' in block && block.text === ''));
|
|
511
523
|
}
|
|
512
524
|
}
|
|
513
525
|
/**
|
|
@@ -542,10 +554,13 @@ function _convertMessagesToAnthropicPayload(messages$1) {
|
|
|
542
554
|
}
|
|
543
555
|
if (messages.isAIMessage(message) && !!message.tool_calls?.length) {
|
|
544
556
|
if (typeof message.content === 'string') {
|
|
557
|
+
const clientToolCalls = message.tool_calls.filter((tc) => !(tc.id?.startsWith(_enum.Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ?? false));
|
|
545
558
|
if (message.content === '') {
|
|
546
559
|
return {
|
|
547
560
|
role,
|
|
548
|
-
content:
|
|
561
|
+
content: clientToolCalls.length > 0
|
|
562
|
+
? clientToolCalls.map(_convertLangChainToolCallToAnthropic)
|
|
563
|
+
: [{ type: 'text', text: ' ' }],
|
|
549
564
|
};
|
|
550
565
|
}
|
|
551
566
|
else {
|
|
@@ -553,7 +568,7 @@ function _convertMessagesToAnthropicPayload(messages$1) {
|
|
|
553
568
|
role,
|
|
554
569
|
content: [
|
|
555
570
|
{ type: 'text', text: message.content },
|
|
556
|
-
...
|
|
571
|
+
...clientToolCalls.map(_convertLangChainToolCallToAnthropic),
|
|
557
572
|
],
|
|
558
573
|
};
|
|
559
574
|
}
|