@ai-sdk-tool/parser 2.1.6 → 3.0.0-canary.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.
@@ -0,0 +1,2514 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/protocols/dummy-protocol.ts
8
+ import { generateId } from "@ai-sdk/provider-utils";
9
+
10
+ // src/protocols/json-mix-protocol.ts
11
+ import { generateId as generateId2 } from "@ai-sdk/provider-utils";
12
+
13
+ // src/utils/debug.ts
14
+ var LINE_SPLIT_REGEX = /\r?\n/;
15
+ function normalizeBooleanString(value) {
16
+ const normalized = value.trim().toLowerCase();
17
+ if (normalized === "1" || normalized === "true" || normalized === "yes") {
18
+ return true;
19
+ }
20
+ if (normalized === "0" || normalized === "false" || normalized === "no") {
21
+ return false;
22
+ }
23
+ return;
24
+ }
25
+ function getDebugLevel() {
26
+ const envVal = typeof process !== "undefined" && process.env && process.env.DEBUG_PARSER_MW || "off";
27
+ const envLower = String(envVal).toLowerCase();
28
+ if (envLower === "stream" || envLower === "parse" || envLower === "off") {
29
+ return envLower;
30
+ }
31
+ const boolEnv = normalizeBooleanString(envLower);
32
+ if (boolEnv === true) {
33
+ return "stream";
34
+ }
35
+ if (envLower === "2") {
36
+ return "parse";
37
+ }
38
+ return "off";
39
+ }
40
+ function color(code) {
41
+ return (text) => `\x1B[${code}m${text}\x1B[0m`;
42
+ }
43
+ var ANSI_GRAY = 90;
44
+ var ANSI_YELLOW = 33;
45
+ var ANSI_CYAN = 36;
46
+ var ANSI_BG_BLUE = 44;
47
+ var ANSI_BG_GREEN = 42;
48
+ var ANSI_INVERSE = 7;
49
+ var ANSI_UNDERLINE = 4;
50
+ var ANSI_BOLD = 1;
51
+ var cGray = color(ANSI_GRAY);
52
+ var cYellow = color(ANSI_YELLOW);
53
+ var cCyan = color(ANSI_CYAN);
54
+ var cBgBlue = color(ANSI_BG_BLUE);
55
+ var cBgGreen = color(ANSI_BG_GREEN);
56
+ var cInverse = color(ANSI_INVERSE);
57
+ var cUnderline = color(ANSI_UNDERLINE);
58
+ var cBold = color(ANSI_BOLD);
59
+ function safeStringify(value) {
60
+ try {
61
+ return `
62
+ ${typeof value === "string" ? value : JSON.stringify(value, null, 2)}`;
63
+ } catch (e) {
64
+ return String(value);
65
+ }
66
+ }
67
+ function logRawChunk(part) {
68
+ console.log(cGray("[debug:mw:raw]"), cYellow(safeStringify(part)));
69
+ }
70
+ function logParsedChunk(part) {
71
+ console.log(cGray("[debug:mw:out]"), cCyan(safeStringify(part)));
72
+ }
73
+ function getHighlightStyle() {
74
+ const envVal = typeof process !== "undefined" && process.env && process.env.DEBUG_PARSER_MW_STYLE || "bg";
75
+ const normalized = String(envVal).trim().toLowerCase();
76
+ if (normalized === "inverse" || normalized === "invert") {
77
+ return "inverse";
78
+ }
79
+ if (normalized === "underline" || normalized === "ul") {
80
+ return "underline";
81
+ }
82
+ if (normalized === "bold") {
83
+ return "bold";
84
+ }
85
+ if (normalized === "bg" || normalized === "background") {
86
+ return "bg";
87
+ }
88
+ const asBool = normalizeBooleanString(normalized);
89
+ if (asBool === true) {
90
+ return "bg";
91
+ }
92
+ return "bg";
93
+ }
94
+ function getHighlightFunction(style) {
95
+ if (style === "inverse") {
96
+ return cInverse;
97
+ }
98
+ if (style === "underline") {
99
+ return cUnderline;
100
+ }
101
+ if (style === "bold") {
102
+ return cBold;
103
+ }
104
+ if (style === "bg") {
105
+ return cBgGreen;
106
+ }
107
+ return cYellow;
108
+ }
109
+ function renderHighlightedText(originalText, style, highlight) {
110
+ if (style === "bg" || style === "inverse" || style === "underline" || style === "bold") {
111
+ return originalText.split(LINE_SPLIT_REGEX).map((line) => line.length ? highlight(line) : line).join("\n");
112
+ }
113
+ return highlight(originalText);
114
+ }
115
+ function logParsedSummary({
116
+ toolCalls,
117
+ originalText
118
+ }) {
119
+ if (originalText) {
120
+ const style = getHighlightStyle();
121
+ const highlight = getHighlightFunction(style);
122
+ const rendered = renderHighlightedText(originalText, style, highlight);
123
+ console.log(cGray("[debug:mw:origin]"), `
124
+ ${rendered}`);
125
+ }
126
+ if (toolCalls.length > 0) {
127
+ const styledSummary = safeStringify(toolCalls).split(LINE_SPLIT_REGEX).map((line) => line.length ? cBgBlue(line) : line).join("\n");
128
+ console.log(cGray("[debug:mw:summary]"), styledSummary);
129
+ }
130
+ }
131
+
132
+ // src/utils/dynamic-tool-schema.ts
133
+ function createDynamicIfThenElseSchema(tools) {
134
+ let currentSchema = {};
135
+ const toolNames = [];
136
+ for (let i = tools.length - 1; i >= 0; i -= 1) {
137
+ const tool = tools[i];
138
+ if (tool.type === "provider-defined") {
139
+ throw new Error(
140
+ "Provider-defined tools are not supported by this middleware. Please use custom tools."
141
+ );
142
+ }
143
+ toolNames.unshift(tool.name);
144
+ const toolCondition = {
145
+ if: {
146
+ properties: {
147
+ name: {
148
+ const: tool.name
149
+ }
150
+ },
151
+ required: ["name"]
152
+ },
153
+ // biome-ignore lint/suspicious/noThenProperty: JSON Schema uses 'then' as a keyword
154
+ then: {
155
+ properties: {
156
+ name: {
157
+ const: tool.name
158
+ },
159
+ arguments: tool.inputSchema
160
+ },
161
+ required: ["name", "arguments"]
162
+ }
163
+ };
164
+ if (Object.keys(currentSchema).length > 0) {
165
+ toolCondition.else = currentSchema;
166
+ }
167
+ currentSchema = toolCondition;
168
+ }
169
+ return {
170
+ type: "object",
171
+ // Explicitly specify type as "object"
172
+ properties: {
173
+ name: {
174
+ type: "string",
175
+ description: "Name of the tool to call",
176
+ enum: toolNames
177
+ },
178
+ arguments: {
179
+ type: "object",
180
+ // By default, arguments is also specified as object type
181
+ description: "Argument object to be passed to the tool"
182
+ }
183
+ },
184
+ required: ["name", "arguments"],
185
+ ...currentSchema
186
+ };
187
+ }
188
+
189
+ // src/utils/get-potential-start-index.ts
190
+ function getPotentialStartIndex(text, searchedText) {
191
+ if (searchedText.length === 0) {
192
+ return null;
193
+ }
194
+ const directIndex = text.indexOf(searchedText);
195
+ if (directIndex !== -1) {
196
+ return directIndex;
197
+ }
198
+ for (let i = text.length - 1; i >= 0; i -= 1) {
199
+ const suffix = text.substring(i);
200
+ if (searchedText.startsWith(suffix)) {
201
+ return i;
202
+ }
203
+ }
204
+ return null;
205
+ }
206
+
207
+ // src/utils/on-error.ts
208
+ function extractOnErrorOption(providerOptions) {
209
+ var _a;
210
+ if (providerOptions && typeof providerOptions === "object") {
211
+ const onError = (_a = providerOptions.toolCallMiddleware) == null ? void 0 : _a.onError;
212
+ return onError ? { onError } : void 0;
213
+ }
214
+ return;
215
+ }
216
+
217
+ // src/utils/provider-options.ts
218
+ var originalToolsSchema = {
219
+ encode: encodeOriginalTools,
220
+ decode: decodeOriginalTools
221
+ };
222
+ function encodeOriginalTools(tools) {
223
+ return (tools == null ? void 0 : tools.map((t) => ({
224
+ name: t.name,
225
+ inputSchema: JSON.stringify(t.inputSchema)
226
+ }))) || [];
227
+ }
228
+ function decodeOriginalTools(originalTools) {
229
+ if (!originalTools) {
230
+ return [];
231
+ }
232
+ return originalTools.map(
233
+ (t) => ({
234
+ type: "function",
235
+ name: t.name,
236
+ inputSchema: JSON.parse(t.inputSchema)
237
+ })
238
+ );
239
+ }
240
+ function extractToolNamesFromOriginalTools(originalTools) {
241
+ return (originalTools == null ? void 0 : originalTools.map((t) => t.name)) || [];
242
+ }
243
+ function isToolChoiceActive(params) {
244
+ var _a, _b, _c;
245
+ const toolChoice = (_b = (_a = params.providerOptions) == null ? void 0 : _a.toolCallMiddleware) == null ? void 0 : _b.toolChoice;
246
+ return !!(typeof params.providerOptions === "object" && params.providerOptions !== null && typeof ((_c = params.providerOptions) == null ? void 0 : _c.toolCallMiddleware) === "object" && toolChoice && typeof toolChoice === "object" && (toolChoice.type === "tool" || toolChoice.type === "required"));
247
+ }
248
+
249
+ // src/utils/regex.ts
250
+ function escapeRegExp(literal) {
251
+ return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
252
+ }
253
+
254
+ // src/utils/robust-json.ts
255
+ var robust_json_exports = {};
256
+ __export(robust_json_exports, {
257
+ parse: () => parse,
258
+ stringify: () => stringify,
259
+ transform: () => transform
260
+ });
261
+ var WHITESPACE_TEST_REGEX = /\s/;
262
+ var WHITESPACE_REGEX = /^\s+/;
263
+ var OBJECT_START_REGEX = /^\{/;
264
+ var OBJECT_END_REGEX = /^\}/;
265
+ var ARRAY_START_REGEX = /^\[/;
266
+ var ARRAY_END_REGEX = /^\]/;
267
+ var COMMA_REGEX = /^,/;
268
+ var COLON_REGEX = /^:/;
269
+ var KEYWORD_REGEX = /^(?:true|false|null)/;
270
+ var NUMBER_REGEX = /^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/;
271
+ var STRING_DOUBLE_REGEX = /^"(?:[^"\\]|\\["bnrtf\\/]|\\u[0-9a-fA-F]{4})*"/;
272
+ var STRING_SINGLE_REGEX = /^'((?:[^'\\]|\\['bnrtf\\/]|\\u[0-9a-fA-F]{4})*)'/;
273
+ var COMMENT_SINGLE_REGEX = /^\/\/.*?(?:\r\n|\r|\n)/;
274
+ var COMMENT_MULTI_REGEX = /^\/\*[\s\S]*?\*\//;
275
+ var IDENTIFIER_REGEX = /^[$a-zA-Z0-9_\-+.*?!|&%^/#\\]+/;
276
+ function some(array, f) {
277
+ let acc = false;
278
+ for (let i = 0; i < array.length; i += 1) {
279
+ const result = f(array[i], i, array);
280
+ acc = result === void 0 ? false : result;
281
+ if (acc) {
282
+ return acc;
283
+ }
284
+ }
285
+ return acc;
286
+ }
287
+ function makeLexer(tokenSpecs) {
288
+ return (contents) => {
289
+ const tokens = [];
290
+ let line = 1;
291
+ let remainingContents = contents;
292
+ function findToken() {
293
+ const result = some(tokenSpecs, (tokenSpec) => {
294
+ const m = tokenSpec.re.exec(remainingContents);
295
+ if (m) {
296
+ const raw = m[0];
297
+ remainingContents = remainingContents.slice(raw.length);
298
+ return {
299
+ raw,
300
+ matched: tokenSpec.f(m)
301
+ // Process the match using the spec's function
302
+ };
303
+ }
304
+ return;
305
+ });
306
+ return result === false ? void 0 : result;
307
+ }
308
+ while (remainingContents !== "") {
309
+ const matched = findToken();
310
+ if (!matched) {
311
+ const err = new SyntaxError(
312
+ `Unexpected character: ${remainingContents[0]}; input: ${remainingContents.substr(
313
+ 0,
314
+ 100
315
+ )}`
316
+ );
317
+ err.line = line;
318
+ throw err;
319
+ }
320
+ const tokenWithLine = matched.matched;
321
+ tokenWithLine.line = line;
322
+ line += matched.raw.replace(/[^\n]/g, "").length;
323
+ tokens.push(tokenWithLine);
324
+ }
325
+ return tokens;
326
+ };
327
+ }
328
+ function fStringSingle(m) {
329
+ const content = m[1].replace(
330
+ /([^'\\]|\\['bnrtf\\]|\\u[0-9a-fA-F]{4})/g,
331
+ (mm) => {
332
+ if (mm === '"') {
333
+ return '\\"';
334
+ }
335
+ if (mm === "\\'") {
336
+ return "'";
337
+ }
338
+ return mm;
339
+ }
340
+ );
341
+ const match = `"${content}"`;
342
+ return {
343
+ type: "string",
344
+ match,
345
+ // The transformed, double-quoted string representation
346
+ // Use JSON.parse on the transformed string to handle escape sequences correctly
347
+ value: JSON.parse(match)
348
+ };
349
+ }
350
+ function fStringDouble(m) {
351
+ return {
352
+ type: "string",
353
+ match: m[0],
354
+ // The raw matched string (including quotes)
355
+ value: JSON.parse(m[0])
356
+ // Use JSON.parse to handle escapes and get the value
357
+ };
358
+ }
359
+ function fIdentifier(m) {
360
+ const value = m[0];
361
+ const match = '"' + value.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + // Escape backslashes and quotes
362
+ '"';
363
+ return {
364
+ type: "string",
365
+ // Treat identifiers as strings
366
+ value,
367
+ // The original identifier name
368
+ match
369
+ // The double-quoted string representation
370
+ };
371
+ }
372
+ function fComment(m) {
373
+ const match = m[0].replace(
374
+ /./g,
375
+ (c) => WHITESPACE_TEST_REGEX.test(c) ? c : " "
376
+ );
377
+ return {
378
+ type: " ",
379
+ // Represent comments as whitespace tokens
380
+ match,
381
+ // String containing original newlines and spaces for other chars
382
+ value: void 0
383
+ // Comments don't have a semantic value
384
+ };
385
+ }
386
+ function fNumber(m) {
387
+ return {
388
+ type: "number",
389
+ match: m[0],
390
+ // The raw matched number string
391
+ value: Number.parseFloat(m[0])
392
+ // Convert string to number
393
+ };
394
+ }
395
+ function fKeyword(m) {
396
+ let value;
397
+ switch (m[0]) {
398
+ case "null":
399
+ value = null;
400
+ break;
401
+ case "true":
402
+ value = true;
403
+ break;
404
+ case "false":
405
+ value = false;
406
+ break;
407
+ default:
408
+ throw new Error(`Unexpected keyword: ${m[0]}`);
409
+ }
410
+ return {
411
+ type: "atom",
412
+ // Use 'atom' type for these literals
413
+ match: m[0],
414
+ // The raw matched keyword
415
+ value
416
+ // The corresponding JavaScript value
417
+ };
418
+ }
419
+ function makeTokenSpecs(relaxed) {
420
+ function f(type) {
421
+ return (m) => {
422
+ return { type, match: m[0], value: void 0 };
423
+ };
424
+ }
425
+ let tokenSpecs = [
426
+ { re: WHITESPACE_REGEX, f: f(" ") },
427
+ // Whitespace
428
+ { re: OBJECT_START_REGEX, f: f("{") },
429
+ // Object start
430
+ { re: OBJECT_END_REGEX, f: f("}") },
431
+ // Object end
432
+ { re: ARRAY_START_REGEX, f: f("[") },
433
+ // Array start
434
+ { re: ARRAY_END_REGEX, f: f("]") },
435
+ // Array end
436
+ { re: COMMA_REGEX, f: f(",") },
437
+ // Comma separator
438
+ { re: COLON_REGEX, f: f(":") },
439
+ // Key-value separator
440
+ { re: KEYWORD_REGEX, f: fKeyword },
441
+ // Keywords
442
+ // Number: optional sign, digits, optional decimal part, optional exponent
443
+ { re: NUMBER_REGEX, f: fNumber },
444
+ // String: double-quoted, handles escapes
445
+ { re: STRING_DOUBLE_REGEX, f: fStringDouble }
446
+ ];
447
+ if (relaxed) {
448
+ tokenSpecs = tokenSpecs.concat([
449
+ // Single-quoted strings
450
+ {
451
+ re: STRING_SINGLE_REGEX,
452
+ f: fStringSingle
453
+ },
454
+ // Single-line comments (// ...)
455
+ { re: COMMENT_SINGLE_REGEX, f: fComment },
456
+ // Multi-line comments (/* ... */)
457
+ { re: COMMENT_MULTI_REGEX, f: fComment },
458
+ // Unquoted identifiers (treated as strings)
459
+ // Allows letters, numbers, _, -, +, ., *, ?, !, |, &, %, ^, /, #, \
460
+ { re: IDENTIFIER_REGEX, f: fIdentifier }
461
+ // Note: The order matters here. Identifiers are checked after keywords/numbers.
462
+ ]);
463
+ }
464
+ return tokenSpecs;
465
+ }
466
+ var lexer = makeLexer(makeTokenSpecs(true));
467
+ var strictLexer = makeLexer(makeTokenSpecs(false));
468
+ function previousNWSToken(tokens, index) {
469
+ let currentIndex = index;
470
+ for (; currentIndex >= 0; currentIndex -= 1) {
471
+ if (tokens[currentIndex].type !== " ") {
472
+ return currentIndex;
473
+ }
474
+ }
475
+ return;
476
+ }
477
+ function stripTrailingComma(tokens) {
478
+ const res = [];
479
+ tokens.forEach((token, index) => {
480
+ if (index > 0 && (token.type === "]" || token.type === "}")) {
481
+ const prevNWSTokenIndex = previousNWSToken(res, res.length - 1);
482
+ if (prevNWSTokenIndex !== void 0 && res[prevNWSTokenIndex].type === ",") {
483
+ const preCommaIndex = previousNWSToken(res, prevNWSTokenIndex - 1);
484
+ if (preCommaIndex !== void 0 && res[preCommaIndex].type !== "[" && res[preCommaIndex].type !== "{") {
485
+ res[prevNWSTokenIndex] = {
486
+ type: " ",
487
+ match: " ",
488
+ // Represent as a single space
489
+ value: void 0,
490
+ // Whitespace has no value
491
+ line: res[prevNWSTokenIndex].line
492
+ // Preserve original line number
493
+ };
494
+ }
495
+ }
496
+ }
497
+ res.push(token);
498
+ });
499
+ return res;
500
+ }
501
+ function transform(text) {
502
+ let tokens = lexer(text);
503
+ tokens = stripTrailingComma(tokens);
504
+ return tokens.reduce((str, token) => str + token.match, "");
505
+ }
506
+ function popToken(tokens, state) {
507
+ var _a, _b;
508
+ const token = tokens[state.pos];
509
+ state.pos += 1;
510
+ if (!token) {
511
+ const lastLine = tokens.length !== 0 ? (_b = (_a = tokens.at(-1)) == null ? void 0 : _a.line) != null ? _b : 1 : 1;
512
+ return { type: "eof", match: "", value: void 0, line: lastLine };
513
+ }
514
+ return token;
515
+ }
516
+ function strToken(token) {
517
+ switch (token.type) {
518
+ case "atom":
519
+ case "string":
520
+ case "number":
521
+ return `${token.type} ${token.match}`;
522
+ case "eof":
523
+ return "end-of-file";
524
+ default:
525
+ return `'${token.type}'`;
526
+ }
527
+ }
528
+ function skipColon(tokens, state) {
529
+ const colon = popToken(tokens, state);
530
+ if (colon.type !== ":") {
531
+ const message = `Unexpected token: ${strToken(colon)}, expected ':'`;
532
+ if (state.tolerant) {
533
+ state.warnings.push({
534
+ message,
535
+ line: colon.line
536
+ });
537
+ state.pos -= 1;
538
+ } else {
539
+ const err = new SyntaxError(message);
540
+ err.line = colon.line;
541
+ throw err;
542
+ }
543
+ }
544
+ }
545
+ function skipPunctuation(tokens, state, valid) {
546
+ const punctuation = [",", ":", "]", "}"];
547
+ let token = popToken(tokens, state);
548
+ while (true) {
549
+ if (valid == null ? void 0 : valid.includes(token.type)) {
550
+ return token;
551
+ }
552
+ if (token.type === "eof") {
553
+ return token;
554
+ }
555
+ if (punctuation.includes(token.type)) {
556
+ const message = `Unexpected token: ${strToken(
557
+ token
558
+ )}, expected '[', '{', number, string or atom`;
559
+ if (state.tolerant) {
560
+ state.warnings.push({
561
+ message,
562
+ line: token.line
563
+ });
564
+ token = popToken(tokens, state);
565
+ } else {
566
+ const err = new SyntaxError(message);
567
+ err.line = token.line;
568
+ throw err;
569
+ }
570
+ } else {
571
+ return token;
572
+ }
573
+ }
574
+ }
575
+ function raiseError(state, token, message) {
576
+ if (state.tolerant) {
577
+ state.warnings.push({
578
+ message,
579
+ line: token.line
580
+ });
581
+ } else {
582
+ const err = new SyntaxError(message);
583
+ err.line = token.line;
584
+ throw err;
585
+ }
586
+ }
587
+ function raiseUnexpected(state, token, expected) {
588
+ raiseError(
589
+ state,
590
+ token,
591
+ `Unexpected token: ${strToken(token)}, expected ${expected}`
592
+ );
593
+ }
594
+ function checkDuplicates(state, obj, token) {
595
+ const key = String(token.value);
596
+ if (!state.duplicate && Object.hasOwn(obj, key)) {
597
+ raiseError(state, token, `Duplicate key: ${key}`);
598
+ }
599
+ }
600
+ function appendPair(state, obj, key, value) {
601
+ const finalValue = state.reviver ? state.reviver(key, value) : value;
602
+ if (finalValue !== void 0) {
603
+ obj[key] = finalValue;
604
+ }
605
+ }
606
+ function parsePair(tokens, state, obj) {
607
+ let token = skipPunctuation(tokens, state, [":", "string", "number", "atom"]);
608
+ let value;
609
+ if (token.type !== "string") {
610
+ raiseUnexpected(state, token, "string key");
611
+ if (state.tolerant) {
612
+ switch (token.type) {
613
+ case ":":
614
+ token = {
615
+ type: "string",
616
+ value: "null",
617
+ match: '"null"',
618
+ line: token.line
619
+ };
620
+ state.pos -= 1;
621
+ break;
622
+ case "number":
623
+ // Use number as string key
624
+ case "atom":
625
+ token = {
626
+ type: "string",
627
+ value: String(token.value),
628
+ match: `"${token.value}"`,
629
+ line: token.line
630
+ };
631
+ break;
632
+ case "[":
633
+ // Assume missing key before an array
634
+ case "{":
635
+ state.pos -= 1;
636
+ value = parseAny(tokens, state);
637
+ checkDuplicates(state, obj, {
638
+ type: "string",
639
+ value: "null",
640
+ match: '"null"',
641
+ line: token.line
642
+ });
643
+ appendPair(state, obj, "null", value);
644
+ return;
645
+ // Finished parsing this "pair"
646
+ case "eof":
647
+ return;
648
+ // Cannot recover
649
+ default:
650
+ return;
651
+ }
652
+ } else {
653
+ return;
654
+ }
655
+ }
656
+ checkDuplicates(state, obj, token);
657
+ const key = String(token.value);
658
+ skipColon(tokens, state);
659
+ value = parseAny(tokens, state);
660
+ appendPair(state, obj, key, value);
661
+ }
662
+ function parseElement(tokens, state, arr) {
663
+ const key = arr.length;
664
+ const value = parseAny(tokens, state);
665
+ arr[key] = state.reviver ? state.reviver(String(key), value) : value;
666
+ }
667
+ function parseObject(tokens, state) {
668
+ const obj = {};
669
+ return parseMany(tokens, state, obj, {
670
+ skip: [":", "}"],
671
+ // Initially skip over colon or closing brace (for empty/tolerant cases)
672
+ elementParser: parsePair,
673
+ // Use parsePair to parse each key-value element
674
+ elementName: "string key",
675
+ // Expected element type for errors
676
+ endSymbol: "}"
677
+ // The closing token for an object
678
+ });
679
+ }
680
+ function parseArray(tokens, state) {
681
+ const arr = [];
682
+ return parseMany(tokens, state, arr, {
683
+ skip: ["]"],
684
+ // Initially skip over closing bracket (for empty/tolerant cases)
685
+ elementParser: parseElement,
686
+ // Use parseElement to parse each array item
687
+ elementName: "json value",
688
+ // Expected element type for errors
689
+ endSymbol: "]"
690
+ // The closing token for an array
691
+ });
692
+ }
693
+ function handleInvalidToken(token, state, opts, result) {
694
+ raiseUnexpected(state, token, `',' or '${opts.endSymbol}'`);
695
+ if (state.tolerant) {
696
+ if (token.type === "eof") {
697
+ return result;
698
+ }
699
+ state.pos -= 1;
700
+ return null;
701
+ }
702
+ return result;
703
+ }
704
+ function handleCommaToken(params) {
705
+ const { token, tokens, state, opts, result } = params;
706
+ const nextToken = tokens[state.pos];
707
+ if (state.tolerant && nextToken && nextToken.type === opts.endSymbol) {
708
+ raiseError(state, token, `Trailing comma before '${opts.endSymbol}'`);
709
+ popToken(tokens, state);
710
+ return result;
711
+ }
712
+ opts.elementParser(tokens, state, result);
713
+ return null;
714
+ }
715
+ function parseManyInitialElement(tokens, state, result, opts) {
716
+ const token = skipPunctuation(tokens, state, opts.skip);
717
+ if (token.type === "eof") {
718
+ raiseUnexpected(state, token, `'${opts.endSymbol}' or ${opts.elementName}`);
719
+ return result;
720
+ }
721
+ if (token.type === opts.endSymbol) {
722
+ return result;
723
+ }
724
+ state.pos -= 1;
725
+ opts.elementParser(tokens, state, result);
726
+ return;
727
+ }
728
+ function parseManyProcessToken(params) {
729
+ const { token, tokens, state, opts, result } = params;
730
+ if (token.type !== opts.endSymbol && token.type !== ",") {
731
+ const handledResult = handleInvalidToken(token, state, opts, result);
732
+ if (handledResult !== null) {
733
+ return handledResult;
734
+ }
735
+ }
736
+ if (token.type === opts.endSymbol) {
737
+ return result;
738
+ }
739
+ if (token.type === ",") {
740
+ const handledResult = handleCommaToken({
741
+ token,
742
+ tokens,
743
+ state,
744
+ opts,
745
+ result
746
+ });
747
+ if (handledResult !== null) {
748
+ return handledResult;
749
+ }
750
+ return;
751
+ }
752
+ opts.elementParser(tokens, state, result);
753
+ return;
754
+ }
755
+ function parseMany(tokens, state, result, opts) {
756
+ const initialResult = parseManyInitialElement(tokens, state, result, opts);
757
+ if (initialResult !== void 0) {
758
+ return initialResult;
759
+ }
760
+ while (true) {
761
+ const token = popToken(tokens, state);
762
+ const processedResult = parseManyProcessToken({
763
+ token,
764
+ tokens,
765
+ state,
766
+ opts,
767
+ result
768
+ });
769
+ if (processedResult !== void 0) {
770
+ return processedResult;
771
+ }
772
+ }
773
+ }
774
+ function endChecks(tokens, state, ret) {
775
+ if (state.pos < tokens.length) {
776
+ if (state.tolerant) {
777
+ skipPunctuation(tokens, state);
778
+ }
779
+ if (state.pos < tokens.length) {
780
+ raiseError(
781
+ state,
782
+ tokens[state.pos],
783
+ `Unexpected token: ${strToken(tokens[state.pos])}, expected end-of-input`
784
+ );
785
+ }
786
+ }
787
+ if (state.tolerant && state.warnings.length > 0) {
788
+ const message = state.warnings.length === 1 ? state.warnings[0].message : `${state.warnings.length} parse warnings`;
789
+ const err = new SyntaxError(message);
790
+ err.line = state.warnings[0].line;
791
+ err.warnings = state.warnings;
792
+ err.obj = ret;
793
+ throw err;
794
+ }
795
+ }
796
+ function parseAny(tokens, state, end = false) {
797
+ const token = skipPunctuation(tokens, state);
798
+ let ret;
799
+ if (token.type === "eof") {
800
+ if (end) {
801
+ raiseUnexpected(state, token, "json value");
802
+ }
803
+ raiseUnexpected(state, token, "json value");
804
+ return;
805
+ }
806
+ switch (token.type) {
807
+ case "{":
808
+ ret = parseObject(tokens, state);
809
+ break;
810
+ case "[":
811
+ ret = parseArray(tokens, state);
812
+ break;
813
+ case "string":
814
+ // String literal
815
+ case "number":
816
+ // Number literal
817
+ case "atom":
818
+ ret = token.value;
819
+ break;
820
+ default:
821
+ raiseUnexpected(state, token, "json value");
822
+ if (state.tolerant) {
823
+ ret = null;
824
+ } else {
825
+ return;
826
+ }
827
+ }
828
+ if (end) {
829
+ ret = state.reviver ? state.reviver("", ret) : ret;
830
+ endChecks(tokens, state, ret);
831
+ }
832
+ return ret;
833
+ }
834
+ function normalizeParseOptions(optsOrReviver) {
835
+ var _a;
836
+ let options = {};
837
+ if (typeof optsOrReviver === "function") {
838
+ options.reviver = optsOrReviver;
839
+ } else if (optsOrReviver !== null && typeof optsOrReviver === "object") {
840
+ options = { ...optsOrReviver };
841
+ } else if (optsOrReviver !== void 0) {
842
+ throw new TypeError(
843
+ "Second argument must be a reviver function or an options object."
844
+ );
845
+ }
846
+ if (options.relaxed === void 0) {
847
+ if (options.warnings === true || options.tolerant === true) {
848
+ options.relaxed = true;
849
+ } else if (options.warnings === false && options.tolerant === false) {
850
+ options.relaxed = false;
851
+ } else {
852
+ options.relaxed = true;
853
+ }
854
+ }
855
+ options.tolerant = options.tolerant || options.warnings;
856
+ options.duplicate = (_a = options.duplicate) != null ? _a : false;
857
+ return options;
858
+ }
859
+ function createParseState(options) {
860
+ var _a, _b;
861
+ return {
862
+ pos: 0,
863
+ reviver: options.reviver,
864
+ tolerant: (_a = options.tolerant) != null ? _a : false,
865
+ duplicate: (_b = options.duplicate) != null ? _b : false,
866
+ warnings: []
867
+ };
868
+ }
869
+ function parseWithCustomParser(text, options) {
870
+ const lexerToUse = options.relaxed ? lexer : strictLexer;
871
+ let tokens = lexerToUse(text);
872
+ if (options.relaxed) {
873
+ tokens = stripTrailingComma(tokens);
874
+ }
875
+ tokens = tokens.filter((token) => token.type !== " ");
876
+ const state = createParseState(options);
877
+ return parseAny(tokens, state, true);
878
+ }
879
+ function parseWithTransform(text, options) {
880
+ let tokens = lexer(text);
881
+ tokens = stripTrailingComma(tokens);
882
+ const newtext = tokens.reduce((str, token) => str + token.match, "");
883
+ return JSON.parse(
884
+ newtext,
885
+ options.reviver
886
+ );
887
+ }
888
+ function parse(text, optsOrReviver) {
889
+ const options = normalizeParseOptions(optsOrReviver);
890
+ if (!(options.relaxed || options.warnings || options.tolerant) && options.duplicate) {
891
+ return JSON.parse(
892
+ text,
893
+ options.reviver
894
+ );
895
+ }
896
+ if (options.warnings || options.tolerant || !options.duplicate) {
897
+ return parseWithCustomParser(text, options);
898
+ }
899
+ return parseWithTransform(text, options);
900
+ }
901
+ function stringifyPair(obj, key) {
902
+ return `${JSON.stringify(key)}:${stringify(obj[key])}`;
903
+ }
904
+ function stringify(obj) {
905
+ const type = typeof obj;
906
+ if (type === "string" || type === "number" || type === "boolean" || obj === null) {
907
+ return JSON.stringify(obj);
908
+ }
909
+ if (type === "undefined") {
910
+ return "null";
911
+ }
912
+ if (Array.isArray(obj)) {
913
+ const elements = obj.map(stringify).join(",");
914
+ return `[${elements}]`;
915
+ }
916
+ if (type === "object") {
917
+ const keys = Object.keys(obj);
918
+ keys.sort();
919
+ const pairs = keys.map((key) => stringifyPair(obj, key)).join(",");
920
+ return `{${pairs}}`;
921
+ }
922
+ return "null";
923
+ }
924
+
925
+ // src/utils/type-guards.ts
926
+ function isToolCallContent(content) {
927
+ return content.type === "tool-call" && typeof content.toolName === "string" && // input may be a JSON string or an already-parsed object depending on provider/runtime
928
+ (typeof content.input === "string" || typeof content.input === "object");
929
+ }
930
+ function isToolResultPart(content) {
931
+ const c = content;
932
+ return !!c && c.type === "tool-result" && typeof c.toolName === "string" && typeof c.toolCallId === "string" && "output" in c;
933
+ }
934
+ function hasInputProperty(obj) {
935
+ return typeof obj === "object" && obj !== null && "input" in obj;
936
+ }
937
+
938
+ // src/protocols/json-mix-protocol.ts
939
+ function processToolCallJson(toolCallJson, fullMatch, processedElements, options) {
940
+ var _a;
941
+ try {
942
+ const parsedToolCall = parse(toolCallJson);
943
+ processedElements.push({
944
+ type: "tool-call",
945
+ toolCallId: generateId2(),
946
+ toolName: parsedToolCall.name,
947
+ input: JSON.stringify((_a = parsedToolCall.arguments) != null ? _a : {})
948
+ });
949
+ } catch (error) {
950
+ if (options == null ? void 0 : options.onError) {
951
+ options.onError(
952
+ "Could not process JSON tool call, keeping original text.",
953
+ { toolCall: fullMatch, error }
954
+ );
955
+ }
956
+ processedElements.push({ type: "text", text: fullMatch });
957
+ }
958
+ }
959
+ function addTextSegment(text, processedElements) {
960
+ if (text.trim()) {
961
+ processedElements.push({ type: "text", text });
962
+ }
963
+ }
964
+ function processMatchedToolCall(context) {
965
+ const { match, text, currentIndex, processedElements, options } = context;
966
+ const startIndex = match.index;
967
+ const toolCallJson = match[1];
968
+ if (startIndex > currentIndex) {
969
+ const textSegment = text.substring(currentIndex, startIndex);
970
+ addTextSegment(textSegment, processedElements);
971
+ }
972
+ if (toolCallJson) {
973
+ processToolCallJson(toolCallJson, match[0], processedElements, options);
974
+ }
975
+ return startIndex + match[0].length;
976
+ }
977
+ function flushBuffer(state, controller, toolCallStart) {
978
+ if (state.buffer.length === 0) {
979
+ return;
980
+ }
981
+ if (!state.currentTextId) {
982
+ state.currentTextId = generateId2();
983
+ controller.enqueue({ type: "text-start", id: state.currentTextId });
984
+ state.hasEmittedTextStart = true;
985
+ }
986
+ const delta = state.isInsideToolCall ? `${toolCallStart}${state.buffer}` : state.buffer;
987
+ controller.enqueue({
988
+ type: "text-delta",
989
+ id: state.currentTextId,
990
+ delta
991
+ });
992
+ state.buffer = "";
993
+ }
994
+ function closeTextBlock(state, controller) {
995
+ if (state.currentTextId && state.hasEmittedTextStart) {
996
+ controller.enqueue({ type: "text-end", id: state.currentTextId });
997
+ state.currentTextId = null;
998
+ state.hasEmittedTextStart = false;
999
+ }
1000
+ }
1001
+ function emitIncompleteToolCall(state, controller, toolCallStart) {
1002
+ if (!state.currentToolCallJson) {
1003
+ return;
1004
+ }
1005
+ const errorId = generateId2();
1006
+ controller.enqueue({ type: "text-start", id: errorId });
1007
+ controller.enqueue({
1008
+ type: "text-delta",
1009
+ id: errorId,
1010
+ delta: `${toolCallStart}${state.currentToolCallJson}`
1011
+ });
1012
+ controller.enqueue({ type: "text-end", id: errorId });
1013
+ state.currentToolCallJson = "";
1014
+ }
1015
+ function handleFinishChunk(state, controller, toolCallStart, chunk) {
1016
+ if (state.buffer.length > 0) {
1017
+ flushBuffer(state, controller, toolCallStart);
1018
+ }
1019
+ closeTextBlock(state, controller);
1020
+ emitIncompleteToolCall(state, controller, toolCallStart);
1021
+ controller.enqueue(chunk);
1022
+ }
1023
+ function publishText(text, state, controller) {
1024
+ if (state.isInsideToolCall) {
1025
+ closeTextBlock(state, controller);
1026
+ state.currentToolCallJson += text;
1027
+ } else if (text.length > 0) {
1028
+ if (!state.currentTextId) {
1029
+ state.currentTextId = generateId2();
1030
+ controller.enqueue({ type: "text-start", id: state.currentTextId });
1031
+ state.hasEmittedTextStart = true;
1032
+ }
1033
+ controller.enqueue({
1034
+ type: "text-delta",
1035
+ id: state.currentTextId,
1036
+ delta: text
1037
+ });
1038
+ }
1039
+ }
1040
+ function emitToolCall(context) {
1041
+ var _a;
1042
+ const { state, controller, toolCallStart, toolCallEnd, options } = context;
1043
+ try {
1044
+ const parsedToolCall = robust_json_exports.parse(state.currentToolCallJson);
1045
+ closeTextBlock(state, controller);
1046
+ controller.enqueue({
1047
+ type: "tool-call",
1048
+ toolCallId: generateId2(),
1049
+ toolName: parsedToolCall.name,
1050
+ input: JSON.stringify((_a = parsedToolCall.arguments) != null ? _a : {})
1051
+ });
1052
+ } catch (e) {
1053
+ const errorId = generateId2();
1054
+ controller.enqueue({ type: "text-start", id: errorId });
1055
+ controller.enqueue({
1056
+ type: "text-delta",
1057
+ id: errorId,
1058
+ delta: `${toolCallStart}${state.currentToolCallJson}${toolCallEnd}`
1059
+ });
1060
+ controller.enqueue({ type: "text-end", id: errorId });
1061
+ if (options == null ? void 0 : options.onError) {
1062
+ options.onError(
1063
+ "Could not process streaming JSON tool call; emitting original text.",
1064
+ {
1065
+ toolCall: `${toolCallStart}${state.currentToolCallJson}${toolCallEnd}`
1066
+ }
1067
+ );
1068
+ }
1069
+ }
1070
+ }
1071
+ function processTagMatch(context) {
1072
+ const { state } = context;
1073
+ if (state.isInsideToolCall) {
1074
+ emitToolCall(context);
1075
+ state.currentToolCallJson = "";
1076
+ state.isInsideToolCall = false;
1077
+ } else {
1078
+ state.currentToolCallJson = "";
1079
+ state.isInsideToolCall = true;
1080
+ }
1081
+ }
1082
+ function processBufferTags(context) {
1083
+ const { state, controller, toolCallStart, toolCallEnd } = context;
1084
+ let startIndex = getPotentialStartIndex(
1085
+ state.buffer,
1086
+ state.isInsideToolCall ? toolCallEnd : toolCallStart
1087
+ );
1088
+ while (startIndex != null) {
1089
+ const tag = state.isInsideToolCall ? toolCallEnd : toolCallStart;
1090
+ if (startIndex + tag.length > state.buffer.length) {
1091
+ break;
1092
+ }
1093
+ publishText(state.buffer.slice(0, startIndex), state, controller);
1094
+ state.buffer = state.buffer.slice(startIndex + tag.length);
1095
+ processTagMatch(context);
1096
+ startIndex = getPotentialStartIndex(
1097
+ state.buffer,
1098
+ state.isInsideToolCall ? toolCallEnd : toolCallStart
1099
+ );
1100
+ }
1101
+ }
1102
+ function handlePartialTag(state, controller, toolCallStart) {
1103
+ if (state.isInsideToolCall) {
1104
+ return;
1105
+ }
1106
+ const potentialIndex = getPotentialStartIndex(state.buffer, toolCallStart);
1107
+ if (potentialIndex != null && potentialIndex + toolCallStart.length > state.buffer.length) {
1108
+ publishText(state.buffer.slice(0, potentialIndex), state, controller);
1109
+ state.buffer = state.buffer.slice(potentialIndex);
1110
+ } else {
1111
+ publishText(state.buffer, state, controller);
1112
+ state.buffer = "";
1113
+ }
1114
+ }
1115
+ var jsonMixProtocol = ({
1116
+ toolCallStart = "<tool_call>",
1117
+ toolCallEnd = "</tool_call>",
1118
+ toolResponseStart = "<tool_response>",
1119
+ toolResponseEnd = "</tool_response>"
1120
+ } = {}) => ({
1121
+ formatTools({ tools, toolSystemPromptTemplate }) {
1122
+ const toolsForPrompt = (tools || []).filter((tool) => tool.type === "function").map((tool) => ({
1123
+ name: tool.name,
1124
+ description: tool.type === "function" && typeof tool.description === "string" ? tool.description : void 0,
1125
+ parameters: tool.inputSchema
1126
+ }));
1127
+ return toolSystemPromptTemplate(JSON.stringify(toolsForPrompt));
1128
+ },
1129
+ formatToolCall(toolCall) {
1130
+ let args = {};
1131
+ try {
1132
+ args = JSON.parse(toolCall.input);
1133
+ } catch (e) {
1134
+ args = toolCall.input;
1135
+ }
1136
+ return `${toolCallStart}${JSON.stringify({
1137
+ name: toolCall.toolName,
1138
+ arguments: args
1139
+ })}${toolCallEnd}`;
1140
+ },
1141
+ formatToolResponse(toolResult) {
1142
+ return `${toolResponseStart}${JSON.stringify({
1143
+ toolName: toolResult.toolName,
1144
+ result: toolResult.output
1145
+ })}${toolResponseEnd}`;
1146
+ },
1147
+ parseGeneratedText({ text, options }) {
1148
+ const startEsc = escapeRegExp(toolCallStart);
1149
+ const endEsc = escapeRegExp(toolCallEnd);
1150
+ const toolCallRegex = new RegExp(
1151
+ `${startEsc}([\0-\uFFFF]*?)${endEsc}`,
1152
+ "gs"
1153
+ );
1154
+ const processedElements = [];
1155
+ let currentIndex = 0;
1156
+ let match = toolCallRegex.exec(text);
1157
+ while (match !== null) {
1158
+ currentIndex = processMatchedToolCall({
1159
+ match,
1160
+ text,
1161
+ currentIndex,
1162
+ processedElements,
1163
+ options
1164
+ });
1165
+ match = toolCallRegex.exec(text);
1166
+ }
1167
+ if (currentIndex < text.length) {
1168
+ const remainingText = text.substring(currentIndex);
1169
+ addTextSegment(remainingText, processedElements);
1170
+ }
1171
+ return processedElements;
1172
+ },
1173
+ createStreamParser({ tools: _tools, options } = { tools: [] }) {
1174
+ const state = {
1175
+ isInsideToolCall: false,
1176
+ buffer: "",
1177
+ currentToolCallJson: "",
1178
+ currentTextId: null,
1179
+ hasEmittedTextStart: false
1180
+ };
1181
+ return new TransformStream({
1182
+ transform(chunk, controller) {
1183
+ if (chunk.type === "finish") {
1184
+ handleFinishChunk(state, controller, toolCallStart, chunk);
1185
+ return;
1186
+ }
1187
+ if (chunk.type !== "text-delta") {
1188
+ controller.enqueue(chunk);
1189
+ return;
1190
+ }
1191
+ state.buffer += chunk.delta;
1192
+ processBufferTags({
1193
+ state,
1194
+ controller,
1195
+ toolCallStart,
1196
+ toolCallEnd,
1197
+ options
1198
+ });
1199
+ handlePartialTag(state, controller, toolCallStart);
1200
+ }
1201
+ });
1202
+ },
1203
+ extractToolCallSegments({ text }) {
1204
+ const startEsc = escapeRegExp(toolCallStart);
1205
+ const endEsc = escapeRegExp(toolCallEnd);
1206
+ const regex = new RegExp(`${startEsc}([\0-\uFFFF]*?)${endEsc}`, "gs");
1207
+ const segments = [];
1208
+ let m = regex.exec(text);
1209
+ while (m != null) {
1210
+ segments.push(m[0]);
1211
+ m = regex.exec(text);
1212
+ }
1213
+ return segments;
1214
+ }
1215
+ });
1216
+
1217
+ // src/protocols/morph-xml-protocol.ts
1218
+ import { generateId as generateId3 } from "@ai-sdk/provider-utils";
1219
+ import {
1220
+ extractRawInner,
1221
+ findFirstTopLevelRange,
1222
+ parse as parse2,
1223
+ RXMLCoercionError,
1224
+ RXMLDuplicateStringTagError,
1225
+ RXMLParseError,
1226
+ stringify as stringify2,
1227
+ unwrapJsonSchema
1228
+ } from "@ai-sdk-tool/rxml";
1229
+ var WHITESPACE_REGEX2 = /\s/;
1230
+ function processTextBeforeToolCall(text, currentIndex, toolCallStartIndex, processedElements) {
1231
+ if (toolCallStartIndex > currentIndex) {
1232
+ const textSegment = text.substring(currentIndex, toolCallStartIndex);
1233
+ if (textSegment.trim()) {
1234
+ processedElements.push({ type: "text", text: textSegment });
1235
+ }
1236
+ }
1237
+ return currentIndex;
1238
+ }
1239
+ function processToolCall(params) {
1240
+ var _a;
1241
+ const { toolCall, tools, options, text, processedElements } = params;
1242
+ try {
1243
+ const toolSchema = getToolSchema(tools, toolCall.toolName);
1244
+ const parsed = parse2(toolCall.content, toolSchema, {
1245
+ onError: options == null ? void 0 : options.onError,
1246
+ // Disable HTML self-closing tag behavior to allow base, meta, link etc. as regular tags
1247
+ noChildNodes: []
1248
+ });
1249
+ processedElements.push({
1250
+ type: "tool-call",
1251
+ toolCallId: generateId3(),
1252
+ toolName: toolCall.toolName,
1253
+ input: JSON.stringify(parsed)
1254
+ });
1255
+ } catch (error) {
1256
+ const originalCallText = text.substring(
1257
+ toolCall.startIndex,
1258
+ toolCall.endIndex
1259
+ );
1260
+ const message = `Could not process XML tool call, keeping original text: ${originalCallText}`;
1261
+ (_a = options == null ? void 0 : options.onError) == null ? void 0 : _a.call(options, message, {
1262
+ toolCall: originalCallText,
1263
+ toolName: toolCall.toolName,
1264
+ error
1265
+ });
1266
+ processedElements.push({ type: "text", text: originalCallText });
1267
+ }
1268
+ }
1269
+ function addRemainingText(text, currentIndex, processedElements) {
1270
+ if (currentIndex < text.length) {
1271
+ const remainingText = text.substring(currentIndex);
1272
+ if (remainingText.trim()) {
1273
+ processedElements.push({ type: "text", text: remainingText });
1274
+ }
1275
+ }
1276
+ }
1277
+ function handleStreamingToolCallEnd(params) {
1278
+ const { toolContent, currentToolCall, tools, options, ctrl, flushText } = params;
1279
+ try {
1280
+ const toolSchema = getToolSchema(tools, currentToolCall.name);
1281
+ const parsed = parse2(toolContent, toolSchema, {
1282
+ onError: options == null ? void 0 : options.onError,
1283
+ noChildNodes: []
1284
+ });
1285
+ flushText(ctrl);
1286
+ ctrl.enqueue({
1287
+ type: "tool-call",
1288
+ toolCallId: generateId3(),
1289
+ toolName: currentToolCall.name,
1290
+ input: JSON.stringify(parsed)
1291
+ });
1292
+ } catch (error) {
1293
+ handleStreamingToolCallError({
1294
+ error,
1295
+ currentToolCall,
1296
+ toolContent,
1297
+ options,
1298
+ ctrl,
1299
+ flushText
1300
+ });
1301
+ }
1302
+ }
1303
+ function handleStreamingToolCallError(params) {
1304
+ var _a;
1305
+ const { error, currentToolCall, toolContent, options, ctrl, flushText } = params;
1306
+ const endTag = `</${currentToolCall.name}>`;
1307
+ const originalCallText = `<${currentToolCall.name}>${toolContent}${endTag}`;
1308
+ let message = "Could not process streaming XML tool call; emitting original text.";
1309
+ if (error instanceof RXMLDuplicateStringTagError) {
1310
+ message = `Duplicate string tags detected in streaming tool call '${currentToolCall.name}'; emitting original text.`;
1311
+ } else if (error instanceof RXMLCoercionError) {
1312
+ message = `Failed to coerce arguments for streaming tool call '${currentToolCall.name}'; emitting original text.`;
1313
+ } else if (error instanceof RXMLParseError) {
1314
+ message = `Failed to parse XML for streaming tool call '${currentToolCall.name}'; emitting original text.`;
1315
+ }
1316
+ (_a = options == null ? void 0 : options.onError) == null ? void 0 : _a.call(options, message, {
1317
+ toolCall: originalCallText,
1318
+ toolName: currentToolCall.name,
1319
+ error
1320
+ });
1321
+ flushText(ctrl, originalCallText);
1322
+ }
1323
+ function findEarliestToolTag(buffer, toolNames) {
1324
+ let earliestStartTagIndex = -1;
1325
+ let earliestToolName = "";
1326
+ if (toolNames.length > 0) {
1327
+ for (const name of toolNames) {
1328
+ const startTag = `<${name}>`;
1329
+ const index = buffer.indexOf(startTag);
1330
+ if (index !== -1 && (earliestStartTagIndex === -1 || index < earliestStartTagIndex)) {
1331
+ earliestStartTagIndex = index;
1332
+ earliestToolName = name;
1333
+ }
1334
+ }
1335
+ }
1336
+ return { index: earliestStartTagIndex, name: earliestToolName };
1337
+ }
1338
+ function handleNoToolTagInBuffer(buffer, maxStartTagLen, controller, flushText) {
1339
+ const tail = Math.max(0, maxStartTagLen - 1);
1340
+ const safeLen = Math.max(0, buffer.length - tail);
1341
+ if (safeLen > 0) {
1342
+ const textToFlush = buffer.slice(0, safeLen);
1343
+ flushText(controller, textToFlush);
1344
+ return { buffer: buffer.slice(safeLen), shouldContinue: true };
1345
+ }
1346
+ return { buffer, shouldContinue: false };
1347
+ }
1348
+ function processToolCallInBuffer(params) {
1349
+ const {
1350
+ buffer,
1351
+ currentToolCall,
1352
+ tools,
1353
+ options,
1354
+ controller,
1355
+ flushText,
1356
+ setBuffer
1357
+ } = params;
1358
+ const endTag = `</${currentToolCall.name}>`;
1359
+ const endTagIndex = buffer.indexOf(endTag);
1360
+ if (endTagIndex !== -1) {
1361
+ const toolContent = buffer.substring(0, endTagIndex);
1362
+ const newBuffer = buffer.substring(endTagIndex + endTag.length);
1363
+ setBuffer("");
1364
+ handleStreamingToolCallEnd({
1365
+ toolContent,
1366
+ currentToolCall,
1367
+ tools,
1368
+ options,
1369
+ ctrl: controller,
1370
+ flushText
1371
+ });
1372
+ setBuffer(newBuffer);
1373
+ return { buffer: newBuffer, currentToolCall: null, shouldBreak: false };
1374
+ }
1375
+ return { buffer, currentToolCall, shouldBreak: true };
1376
+ }
1377
+ function processNoToolCallInBuffer(params) {
1378
+ const { buffer, toolNames, maxStartTagLen, controller, flushText } = params;
1379
+ const { index: earliestStartTagIndex, name: earliestToolName } = findEarliestToolTag(buffer, toolNames);
1380
+ if (earliestStartTagIndex !== -1) {
1381
+ const textBeforeTag = buffer.substring(0, earliestStartTagIndex);
1382
+ flushText(controller, textBeforeTag);
1383
+ const startTag = `<${earliestToolName}>`;
1384
+ const newBuffer = buffer.substring(earliestStartTagIndex + startTag.length);
1385
+ return {
1386
+ buffer: newBuffer,
1387
+ currentToolCall: { name: earliestToolName, content: "" },
1388
+ shouldBreak: false,
1389
+ shouldContinue: false
1390
+ };
1391
+ }
1392
+ const result = handleNoToolTagInBuffer(
1393
+ buffer,
1394
+ maxStartTagLen,
1395
+ controller,
1396
+ flushText
1397
+ );
1398
+ return {
1399
+ buffer: result.buffer,
1400
+ currentToolCall: null,
1401
+ shouldBreak: !result.shouldContinue,
1402
+ shouldContinue: result.shouldContinue
1403
+ };
1404
+ }
1405
+ function createFlushTextHandler(getBuffer, setBuffer, getCurrentTextId, setCurrentTextId) {
1406
+ return (controller, text) => {
1407
+ const content = text != null ? text : getBuffer();
1408
+ if (content) {
1409
+ const currentTextId2 = getCurrentTextId();
1410
+ if (!currentTextId2) {
1411
+ const newId = generateId3();
1412
+ setCurrentTextId(newId);
1413
+ controller.enqueue({ type: "text-start", id: newId });
1414
+ }
1415
+ controller.enqueue({
1416
+ type: "text-delta",
1417
+ id: getCurrentTextId(),
1418
+ delta: content
1419
+ });
1420
+ if (text === void 0) {
1421
+ setBuffer("");
1422
+ }
1423
+ }
1424
+ const currentTextId = getCurrentTextId();
1425
+ if (currentTextId && !text) {
1426
+ controller.enqueue({ type: "text-end", id: currentTextId });
1427
+ setCurrentTextId(null);
1428
+ }
1429
+ };
1430
+ }
1431
+ function processBufferWithToolCall(params, controller) {
1432
+ const {
1433
+ getBuffer,
1434
+ setBuffer,
1435
+ getCurrentToolCall,
1436
+ setCurrentToolCall,
1437
+ tools,
1438
+ options,
1439
+ flushText
1440
+ } = params;
1441
+ const currentToolCall = getCurrentToolCall();
1442
+ if (!currentToolCall) {
1443
+ return true;
1444
+ }
1445
+ const result = processToolCallInBuffer({
1446
+ buffer: getBuffer(),
1447
+ currentToolCall,
1448
+ tools,
1449
+ options,
1450
+ controller,
1451
+ flushText,
1452
+ setBuffer
1453
+ });
1454
+ setBuffer(result.buffer);
1455
+ setCurrentToolCall(result.currentToolCall);
1456
+ return result.shouldBreak;
1457
+ }
1458
+ function processBufferWithoutToolCall(params, controller) {
1459
+ const {
1460
+ getBuffer,
1461
+ setBuffer,
1462
+ setCurrentToolCall,
1463
+ toolNames,
1464
+ maxStartTagLen,
1465
+ flushText
1466
+ } = params;
1467
+ const result = processNoToolCallInBuffer({
1468
+ buffer: getBuffer(),
1469
+ toolNames,
1470
+ maxStartTagLen,
1471
+ controller,
1472
+ flushText
1473
+ });
1474
+ setBuffer(result.buffer);
1475
+ setCurrentToolCall(result.currentToolCall);
1476
+ return {
1477
+ shouldBreak: result.shouldBreak,
1478
+ shouldContinue: result.shouldContinue
1479
+ };
1480
+ }
1481
+ function processBufferLoop(params, controller) {
1482
+ while (true) {
1483
+ const currentToolCall = params.getCurrentToolCall();
1484
+ if (currentToolCall) {
1485
+ const shouldBreak = processBufferWithToolCall(params, controller);
1486
+ if (shouldBreak) {
1487
+ break;
1488
+ }
1489
+ } else {
1490
+ const { shouldBreak, shouldContinue } = processBufferWithoutToolCall(
1491
+ params,
1492
+ controller
1493
+ );
1494
+ if (shouldContinue) {
1495
+ continue;
1496
+ }
1497
+ if (shouldBreak) {
1498
+ break;
1499
+ }
1500
+ }
1501
+ }
1502
+ }
1503
+ function createProcessBufferHandler(params) {
1504
+ return (controller) => {
1505
+ processBufferLoop(params, controller);
1506
+ };
1507
+ }
1508
+ var morphXmlProtocol = () => ({
1509
+ formatTools({ tools, toolSystemPromptTemplate }) {
1510
+ const toolsForPrompt = (tools || []).map((tool) => ({
1511
+ name: tool.name,
1512
+ description: tool.description,
1513
+ parameters: unwrapJsonSchema(tool.inputSchema)
1514
+ }));
1515
+ return toolSystemPromptTemplate(JSON.stringify(toolsForPrompt));
1516
+ },
1517
+ formatToolCall(toolCall) {
1518
+ let args = {};
1519
+ const inputValue = hasInputProperty(toolCall) ? toolCall.input : void 0;
1520
+ if (typeof inputValue === "string") {
1521
+ try {
1522
+ args = JSON.parse(inputValue);
1523
+ } catch (e) {
1524
+ args = inputValue;
1525
+ }
1526
+ } else {
1527
+ args = inputValue;
1528
+ }
1529
+ return stringify2(toolCall.toolName, args, {
1530
+ suppressEmptyNode: false,
1531
+ format: false
1532
+ });
1533
+ },
1534
+ formatToolResponse(toolResult) {
1535
+ return stringify2("tool_response", {
1536
+ tool_name: toolResult.toolName,
1537
+ result: toolResult.output
1538
+ });
1539
+ },
1540
+ parseGeneratedText({ text, tools, options }) {
1541
+ const toolNames = tools.map((t) => t.name).filter((name) => name != null);
1542
+ if (toolNames.length === 0) {
1543
+ return [{ type: "text", text }];
1544
+ }
1545
+ const processedElements = [];
1546
+ let currentIndex = 0;
1547
+ const toolCalls = findToolCalls(text, toolNames);
1548
+ for (const toolCall of toolCalls) {
1549
+ currentIndex = processTextBeforeToolCall(
1550
+ text,
1551
+ currentIndex,
1552
+ toolCall.startIndex,
1553
+ processedElements
1554
+ );
1555
+ processToolCall({ toolCall, tools, options, text, processedElements });
1556
+ currentIndex = toolCall.endIndex;
1557
+ }
1558
+ addRemainingText(text, currentIndex, processedElements);
1559
+ return processedElements;
1560
+ },
1561
+ createStreamParser({ tools, options }) {
1562
+ const toolNames = tools.map((t) => t.name).filter((name) => name != null);
1563
+ const maxStartTagLen = toolNames.length ? Math.max(...toolNames.map((n) => `<${n}>`.length)) : 0;
1564
+ let buffer = "";
1565
+ let currentToolCall = null;
1566
+ let currentTextId = null;
1567
+ const flushText = createFlushTextHandler(
1568
+ () => buffer,
1569
+ (newBuffer) => {
1570
+ buffer = newBuffer;
1571
+ },
1572
+ () => currentTextId,
1573
+ (newId) => {
1574
+ currentTextId = newId;
1575
+ }
1576
+ );
1577
+ const processChunk = (chunk, controller) => {
1578
+ if (chunk.type !== "text-delta") {
1579
+ if (buffer) {
1580
+ flushText(controller);
1581
+ }
1582
+ controller.enqueue(chunk);
1583
+ return;
1584
+ }
1585
+ buffer += chunk.delta;
1586
+ processBuffer(controller);
1587
+ };
1588
+ const processBuffer = createProcessBufferHandler({
1589
+ getBuffer: () => buffer,
1590
+ setBuffer: (newBuffer) => {
1591
+ buffer = newBuffer;
1592
+ },
1593
+ getCurrentToolCall: () => currentToolCall,
1594
+ setCurrentToolCall: (newToolCall) => {
1595
+ currentToolCall = newToolCall;
1596
+ },
1597
+ tools,
1598
+ options,
1599
+ toolNames,
1600
+ maxStartTagLen,
1601
+ flushText
1602
+ });
1603
+ const flushBuffer2 = (controller) => {
1604
+ if (currentToolCall) {
1605
+ const unfinishedCall = `<${currentToolCall.name}>${buffer}`;
1606
+ flushText(controller, unfinishedCall);
1607
+ } else if (buffer) {
1608
+ flushText(controller);
1609
+ }
1610
+ if (currentTextId) {
1611
+ controller.enqueue({ type: "text-end", id: currentTextId });
1612
+ }
1613
+ };
1614
+ return new TransformStream({
1615
+ transform(chunk, controller) {
1616
+ processChunk(chunk, controller);
1617
+ },
1618
+ flush(controller) {
1619
+ flushBuffer2(controller);
1620
+ }
1621
+ });
1622
+ },
1623
+ extractToolCallSegments({ text, tools }) {
1624
+ const toolNames = tools.map((t) => t.name).filter(Boolean);
1625
+ if (toolNames.length === 0) {
1626
+ return [];
1627
+ }
1628
+ return findToolCalls(text, toolNames).map((tc) => tc.segment);
1629
+ }
1630
+ });
1631
+ function getToolSchema(tools, toolName) {
1632
+ var _a;
1633
+ return (_a = tools.find((t) => t.name === toolName)) == null ? void 0 : _a.inputSchema;
1634
+ }
1635
+ function computeFullTagEnd(text, contentEnd, toolName) {
1636
+ let fullTagEnd = contentEnd + `</${toolName}>`.length;
1637
+ const closeHead = text.indexOf(`</${toolName}`, contentEnd);
1638
+ if (closeHead === contentEnd) {
1639
+ let p = closeHead + 2 + toolName.length;
1640
+ while (p < text.length && WHITESPACE_REGEX2.test(text[p])) {
1641
+ p += 1;
1642
+ }
1643
+ if (text[p] === ">") {
1644
+ fullTagEnd = p + 1;
1645
+ }
1646
+ }
1647
+ return fullTagEnd;
1648
+ }
1649
+ function extractToolCallInfo(text, tagStart, toolName, range) {
1650
+ var _a;
1651
+ const startTag = `<${toolName}>`;
1652
+ const contentStart = tagStart + startTag.length;
1653
+ const contentEnd = contentStart + (range.end - range.start);
1654
+ const fullTagEnd = computeFullTagEnd(text, contentEnd, toolName);
1655
+ const segment = text.substring(tagStart, fullTagEnd);
1656
+ const content = (_a = extractRawInner(segment, toolName)) != null ? _a : text.substring(contentStart, contentEnd);
1657
+ return {
1658
+ toolName,
1659
+ startIndex: tagStart,
1660
+ endIndex: fullTagEnd,
1661
+ content,
1662
+ segment
1663
+ };
1664
+ }
1665
+ function findToolCallsForName(text, toolName) {
1666
+ const toolCalls = [];
1667
+ const startTag = `<${toolName}>`;
1668
+ let searchIndex = 0;
1669
+ while (searchIndex < text.length) {
1670
+ const tagStart = text.indexOf(startTag, searchIndex);
1671
+ if (tagStart === -1) {
1672
+ break;
1673
+ }
1674
+ const remainingText = text.substring(tagStart);
1675
+ const range = findFirstTopLevelRange(remainingText, toolName);
1676
+ if (range) {
1677
+ const toolCallInfo = extractToolCallInfo(text, tagStart, toolName, range);
1678
+ toolCalls.push(toolCallInfo);
1679
+ searchIndex = toolCallInfo.endIndex;
1680
+ } else {
1681
+ searchIndex = tagStart + startTag.length;
1682
+ }
1683
+ }
1684
+ return toolCalls;
1685
+ }
1686
+ function findToolCalls(text, toolNames) {
1687
+ const toolCalls = [];
1688
+ for (const toolName of toolNames) {
1689
+ const calls = findToolCallsForName(text, toolName);
1690
+ toolCalls.push(...calls);
1691
+ }
1692
+ return toolCalls.sort((a, b) => a.startIndex - b.startIndex);
1693
+ }
1694
+
1695
+ // src/protocols/tool-call-protocol.ts
1696
+ function isProtocolFactory(protocol) {
1697
+ return typeof protocol === "function";
1698
+ }
1699
+
1700
+ // src/generate-handler.ts
1701
+ import { generateId as generateId4 } from "@ai-sdk/provider-utils";
1702
+ import { coerceBySchema } from "@ai-sdk-tool/rxml";
1703
+ function parseToolChoiceJson(text, providerOptions) {
1704
+ var _a;
1705
+ try {
1706
+ return JSON.parse(text);
1707
+ } catch (error) {
1708
+ const options = extractOnErrorOption(providerOptions);
1709
+ (_a = options == null ? void 0 : options.onError) == null ? void 0 : _a.call(
1710
+ options,
1711
+ "Failed to parse toolChoice JSON from generated model output",
1712
+ {
1713
+ text,
1714
+ error: error instanceof Error ? error.message : String(error)
1715
+ }
1716
+ );
1717
+ return {};
1718
+ }
1719
+ }
1720
+ function logDebugSummary(debugSummary, toolCall, originText) {
1721
+ if (debugSummary) {
1722
+ debugSummary.originalText = originText;
1723
+ try {
1724
+ debugSummary.toolCalls = JSON.stringify([
1725
+ { toolName: toolCall.toolName, input: toolCall.input }
1726
+ ]);
1727
+ } catch (e) {
1728
+ }
1729
+ } else if (getDebugLevel() === "parse") {
1730
+ logParsedSummary({ toolCalls: [toolCall], originalText: originText });
1731
+ }
1732
+ }
1733
+ async function handleToolChoice(doGenerate, params) {
1734
+ var _a, _b, _c;
1735
+ const result = await doGenerate();
1736
+ const first = (_a = result.content) == null ? void 0 : _a[0];
1737
+ let parsed = {};
1738
+ if (first && first.type === "text") {
1739
+ if (getDebugLevel() === "parse") {
1740
+ logRawChunk(first.text);
1741
+ }
1742
+ parsed = parseToolChoiceJson(first.text, params.providerOptions);
1743
+ }
1744
+ const toolCall = {
1745
+ type: "tool-call",
1746
+ toolCallId: generateId4(),
1747
+ toolName: parsed.name || "unknown",
1748
+ input: JSON.stringify(parsed.arguments || {})
1749
+ };
1750
+ const originText = first && first.type === "text" ? first.text : "";
1751
+ const debugSummary = (_c = (_b = params.providerOptions) == null ? void 0 : _b.toolCallMiddleware) == null ? void 0 : _c.debugSummary;
1752
+ logDebugSummary(debugSummary, toolCall, originText);
1753
+ return {
1754
+ ...result,
1755
+ content: [toolCall]
1756
+ };
1757
+ }
1758
+ function parseContent(content, protocol, tools, providerOptions) {
1759
+ const parsed = content.flatMap((contentItem) => {
1760
+ if (contentItem.type !== "text") {
1761
+ return [contentItem];
1762
+ }
1763
+ if (getDebugLevel() === "stream") {
1764
+ logRawChunk(contentItem.text);
1765
+ }
1766
+ return protocol.parseGeneratedText({
1767
+ text: contentItem.text,
1768
+ tools,
1769
+ options: {
1770
+ ...extractOnErrorOption(providerOptions),
1771
+ ...providerOptions == null ? void 0 : providerOptions.toolCallMiddleware
1772
+ }
1773
+ });
1774
+ });
1775
+ return parsed.map(
1776
+ (part) => fixToolCallWithSchema(part, tools)
1777
+ );
1778
+ }
1779
+ function logParsedContent(content) {
1780
+ if (getDebugLevel() === "stream") {
1781
+ for (const part of content) {
1782
+ logParsedChunk(part);
1783
+ }
1784
+ }
1785
+ }
1786
+ function computeDebugSummary(options) {
1787
+ var _a;
1788
+ const { result, newContent, protocol, tools, providerOptions } = options;
1789
+ const allText = result.content.filter(
1790
+ (c) => c.type === "text"
1791
+ ).map((c) => c.text).join("\n\n");
1792
+ const segments = protocol.extractToolCallSegments ? protocol.extractToolCallSegments({ text: allText, tools }) : [];
1793
+ const originalText = segments.join("\n\n");
1794
+ const toolCalls = newContent.filter(
1795
+ (p) => p.type === "tool-call"
1796
+ );
1797
+ const dbg = (_a = providerOptions == null ? void 0 : providerOptions.toolCallMiddleware) == null ? void 0 : _a.debugSummary;
1798
+ if (dbg) {
1799
+ dbg.originalText = originalText;
1800
+ try {
1801
+ dbg.toolCalls = JSON.stringify(
1802
+ toolCalls.map((tc) => ({
1803
+ toolName: tc.toolName,
1804
+ input: tc.input
1805
+ }))
1806
+ );
1807
+ } catch (e) {
1808
+ }
1809
+ } else if (getDebugLevel() === "parse") {
1810
+ logParsedSummary({ toolCalls, originalText });
1811
+ }
1812
+ }
1813
+ async function wrapGenerate({
1814
+ protocol,
1815
+ doGenerate,
1816
+ params
1817
+ }) {
1818
+ var _a, _b;
1819
+ if (isToolChoiceActive(params)) {
1820
+ return handleToolChoice(doGenerate, params);
1821
+ }
1822
+ const tools = originalToolsSchema.decode(
1823
+ (_b = (_a = params.providerOptions) == null ? void 0 : _a.toolCallMiddleware) == null ? void 0 : _b.originalTools
1824
+ );
1825
+ const result = await doGenerate();
1826
+ if (result.content.length === 0) {
1827
+ return result;
1828
+ }
1829
+ const newContent = parseContent(
1830
+ result.content,
1831
+ protocol,
1832
+ tools,
1833
+ params.providerOptions
1834
+ );
1835
+ logParsedContent(newContent);
1836
+ computeDebugSummary({
1837
+ result,
1838
+ newContent,
1839
+ protocol,
1840
+ tools,
1841
+ providerOptions: params.providerOptions
1842
+ });
1843
+ return {
1844
+ ...result,
1845
+ content: newContent
1846
+ };
1847
+ }
1848
+ function fixToolCallWithSchema(part, tools) {
1849
+ var _a;
1850
+ if (part.type !== "tool-call") {
1851
+ return part;
1852
+ }
1853
+ const tc = part;
1854
+ let args = {};
1855
+ if (typeof tc.input === "string") {
1856
+ try {
1857
+ args = JSON.parse(tc.input);
1858
+ } catch (e) {
1859
+ return part;
1860
+ }
1861
+ } else if (tc.input && typeof tc.input === "object") {
1862
+ args = tc.input;
1863
+ }
1864
+ const schema = (_a = tools.find((t) => t.name === tc.toolName)) == null ? void 0 : _a.inputSchema;
1865
+ const coerced = coerceBySchema(args, schema);
1866
+ return {
1867
+ ...part,
1868
+ input: JSON.stringify(coerced != null ? coerced : {})
1869
+ };
1870
+ }
1871
+
1872
+ // src/stream-handler.ts
1873
+ import { generateId as generateId5 } from "@ai-sdk/provider-utils";
1874
+ function extractToolCallSegments(protocol, fullRawText, tools) {
1875
+ const segments = protocol.extractToolCallSegments ? protocol.extractToolCallSegments({
1876
+ text: fullRawText,
1877
+ tools
1878
+ }) : [];
1879
+ return segments.join("\n\n");
1880
+ }
1881
+ function serializeToolCalls(parsedToolCalls) {
1882
+ const toolCallParts = parsedToolCalls.filter(
1883
+ (p) => p.type === "tool-call"
1884
+ );
1885
+ return JSON.stringify(
1886
+ toolCallParts.map((tc) => ({
1887
+ toolName: tc.toolName,
1888
+ input: tc.input
1889
+ }))
1890
+ );
1891
+ }
1892
+ function handleDebugSummary(parsedToolCalls, origin, params) {
1893
+ var _a, _b;
1894
+ const dbg = (_b = (_a = params.providerOptions) == null ? void 0 : _a.toolCallMiddleware) == null ? void 0 : _b.debugSummary;
1895
+ if (dbg) {
1896
+ dbg.originalText = origin;
1897
+ try {
1898
+ dbg.toolCalls = serializeToolCalls(parsedToolCalls);
1899
+ } catch (e) {
1900
+ }
1901
+ } else {
1902
+ logParsedSummary({
1903
+ toolCalls: parsedToolCalls,
1904
+ originalText: origin
1905
+ });
1906
+ }
1907
+ }
1908
+ function createDebugSummaryTransform({
1909
+ protocol,
1910
+ fullRawText,
1911
+ tools,
1912
+ params
1913
+ }) {
1914
+ return new TransformStream({
1915
+ transform: /* @__PURE__ */ (() => {
1916
+ const parsedToolCalls = [];
1917
+ return (part, controller) => {
1918
+ if (part.type === "tool-call") {
1919
+ parsedToolCalls.push(part);
1920
+ }
1921
+ if (part.type === "finish") {
1922
+ try {
1923
+ const origin = extractToolCallSegments(
1924
+ protocol,
1925
+ fullRawText,
1926
+ tools
1927
+ );
1928
+ handleDebugSummary(parsedToolCalls, origin, params);
1929
+ } catch (e) {
1930
+ }
1931
+ }
1932
+ controller.enqueue(part);
1933
+ };
1934
+ })()
1935
+ });
1936
+ }
1937
+ async function wrapStream({
1938
+ protocol,
1939
+ doStream,
1940
+ doGenerate,
1941
+ params
1942
+ }) {
1943
+ var _a, _b, _c;
1944
+ if (isToolChoiceActive(params)) {
1945
+ return toolChoiceStream({
1946
+ doGenerate,
1947
+ options: extractOnErrorOption(params.providerOptions)
1948
+ });
1949
+ }
1950
+ const { stream, ...rest } = await doStream();
1951
+ const debugLevel = getDebugLevel();
1952
+ const tools = originalToolsSchema.decode(
1953
+ (_b = (_a = params.providerOptions) == null ? void 0 : _a.toolCallMiddleware) == null ? void 0 : _b.originalTools
1954
+ );
1955
+ const options = {
1956
+ ...extractOnErrorOption(params.providerOptions),
1957
+ ...(_c = params.providerOptions) == null ? void 0 : _c.toolCallMiddleware
1958
+ };
1959
+ if (debugLevel === "off") {
1960
+ return {
1961
+ stream: stream.pipeThrough(
1962
+ protocol.createStreamParser({
1963
+ tools,
1964
+ options
1965
+ })
1966
+ ),
1967
+ ...rest
1968
+ };
1969
+ }
1970
+ if (debugLevel === "stream") {
1971
+ const withRawTap2 = stream.pipeThrough(
1972
+ new TransformStream(
1973
+ {
1974
+ transform(part, controller) {
1975
+ logRawChunk(part);
1976
+ controller.enqueue(part);
1977
+ }
1978
+ }
1979
+ )
1980
+ );
1981
+ const parsed2 = withRawTap2.pipeThrough(
1982
+ protocol.createStreamParser({
1983
+ tools,
1984
+ options
1985
+ })
1986
+ );
1987
+ const withParsedTap = parsed2.pipeThrough(
1988
+ new TransformStream(
1989
+ {
1990
+ transform(part, controller) {
1991
+ logParsedChunk(part);
1992
+ controller.enqueue(part);
1993
+ }
1994
+ }
1995
+ )
1996
+ );
1997
+ return {
1998
+ stream: withParsedTap,
1999
+ ...rest
2000
+ };
2001
+ }
2002
+ let fullRawText = "";
2003
+ const withRawTap = stream.pipeThrough(
2004
+ new TransformStream({
2005
+ transform(part, controller) {
2006
+ if (part.type === "text-delta") {
2007
+ const delta = part.delta;
2008
+ if (typeof delta === "string" && delta.length > 0) {
2009
+ fullRawText += delta;
2010
+ }
2011
+ }
2012
+ controller.enqueue(part);
2013
+ }
2014
+ })
2015
+ );
2016
+ const parsed = withRawTap.pipeThrough(
2017
+ protocol.createStreamParser({
2018
+ tools,
2019
+ options
2020
+ })
2021
+ );
2022
+ const withSummary = parsed.pipeThrough(
2023
+ createDebugSummaryTransform({
2024
+ protocol,
2025
+ fullRawText,
2026
+ tools,
2027
+ params
2028
+ })
2029
+ );
2030
+ return {
2031
+ stream: withSummary,
2032
+ ...rest
2033
+ };
2034
+ }
2035
+ async function toolChoiceStream({
2036
+ doGenerate,
2037
+ options
2038
+ }) {
2039
+ var _a, _b, _c;
2040
+ const result = await doGenerate();
2041
+ let toolJson = {};
2042
+ if ((result == null ? void 0 : result.content) && result.content.length > 0 && ((_a = result.content[0]) == null ? void 0 : _a.type) === "text") {
2043
+ try {
2044
+ toolJson = JSON.parse(result.content[0].text);
2045
+ } catch (error) {
2046
+ (_b = options == null ? void 0 : options.onError) == null ? void 0 : _b.call(
2047
+ options,
2048
+ "Failed to parse toolChoice JSON from streamed model output",
2049
+ {
2050
+ text: result.content[0].text,
2051
+ error: error instanceof Error ? error.message : String(error)
2052
+ }
2053
+ );
2054
+ toolJson = {};
2055
+ }
2056
+ }
2057
+ const toolCallChunk = {
2058
+ type: "tool-call",
2059
+ toolCallId: generateId5(),
2060
+ toolName: toolJson.name || "unknown",
2061
+ input: JSON.stringify(toolJson.arguments || {})
2062
+ };
2063
+ const finishChunk = {
2064
+ type: "finish",
2065
+ usage: (result == null ? void 0 : result.usage) || // TODO: If possible, try to return a certain amount of LLM usage.
2066
+ {
2067
+ inputTokens: 0,
2068
+ outputTokens: 0,
2069
+ totalTokens: 0
2070
+ },
2071
+ finishReason: "tool-calls"
2072
+ };
2073
+ const stream = new ReadableStream({
2074
+ start(controller) {
2075
+ controller.enqueue(toolCallChunk);
2076
+ controller.enqueue(finishChunk);
2077
+ controller.close();
2078
+ }
2079
+ });
2080
+ const debugLevel = getDebugLevel();
2081
+ const firstText = ((_c = result == null ? void 0 : result.content) == null ? void 0 : _c[0]) && result.content[0].type === "text" && result.content[0].text || "";
2082
+ const streamWithSummary = debugLevel === "parse" ? stream.pipeThrough(
2083
+ new TransformStream({
2084
+ transform(part, controller) {
2085
+ if (part.type === "finish") {
2086
+ try {
2087
+ logParsedSummary({
2088
+ toolCalls: [toolCallChunk],
2089
+ originalText: typeof firstText === "string" ? firstText : ""
2090
+ });
2091
+ } catch (e) {
2092
+ }
2093
+ }
2094
+ controller.enqueue(part);
2095
+ }
2096
+ })
2097
+ ) : stream;
2098
+ return {
2099
+ request: (result == null ? void 0 : result.request) || {},
2100
+ response: (result == null ? void 0 : result.response) || {},
2101
+ stream: streamWithSummary
2102
+ };
2103
+ }
2104
+
2105
+ // src/transform-handler.ts
2106
+ function buildFinalPrompt(systemPrompt, processedPrompt) {
2107
+ var _a;
2108
+ if (((_a = processedPrompt[0]) == null ? void 0 : _a.role) === "system") {
2109
+ return [
2110
+ {
2111
+ role: "system",
2112
+ content: `${systemPrompt}
2113
+
2114
+ ${processedPrompt[0].content}`
2115
+ },
2116
+ ...processedPrompt.slice(1)
2117
+ ];
2118
+ }
2119
+ return [
2120
+ {
2121
+ role: "system",
2122
+ content: systemPrompt
2123
+ },
2124
+ ...processedPrompt
2125
+ ];
2126
+ }
2127
+ function buildBaseReturnParams(params, finalPrompt, functionTools) {
2128
+ return {
2129
+ ...params,
2130
+ prompt: finalPrompt,
2131
+ tools: [],
2132
+ toolChoice: void 0,
2133
+ providerOptions: {
2134
+ ...params.providerOptions || {},
2135
+ toolCallMiddleware: {
2136
+ ...params.providerOptions && typeof params.providerOptions === "object" && params.providerOptions.toolCallMiddleware || {},
2137
+ originalTools: originalToolsSchema.encode(functionTools)
2138
+ }
2139
+ }
2140
+ };
2141
+ }
2142
+ function findProviderDefinedTool(tools, selectedToolName) {
2143
+ return tools.find((t) => {
2144
+ if (t.type === "function") {
2145
+ return false;
2146
+ }
2147
+ const anyTool = t;
2148
+ return anyTool.id === selectedToolName || anyTool.name === selectedToolName;
2149
+ });
2150
+ }
2151
+ function handleToolChoiceTool(params, baseReturnParams) {
2152
+ var _a, _b, _c;
2153
+ const selectedToolName = (_a = params.toolChoice) == null ? void 0 : _a.toolName;
2154
+ if (!selectedToolName) {
2155
+ throw new Error("Tool name is required for 'tool' toolChoice type.");
2156
+ }
2157
+ const providerDefinedMatch = findProviderDefinedTool(
2158
+ (_b = params.tools) != null ? _b : [],
2159
+ selectedToolName
2160
+ );
2161
+ if (providerDefinedMatch) {
2162
+ throw new Error(
2163
+ "Provider-defined tools are not supported by this middleware. Please use custom tools."
2164
+ );
2165
+ }
2166
+ const selectedTool = ((_c = params.tools) != null ? _c : []).find(
2167
+ (t) => t.type === "function" && t.name === selectedToolName
2168
+ );
2169
+ if (!selectedTool) {
2170
+ throw new Error(
2171
+ `Tool with name '${selectedToolName}' not found in params.tools.`
2172
+ );
2173
+ }
2174
+ return {
2175
+ ...baseReturnParams,
2176
+ responseFormat: {
2177
+ type: "json",
2178
+ schema: {
2179
+ type: "object",
2180
+ properties: {
2181
+ name: {
2182
+ const: selectedTool.name
2183
+ },
2184
+ arguments: selectedTool.inputSchema
2185
+ },
2186
+ required: ["name", "arguments"]
2187
+ },
2188
+ name: selectedTool.name,
2189
+ description: typeof selectedTool.description === "string" ? selectedTool.description : void 0
2190
+ },
2191
+ providerOptions: {
2192
+ ...baseReturnParams.providerOptions || {},
2193
+ toolCallMiddleware: {
2194
+ ...baseReturnParams.providerOptions && typeof baseReturnParams.providerOptions === "object" && baseReturnParams.providerOptions.toolCallMiddleware || {},
2195
+ ...params.toolChoice ? { toolChoice: params.toolChoice } : {}
2196
+ }
2197
+ }
2198
+ };
2199
+ }
2200
+ function handleToolChoiceRequired(params, baseReturnParams, functionTools) {
2201
+ if (!params.tools || params.tools.length === 0) {
2202
+ throw new Error(
2203
+ "Tool choice type 'required' is set, but no tools are provided in params.tools."
2204
+ );
2205
+ }
2206
+ return {
2207
+ ...baseReturnParams,
2208
+ responseFormat: {
2209
+ type: "json",
2210
+ schema: createDynamicIfThenElseSchema(functionTools)
2211
+ },
2212
+ providerOptions: {
2213
+ ...baseReturnParams.providerOptions || {},
2214
+ toolCallMiddleware: {
2215
+ ...baseReturnParams.providerOptions && typeof baseReturnParams.providerOptions === "object" && baseReturnParams.providerOptions.toolCallMiddleware || {},
2216
+ toolChoice: { type: "required" }
2217
+ }
2218
+ }
2219
+ };
2220
+ }
2221
+ function transformParams({
2222
+ params,
2223
+ protocol,
2224
+ toolSystemPromptTemplate
2225
+ }) {
2226
+ var _a, _b, _c, _d, _e;
2227
+ const resolvedProtocol = isProtocolFactory(protocol) ? protocol() : protocol;
2228
+ const functionTools = ((_a = params.tools) != null ? _a : []).filter(
2229
+ (t) => t.type === "function"
2230
+ );
2231
+ const systemPrompt = resolvedProtocol.formatTools({
2232
+ tools: functionTools,
2233
+ toolSystemPromptTemplate
2234
+ });
2235
+ const processedPrompt = convertToolPrompt(
2236
+ (_b = params.prompt) != null ? _b : [],
2237
+ resolvedProtocol,
2238
+ extractOnErrorOption(params.providerOptions)
2239
+ );
2240
+ const finalPrompt = buildFinalPrompt(systemPrompt, processedPrompt);
2241
+ const baseReturnParams = buildBaseReturnParams(
2242
+ params,
2243
+ finalPrompt,
2244
+ functionTools
2245
+ );
2246
+ if (((_c = params.toolChoice) == null ? void 0 : _c.type) === "none") {
2247
+ throw new Error(
2248
+ "The 'none' toolChoice type is not supported by this middleware. Please use 'auto', 'required', or specify a tool name."
2249
+ );
2250
+ }
2251
+ if (((_d = params.toolChoice) == null ? void 0 : _d.type) === "tool") {
2252
+ return handleToolChoiceTool(params, baseReturnParams);
2253
+ }
2254
+ if (((_e = params.toolChoice) == null ? void 0 : _e.type) === "required") {
2255
+ return handleToolChoiceRequired(params, baseReturnParams, functionTools);
2256
+ }
2257
+ return baseReturnParams;
2258
+ }
2259
+ function processAssistantContent(content, resolvedProtocol, providerOptions) {
2260
+ var _a;
2261
+ const newContent = [];
2262
+ for (const item of content) {
2263
+ if (isToolCallContent(item)) {
2264
+ newContent.push({
2265
+ type: "text",
2266
+ text: resolvedProtocol.formatToolCall(item)
2267
+ });
2268
+ } else if (item.type === "text") {
2269
+ newContent.push(item);
2270
+ } else if (item.type === "reasoning") {
2271
+ newContent.push(item);
2272
+ } else {
2273
+ const options = extractOnErrorOption(providerOptions);
2274
+ (_a = options == null ? void 0 : options.onError) == null ? void 0 : _a.call(
2275
+ options,
2276
+ "tool-call-middleware: unknown assistant content; stringifying for provider compatibility",
2277
+ { content: item }
2278
+ );
2279
+ newContent.push({
2280
+ type: "text",
2281
+ text: JSON.stringify(item)
2282
+ });
2283
+ }
2284
+ }
2285
+ const onlyText = newContent.every((c) => c.type === "text");
2286
+ return onlyText ? [
2287
+ {
2288
+ type: "text",
2289
+ text: newContent.map((c) => c.text).join("\n")
2290
+ }
2291
+ ] : newContent;
2292
+ }
2293
+ function processToolMessage(content, resolvedProtocol) {
2294
+ return {
2295
+ role: "user",
2296
+ content: [
2297
+ {
2298
+ type: "text",
2299
+ text: content.map((toolResult) => resolvedProtocol.formatToolResponse(toolResult)).join("\n")
2300
+ }
2301
+ ]
2302
+ };
2303
+ }
2304
+ function processMessage(message, resolvedProtocol, providerOptions) {
2305
+ if (message.role === "assistant") {
2306
+ const condensedContent = processAssistantContent(
2307
+ message.content,
2308
+ resolvedProtocol,
2309
+ providerOptions
2310
+ );
2311
+ return {
2312
+ role: "assistant",
2313
+ content: condensedContent
2314
+ };
2315
+ }
2316
+ if (message.role === "tool") {
2317
+ return processToolMessage(message.content, resolvedProtocol);
2318
+ }
2319
+ return message;
2320
+ }
2321
+ function isAllTextContent(content) {
2322
+ if (!Array.isArray(content)) {
2323
+ return false;
2324
+ }
2325
+ return content.every(
2326
+ (c) => (c == null ? void 0 : c.type) === "text"
2327
+ );
2328
+ }
2329
+ function joinTextContent(content) {
2330
+ return content.map((c) => c.text).join("\n");
2331
+ }
2332
+ function createCondensedMessage(role, joinedText) {
2333
+ if (role === "system") {
2334
+ return {
2335
+ role: "system",
2336
+ content: joinedText
2337
+ };
2338
+ }
2339
+ return {
2340
+ role,
2341
+ content: [
2342
+ {
2343
+ type: "text",
2344
+ text: joinedText
2345
+ }
2346
+ ]
2347
+ };
2348
+ }
2349
+ function condenseTextContent(processedPrompt) {
2350
+ for (let i = 0; i < processedPrompt.length; i += 1) {
2351
+ const msg = processedPrompt[i];
2352
+ if (!Array.isArray(msg.content)) {
2353
+ continue;
2354
+ }
2355
+ const shouldCondense = isAllTextContent(msg.content) && msg.content.length > 1;
2356
+ if (shouldCondense) {
2357
+ const joinedText = joinTextContent(msg.content);
2358
+ processedPrompt[i] = createCondensedMessage(msg.role, joinedText);
2359
+ }
2360
+ }
2361
+ return processedPrompt;
2362
+ }
2363
+ function mergeConsecutiveUserMessages(processedPrompt) {
2364
+ for (let i = processedPrompt.length - 1; i > 0; i -= 1) {
2365
+ const current = processedPrompt[i];
2366
+ const prev = processedPrompt[i - 1];
2367
+ if (current.role === "user" && prev.role === "user") {
2368
+ const prevContent = prev.content.map((c) => c.type === "text" ? c.text : "").join("\n");
2369
+ const currentContent = current.content.map((c) => c.type === "text" ? c.text : "").join("\n");
2370
+ processedPrompt[i - 1] = {
2371
+ role: "user",
2372
+ content: [{ type: "text", text: `${prevContent}
2373
+ ${currentContent}` }]
2374
+ };
2375
+ processedPrompt.splice(i, 1);
2376
+ }
2377
+ }
2378
+ return processedPrompt;
2379
+ }
2380
+ function convertToolPrompt(prompt, resolvedProtocol, providerOptions) {
2381
+ let processedPrompt = prompt.map(
2382
+ (message) => processMessage(message, resolvedProtocol, providerOptions)
2383
+ );
2384
+ processedPrompt = condenseTextContent(processedPrompt);
2385
+ processedPrompt = mergeConsecutiveUserMessages(processedPrompt);
2386
+ return processedPrompt;
2387
+ }
2388
+
2389
+ // src/tool-call-middleware.ts
2390
+ function createToolMiddleware({
2391
+ protocol,
2392
+ toolSystemPromptTemplate
2393
+ }) {
2394
+ const resolvedProtocol = isProtocolFactory(protocol) ? protocol() : protocol;
2395
+ return {
2396
+ specificationVersion: "v3",
2397
+ wrapStream: ({ doStream, doGenerate, params }) => {
2398
+ if (isToolChoiceActive(params)) {
2399
+ return toolChoiceStream({
2400
+ doGenerate,
2401
+ options: extractOnErrorOption(params.providerOptions)
2402
+ });
2403
+ }
2404
+ return wrapStream({
2405
+ protocol: resolvedProtocol,
2406
+ doStream,
2407
+ doGenerate,
2408
+ params
2409
+ });
2410
+ },
2411
+ wrapGenerate: async ({ doGenerate, params }) => wrapGenerate({
2412
+ protocol: resolvedProtocol,
2413
+ doGenerate,
2414
+ params
2415
+ }),
2416
+ transformParams: async ({ params }) => transformParams({
2417
+ protocol: resolvedProtocol,
2418
+ toolSystemPromptTemplate,
2419
+ params
2420
+ })
2421
+ };
2422
+ }
2423
+
2424
+ // src/index.ts
2425
+ var gemmaToolMiddleware = createToolMiddleware({
2426
+ protocol: jsonMixProtocol(
2427
+ // Customize the tool call delimiters to use markdown code fences
2428
+ {
2429
+ toolCallStart: "```tool_call\n",
2430
+ // TODO: Support specifying multiple possible tags,
2431
+ // e.g., for gemma, it would be nice to be able to set both `` and ``` at the same time.
2432
+ toolCallEnd: "\n```",
2433
+ toolResponseStart: "```tool_response\n",
2434
+ toolResponseEnd: "\n```"
2435
+ }
2436
+ ),
2437
+ toolSystemPromptTemplate(tools) {
2438
+ return `You have access to functions. If you decide to invoke any of the function(s),
2439
+ you MUST put it in the format of markdown code fence block with the language name of tool_call , e.g.
2440
+ \`\`\`tool_call
2441
+ {'name': <function-name>, 'arguments': <args-dict>}
2442
+ \`\`\`
2443
+ You SHOULD NOT include any other text in the response if you call a function
2444
+ ${tools}`;
2445
+ }
2446
+ });
2447
+ var hermesToolMiddleware = createToolMiddleware({
2448
+ protocol: jsonMixProtocol,
2449
+ toolSystemPromptTemplate(tools) {
2450
+ return `You are a function calling AI model.
2451
+ You are provided with function signatures within <tools></tools> XML tags.
2452
+ You may call one or more functions to assist with the user query.
2453
+ Don't make assumptions about what values to plug into functions.
2454
+ Here are the available tools: <tools>${tools}</tools>
2455
+ Use the following pydantic model json schema for each tool call you will make: {"title": "FunctionCall", "type": "object", "properties": {"arguments": {"title": "Arguments", "type": "object"}, "name": {"title": "Name", "type": "string"}}, "required": ["arguments", "name"]}
2456
+ For each function call return a json object with function name and arguments within <tool_call></tool_call> XML tags as follows:
2457
+ <tool_call>
2458
+ {"name": "<function-name>", "arguments": <args-dict>}
2459
+ </tool_call>`;
2460
+ }
2461
+ });
2462
+ var morphXmlToolMiddleware = createToolMiddleware({
2463
+ protocol: morphXmlProtocol,
2464
+ toolSystemPromptTemplate(tools) {
2465
+ return `You are a function calling AI model.
2466
+
2467
+ Available functions are listed inside <tools></tools>.
2468
+ <tools>${tools}</tools>
2469
+
2470
+ # Rules
2471
+ - Use exactly one XML element whose tag name is the function name.
2472
+ - Put each parameter as a child element.
2473
+ - Values must follow the schema exactly (numbers, arrays, objects, enums \u2192 copy as-is).
2474
+ - Do not add or remove functions or parameters.
2475
+ - Each required parameter must appear once.
2476
+ - Output nothing before or after the function call.
2477
+
2478
+ # Example
2479
+ <get_weather>
2480
+ <location>New York</location>
2481
+ <unit>celsius</unit>
2482
+ </get_weather>`;
2483
+ }
2484
+ });
2485
+
2486
+ export {
2487
+ getDebugLevel,
2488
+ logRawChunk,
2489
+ logParsedChunk,
2490
+ logParsedSummary,
2491
+ createDynamicIfThenElseSchema,
2492
+ getPotentialStartIndex,
2493
+ extractOnErrorOption,
2494
+ originalToolsSchema,
2495
+ encodeOriginalTools,
2496
+ decodeOriginalTools,
2497
+ extractToolNamesFromOriginalTools,
2498
+ isToolChoiceActive,
2499
+ escapeRegExp,
2500
+ transform,
2501
+ parse,
2502
+ stringify,
2503
+ robust_json_exports,
2504
+ isToolCallContent,
2505
+ isToolResultPart,
2506
+ hasInputProperty,
2507
+ jsonMixProtocol,
2508
+ morphXmlProtocol,
2509
+ createToolMiddleware,
2510
+ gemmaToolMiddleware,
2511
+ hermesToolMiddleware,
2512
+ morphXmlToolMiddleware
2513
+ };
2514
+ //# sourceMappingURL=chunk-FOANBZRH.js.map