@ai-sdk-tool/parser 2.1.5 → 2.1.7

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