@ai-sdk-tool/parser 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -43,32 +43,35 @@ __export(src_exports, {
43
43
  escapeRegExp: () => escapeRegExp2,
44
44
  extractOnErrorOption: () => extractOnErrorOption,
45
45
  extractToolNamesFromOriginalTools: () => extractToolNamesFromOriginalTools,
46
- gemmaToolMiddleware: () => gemmaToolMiddleware,
47
46
  getDebugLevel: () => getDebugLevel,
48
47
  getPotentialStartIndex: () => getPotentialStartIndex,
49
48
  hasInputProperty: () => hasInputProperty,
50
49
  hermesToolMiddleware: () => hermesToolMiddleware,
51
50
  isProtocolFactory: () => isProtocolFactory,
51
+ isTCMProtocolFactory: () => isTCMProtocolFactory,
52
52
  isToolCallContent: () => isToolCallContent,
53
53
  isToolChoiceActive: () => isToolChoiceActive,
54
54
  isToolResultPart: () => isToolResultPart,
55
- jsonMixProtocol: () => jsonMixProtocol,
55
+ jsonProtocol: () => jsonProtocol,
56
56
  logParseFailure: () => logParseFailure,
57
57
  logParsedChunk: () => logParsedChunk,
58
58
  logParsedSummary: () => logParsedSummary,
59
59
  logRawChunk: () => logRawChunk,
60
60
  mergePipelineConfigs: () => mergePipelineConfigs,
61
- morphXmlProtocol: () => morphXmlProtocol,
62
- morphXmlToolMiddleware: () => morphXmlToolMiddleware,
63
61
  normalizeCloseTagsHeuristic: () => normalizeCloseTagsHeuristic,
64
- orchestratorSystemPromptTemplate: () => orchestratorSystemPromptTemplate,
65
- orchestratorToolMiddleware: () => orchestratorToolMiddleware,
66
62
  originalToolsSchema: () => originalToolsSchema,
67
63
  parse: () => parse2,
68
64
  repairAgainstSchemaHeuristic: () => repairAgainstSchemaHeuristic,
69
65
  stringify: () => stringify,
66
+ toolChoiceStream: () => toolChoiceStream,
70
67
  transform: () => transform,
71
- yamlXmlProtocol: () => yamlXmlProtocol
68
+ transformParams: () => transformParams,
69
+ wrapGenerate: () => wrapGenerate,
70
+ wrapStream: () => wrapStream,
71
+ xmlProtocol: () => xmlProtocol,
72
+ xmlToolMiddleware: () => xmlToolMiddleware,
73
+ yamlProtocol: () => yamlProtocol,
74
+ yamlToolMiddleware: () => yamlToolMiddleware
72
75
  });
73
76
  module.exports = __toCommonJS(src_exports);
74
77
 
@@ -1397,7 +1400,7 @@ function stringify(obj) {
1397
1400
  return "null";
1398
1401
  }
1399
1402
 
1400
- // src/core/protocols/json-mix-protocol.ts
1403
+ // src/core/protocols/json-protocol.ts
1401
1404
  function processToolCallJson(toolCallJson, fullMatch, processedElements, options) {
1402
1405
  var _a, _b;
1403
1406
  try {
@@ -1457,7 +1460,6 @@ function flushBuffer(state, controller, toolCallStart) {
1457
1460
  controller.enqueue({
1458
1461
  type: "text-delta",
1459
1462
  id: state.currentTextId,
1460
- textDelta: deltaContent,
1461
1463
  delta: deltaContent
1462
1464
  });
1463
1465
  state.buffer = "";
@@ -1490,7 +1492,6 @@ function emitIncompleteToolCall(state, controller, toolCallStart) {
1490
1492
  controller.enqueue({
1491
1493
  type: "text-delta",
1492
1494
  id: errorId,
1493
- textDelta: errorContent,
1494
1495
  delta: errorContent
1495
1496
  });
1496
1497
  controller.enqueue({
@@ -1523,7 +1524,6 @@ function publishText(text, state, controller) {
1523
1524
  controller.enqueue({
1524
1525
  type: "text-delta",
1525
1526
  id: state.currentTextId,
1526
- textDelta: text,
1527
1527
  delta: text
1528
1528
  });
1529
1529
  }
@@ -1556,7 +1556,6 @@ function emitToolCall(context) {
1556
1556
  controller.enqueue({
1557
1557
  type: "text-delta",
1558
1558
  id: errorId,
1559
- textDelta: errorContent,
1560
1559
  delta: errorContent
1561
1560
  });
1562
1561
  controller.enqueue({
@@ -1616,19 +1615,15 @@ function handlePartialTag(state, controller, toolCallStart) {
1616
1615
  state.buffer = "";
1617
1616
  }
1618
1617
  }
1619
- var jsonMixProtocol = ({
1618
+ var jsonProtocol = ({
1620
1619
  toolCallStart = "<tool_call>",
1621
- toolCallEnd = "</tool_call>",
1622
- toolResponseStart = "<tool_response>",
1623
- toolResponseEnd = "</tool_response>"
1620
+ toolCallEnd = "</tool_call>"
1624
1621
  } = {}) => ({
1625
- formatTools({ tools, toolSystemPromptTemplate }) {
1626
- const toolsForPrompt = (tools || []).filter((tool) => tool.type === "function").map((tool) => ({
1627
- name: tool.name,
1628
- description: tool.type === "function" && typeof tool.description === "string" ? tool.description : void 0,
1629
- parameters: tool.inputSchema
1630
- }));
1631
- return toolSystemPromptTemplate(JSON.stringify(toolsForPrompt));
1622
+ formatTools({
1623
+ tools,
1624
+ toolSystemPromptTemplate
1625
+ }) {
1626
+ return toolSystemPromptTemplate(tools || []);
1632
1627
  },
1633
1628
  formatToolCall(toolCall) {
1634
1629
  let args = {};
@@ -1642,13 +1637,10 @@ var jsonMixProtocol = ({
1642
1637
  arguments: args
1643
1638
  })}${toolCallEnd}`;
1644
1639
  },
1645
- formatToolResponse(toolResult) {
1646
- return `${toolResponseStart}${JSON.stringify({
1647
- toolName: toolResult.toolName,
1648
- result: toolResult.result
1649
- })}${toolResponseEnd}`;
1650
- },
1651
- parseGeneratedText({ text, options }) {
1640
+ parseGeneratedText({
1641
+ text,
1642
+ options
1643
+ }) {
1652
1644
  const startEsc = escapeRegExp2(toolCallStart);
1653
1645
  const endEsc = escapeRegExp2(toolCallEnd);
1654
1646
  const toolCallRegex = new RegExp(
@@ -1674,7 +1666,9 @@ var jsonMixProtocol = ({
1674
1666
  }
1675
1667
  return processedElements;
1676
1668
  },
1677
- createStreamParser({ options }) {
1669
+ createStreamParser({
1670
+ options
1671
+ }) {
1678
1672
  const state = {
1679
1673
  isInsideToolCall: false,
1680
1674
  buffer: "",
@@ -1684,7 +1678,7 @@ var jsonMixProtocol = ({
1684
1678
  };
1685
1679
  return new TransformStream({
1686
1680
  transform(chunk, controller) {
1687
- var _a, _b;
1681
+ var _a;
1688
1682
  if (chunk.type === "finish") {
1689
1683
  handleFinishChunk(state, controller, toolCallStart, chunk);
1690
1684
  return;
@@ -1693,7 +1687,7 @@ var jsonMixProtocol = ({
1693
1687
  controller.enqueue(chunk);
1694
1688
  return;
1695
1689
  }
1696
- const textContent = (_b = (_a = chunk.textDelta) != null ? _a : chunk.delta) != null ? _b : "";
1690
+ const textContent = (_a = chunk.delta) != null ? _a : "";
1697
1691
  state.buffer += textContent;
1698
1692
  processBufferTags({
1699
1693
  state,
@@ -1720,7 +1714,15 @@ var jsonMixProtocol = ({
1720
1714
  }
1721
1715
  });
1722
1716
 
1723
- // src/core/protocols/morph-xml-protocol.ts
1717
+ // src/core/protocols/protocol-interface.ts
1718
+ function isProtocolFactory(protocol) {
1719
+ return typeof protocol === "function";
1720
+ }
1721
+ function isTCMProtocolFactory(protocol) {
1722
+ return typeof protocol === "function";
1723
+ }
1724
+
1725
+ // src/core/protocols/xml-protocol.ts
1724
1726
  var import_rxml2 = require("@ai-sdk-tool/rxml");
1725
1727
  var defaultPipelineConfig2 = defaultPipelineConfig;
1726
1728
  var NAME_CHAR_RE2 = /[A-Za-z0-9_:-]/;
@@ -2055,7 +2057,6 @@ function createFlushTextHandler(getCurrentTextId, setCurrentTextId, getHasEmitte
2055
2057
  controller.enqueue({
2056
2058
  type: "text-delta",
2057
2059
  id: getCurrentTextId(),
2058
- textDelta: content,
2059
2060
  delta: content
2060
2061
  });
2061
2062
  }
@@ -2217,7 +2218,7 @@ function createProcessBufferHandler(getBuffer, setBuffer, getCurrentToolCall, se
2217
2218
  }
2218
2219
  };
2219
2220
  }
2220
- var morphXmlProtocol = (protocolOptions) => {
2221
+ var xmlProtocol = (protocolOptions) => {
2221
2222
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2222
2223
  let pipelineConfig = protocolOptions == null ? void 0 : protocolOptions.pipeline;
2223
2224
  const maxReparses = protocolOptions == null ? void 0 : protocolOptions.maxReparses;
@@ -2257,12 +2258,7 @@ var morphXmlProtocol = (protocolOptions) => {
2257
2258
  }
2258
2259
  return {
2259
2260
  formatTools({ tools, toolSystemPromptTemplate }) {
2260
- const toolsForPrompt = (tools || []).map((tool) => ({
2261
- name: tool.name,
2262
- description: tool.description,
2263
- parameters: (0, import_rxml2.unwrapJsonSchema)(tool.inputSchema)
2264
- }));
2265
- return toolSystemPromptTemplate(JSON.stringify(toolsForPrompt));
2261
+ return toolSystemPromptTemplate(tools || []);
2266
2262
  },
2267
2263
  formatToolCall(toolCall) {
2268
2264
  let args = {};
@@ -2276,21 +2272,6 @@ var morphXmlProtocol = (protocolOptions) => {
2276
2272
  format: false
2277
2273
  });
2278
2274
  },
2279
- formatToolResponse(toolResult) {
2280
- let result = toolResult.result;
2281
- if (result && typeof result === "object" && "type" in result && result.type === "json" && "value" in result) {
2282
- result = result.value;
2283
- }
2284
- const xml = (0, import_rxml2.stringify)(
2285
- "tool_response",
2286
- {
2287
- tool_name: toolResult.toolName,
2288
- result
2289
- },
2290
- { declaration: false }
2291
- );
2292
- return xml;
2293
- },
2294
2275
  parseGeneratedText({ text, tools, options }) {
2295
2276
  const toolNames = tools.map((t) => t.name).filter(Boolean);
2296
2277
  if (toolNames.length === 0) {
@@ -2359,7 +2340,7 @@ var morphXmlProtocol = (protocolOptions) => {
2359
2340
  );
2360
2341
  return new TransformStream({
2361
2342
  transform(chunk, controller) {
2362
- var _a2, _b2;
2343
+ var _a2;
2363
2344
  if (chunk.type !== "text-delta") {
2364
2345
  if (buffer) {
2365
2346
  flushText(controller, buffer);
@@ -2368,7 +2349,7 @@ var morphXmlProtocol = (protocolOptions) => {
2368
2349
  controller.enqueue(chunk);
2369
2350
  return;
2370
2351
  }
2371
- const textContent = (_b2 = (_a2 = chunk.textDelta) != null ? _a2 : chunk.delta) != null ? _b2 : "";
2352
+ const textContent = (_a2 = chunk.delta) != null ? _a2 : "";
2372
2353
  buffer += textContent;
2373
2354
  processBuffer(controller);
2374
2355
  },
@@ -2403,13 +2384,7 @@ var morphXmlProtocol = (protocolOptions) => {
2403
2384
  };
2404
2385
  };
2405
2386
 
2406
- // src/core/protocols/tool-call-protocol.ts
2407
- function isProtocolFactory(protocol) {
2408
- return typeof protocol === "function";
2409
- }
2410
-
2411
- // src/core/protocols/yaml-xml-protocol.ts
2412
- var import_rxml3 = require("@ai-sdk-tool/rxml");
2387
+ // src/core/protocols/yaml-protocol.ts
2413
2388
  var import_yaml = __toESM(require("yaml"), 1);
2414
2389
  var NAME_CHAR_RE3 = /[A-Za-z0-9_:-]/;
2415
2390
  var WHITESPACE_REGEX4 = /\s/;
@@ -2630,7 +2605,6 @@ function createFlushTextHandler2(getCurrentTextId, setCurrentTextId, getHasEmitt
2630
2605
  controller.enqueue({
2631
2606
  type: "text-delta",
2632
2607
  id: getCurrentTextId(),
2633
- textDelta: content,
2634
2608
  delta: content
2635
2609
  });
2636
2610
  }
@@ -2678,15 +2652,10 @@ function findEarliestToolTag2(buffer, toolNames) {
2678
2652
  tagLength: bestTagLength
2679
2653
  };
2680
2654
  }
2681
- var yamlXmlProtocol = (_protocolOptions) => {
2655
+ var yamlProtocol = (_protocolOptions) => {
2682
2656
  return {
2683
2657
  formatTools({ tools, toolSystemPromptTemplate }) {
2684
- const toolsForPrompt = (tools || []).map((tool) => ({
2685
- name: tool.name,
2686
- description: tool.description,
2687
- parameters: (0, import_rxml3.unwrapJsonSchema)(tool.inputSchema)
2688
- }));
2689
- return toolSystemPromptTemplate(JSON.stringify(toolsForPrompt));
2658
+ return toolSystemPromptTemplate(tools || []);
2690
2659
  },
2691
2660
  formatToolCall(toolCall) {
2692
2661
  let args = {};
@@ -2699,21 +2668,6 @@ var yamlXmlProtocol = (_protocolOptions) => {
2699
2668
  return `<${toolCall.toolName}>
2700
2669
  ${yamlContent}</${toolCall.toolName}>`;
2701
2670
  },
2702
- formatToolResponse(toolResult) {
2703
- let result = toolResult.result;
2704
- if (result && typeof result === "object" && "type" in result && result.type === "json" && "value" in result) {
2705
- result = result.value;
2706
- }
2707
- const xml = (0, import_rxml3.stringify)(
2708
- "tool_response",
2709
- {
2710
- tool_name: toolResult.toolName,
2711
- result
2712
- },
2713
- { declaration: false }
2714
- );
2715
- return xml;
2716
- },
2717
2671
  parseGeneratedText({ text, tools, options }) {
2718
2672
  const toolNames = tools.map((t) => t.name).filter(Boolean);
2719
2673
  if (toolNames.length === 0) {
@@ -2827,7 +2781,7 @@ ${yamlContent}</${toolCall.toolName}>`;
2827
2781
  };
2828
2782
  return new TransformStream({
2829
2783
  transform(chunk, controller) {
2830
- var _a, _b;
2784
+ var _a;
2831
2785
  if (chunk.type !== "text-delta") {
2832
2786
  if (buffer) {
2833
2787
  flushText(controller, buffer);
@@ -2836,7 +2790,7 @@ ${yamlContent}</${toolCall.toolName}>`;
2836
2790
  controller.enqueue(chunk);
2837
2791
  return;
2838
2792
  }
2839
- const textContent = (_b = (_a = chunk.textDelta) != null ? _a : chunk.delta) != null ? _b : "";
2793
+ const textContent = (_a = chunk.delta) != null ? _a : "";
2840
2794
  buffer += textContent;
2841
2795
  processBuffer(controller);
2842
2796
  },
@@ -2872,44 +2826,6 @@ ${yamlContent}</${toolCall.toolName}>`;
2872
2826
  }
2873
2827
  };
2874
2828
  };
2875
- function orchestratorSystemPromptTemplate(tools, includeMultilineExample = true) {
2876
- const multilineExample = includeMultilineExample ? `
2877
-
2878
- For multiline values, use YAML's literal block syntax:
2879
- <write_file>
2880
- file_path: /tmp/example.txt
2881
- contents: |
2882
- First line
2883
- Second line
2884
- Third line
2885
- </write_file>` : "";
2886
- return `# Tools
2887
-
2888
- You may call one or more functions to assist with the user query.
2889
-
2890
- You are provided with function signatures within <tools></tools> XML tags:
2891
- <tools>${tools}</tools>
2892
-
2893
- # Format
2894
-
2895
- Use exactly one XML element whose tag name is the function name.
2896
- Inside the XML element, specify parameters using YAML syntax (key: value pairs).
2897
-
2898
- # Example
2899
- <get_weather>
2900
- location: New York
2901
- unit: celsius
2902
- </get_weather>${multilineExample}
2903
-
2904
- # Rules
2905
- - Parameter names and values must follow the schema exactly.
2906
- - Use proper YAML syntax for values (strings, numbers, booleans, arrays, objects).
2907
- - Each required parameter must appear once.
2908
- - Do not add functions or parameters not in the schema.
2909
- - After calling a tool, you will receive a response. Use this result to answer the user.
2910
- - Do NOT ask clarifying questions. Use reasonable defaults for optional parameters.
2911
- - If a task requires multiple function calls, make ALL of them at once.`;
2912
- }
2913
2829
 
2914
2830
  // src/core/utils/dynamic-tool-schema.ts
2915
2831
  function createDynamicIfThenElseSchema(tools) {
@@ -3023,9 +2939,9 @@ function hasInputProperty(obj) {
3023
2939
  return typeof obj === "object" && obj !== null && "input" in obj;
3024
2940
  }
3025
2941
 
3026
- // src/v6/generate-handler.ts
2942
+ // src/generate-handler.ts
3027
2943
  var import_provider_utils = require("@ai-sdk/provider-utils");
3028
- var import_rxml4 = require("@ai-sdk-tool/rxml");
2944
+ var import_rxml3 = require("@ai-sdk-tool/rxml");
3029
2945
  function parseToolChoiceJson(text, providerOptions) {
3030
2946
  var _a;
3031
2947
  try {
@@ -3188,80 +3104,207 @@ function fixToolCallWithSchema(part, tools) {
3188
3104
  args = tc.input;
3189
3105
  }
3190
3106
  const schema = (_a = tools.find((t) => t.name === tc.toolName)) == null ? void 0 : _a.inputSchema;
3191
- const coerced = (0, import_rxml4.coerceBySchema)(args, schema);
3107
+ const coerced = (0, import_rxml3.coerceBySchema)(args, schema);
3192
3108
  return {
3193
3109
  ...part,
3194
3110
  input: JSON.stringify(coerced != null ? coerced : {})
3195
3111
  };
3196
3112
  }
3197
3113
 
3198
- // src/v6/stream-handler.ts
3199
- var import_provider_utils2 = require("@ai-sdk/provider-utils");
3200
- function mapCorePartToV3(part) {
3201
- switch (part.type) {
3202
- case "text-delta":
3203
- return {
3204
- type: "text-delta",
3205
- id: part.id || (0, import_provider_utils2.generateId)(),
3206
- delta: part.textDelta
3207
- };
3208
- case "tool-call":
3209
- return {
3210
- type: "tool-call",
3211
- toolCallId: part.toolCallId,
3212
- toolName: part.toolName,
3213
- input: part.input
3214
- };
3215
- case "tool-call-delta":
3216
- return {
3217
- type: "tool-call-delta",
3218
- toolCallId: part.toolCallId,
3219
- toolName: part.toolName,
3220
- argsTextDelta: part.argsTextDelta
3221
- };
3222
- case "finish":
3223
- return {
3224
- type: "finish",
3225
- finishReason: part.finishReason,
3226
- usage: part.usage
3227
- };
3228
- case "error":
3229
- return {
3230
- type: "error",
3231
- error: part.error
3232
- };
3233
- default:
3234
- return part;
3114
+ // src/core/prompts/hermes-system-prompt.ts
3115
+ function hermesSystemPromptTemplate(tools) {
3116
+ const toolsJson = JSON.stringify(tools);
3117
+ return `You are a function calling AI model.
3118
+ You are provided with function signatures within <tools></tools> XML tags.
3119
+ You may call one or more functions to assist with the user query.
3120
+ Don't make assumptions about what values to plug into functions.
3121
+ Here are the available tools: <tools>${toolsJson}</tools>
3122
+ 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"]}
3123
+ For each function call return a json object with function name and arguments within <tool_call></tool_call> XML tags as follows:
3124
+ <tool_call>
3125
+ {"name": "<function-name>", "arguments": <args-dict>}
3126
+ </tool_call>`;
3127
+ }
3128
+
3129
+ // src/core/prompts/tool-response.ts
3130
+ function unwrapToolResult(result) {
3131
+ var _a, _b;
3132
+ switch (result.type) {
3133
+ case "text":
3134
+ return (_a = result.value) != null ? _a : "";
3135
+ case "json":
3136
+ return result.value;
3137
+ case "execution-denied": {
3138
+ const reason = result.reason;
3139
+ return reason ? `[Execution Denied: ${reason}]` : "[Execution Denied]";
3140
+ }
3141
+ case "error-text":
3142
+ return `[Error: ${(_b = result.value) != null ? _b : ""}]`;
3143
+ case "error-json":
3144
+ return `[Error: ${JSON.stringify(result.value)}]`;
3145
+ case "content": {
3146
+ return result.value.map((part) => {
3147
+ var _a2;
3148
+ const contentPart = part;
3149
+ switch (contentPart.type) {
3150
+ case "text":
3151
+ return (_a2 = contentPart.text) != null ? _a2 : "";
3152
+ case "image-data":
3153
+ return `[Image: ${contentPart.mediaType}]`;
3154
+ case "image-url":
3155
+ return `[Image URL: ${contentPart.url}]`;
3156
+ case "image-file-id": {
3157
+ const fileId = contentPart.fileId;
3158
+ const displayId = typeof fileId === "string" ? fileId : JSON.stringify(fileId);
3159
+ return `[Image ID: ${displayId}]`;
3160
+ }
3161
+ case "file-data": {
3162
+ const filePart = contentPart;
3163
+ if (filePart.filename) {
3164
+ return `[File: ${filePart.filename} (${filePart.mediaType})]`;
3165
+ }
3166
+ return `[File: ${filePart.mediaType}]`;
3167
+ }
3168
+ case "file-url":
3169
+ return `[File URL: ${contentPart.url}]`;
3170
+ case "file-id": {
3171
+ const fileId = contentPart.fileId;
3172
+ const displayId = typeof fileId === "string" ? fileId : JSON.stringify(fileId);
3173
+ return `[File ID: ${displayId}]`;
3174
+ }
3175
+ case "media":
3176
+ return `[Media: ${contentPart.mediaType}]`;
3177
+ case "custom":
3178
+ return "[Custom content]";
3179
+ default:
3180
+ return "[Unknown content]";
3181
+ }
3182
+ }).join("\n");
3183
+ }
3184
+ default: {
3185
+ const _exhaustive = result;
3186
+ return _exhaustive;
3187
+ }
3235
3188
  }
3236
3189
  }
3237
- function mapV3PartToCore(part) {
3238
- const p = part;
3239
- switch (p.type) {
3240
- case "text-delta":
3241
- return {
3242
- type: "text-delta",
3243
- id: p.id,
3244
- textDelta: p.delta || p.textDelta || ""
3245
- };
3246
- case "tool-call":
3247
- return {
3248
- type: "tool-call",
3249
- toolCallId: p.toolCallId,
3250
- toolName: p.toolName,
3251
- input: p.input
3252
- };
3253
- case "finish": {
3254
- const finishReason = p.finishReason;
3255
- return {
3256
- type: "finish",
3257
- finishReason: (typeof finishReason === "object" ? finishReason == null ? void 0 : finishReason.unified : finishReason) || "stop",
3258
- usage: p.usage
3259
- };
3190
+ function formatToolResponseAsJsonInXml(toolResult) {
3191
+ const unwrappedResult = unwrapToolResult(toolResult.output);
3192
+ return `<tool_response>${JSON.stringify({
3193
+ toolName: toolResult.toolName,
3194
+ result: unwrappedResult
3195
+ })}</tool_response>`;
3196
+ }
3197
+ function formatToolResponseAsXml(toolResult) {
3198
+ const unwrappedResult = unwrapToolResult(toolResult.output);
3199
+ const toolNameXml = `<tool_name>${toolResult.toolName}</tool_name>`;
3200
+ const resultLines = formatXmlNode("result", unwrappedResult, 1);
3201
+ return [
3202
+ "<tool_response>",
3203
+ ` ${toolNameXml}`,
3204
+ ...resultLines,
3205
+ "</tool_response>"
3206
+ ].join("\n");
3207
+ }
3208
+ function formatXmlNode(tagName, value, depth) {
3209
+ const indent = " ".repeat(depth);
3210
+ if (value === null || value === void 0) {
3211
+ return [`${indent}<${tagName}></${tagName}>`];
3212
+ }
3213
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
3214
+ return [`${indent}<${tagName}>${String(value)}</${tagName}>`];
3215
+ }
3216
+ if (Array.isArray(value)) {
3217
+ if (value.length === 0) {
3218
+ return [`${indent}<${tagName}></${tagName}>`];
3260
3219
  }
3261
- default:
3262
- return p;
3220
+ const lines2 = [`${indent}<${tagName}>`];
3221
+ for (const item of value) {
3222
+ lines2.push(...formatXmlNode("item", item, depth + 1));
3223
+ }
3224
+ lines2.push(`${indent}</${tagName}>`);
3225
+ return lines2;
3226
+ }
3227
+ const entries = Object.entries(value);
3228
+ if (entries.length === 0) {
3229
+ return [`${indent}<${tagName}></${tagName}>`];
3263
3230
  }
3231
+ const lines = [`${indent}<${tagName}>`];
3232
+ for (const [key, entryValue] of entries) {
3233
+ lines.push(...formatXmlNode(key, entryValue, depth + 1));
3234
+ }
3235
+ lines.push(`${indent}</${tagName}>`);
3236
+ return lines;
3264
3237
  }
3238
+
3239
+ // src/core/prompts/xml-system-prompt.ts
3240
+ function xmlSystemPromptTemplate(tools) {
3241
+ const toolsJson = JSON.stringify(tools);
3242
+ return `# Tools
3243
+
3244
+ You may call one or more functions to assist with the user query.
3245
+
3246
+ You are provided with function signatures within <tools></tools> XML tags:
3247
+ <tools>${toolsJson}</tools>
3248
+
3249
+ # Rules
3250
+ - Use exactly one XML element whose tag name is the function name.
3251
+ - Put each parameter as a child element.
3252
+ - Values must follow the schema exactly (numbers, arrays, objects, enums \u2192 copy as-is).
3253
+ - Do not add or remove functions or parameters.
3254
+ - Each required parameter must appear once.
3255
+ - Output nothing before or after the function call.
3256
+ - After calling a tool, you will receive a response in the format: <tool_response><tool_name>NAME</tool_name><result>RESULT</result></tool_response>. Use this result to answer the user.
3257
+
3258
+ # Example
3259
+ <get_weather>
3260
+ <location>New York</location>
3261
+ <unit>celsius</unit>
3262
+ </get_weather>`;
3263
+ }
3264
+
3265
+ // src/core/prompts/yaml-system-prompt.ts
3266
+ function yamlSystemPromptTemplate(tools, includeMultilineExample = true) {
3267
+ const toolsJson = JSON.stringify(tools);
3268
+ const multilineExample = includeMultilineExample ? `
3269
+
3270
+ For multiline values, use YAML's literal block syntax:
3271
+ <write_file>
3272
+ file_path: /tmp/example.txt
3273
+ contents: |
3274
+ First line
3275
+ Second line
3276
+ Third line
3277
+ </write_file>` : "";
3278
+ return `# Tools
3279
+
3280
+ You may call one or more functions to assist with the user query.
3281
+
3282
+ You are provided with function signatures within <tools></tools> XML tags:
3283
+ <tools>${toolsJson}</tools>
3284
+
3285
+ # Format
3286
+
3287
+ Use exactly one XML element whose tag name is the function name.
3288
+ Inside the XML element, specify parameters using YAML syntax (key: value pairs).
3289
+
3290
+ # Example
3291
+ <get_weather>
3292
+ location: New York
3293
+ unit: celsius
3294
+ </get_weather>${multilineExample}
3295
+
3296
+ # Rules
3297
+ - Parameter names and values must follow the schema exactly.
3298
+ - Use proper YAML syntax for values (strings, numbers, booleans, arrays, objects).
3299
+ - Each required parameter must appear once.
3300
+ - Do not add functions or parameters not in the schema.
3301
+ - After calling a tool, you will receive a response. Use this result to answer the user.
3302
+ - Do NOT ask clarifying questions. Use reasonable defaults for optional parameters.
3303
+ - If a task requires multiple function calls, make ALL of them at once.`;
3304
+ }
3305
+
3306
+ // src/stream-handler.ts
3307
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
3265
3308
  async function wrapStream({
3266
3309
  protocol,
3267
3310
  doStream,
@@ -3285,23 +3328,24 @@ async function wrapStream({
3285
3328
  ...((_c = params.providerOptions) == null ? void 0 : _c.toolCallMiddleware) || {}
3286
3329
  };
3287
3330
  const coreStream = stream.pipeThrough(
3288
- new TransformStream({
3289
- transform(part, controller) {
3290
- if (debugLevel === "stream") {
3291
- logRawChunk(part);
3331
+ new TransformStream(
3332
+ {
3333
+ transform(part, controller) {
3334
+ if (debugLevel === "stream") {
3335
+ logRawChunk(part);
3336
+ }
3337
+ controller.enqueue(part);
3292
3338
  }
3293
- controller.enqueue(mapV3PartToCore(part));
3294
3339
  }
3295
- })
3340
+ )
3296
3341
  ).pipeThrough(protocol.createStreamParser({ tools, options }));
3297
3342
  const v3Stream = coreStream.pipeThrough(
3298
3343
  new TransformStream({
3299
3344
  transform(part, controller) {
3300
- const v3Part = mapCorePartToV3(part);
3301
3345
  if (debugLevel === "stream") {
3302
- logParsedChunk(v3Part);
3346
+ logParsedChunk(part);
3303
3347
  }
3304
- controller.enqueue(v3Part);
3348
+ controller.enqueue(part);
3305
3349
  }
3306
3350
  })
3307
3351
  );
@@ -3358,7 +3402,7 @@ async function toolChoiceStream({
3358
3402
  };
3359
3403
  }
3360
3404
 
3361
- // src/v6/transform-handler.ts
3405
+ // src/transform-handler.ts
3362
3406
  function buildFinalPrompt(systemPrompt, processedPrompt, placement) {
3363
3407
  const systemIndex = processedPrompt.findIndex((m) => m.role === "system");
3364
3408
  if (systemIndex !== -1) {
@@ -3501,10 +3545,11 @@ function transformParams({
3501
3545
  params,
3502
3546
  protocol,
3503
3547
  toolSystemPromptTemplate,
3548
+ toolResponsePromptTemplate,
3504
3549
  placement = "first"
3505
3550
  }) {
3506
- var _a, _b, _c, _d, _e;
3507
- const resolvedProtocol = isProtocolFactory(protocol) ? protocol() : protocol;
3551
+ var _a, _b, _c, _d;
3552
+ const resolvedProtocol = isTCMProtocolFactory(protocol) ? protocol() : protocol;
3508
3553
  const functionTools = ((_a = params.tools) != null ? _a : []).filter(
3509
3554
  (t) => t.type === "function"
3510
3555
  );
@@ -3512,9 +3557,18 @@ function transformParams({
3512
3557
  tools: functionTools,
3513
3558
  toolSystemPromptTemplate
3514
3559
  });
3560
+ let normalizedPrompt;
3561
+ if (Array.isArray(params.prompt)) {
3562
+ normalizedPrompt = params.prompt;
3563
+ } else if (params.prompt) {
3564
+ normalizedPrompt = [params.prompt];
3565
+ } else {
3566
+ normalizedPrompt = [];
3567
+ }
3515
3568
  const processedPrompt = convertToolPrompt(
3516
- (_b = params.prompt) != null ? _b : [],
3569
+ normalizedPrompt,
3517
3570
  resolvedProtocol,
3571
+ toolResponsePromptTemplate,
3518
3572
  extractOnErrorOption(params.providerOptions)
3519
3573
  );
3520
3574
  const finalPrompt = buildFinalPrompt(
@@ -3527,15 +3581,15 @@ function transformParams({
3527
3581
  finalPrompt,
3528
3582
  functionTools
3529
3583
  );
3530
- if (((_c = params.toolChoice) == null ? void 0 : _c.type) === "none") {
3584
+ if (((_b = params.toolChoice) == null ? void 0 : _b.type) === "none") {
3531
3585
  throw new Error(
3532
3586
  "The 'none' toolChoice type is not supported by this middleware. Please use 'auto', 'required', or specify a tool name."
3533
3587
  );
3534
3588
  }
3535
- if (((_d = params.toolChoice) == null ? void 0 : _d.type) === "tool") {
3589
+ if (((_c = params.toolChoice) == null ? void 0 : _c.type) === "tool") {
3536
3590
  return handleToolChoiceTool(params, baseReturnParams);
3537
3591
  }
3538
- if (((_e = params.toolChoice) == null ? void 0 : _e.type) === "required") {
3592
+ if (((_d = params.toolChoice) == null ? void 0 : _d.type) === "required") {
3539
3593
  return handleToolChoiceRequired(params, baseReturnParams, functionTools);
3540
3594
  }
3541
3595
  return baseReturnParams;
@@ -3574,25 +3628,28 @@ function processAssistantContent(content, resolvedProtocol, providerOptions) {
3574
3628
  }
3575
3629
  ] : newContent;
3576
3630
  }
3577
- function processToolMessage(content, resolvedProtocol) {
3631
+ function formatApprovalResponse(part) {
3632
+ const status = part.approved ? "Approved" : "Denied";
3633
+ const reason = part.reason ? `: ${part.reason}` : "";
3634
+ return `[Tool Approval ${status}${reason}]`;
3635
+ }
3636
+ function processToolMessage(toolResults, approvalResponses, toolResponsePromptTemplate) {
3637
+ const resultTexts = toolResults.map((toolResult) => {
3638
+ return toolResponsePromptTemplate(toolResult);
3639
+ });
3640
+ const approvalTexts = approvalResponses.map(formatApprovalResponse);
3641
+ const allTexts = [...resultTexts, ...approvalTexts];
3578
3642
  return {
3579
3643
  role: "user",
3580
3644
  content: [
3581
3645
  {
3582
3646
  type: "text",
3583
- text: content.map((toolResult) => {
3584
- var _a, _b;
3585
- const tr = toolResult;
3586
- return resolvedProtocol.formatToolResponse({
3587
- ...toolResult,
3588
- result: (_b = (_a = tr.result) != null ? _a : tr.content) != null ? _b : tr.output
3589
- });
3590
- }).join("\n")
3647
+ text: allTexts.join("\n")
3591
3648
  }
3592
3649
  ]
3593
3650
  };
3594
3651
  }
3595
- function processMessage(message, resolvedProtocol, providerOptions) {
3652
+ function processMessage(message, resolvedProtocol, providerOptions, toolResponsePromptTemplate) {
3596
3653
  if (message.role === "assistant") {
3597
3654
  const condensedContent = processAssistantContent(
3598
3655
  message.content,
@@ -3605,10 +3662,23 @@ function processMessage(message, resolvedProtocol, providerOptions) {
3605
3662
  };
3606
3663
  }
3607
3664
  if (message.role === "tool") {
3608
- const toolResultParts = message.content.filter(
3665
+ const toolContent = message.content;
3666
+ const toolResultParts = toolContent.filter(
3609
3667
  (part) => part.type === "tool-result"
3610
3668
  );
3611
- return processToolMessage(toolResultParts, resolvedProtocol);
3669
+ const approvalResponseParts = toolContent.filter(
3670
+ (part) => part.type === "tool-approval-response"
3671
+ );
3672
+ if (!toolResponsePromptTemplate) {
3673
+ throw new Error(
3674
+ 'toolResponsePromptTemplate is required when processing messages with role "tool". This parameter is optional for other roles but is required here so tool-result content can be converted into a prompt. Ensure your middleware or transform configuration passes a toolResponsePromptTemplate when tool message processing is enabled.'
3675
+ );
3676
+ }
3677
+ return processToolMessage(
3678
+ toolResultParts,
3679
+ approvalResponseParts,
3680
+ toolResponsePromptTemplate
3681
+ );
3612
3682
  }
3613
3683
  return message;
3614
3684
  }
@@ -3671,22 +3741,28 @@ ${currentContent}` }]
3671
3741
  }
3672
3742
  return processedPrompt;
3673
3743
  }
3674
- function convertToolPrompt(prompt, resolvedProtocol, providerOptions) {
3744
+ function convertToolPrompt(prompt, resolvedProtocol, toolResponsePromptTemplate, providerOptions) {
3675
3745
  let processedPrompt = prompt.map(
3676
- (message) => processMessage(message, resolvedProtocol, providerOptions)
3746
+ (message) => processMessage(
3747
+ message,
3748
+ resolvedProtocol,
3749
+ providerOptions,
3750
+ toolResponsePromptTemplate
3751
+ )
3677
3752
  );
3678
3753
  processedPrompt = condenseTextContent(processedPrompt);
3679
3754
  processedPrompt = mergeConsecutiveUserMessages(processedPrompt);
3680
3755
  return processedPrompt;
3681
3756
  }
3682
3757
 
3683
- // src/v6/tool-call-middleware.ts
3758
+ // src/tool-call-middleware.ts
3684
3759
  function createToolMiddleware({
3685
3760
  protocol,
3686
3761
  toolSystemPromptTemplate,
3762
+ toolResponsePromptTemplate,
3687
3763
  placement = "last"
3688
3764
  }) {
3689
- const resolvedProtocol = isProtocolFactory(protocol) ? protocol() : protocol;
3765
+ const resolvedProtocol = isTCMProtocolFactory(protocol) ? protocol() : protocol;
3690
3766
  return {
3691
3767
  specificationVersion: "v3",
3692
3768
  wrapStream: ({ doStream, doGenerate, params }) => {
@@ -3711,76 +3787,28 @@ function createToolMiddleware({
3711
3787
  transformParams: async ({ params }) => transformParams({
3712
3788
  protocol: resolvedProtocol,
3713
3789
  toolSystemPromptTemplate,
3790
+ toolResponsePromptTemplate,
3714
3791
  placement,
3715
3792
  params
3716
3793
  })
3717
3794
  };
3718
3795
  }
3719
3796
 
3720
- // src/v6/index.ts
3721
- var gemmaToolMiddleware = createToolMiddleware({
3722
- protocol: jsonMixProtocol({
3723
- toolCallStart: "```tool_call\n",
3724
- toolCallEnd: "\n```",
3725
- toolResponseStart: "```tool_response\n",
3726
- toolResponseEnd: "\n```"
3727
- }),
3728
- toolSystemPromptTemplate(tools) {
3729
- return `You have access to functions. If you decide to invoke any of the function(s),
3730
- you MUST put it in the format of markdown code fence block with the language name of tool_call , e.g.
3731
- \`\`\`tool_call
3732
- {'name': <function-name>, 'arguments': <args-dict>}
3733
- \`\`\`
3734
- You SHOULD NOT include any other text in the response if you call a function
3735
- ${tools}`;
3736
- }
3737
- });
3797
+ // src/preconfigured-middleware.ts
3738
3798
  var hermesToolMiddleware = createToolMiddleware({
3739
- protocol: jsonMixProtocol,
3740
- toolSystemPromptTemplate(tools) {
3741
- return `You are a function calling AI model.
3742
- You are provided with function signatures within <tools></tools> XML tags.
3743
- You may call one or more functions to assist with the user query.
3744
- Don't make assumptions about what values to plug into functions.
3745
- Here are the available tools: <tools>${tools}</tools>
3746
- 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"]}
3747
- For each function call return a json object with function name and arguments within <tool_call></tool_call> XML tags as follows:
3748
- <tool_call>
3749
- {"name": "<function-name>", "arguments": <args-dict>}
3750
- </tool_call>`;
3751
- }
3799
+ protocol: jsonProtocol({}),
3800
+ toolSystemPromptTemplate: hermesSystemPromptTemplate,
3801
+ toolResponsePromptTemplate: formatToolResponseAsJsonInXml
3752
3802
  });
3753
- var morphXmlToolMiddleware = createToolMiddleware({
3754
- protocol: morphXmlProtocol,
3755
- placement: "first",
3756
- toolSystemPromptTemplate(tools) {
3757
- return `# Tools
3758
-
3759
- You may call one or more functions to assist with the user query.
3760
-
3761
- You are provided with function signatures within <tools></tools> XML tags:
3762
- <tools>${tools}</tools>
3763
-
3764
- # Rules
3765
- - Use exactly one XML element whose tag name is the function name.
3766
- - Put each parameter as a child element.
3767
- - Values must follow the schema exactly (numbers, arrays, objects, enums \u2192 copy as-is).
3768
- - Do not add or remove functions or parameters.
3769
- - Each required parameter must appear once.
3770
- - Output nothing before or after the function call.
3771
- - After calling a tool, you will receive a response in the format: <tool_response><tool_name>NAME</tool_name><result>RESULT</result></tool_response>. Use this result to answer the user.
3772
-
3773
- # Example
3774
- <get_weather>
3775
- <location>New York</location>
3776
- <unit>celsius</unit>
3777
- </get_weather>`;
3778
- }
3803
+ var xmlToolMiddleware = createToolMiddleware({
3804
+ protocol: xmlProtocol({}),
3805
+ toolSystemPromptTemplate: xmlSystemPromptTemplate,
3806
+ toolResponsePromptTemplate: formatToolResponseAsXml
3779
3807
  });
3780
- var orchestratorToolMiddleware = createToolMiddleware({
3781
- protocol: yamlXmlProtocol(),
3782
- placement: "first",
3783
- toolSystemPromptTemplate: orchestratorSystemPromptTemplate
3808
+ var yamlToolMiddleware = createToolMiddleware({
3809
+ protocol: yamlProtocol({}),
3810
+ toolSystemPromptTemplate: yamlSystemPromptTemplate,
3811
+ toolResponsePromptTemplate: formatToolResponseAsXml
3784
3812
  });
3785
3813
  // Annotate the CommonJS export names for ESM import in node:
3786
3814
  0 && (module.exports = {
@@ -3797,31 +3825,34 @@ var orchestratorToolMiddleware = createToolMiddleware({
3797
3825
  escapeRegExp,
3798
3826
  extractOnErrorOption,
3799
3827
  extractToolNamesFromOriginalTools,
3800
- gemmaToolMiddleware,
3801
3828
  getDebugLevel,
3802
3829
  getPotentialStartIndex,
3803
3830
  hasInputProperty,
3804
3831
  hermesToolMiddleware,
3805
3832
  isProtocolFactory,
3833
+ isTCMProtocolFactory,
3806
3834
  isToolCallContent,
3807
3835
  isToolChoiceActive,
3808
3836
  isToolResultPart,
3809
- jsonMixProtocol,
3837
+ jsonProtocol,
3810
3838
  logParseFailure,
3811
3839
  logParsedChunk,
3812
3840
  logParsedSummary,
3813
3841
  logRawChunk,
3814
3842
  mergePipelineConfigs,
3815
- morphXmlProtocol,
3816
- morphXmlToolMiddleware,
3817
3843
  normalizeCloseTagsHeuristic,
3818
- orchestratorSystemPromptTemplate,
3819
- orchestratorToolMiddleware,
3820
3844
  originalToolsSchema,
3821
3845
  parse,
3822
3846
  repairAgainstSchemaHeuristic,
3823
3847
  stringify,
3848
+ toolChoiceStream,
3824
3849
  transform,
3825
- yamlXmlProtocol
3850
+ transformParams,
3851
+ wrapGenerate,
3852
+ wrapStream,
3853
+ xmlProtocol,
3854
+ xmlToolMiddleware,
3855
+ yamlProtocol,
3856
+ yamlToolMiddleware
3826
3857
  });
3827
3858
  //# sourceMappingURL=index.cjs.map