@ai-sdk-tool/parser 3.1.2 → 3.1.3

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.
@@ -17,6 +17,7 @@ var __copyProps = (to, from, except, desc) => {
17
17
  }
18
18
  return to;
19
19
  };
20
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
20
21
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
22
  // If the importer is in node compatibility mode or this is not an ESM
22
23
  // file that has been converted to a CommonJS file using a Babel-
@@ -35,6 +36,50 @@ __export(community_exports, {
35
36
  });
36
37
  module.exports = __toCommonJS(community_exports);
37
38
 
39
+ // src/index.ts
40
+ var src_exports = {};
41
+ __export(src_exports, {
42
+ applyHeuristicPipeline: () => applyHeuristicPipeline,
43
+ balanceTagsHeuristic: () => balanceTagsHeuristic,
44
+ createDynamicIfThenElseSchema: () => createDynamicIfThenElseSchema,
45
+ createIntermediateCall: () => createIntermediateCall,
46
+ createToolMiddleware: () => createToolMiddleware,
47
+ decodeOriginalTools: () => decodeOriginalTools,
48
+ dedupeShellStringTagsHeuristic: () => dedupeShellStringTagsHeuristic,
49
+ defaultPipelineConfig: () => defaultPipelineConfig,
50
+ encodeOriginalTools: () => encodeOriginalTools,
51
+ escapeInvalidLtHeuristic: () => escapeInvalidLtHeuristic,
52
+ escapeRegExp: () => escapeRegExp2,
53
+ extractOnErrorOption: () => extractOnErrorOption,
54
+ extractToolNamesFromOriginalTools: () => extractToolNamesFromOriginalTools,
55
+ getDebugLevel: () => getDebugLevel,
56
+ getPotentialStartIndex: () => getPotentialStartIndex,
57
+ hasInputProperty: () => hasInputProperty,
58
+ hermesToolMiddleware: () => hermesToolMiddleware,
59
+ isProtocolFactory: () => isProtocolFactory,
60
+ isTCMProtocolFactory: () => isTCMProtocolFactory,
61
+ isToolChoiceActive: () => isToolChoiceActive,
62
+ isToolResultPart: () => isToolResultPart,
63
+ jsonProtocol: () => jsonProtocol,
64
+ logParseFailure: () => logParseFailure,
65
+ logParsedChunk: () => logParsedChunk,
66
+ logParsedSummary: () => logParsedSummary,
67
+ logRawChunk: () => logRawChunk,
68
+ mergePipelineConfigs: () => mergePipelineConfigs,
69
+ normalizeCloseTagsHeuristic: () => normalizeCloseTagsHeuristic,
70
+ originalToolsSchema: () => originalToolsSchema,
71
+ repairAgainstSchemaHeuristic: () => repairAgainstSchemaHeuristic,
72
+ toolChoiceStream: () => toolChoiceStream,
73
+ transformParams: () => transformParams,
74
+ wrapGenerate: () => wrapGenerate,
75
+ wrapStream: () => wrapStream,
76
+ xmlProtocol: () => xmlProtocol,
77
+ xmlToolMiddleware: () => xmlToolMiddleware,
78
+ yamlProtocol: () => yamlProtocol,
79
+ yamlToolMiddleware: () => yamlToolMiddleware
80
+ });
81
+ __reExport(src_exports, require("@ai-sdk-tool/rjson"));
82
+
38
83
  // src/core/heuristics/engine.ts
39
84
  function applyRawSegmentUpdate(current, result) {
40
85
  if (result.rawSegment !== void 0) {
@@ -60,12 +105,12 @@ function applyWarningsUpdate(current, result) {
60
105
  }
61
106
  return current;
62
107
  }
63
- function attemptReparse(current, result, reparseCount, maxReparses, parse4) {
108
+ function attemptReparse(current, result, reparseCount, maxReparses, parse3) {
64
109
  if (!result.reparse || result.rawSegment === void 0 || reparseCount >= maxReparses) {
65
110
  return { state: current, newCount: reparseCount };
66
111
  }
67
112
  try {
68
- const reparsed = parse4(result.rawSegment, current.schema);
113
+ const reparsed = parse3(result.rawSegment, current.schema);
69
114
  return {
70
115
  state: { ...current, parsed: reparsed, errors: [] },
71
116
  newCount: reparseCount + 1
@@ -136,6 +181,29 @@ function createIntermediateCall(toolName, rawSegment, schema) {
136
181
  meta: { originalContent: rawSegment }
137
182
  };
138
183
  }
184
+ function mergePipelineConfigs(...configs) {
185
+ var _a, _b, _c;
186
+ const result = {
187
+ preParse: [],
188
+ fallbackReparse: [],
189
+ postParse: []
190
+ };
191
+ for (const config of configs) {
192
+ if (config.preParse) {
193
+ result.preParse = [...(_a = result.preParse) != null ? _a : [], ...config.preParse];
194
+ }
195
+ if (config.fallbackReparse) {
196
+ result.fallbackReparse = [
197
+ ...(_b = result.fallbackReparse) != null ? _b : [],
198
+ ...config.fallbackReparse
199
+ ];
200
+ }
201
+ if (config.postParse) {
202
+ result.postParse = [...(_c = result.postParse) != null ? _c : [], ...config.postParse];
203
+ }
204
+ }
205
+ return result;
206
+ }
139
207
 
140
208
  // src/core/heuristics/xml-defaults.ts
141
209
  var import_rxml = require("@ai-sdk-tool/rxml");
@@ -479,6 +547,9 @@ function extractStepStatusFromString(normXml) {
479
547
  return null;
480
548
  }
481
549
 
550
+ // src/core/protocols/json-protocol.ts
551
+ var import_rjson = require("@ai-sdk-tool/rjson");
552
+
482
553
  // src/core/utils/debug.ts
483
554
  var LINE_SPLIT_REGEX = /\r?\n/;
484
555
  function normalizeBooleanString(value) {
@@ -662,648 +733,11 @@ function escapeRegExp2(literal) {
662
733
  return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
663
734
  }
664
735
 
665
- // src/core/utils/robust-json.ts
666
- var WHITESPACE_TEST_REGEX = /\s/;
667
- var WHITESPACE_REGEX2 = /^\s+/;
668
- var OBJECT_START_REGEX = /^\{/;
669
- var OBJECT_END_REGEX = /^\}/;
670
- var ARRAY_START_REGEX = /^\[/;
671
- var ARRAY_END_REGEX = /^\]/;
672
- var COMMA_REGEX = /^,/;
673
- var COLON_REGEX = /^:/;
674
- var KEYWORD_REGEX = /^(?:true|false|null)/;
675
- var NUMBER_REGEX = /^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/;
676
- var STRING_DOUBLE_REGEX = /^"(?:[^"\\]|\\["bnrtf\\/]|\\u[0-9a-fA-F]{4})*"/;
677
- var STRING_SINGLE_REGEX = /^'((?:[^'\\]|\\['bnrtf\\/]|\\u[0-9a-fA-F]{4})*)'/;
678
- var COMMENT_SINGLE_REGEX = /^\/\/.*?(?:\r\n|\r|\n)/;
679
- var COMMENT_MULTI_REGEX = /^\/\*[\s\S]*?\*\//;
680
- var IDENTIFIER_REGEX = /^[$a-zA-Z0-9_\-+.*?!|&%^/#\\]+/;
681
- function some(array, f) {
682
- let acc = false;
683
- for (let i = 0; i < array.length; i += 1) {
684
- const result = f(array[i], i, array);
685
- acc = result === void 0 ? false : result;
686
- if (acc) {
687
- return acc;
688
- }
689
- }
690
- return acc;
691
- }
692
- function makeLexer(tokenSpecs) {
693
- return (contents) => {
694
- const tokens = [];
695
- let line = 1;
696
- let remainingContents = contents;
697
- function findToken() {
698
- const result = some(tokenSpecs, (tokenSpec) => {
699
- const m = tokenSpec.re.exec(remainingContents);
700
- if (m) {
701
- const raw = m[0];
702
- remainingContents = remainingContents.slice(raw.length);
703
- return {
704
- raw,
705
- matched: tokenSpec.f(m)
706
- // Process the match using the spec's function
707
- };
708
- }
709
- return;
710
- });
711
- return result === false ? void 0 : result;
712
- }
713
- while (remainingContents !== "") {
714
- const matched = findToken();
715
- if (!matched) {
716
- const err = new SyntaxError(
717
- `Unexpected character: ${remainingContents[0]}; input: ${remainingContents.substr(
718
- 0,
719
- 100
720
- )}`
721
- );
722
- err.line = line;
723
- throw err;
724
- }
725
- const tokenWithLine = matched.matched;
726
- tokenWithLine.line = line;
727
- line += matched.raw.replace(/[^\n]/g, "").length;
728
- tokens.push(tokenWithLine);
729
- }
730
- return tokens;
731
- };
732
- }
733
- function fStringSingle(m) {
734
- const content = m[1].replace(
735
- /([^'\\]|\\['bnrtf\\]|\\u[0-9a-fA-F]{4})/g,
736
- (mm) => {
737
- if (mm === '"') {
738
- return '\\"';
739
- }
740
- if (mm === "\\'") {
741
- return "'";
742
- }
743
- return mm;
744
- }
745
- );
746
- const match = `"${content}"`;
747
- return {
748
- type: "string",
749
- match,
750
- // The transformed, double-quoted string representation
751
- // Use JSON.parse on the transformed string to handle escape sequences correctly
752
- value: JSON.parse(match)
753
- };
754
- }
755
- function fStringDouble(m) {
756
- return {
757
- type: "string",
758
- match: m[0],
759
- // The raw matched string (including quotes)
760
- value: JSON.parse(m[0])
761
- // Use JSON.parse to handle escapes and get the value
762
- };
763
- }
764
- function fIdentifier(m) {
765
- const value = m[0];
766
- const match = '"' + value.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + // Escape backslashes and quotes
767
- '"';
768
- return {
769
- type: "string",
770
- // Treat identifiers as strings
771
- value,
772
- // The original identifier name
773
- match
774
- // The double-quoted string representation
775
- };
776
- }
777
- function fComment(m) {
778
- const match = m[0].replace(
779
- /./g,
780
- (c) => WHITESPACE_TEST_REGEX.test(c) ? c : " "
781
- );
782
- return {
783
- type: " ",
784
- // Represent comments as whitespace tokens
785
- match,
786
- // String containing original newlines and spaces for other chars
787
- value: void 0
788
- // Comments don't have a semantic value
789
- };
790
- }
791
- function fNumber(m) {
792
- return {
793
- type: "number",
794
- match: m[0],
795
- // The raw matched number string
796
- value: Number.parseFloat(m[0])
797
- // Convert string to number
798
- };
799
- }
800
- function fKeyword(m) {
801
- let value;
802
- switch (m[0]) {
803
- case "null":
804
- value = null;
805
- break;
806
- case "true":
807
- value = true;
808
- break;
809
- case "false":
810
- value = false;
811
- break;
812
- default:
813
- throw new Error(`Unexpected keyword: ${m[0]}`);
814
- }
815
- return {
816
- type: "atom",
817
- // Use 'atom' type for these literals
818
- match: m[0],
819
- // The raw matched keyword
820
- value
821
- // The corresponding JavaScript value
822
- };
823
- }
824
- function makeTokenSpecs(relaxed) {
825
- function f(type) {
826
- return (m) => {
827
- return { type, match: m[0], value: void 0 };
828
- };
829
- }
830
- let tokenSpecs = [
831
- { re: WHITESPACE_REGEX2, f: f(" ") },
832
- // Whitespace
833
- { re: OBJECT_START_REGEX, f: f("{") },
834
- // Object start
835
- { re: OBJECT_END_REGEX, f: f("}") },
836
- // Object end
837
- { re: ARRAY_START_REGEX, f: f("[") },
838
- // Array start
839
- { re: ARRAY_END_REGEX, f: f("]") },
840
- // Array end
841
- { re: COMMA_REGEX, f: f(",") },
842
- // Comma separator
843
- { re: COLON_REGEX, f: f(":") },
844
- // Key-value separator
845
- { re: KEYWORD_REGEX, f: fKeyword },
846
- // Keywords
847
- // Number: optional sign, digits, optional decimal part, optional exponent
848
- { re: NUMBER_REGEX, f: fNumber },
849
- // String: double-quoted, handles escapes
850
- { re: STRING_DOUBLE_REGEX, f: fStringDouble }
851
- ];
852
- if (relaxed) {
853
- tokenSpecs = tokenSpecs.concat([
854
- // Single-quoted strings
855
- {
856
- re: STRING_SINGLE_REGEX,
857
- f: fStringSingle
858
- },
859
- // Single-line comments (// ...)
860
- { re: COMMENT_SINGLE_REGEX, f: fComment },
861
- // Multi-line comments (/* ... */)
862
- { re: COMMENT_MULTI_REGEX, f: fComment },
863
- // Unquoted identifiers (treated as strings)
864
- // Allows letters, numbers, _, -, +, ., *, ?, !, |, &, %, ^, /, #, \
865
- { re: IDENTIFIER_REGEX, f: fIdentifier }
866
- // Note: The order matters here. Identifiers are checked after keywords/numbers.
867
- ]);
868
- }
869
- return tokenSpecs;
870
- }
871
- var lexer = makeLexer(makeTokenSpecs(true));
872
- var strictLexer = makeLexer(makeTokenSpecs(false));
873
- function previousNWSToken(tokens, index) {
874
- let currentIndex = index;
875
- for (; currentIndex >= 0; currentIndex -= 1) {
876
- if (tokens[currentIndex].type !== " ") {
877
- return currentIndex;
878
- }
879
- }
880
- return;
881
- }
882
- function stripTrailingComma(tokens) {
883
- const res = [];
884
- tokens.forEach((token, index) => {
885
- if (index > 0 && (token.type === "]" || token.type === "}")) {
886
- const prevNWSTokenIndex = previousNWSToken(res, res.length - 1);
887
- if (prevNWSTokenIndex !== void 0 && res[prevNWSTokenIndex].type === ",") {
888
- const preCommaIndex = previousNWSToken(res, prevNWSTokenIndex - 1);
889
- if (preCommaIndex !== void 0 && res[preCommaIndex].type !== "[" && res[preCommaIndex].type !== "{") {
890
- res[prevNWSTokenIndex] = {
891
- type: " ",
892
- match: " ",
893
- // Represent as a single space
894
- value: void 0,
895
- // Whitespace has no value
896
- line: res[prevNWSTokenIndex].line
897
- // Preserve original line number
898
- };
899
- }
900
- }
901
- }
902
- res.push(token);
903
- });
904
- return res;
905
- }
906
- function popToken(tokens, state) {
907
- var _a, _b;
908
- const token = tokens[state.pos];
909
- state.pos += 1;
910
- if (!token) {
911
- const lastLine = tokens.length !== 0 ? (_b = (_a = tokens.at(-1)) == null ? void 0 : _a.line) != null ? _b : 1 : 1;
912
- return { type: "eof", match: "", value: void 0, line: lastLine };
913
- }
914
- return token;
915
- }
916
- function strToken(token) {
917
- switch (token.type) {
918
- case "atom":
919
- case "string":
920
- case "number":
921
- return `${token.type} ${token.match}`;
922
- case "eof":
923
- return "end-of-file";
924
- default:
925
- return `'${token.type}'`;
926
- }
927
- }
928
- function skipColon(tokens, state) {
929
- const colon = popToken(tokens, state);
930
- if (colon.type !== ":") {
931
- const message = `Unexpected token: ${strToken(colon)}, expected ':'`;
932
- if (state.tolerant) {
933
- state.warnings.push({
934
- message,
935
- line: colon.line
936
- });
937
- state.pos -= 1;
938
- } else {
939
- const err = new SyntaxError(message);
940
- err.line = colon.line;
941
- throw err;
942
- }
943
- }
944
- }
945
- function skipPunctuation(tokens, state, valid) {
946
- const punctuation = [",", ":", "]", "}"];
947
- let token = popToken(tokens, state);
948
- while (true) {
949
- if (valid == null ? void 0 : valid.includes(token.type)) {
950
- return token;
951
- }
952
- if (token.type === "eof") {
953
- return token;
954
- }
955
- if (punctuation.includes(token.type)) {
956
- const message = `Unexpected token: ${strToken(
957
- token
958
- )}, expected '[', '{', number, string or atom`;
959
- if (state.tolerant) {
960
- state.warnings.push({
961
- message,
962
- line: token.line
963
- });
964
- token = popToken(tokens, state);
965
- } else {
966
- const err = new SyntaxError(message);
967
- err.line = token.line;
968
- throw err;
969
- }
970
- } else {
971
- return token;
972
- }
973
- }
974
- }
975
- function raiseError(state, token, message) {
976
- if (state.tolerant) {
977
- state.warnings.push({
978
- message,
979
- line: token.line
980
- });
981
- } else {
982
- const err = new SyntaxError(message);
983
- err.line = token.line;
984
- throw err;
985
- }
986
- }
987
- function raiseUnexpected(state, token, expected) {
988
- raiseError(
989
- state,
990
- token,
991
- `Unexpected token: ${strToken(token)}, expected ${expected}`
992
- );
993
- }
994
- function checkDuplicates(state, obj, token) {
995
- const key = String(token.value);
996
- if (!state.duplicate && Object.hasOwn(obj, key)) {
997
- raiseError(state, token, `Duplicate key: ${key}`);
998
- }
999
- }
1000
- function appendPair(state, obj, key, value) {
1001
- const finalValue = state.reviver ? state.reviver(key, value) : value;
1002
- if (finalValue !== void 0) {
1003
- obj[key] = finalValue;
1004
- }
1005
- }
1006
- function parsePair(tokens, state, obj) {
1007
- let token = skipPunctuation(tokens, state, [":", "string", "number", "atom"]);
1008
- let value;
1009
- if (token.type !== "string") {
1010
- raiseUnexpected(state, token, "string key");
1011
- if (state.tolerant) {
1012
- switch (token.type) {
1013
- case ":":
1014
- token = {
1015
- type: "string",
1016
- value: "null",
1017
- match: '"null"',
1018
- line: token.line
1019
- };
1020
- state.pos -= 1;
1021
- break;
1022
- case "number":
1023
- // Use number as string key
1024
- case "atom":
1025
- token = {
1026
- type: "string",
1027
- value: String(token.value),
1028
- match: `"${token.value}"`,
1029
- line: token.line
1030
- };
1031
- break;
1032
- case "[":
1033
- // Assume missing key before an array
1034
- case "{":
1035
- state.pos -= 1;
1036
- value = parseAny(tokens, state);
1037
- checkDuplicates(state, obj, {
1038
- type: "string",
1039
- value: "null",
1040
- match: '"null"',
1041
- line: token.line
1042
- });
1043
- appendPair(state, obj, "null", value);
1044
- return;
1045
- // Finished parsing this "pair"
1046
- case "eof":
1047
- return;
1048
- // Cannot recover
1049
- default:
1050
- return;
1051
- }
1052
- } else {
1053
- return;
1054
- }
1055
- }
1056
- checkDuplicates(state, obj, token);
1057
- const key = String(token.value);
1058
- skipColon(tokens, state);
1059
- value = parseAny(tokens, state);
1060
- appendPair(state, obj, key, value);
1061
- }
1062
- function parseElement(tokens, state, arr) {
1063
- const key = arr.length;
1064
- const value = parseAny(tokens, state);
1065
- arr[key] = state.reviver ? state.reviver(String(key), value) : value;
1066
- }
1067
- function parseObject(tokens, state) {
1068
- const obj = {};
1069
- return parseMany(tokens, state, obj, {
1070
- skip: [":", "}"],
1071
- // Initially skip over colon or closing brace (for empty/tolerant cases)
1072
- elementParser: parsePair,
1073
- // Use parsePair to parse each key-value element
1074
- elementName: "string key",
1075
- // Expected element type for errors
1076
- endSymbol: "}"
1077
- // The closing token for an object
1078
- });
1079
- }
1080
- function parseArray(tokens, state) {
1081
- const arr = [];
1082
- return parseMany(tokens, state, arr, {
1083
- skip: ["]"],
1084
- // Initially skip over closing bracket (for empty/tolerant cases)
1085
- elementParser: parseElement,
1086
- // Use parseElement to parse each array item
1087
- elementName: "json value",
1088
- // Expected element type for errors
1089
- endSymbol: "]"
1090
- // The closing token for an array
1091
- });
1092
- }
1093
- function handleInvalidToken(token, state, opts, result) {
1094
- raiseUnexpected(state, token, `',' or '${opts.endSymbol}'`);
1095
- if (state.tolerant) {
1096
- if (token.type === "eof") {
1097
- return result;
1098
- }
1099
- state.pos -= 1;
1100
- return null;
1101
- }
1102
- return result;
1103
- }
1104
- function handleCommaToken(params) {
1105
- const { token, tokens, state, opts, result } = params;
1106
- const nextToken = tokens[state.pos];
1107
- if (state.tolerant && nextToken && nextToken.type === opts.endSymbol) {
1108
- raiseError(state, token, `Trailing comma before '${opts.endSymbol}'`);
1109
- popToken(tokens, state);
1110
- return result;
1111
- }
1112
- opts.elementParser(tokens, state, result);
1113
- return null;
1114
- }
1115
- function parseManyInitialElement(tokens, state, result, opts) {
1116
- const token = skipPunctuation(tokens, state, opts.skip);
1117
- if (token.type === "eof") {
1118
- raiseUnexpected(state, token, `'${opts.endSymbol}' or ${opts.elementName}`);
1119
- return result;
1120
- }
1121
- if (token.type === opts.endSymbol) {
1122
- return result;
1123
- }
1124
- state.pos -= 1;
1125
- opts.elementParser(tokens, state, result);
1126
- return;
1127
- }
1128
- function parseManyProcessToken(params) {
1129
- const { token, tokens, state, opts, result } = params;
1130
- if (token.type !== opts.endSymbol && token.type !== ",") {
1131
- const handledResult = handleInvalidToken(token, state, opts, result);
1132
- if (handledResult !== null) {
1133
- return handledResult;
1134
- }
1135
- }
1136
- if (token.type === opts.endSymbol) {
1137
- return result;
1138
- }
1139
- if (token.type === ",") {
1140
- const handledResult = handleCommaToken({
1141
- token,
1142
- tokens,
1143
- state,
1144
- opts,
1145
- result
1146
- });
1147
- if (handledResult !== null) {
1148
- return handledResult;
1149
- }
1150
- return;
1151
- }
1152
- opts.elementParser(tokens, state, result);
1153
- return;
1154
- }
1155
- function parseMany(tokens, state, result, opts) {
1156
- const initialResult = parseManyInitialElement(tokens, state, result, opts);
1157
- if (initialResult !== void 0) {
1158
- return initialResult;
1159
- }
1160
- while (true) {
1161
- const token = popToken(tokens, state);
1162
- const processedResult = parseManyProcessToken({
1163
- token,
1164
- tokens,
1165
- state,
1166
- opts,
1167
- result
1168
- });
1169
- if (processedResult !== void 0) {
1170
- return processedResult;
1171
- }
1172
- }
1173
- }
1174
- function endChecks(tokens, state, ret) {
1175
- if (state.pos < tokens.length) {
1176
- if (state.tolerant) {
1177
- skipPunctuation(tokens, state);
1178
- }
1179
- if (state.pos < tokens.length) {
1180
- raiseError(
1181
- state,
1182
- tokens[state.pos],
1183
- `Unexpected token: ${strToken(tokens[state.pos])}, expected end-of-input`
1184
- );
1185
- }
1186
- }
1187
- if (state.tolerant && state.warnings.length > 0) {
1188
- const message = state.warnings.length === 1 ? state.warnings[0].message : `${state.warnings.length} parse warnings`;
1189
- const err = new SyntaxError(message);
1190
- err.line = state.warnings[0].line;
1191
- err.warnings = state.warnings;
1192
- err.obj = ret;
1193
- throw err;
1194
- }
1195
- }
1196
- function parseAny(tokens, state, end = false) {
1197
- const token = skipPunctuation(tokens, state);
1198
- let ret;
1199
- if (token.type === "eof") {
1200
- if (end) {
1201
- raiseUnexpected(state, token, "json value");
1202
- }
1203
- raiseUnexpected(state, token, "json value");
1204
- return;
1205
- }
1206
- switch (token.type) {
1207
- case "{":
1208
- ret = parseObject(tokens, state);
1209
- break;
1210
- case "[":
1211
- ret = parseArray(tokens, state);
1212
- break;
1213
- case "string":
1214
- // String literal
1215
- case "number":
1216
- // Number literal
1217
- case "atom":
1218
- ret = token.value;
1219
- break;
1220
- default:
1221
- raiseUnexpected(state, token, "json value");
1222
- if (state.tolerant) {
1223
- ret = null;
1224
- } else {
1225
- return;
1226
- }
1227
- }
1228
- if (end) {
1229
- ret = state.reviver ? state.reviver("", ret) : ret;
1230
- endChecks(tokens, state, ret);
1231
- }
1232
- return ret;
1233
- }
1234
- function normalizeParseOptions(optsOrReviver) {
1235
- var _a;
1236
- let options = {};
1237
- if (typeof optsOrReviver === "function") {
1238
- options.reviver = optsOrReviver;
1239
- } else if (optsOrReviver !== null && typeof optsOrReviver === "object") {
1240
- options = { ...optsOrReviver };
1241
- } else if (optsOrReviver !== void 0) {
1242
- throw new TypeError(
1243
- "Second argument must be a reviver function or an options object."
1244
- );
1245
- }
1246
- if (options.relaxed === void 0) {
1247
- if (options.warnings === true || options.tolerant === true) {
1248
- options.relaxed = true;
1249
- } else if (options.warnings === false && options.tolerant === false) {
1250
- options.relaxed = false;
1251
- } else {
1252
- options.relaxed = true;
1253
- }
1254
- }
1255
- options.tolerant = options.tolerant || options.warnings;
1256
- options.duplicate = (_a = options.duplicate) != null ? _a : false;
1257
- return options;
1258
- }
1259
- function createParseState(options) {
1260
- var _a, _b;
1261
- return {
1262
- pos: 0,
1263
- reviver: options.reviver,
1264
- tolerant: (_a = options.tolerant) != null ? _a : false,
1265
- duplicate: (_b = options.duplicate) != null ? _b : false,
1266
- warnings: []
1267
- };
1268
- }
1269
- function parseWithCustomParser(text, options) {
1270
- const lexerToUse = options.relaxed ? lexer : strictLexer;
1271
- let tokens = lexerToUse(text);
1272
- if (options.relaxed) {
1273
- tokens = stripTrailingComma(tokens);
1274
- }
1275
- tokens = tokens.filter((token) => token.type !== " ");
1276
- const state = createParseState(options);
1277
- return parseAny(tokens, state, true);
1278
- }
1279
- function parseWithTransform(text, options) {
1280
- let tokens = lexer(text);
1281
- tokens = stripTrailingComma(tokens);
1282
- const newtext = tokens.reduce((str, token) => str + token.match, "");
1283
- return JSON.parse(
1284
- newtext,
1285
- options.reviver
1286
- );
1287
- }
1288
- function parse2(text, optsOrReviver) {
1289
- const options = normalizeParseOptions(optsOrReviver);
1290
- if (!(options.relaxed || options.warnings || options.tolerant) && options.duplicate) {
1291
- return JSON.parse(
1292
- text,
1293
- options.reviver
1294
- );
1295
- }
1296
- if (options.warnings || options.tolerant || !options.duplicate) {
1297
- return parseWithCustomParser(text, options);
1298
- }
1299
- return parseWithTransform(text, options);
1300
- }
1301
-
1302
736
  // src/core/protocols/json-protocol.ts
1303
737
  function processToolCallJson(toolCallJson, fullMatch, processedElements, options) {
1304
738
  var _a, _b;
1305
739
  try {
1306
- const parsedToolCall = parse2(toolCallJson);
740
+ const parsedToolCall = (0, import_rjson.parse)(toolCallJson);
1307
741
  processedElements.push({
1308
742
  type: "tool-call",
1309
743
  toolCallId: generateId(),
@@ -1431,7 +865,7 @@ function emitToolCall(context) {
1431
865
  var _a, _b;
1432
866
  const { state, controller, toolCallStart, toolCallEnd, options } = context;
1433
867
  try {
1434
- const parsedToolCall = parse2(state.currentToolCallJson);
868
+ const parsedToolCall = (0, import_rjson.parse)(state.currentToolCallJson);
1435
869
  closeTextBlock(state, controller);
1436
870
  controller.enqueue({
1437
871
  type: "tool-call",
@@ -1616,6 +1050,9 @@ var jsonProtocol = ({
1616
1050
  });
1617
1051
 
1618
1052
  // src/core/protocols/protocol-interface.ts
1053
+ function isProtocolFactory(protocol) {
1054
+ return typeof protocol === "function";
1055
+ }
1619
1056
  function isTCMProtocolFactory(protocol) {
1620
1057
  return typeof protocol === "function";
1621
1058
  }
@@ -1624,7 +1061,7 @@ function isTCMProtocolFactory(protocol) {
1624
1061
  var import_rxml2 = require("@ai-sdk-tool/rxml");
1625
1062
  var defaultPipelineConfig2 = defaultPipelineConfig;
1626
1063
  var NAME_CHAR_RE2 = /[A-Za-z0-9_:-]/;
1627
- var WHITESPACE_REGEX3 = /\s/;
1064
+ var WHITESPACE_REGEX2 = /\s/;
1628
1065
  function getToolSchema(tools, toolName) {
1629
1066
  var _a;
1630
1067
  return (_a = tools.find((t) => t.name === toolName)) == null ? void 0 : _a.inputSchema;
@@ -1798,7 +1235,7 @@ function consumeClosingTag(text, lt) {
1798
1235
  }
1799
1236
  function consumeOpenTag(text, lt) {
1800
1237
  let p = lt + 1;
1801
- while (p < text.length && WHITESPACE_REGEX3.test(text[p])) {
1238
+ while (p < text.length && WHITESPACE_REGEX2.test(text[p])) {
1802
1239
  p += 1;
1803
1240
  }
1804
1241
  const nameStart = p;
@@ -1811,7 +1248,7 @@ function consumeOpenTag(text, lt) {
1811
1248
  return null;
1812
1249
  }
1813
1250
  let r = q - 1;
1814
- while (r >= nameStart && WHITESPACE_REGEX3.test(text[r])) {
1251
+ while (r >= nameStart && WHITESPACE_REGEX2.test(text[r])) {
1815
1252
  r -= 1;
1816
1253
  }
1817
1254
  const selfClosing = text[r] === "/";
@@ -1840,7 +1277,7 @@ function nextTagToken(text, fromPos) {
1840
1277
  if (next === "/") {
1841
1278
  const closing = consumeClosingTag(text, lt);
1842
1279
  let p = lt + 2;
1843
- while (p < text.length && WHITESPACE_REGEX3.test(text[p])) {
1280
+ while (p < text.length && WHITESPACE_REGEX2.test(text[p])) {
1844
1281
  p += 1;
1845
1282
  }
1846
1283
  const nameStart = p;
@@ -2288,7 +1725,7 @@ var xmlProtocol = (protocolOptions) => {
2288
1725
  // src/core/protocols/yaml-protocol.ts
2289
1726
  var import_yaml = __toESM(require("yaml"), 1);
2290
1727
  var NAME_CHAR_RE3 = /[A-Za-z0-9_:-]/;
2291
- var WHITESPACE_REGEX4 = /\s/;
1728
+ var WHITESPACE_REGEX3 = /\s/;
2292
1729
  var LEADING_WHITESPACE_RE = /^(\s*)/;
2293
1730
  function findClosingTagEnd(text, contentStart, toolName) {
2294
1731
  let pos = contentStart;
@@ -2305,7 +1742,7 @@ function findClosingTagEnd(text, contentStart, toolName) {
2305
1742
  break;
2306
1743
  }
2307
1744
  let p = ltIdx + 2;
2308
- while (p < gtIdx && WHITESPACE_REGEX4.test(text[p])) {
1745
+ while (p < gtIdx && WHITESPACE_REGEX3.test(text[p])) {
2309
1746
  p++;
2310
1747
  }
2311
1748
  const nameStart = p;
@@ -2325,7 +1762,7 @@ function findClosingTagEnd(text, contentStart, toolName) {
2325
1762
  pos = gtIdx === -1 ? text.length : gtIdx + 1;
2326
1763
  } else {
2327
1764
  let p = ltIdx + 1;
2328
- while (p < text.length && WHITESPACE_REGEX4.test(text[p])) {
1765
+ while (p < text.length && WHITESPACE_REGEX3.test(text[p])) {
2329
1766
  p++;
2330
1767
  }
2331
1768
  const nameStart = p;
@@ -2338,7 +1775,7 @@ function findClosingTagEnd(text, contentStart, toolName) {
2338
1775
  break;
2339
1776
  }
2340
1777
  let r = gtIdx - 1;
2341
- while (r >= nameStart && WHITESPACE_REGEX4.test(text[r])) {
1778
+ while (r >= nameStart && WHITESPACE_REGEX3.test(text[r])) {
2342
1779
  r--;
2343
1780
  }
2344
1781
  const selfClosing = text[r] === "/";
@@ -2820,12 +2257,27 @@ function decodeOriginalTools(originalTools) {
2820
2257
  })
2821
2258
  );
2822
2259
  }
2260
+ function extractToolNamesFromOriginalTools(originalTools) {
2261
+ return (originalTools == null ? void 0 : originalTools.map((t) => t.name)) || [];
2262
+ }
2823
2263
  function isToolChoiceActive(params) {
2824
2264
  var _a, _b, _c;
2825
2265
  const toolChoice = (_b = (_a = params.providerOptions) == null ? void 0 : _a.toolCallMiddleware) == null ? void 0 : _b.toolChoice;
2826
2266
  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"));
2827
2267
  }
2828
2268
 
2269
+ // src/core/utils/type-guards.ts
2270
+ function isToolResultPart(content) {
2271
+ if (!content || typeof content !== "object") {
2272
+ return false;
2273
+ }
2274
+ const c = content;
2275
+ return c.type === "tool-result" && typeof c.toolName === "string" && typeof c.toolCallId === "string" && "output" in c;
2276
+ }
2277
+ function hasInputProperty(obj) {
2278
+ return typeof obj === "object" && obj !== null && "input" in obj;
2279
+ }
2280
+
2829
2281
  // src/generate-handler.ts
2830
2282
  var import_provider_utils = require("@ai-sdk/provider-utils");
2831
2283
  var import_rxml3 = require("@ai-sdk-tool/rxml");