@caupulican/pi-ai 0.81.13 → 0.81.16

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.
@@ -1,37 +1,99 @@
1
- const MAX_SCHEMA_CHARS = 600;
2
1
  const DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT = "tool-tag";
3
2
  function isRecord(value) {
4
3
  return typeof value === "object" && value !== null && !Array.isArray(value);
5
4
  }
6
- function compactJson(value, maxChars = MAX_SCHEMA_CHARS) {
7
- const json = JSON.stringify(value);
8
- if (json.length <= maxChars)
9
- return json;
10
- return `${json.slice(0, maxChars - 1)}…`;
11
- }
12
5
  function escapeAttribute(value) {
13
6
  return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
14
7
  }
15
8
  function unescapeAttribute(value) {
16
9
  return value
17
10
  .replace(/&quot;/g, '"')
11
+ .replace(/&apos;/g, "'")
12
+ .replace(/&lt;/g, "<")
13
+ .replace(/&gt;/g, ">")
14
+ .replace(/&amp;/g, "&");
15
+ }
16
+ function escapeXmlText(value) {
17
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
18
+ }
19
+ function unescapeXmlText(value) {
20
+ return value
18
21
  .replace(/&lt;/g, "<")
19
22
  .replace(/&gt;/g, ">")
23
+ .replace(/&apos;/g, "'")
24
+ .replace(/&quot;/g, '"')
20
25
  .replace(/&amp;/g, "&");
21
26
  }
22
27
  function knownToolNames(tools) {
23
28
  return new Set(tools.map((tool) => tool.name));
24
29
  }
30
+ function findJsonObjectEnd(text, start) {
31
+ let index = start;
32
+ while (/\s/.test(text[index] ?? ""))
33
+ index++;
34
+ if (text[index] !== "{")
35
+ return undefined;
36
+ let depth = 0;
37
+ let inString = false;
38
+ let escaped = false;
39
+ for (; index < text.length; index++) {
40
+ const char = text[index];
41
+ if (inString) {
42
+ if (escaped) {
43
+ escaped = false;
44
+ continue;
45
+ }
46
+ if (char === "\\") {
47
+ escaped = true;
48
+ continue;
49
+ }
50
+ if (char === '"')
51
+ inString = false;
52
+ continue;
53
+ }
54
+ if (char === '"') {
55
+ inString = true;
56
+ continue;
57
+ }
58
+ if (char === "{")
59
+ depth++;
60
+ if (char === "}") {
61
+ depth--;
62
+ if (depth === 0)
63
+ return index + 1;
64
+ }
65
+ }
66
+ return undefined;
67
+ }
68
+ function isInsideMatch(index, matches) {
69
+ return matches.some((match) => index >= match.start && index < match.end);
70
+ }
25
71
  function findToolEnvelopes(text) {
26
72
  const matches = [];
27
- const piCallEnvelope = /<pi:call\s+name="([^"]+)"\s*>([\s\S]*?)<\/pi:call>/g;
73
+ const piCallEnvelope = /<pi:call\s+name=(["'])(.*?)\1\s*>([\s\S]*?)<\/pi:call\s*>/g;
28
74
  for (const match of text.matchAll(piCallEnvelope)) {
29
75
  matches.push({
30
76
  kind: "pi_call",
31
77
  start: match.index,
32
78
  end: match.index + match[0].length,
33
- name: unescapeAttribute(match[1] ?? ""),
34
- body: match[2] ?? "",
79
+ name: unescapeAttribute(match[2] ?? ""),
80
+ body: match[3] ?? "",
81
+ });
82
+ }
83
+ const openPiCallEnvelope = /<pi:call\s+name=(["'])(.*?)\1\s*>/g;
84
+ for (const match of text.matchAll(openPiCallEnvelope)) {
85
+ if (isInsideMatch(match.index, matches))
86
+ continue;
87
+ const bodyStart = match.index + match[0].length;
88
+ const bodyEnd = findJsonObjectEnd(text, bodyStart);
89
+ if (bodyEnd === undefined)
90
+ continue;
91
+ matches.push({
92
+ kind: "pi_call",
93
+ start: match.index,
94
+ end: bodyEnd,
95
+ name: unescapeAttribute(match[2] ?? ""),
96
+ body: text.slice(bodyStart, bodyEnd),
35
97
  });
36
98
  }
37
99
  const toolCallEnvelope = /<tool_call>([\s\S]*?)<\/tool_call>/g;
@@ -43,7 +105,7 @@ function findToolEnvelopes(text) {
43
105
  body: match[1] ?? "",
44
106
  });
45
107
  }
46
- const fence = /```(?:tool|tool_call)\s*\n([\s\S]*?)\n?```/gi;
108
+ const fence = /```(?:tool|tool_call|json)\s*\n([\s\S]*?)\n?```/gi;
47
109
  for (const match of text.matchAll(fence)) {
48
110
  matches.push({
49
111
  kind: "fenced_json",
@@ -52,6 +114,16 @@ function findToolEnvelopes(text) {
52
114
  body: match[1] ?? "",
53
115
  });
54
116
  }
117
+ const functionEnvelope = /<function\s+name=(["'])(.*?)\1\s*>([\s\S]*?)<\/function\s*>/g;
118
+ for (const match of text.matchAll(functionEnvelope)) {
119
+ matches.push({
120
+ kind: "function_xml",
121
+ start: match.index,
122
+ end: match.index + match[0].length,
123
+ name: unescapeAttribute(match[2] ?? ""),
124
+ body: match[3] ?? "",
125
+ });
126
+ }
55
127
  return matches.sort((a, b) => a.start - b.start);
56
128
  }
57
129
  function hasOverlap(matches) {
@@ -78,11 +150,62 @@ function coerceArguments(value) {
78
150
  return { arguments: value };
79
151
  return { arguments: value, rawArguments: { value } };
80
152
  }
153
+ function normalizeSingleQuotedJson(raw) {
154
+ const trimmed = raw.trim();
155
+ if (!/^\{[\s\S]*\}$/.test(trimmed))
156
+ return undefined;
157
+ if (!/'[^'\\]*(?:\\.[^'\\]*)*'/.test(trimmed))
158
+ return undefined;
159
+ return trimmed.replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g, (_match, inner) => {
160
+ return JSON.stringify(inner.replace(/\\'/g, "'"));
161
+ });
162
+ }
163
+ function normalizeBareJsonObject(raw) {
164
+ const trimmed = raw.trim();
165
+ if (!/^\{[\s\S]*\}$/.test(trimmed))
166
+ return undefined;
167
+ let changed = false;
168
+ let normalized = trimmed.replace(/([{,]\s*)([A-Za-z_][A-Za-z0-9_-]*)(\s*:)/g, (_match, prefix, key, suffix) => {
169
+ changed = true;
170
+ return `${prefix}${JSON.stringify(key)}${suffix}`;
171
+ });
172
+ normalized = normalized.replace(/:\s*([A-Za-z_./-][A-Za-z0-9_./:-]*)(?=\s*[,}])/g, (_match, value) => {
173
+ if (["true", "false", "null"].includes(value))
174
+ return `:${value}`;
175
+ changed = true;
176
+ return `:${JSON.stringify(value)}`;
177
+ });
178
+ return changed ? normalized : undefined;
179
+ }
180
+ function normalizedJsonCandidates(raw) {
181
+ const candidates = [];
182
+ const objectEnd = findJsonObjectEnd(raw, 0);
183
+ if (objectEnd !== undefined && raw.slice(objectEnd).trim())
184
+ candidates.push(raw.slice(0, objectEnd));
185
+ const singleQuoted = normalizeSingleQuotedJson(raw);
186
+ if (singleQuoted)
187
+ candidates.push(singleQuoted);
188
+ const bare = normalizeBareJsonObject(raw);
189
+ if (bare)
190
+ candidates.push(bare);
191
+ const singleQuotedBare = singleQuoted ? normalizeBareJsonObject(singleQuoted) : undefined;
192
+ if (singleQuotedBare)
193
+ candidates.push(singleQuotedBare);
194
+ return candidates;
195
+ }
81
196
  function parseJsonValue(raw) {
82
197
  try {
83
198
  return { ok: true, value: JSON.parse(raw) };
84
199
  }
85
200
  catch {
201
+ for (const normalized of normalizedJsonCandidates(raw)) {
202
+ try {
203
+ return { ok: true, value: JSON.parse(normalized) };
204
+ }
205
+ catch {
206
+ // Try the next bounded normalization candidate.
207
+ }
208
+ }
86
209
  return { ok: false };
87
210
  }
88
211
  }
@@ -114,9 +237,43 @@ function parsePiCallEnvelope(match, names, index) {
114
237
  errorMessage: textToolErrorMessage(match.name, names),
115
238
  };
116
239
  }
240
+ function parseFunctionXmlEnvelope(match, names, index) {
241
+ if (!match.name)
242
+ return undefined;
243
+ if (/<\/?function\b/i.test(match.body))
244
+ return undefined;
245
+ const params = {};
246
+ let cursor = 0;
247
+ let sawParam = false;
248
+ const paramPattern = /<param\s+name=(["'])(.*?)\1\s*>([\s\S]*?)<\/param\s*>/g;
249
+ for (const param of match.body.matchAll(paramPattern)) {
250
+ if (match.body.slice(cursor, param.index).trim())
251
+ return undefined;
252
+ const name = unescapeAttribute(param[2] ?? "");
253
+ if (!name || name in params)
254
+ return undefined;
255
+ params[name] = unescapeXmlText((param[3] ?? "").trim());
256
+ cursor = param.index + param[0].length;
257
+ sawParam = true;
258
+ }
259
+ if (match.body.slice(cursor).trim())
260
+ return undefined;
261
+ if (!sawParam)
262
+ return undefined;
263
+ return {
264
+ type: "toolCall",
265
+ id: `text-tool-${index}`,
266
+ name: match.name,
267
+ arguments: params,
268
+ source: "text-protocol",
269
+ errorMessage: textToolErrorMessage(match.name, names),
270
+ };
271
+ }
117
272
  function parseEnvelope(match, names, index) {
118
273
  if (match.kind === "pi_call")
119
274
  return parsePiCallEnvelope(match, names, index);
275
+ if (match.kind === "function_xml")
276
+ return parseFunctionXmlEnvelope(match, names, index);
120
277
  const parsed = parseJsonObject(match.body);
121
278
  if (!parsed) {
122
279
  const name = extractNameFromMalformedJson(match.body);
@@ -132,10 +289,11 @@ function parseEnvelope(match, names, index) {
132
289
  errorMessage: textToolErrorMessage(name, names),
133
290
  };
134
291
  }
135
- const nameValue = parsed.name ?? parsed.tool;
292
+ const wrappedTool = isRecord(parsed.tool) ? parsed.tool : undefined;
293
+ const nameValue = parsed.name ?? (typeof parsed.tool === "string" ? parsed.tool : undefined) ?? wrappedTool?.name;
136
294
  if (typeof nameValue !== "string")
137
295
  return undefined;
138
- const argsValue = parsed.arguments ?? parsed.args ?? {};
296
+ const argsValue = parsed.arguments ?? parsed.args ?? wrappedTool?.arguments ?? wrappedTool?.args ?? {};
139
297
  const args = coerceArguments(argsValue);
140
298
  return {
141
299
  type: "toolCall",
@@ -154,28 +312,194 @@ export function normalizeTextToolProtocolOptions(option) {
154
312
  return { variant: DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };
155
313
  return { variant: option.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };
156
314
  }
315
+ function functionXmlParamValue(value) {
316
+ if (typeof value === "string")
317
+ return value;
318
+ const json = JSON.stringify(value);
319
+ return json ?? String(value);
320
+ }
321
+ function formatFunctionXmlEnvelope(toolName, argsJson) {
322
+ const args = parseJsonObject(argsJson) ?? {};
323
+ const params = Object.entries(args)
324
+ .map(([name, value]) => `<param name="${escapeAttribute(name)}">${escapeXmlText(functionXmlParamValue(value))}</param>`)
325
+ .join("");
326
+ return `<function name="${escapeAttribute(toolName)}">${params}</function>`;
327
+ }
157
328
  function formatVariantEnvelope(variant, toolName, argsJson) {
158
329
  if (variant === "tool-call")
159
330
  return `<tool_call>{"name":"${toolName}","arguments":${argsJson}}</tool_call>`;
160
331
  if (variant === "fenced-json")
161
332
  return `\`\`\`tool_call\n{"name":"${toolName}","arguments":${argsJson}}\n\`\`\``;
333
+ if (variant === "function-xml")
334
+ return formatFunctionXmlEnvelope(toolName, argsJson);
162
335
  return `<pi:call name="${escapeAttribute(toolName)}">${argsJson}</pi:call>`;
163
336
  }
337
+ function schemaRecord(value) {
338
+ return isRecord(value) ? value : undefined;
339
+ }
340
+ function firstString(value) {
341
+ return typeof value === "string" ? value : undefined;
342
+ }
343
+ function schemaType(schema) {
344
+ const type = schema.type;
345
+ if (typeof type === "string")
346
+ return type;
347
+ if (!Array.isArray(type))
348
+ return undefined;
349
+ return type.filter(firstString).find((entry) => entry !== "null");
350
+ }
351
+ function stringExampleForProperty(propertyName) {
352
+ if (propertyName === "path")
353
+ return "src/index.ts";
354
+ if (propertyName === "command")
355
+ return "echo ok";
356
+ if (propertyName === "oldText")
357
+ return "foo";
358
+ if (propertyName === "newText")
359
+ return "bar";
360
+ if (propertyName === "content")
361
+ return "text";
362
+ return "value";
363
+ }
364
+ function exampleValueForSchema(schemaValue, propertyName) {
365
+ const schema = schemaRecord(schemaValue);
366
+ if (!schema)
367
+ return stringExampleForProperty(propertyName);
368
+ const constValue = schema.const;
369
+ if (constValue !== undefined)
370
+ return constValue;
371
+ const enumValues = Array.isArray(schema.enum) ? schema.enum : [];
372
+ if (enumValues.length > 0)
373
+ return enumValues[0];
374
+ const defaultValue = schema.default;
375
+ if (defaultValue !== undefined)
376
+ return defaultValue;
377
+ const type = schemaType(schema);
378
+ if (type === "number" || type === "integer")
379
+ return 1;
380
+ if (type === "boolean")
381
+ return true;
382
+ if (type === "array")
383
+ return [exampleValueForSchema(schema.items, propertyName)];
384
+ if (type === "object")
385
+ return exampleArgumentsForParameters(schema);
386
+ return stringExampleForProperty(propertyName);
387
+ }
388
+ function requiredPropertyNames(parameters) {
389
+ return Array.isArray(parameters?.required) ? parameters.required.filter(firstString) : [];
390
+ }
391
+ function exampleArgumentsForParameters(parametersValue) {
392
+ const parameters = schemaRecord(parametersValue);
393
+ const properties = schemaRecord(parameters?.properties);
394
+ if (!properties)
395
+ return {};
396
+ const args = {};
397
+ for (const name of requiredPropertyNames(parameters)) {
398
+ args[name] = exampleValueForSchema(properties[name], name);
399
+ }
400
+ return args;
401
+ }
402
+ function typeLabel(schemaValue) {
403
+ const schema = schemaRecord(schemaValue);
404
+ if (!schema)
405
+ return "string";
406
+ const enumValues = Array.isArray(schema.enum) ? schema.enum : [];
407
+ if (enumValues.length > 0 && enumValues.every((entry) => ["string", "number", "boolean"].includes(typeof entry))) {
408
+ return enumValues.map(String).join("|");
409
+ }
410
+ const type = schemaType(schema);
411
+ if (type === "integer" || type === "number")
412
+ return "number";
413
+ if (type === "boolean")
414
+ return "bool";
415
+ if (type === "array")
416
+ return `${typeLabel(schema.items)}[]`;
417
+ if (type === "object") {
418
+ const properties = schemaRecord(schema.properties);
419
+ if (!properties)
420
+ return "{}";
421
+ const entries = Object.entries(properties)
422
+ .slice(0, 4)
423
+ .map(([name, value]) => `${name}:${typeLabel(value)}`);
424
+ const suffix = Object.keys(properties).length > entries.length ? ",..." : "";
425
+ return `{${entries.join(",")}${suffix}}`;
426
+ }
427
+ return "string";
428
+ }
429
+ function orderedPropertyNames(properties, required) {
430
+ const requiredSet = new Set(required);
431
+ return [
432
+ ...required.filter((name) => name in properties),
433
+ ...Object.keys(properties).filter((name) => !requiredSet.has(name)),
434
+ ];
435
+ }
436
+ function formatDefault(value) {
437
+ const json = JSON.stringify(value);
438
+ return json ? `=${json}` : "";
439
+ }
440
+ function formatToolProjection(tool) {
441
+ const parameters = schemaRecord(tool.parameters);
442
+ const properties = schemaRecord(parameters?.properties);
443
+ const required = requiredPropertyNames(parameters);
444
+ const requiredSet = new Set(required);
445
+ const args = properties
446
+ ? orderedPropertyNames(properties, required)
447
+ .map((name) => {
448
+ const schema = schemaRecord(properties[name]);
449
+ const optional = requiredSet.has(name) ? "" : "?";
450
+ const defaultText = schema && "default" in schema ? formatDefault(schema.default) : "";
451
+ return `${name}:${typeLabel(schema)}${optional}${defaultText}`;
452
+ })
453
+ .join(", ")
454
+ : "";
455
+ const description = tool.description.replace(/\s+/g, " ").trim();
456
+ return `${tool.name}(${args}) - ${description}`;
457
+ }
458
+ function toolHasArrayParameter(tool) {
459
+ const parameters = schemaRecord(tool.parameters);
460
+ const properties = schemaRecord(parameters?.properties);
461
+ if (!properties)
462
+ return false;
463
+ return Object.values(properties).some((schemaValue) => schemaType(schemaRecord(schemaValue) ?? {}) === "array");
464
+ }
465
+ function exampleTools(tools) {
466
+ const examples = [];
467
+ const readTool = tools.find((tool) => tool.name === "read");
468
+ if (readTool)
469
+ examples.push(readTool);
470
+ if (examples.length === 0)
471
+ examples.push(tools[0]);
472
+ const editTool = tools.find((tool) => tool.name === "edit" && !examples.includes(tool));
473
+ const arrayTool = editTool ?? tools.find((tool) => !examples.includes(tool) && toolHasArrayParameter(tool));
474
+ if (arrayTool)
475
+ examples.push(arrayTool);
476
+ return examples;
477
+ }
478
+ function protocolHeader(variant) {
479
+ return [
480
+ "Text tool-call protocol is enabled.",
481
+ "When calling tools, output only one or more envelopes and no prose:",
482
+ formatVariantEnvelope(variant, "TOOL", '{"arg":"value"}'),
483
+ "Arguments must be valid JSON objects. Use double quotes for JSON keys and string values. Arrays are JSON arrays [ ], never quoted strings. Omit optional args you do not need - do not send null.",
484
+ "User requests about files, directories, searches, edits, writes, or shell commands require a tool envelope first; do not describe results yourself.",
485
+ 'If the user asks to read /tmp/example.txt, output exactly: <pi:call name="read">{"path":"/tmp/example.txt"}</pi:call>',
486
+ 'For any request to read a file path, call read with {"path":"THE_PATH"}; never output {"file_path":..., "content":...} or invented file contents.',
487
+ "Never write raw shell commands such as read -t PATH, cat PATH, or ls PATH; use a tool-call envelope instead.",
488
+ "Never output markdown code blocks, raw shell commands, file paths, or invented tool results instead of a tool call; use the envelope and wait for the real result.",
489
+ ];
490
+ }
164
491
  export function generateTextToolProtocolPrimer(tools, options) {
165
492
  if (tools.length === 0)
166
493
  return "";
167
494
  const variant = options?.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT;
168
- const lines = [
169
- "Text tool-call protocol is enabled.",
170
- "When calling tools, output only one or more envelopes and no prose:",
171
- formatVariantEnvelope(variant, "TOOL_NAME", '{"argument":"value"}'),
172
- "Available tools:",
173
- ];
495
+ const lines = [...protocolHeader(variant), "Examples:"];
496
+ for (const tool of exampleTools(tools)) {
497
+ lines.push(formatVariantEnvelope(variant, tool.name, JSON.stringify(exampleArgumentsForParameters(tool.parameters))));
498
+ }
499
+ lines.push("Available tools:");
174
500
  for (const tool of tools) {
175
- lines.push(`- ${escapeAttribute(tool.name)}: ${tool.description}; args schema ${compactJson(tool.parameters)}`);
501
+ lines.push(formatToolProjection(tool));
176
502
  }
177
- const exampleTool = tools[0];
178
- lines.push("Examples:", formatVariantEnvelope(variant, exampleTool.name, "{}"));
179
503
  return lines.join("\n");
180
504
  }
181
505
  export function parseTextToolCalls(text, knownTools) {
@@ -1 +1 @@
1
- {"version":3,"file":"text-protocol.js","sourceRoot":"","sources":["../../../src/utils/tool-repair/text-protocol.ts"],"names":[],"mappings":"AA2BA,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,kCAAkC,GAA4B,UAAU,CAAC;AAE/E,SAAS,QAAQ,CAAC,KAAc,EAAoC;IACnE,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E;AAED,SAAS,WAAW,CAAC,KAAc,EAAE,QAAQ,GAAG,gBAAgB,EA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AAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,cAAc,EAAE,CAAC;AAAA,CACjE","sourcesContent":["import type { Tool, ToolCall } from \"../../types.ts\";\n\nexport type TextToolProtocolParseFailure = \"overlap\" | \"mixed-prose\" | \"unrecognized\";\n\nexport interface ParsedTextToolCalls {\n\tcalls: ToolCall[];\n\ttext: string;\n\tattempted: boolean;\n\tfailure?: TextToolProtocolParseFailure;\n}\n\nexport type TextToolProtocolVariant = \"tool-tag\" | \"tool-call\" | \"fenced-json\";\n\nexport interface TextToolProtocolOptions {\n\tvariant?: TextToolProtocolVariant;\n}\n\ntype EnvelopeKind = \"pi_call\" | \"tool_call\" | \"fenced_json\";\n\ninterface EnvelopeMatch {\n\tkind: EnvelopeKind;\n\tstart: number;\n\tend: number;\n\tname?: string;\n\tbody: string;\n}\n\nconst MAX_SCHEMA_CHARS = 600;\nconst DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT: TextToolProtocolVariant = \"tool-tag\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction compactJson(value: unknown, maxChars = MAX_SCHEMA_CHARS): string {\n\tconst json = JSON.stringify(value);\n\tif (json.length <= maxChars) return json;\n\treturn `${json.slice(0, maxChars - 1)}…`;\n}\n\nfunction escapeAttribute(value: string): string {\n\treturn value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction unescapeAttribute(value: string): string {\n\treturn value\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&lt;/g, \"<\")\n\t\t.replace(/&gt;/g, \">\")\n\t\t.replace(/&amp;/g, \"&\");\n}\n\nfunction knownToolNames(tools: readonly Tool[]): Set<string> {\n\treturn new Set(tools.map((tool) => tool.name));\n}\n\nfunction findToolEnvelopes(text: string): EnvelopeMatch[] {\n\tconst matches: EnvelopeMatch[] = [];\n\tconst piCallEnvelope = /<pi:call\\s+name=\"([^\"]+)\"\\s*>([\\s\\S]*?)<\\/pi:call>/g;\n\tfor (const match of text.matchAll(piCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"pi_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tname: unescapeAttribute(match[1] ?? \"\"),\n\t\t\tbody: match[2] ?? \"\",\n\t\t});\n\t}\n\n\tconst toolCallEnvelope = /<tool_call>([\\s\\S]*?)<\\/tool_call>/g;\n\tfor (const match of text.matchAll(toolCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"tool_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\tconst fence = /```(?:tool|tool_call)\\s*\\n([\\s\\S]*?)\\n?```/gi;\n\tfor (const match of text.matchAll(fence)) {\n\t\tmatches.push({\n\t\t\tkind: \"fenced_json\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\treturn matches.sort((a, b) => a.start - b.start);\n}\n\nfunction hasOverlap(matches: readonly EnvelopeMatch[]): boolean {\n\tlet previousEnd = -1;\n\tfor (const match of matches) {\n\t\tif (match.start < previousEnd) return true;\n\t\tpreviousEnd = match.end;\n\t}\n\treturn false;\n}\n\nfunction remainingText(text: string, matches: readonly EnvelopeMatch[]): string {\n\tlet cursor = 0;\n\tconst pieces: string[] = [];\n\tfor (const match of matches) {\n\t\tpieces.push(text.slice(cursor, match.start));\n\t\tcursor = match.end;\n\t}\n\tpieces.push(text.slice(cursor));\n\treturn pieces.join(\"\");\n}\n\nfunction coerceArguments(value: unknown): {\n\targuments: Record<string, unknown>;\n\trawArguments?: Record<string, unknown>;\n} {\n\tif (isRecord(value)) return { arguments: value };\n\treturn { arguments: value as Record<string, unknown>, rawArguments: { value } };\n}\n\nfunction parseJsonValue(raw: string): { ok: true; value: unknown } | { ok: false } {\n\ttry {\n\t\treturn { ok: true, value: JSON.parse(raw) as unknown };\n\t} catch {\n\t\treturn { ok: false };\n\t}\n}\n\nfunction parseJsonObject(raw: string): Record<string, unknown> | undefined {\n\tconst parsed = parseJsonValue(raw);\n\treturn parsed.ok && isRecord(parsed.value) ? parsed.value : undefined;\n}\n\nfunction textToolErrorMessage(name: string, names: readonly string[]): string | undefined {\n\tif (names.includes(name)) return undefined;\n\treturn `Unknown tool \"${name}\". Valid tools: ${names.join(\", \")}.`;\n}\n\nfunction extractNameFromMalformedJson(raw: string): string | undefined {\n\tconst match = /\"(?:name|tool)\"\\s*:\\s*\"([^\"]+)\"/.exec(raw);\n\treturn match?.[1];\n}\n\nfunction parsePiCallEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (!match.name) return undefined;\n\tconst parsed = parseJsonValue(match.body);\n\tconst args = parsed.ok ? coerceArguments(parsed.value) : coerceArguments(match.body.trim());\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: match.name,\n\t\targuments: args.arguments,\n\t\trawArguments: parsed.ok ? args.rawArguments : { text: match.body.trim() },\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(match.name, names),\n\t};\n}\n\nfunction parseEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (match.kind === \"pi_call\") return parsePiCallEnvelope(match, names, index);\n\n\tconst parsed = parseJsonObject(match.body);\n\tif (!parsed) {\n\t\tconst name = extractNameFromMalformedJson(match.body);\n\t\tif (!name) return undefined;\n\t\treturn {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: `text-tool-${index}`,\n\t\t\tname,\n\t\t\targuments: match.body.trim() as unknown as Record<string, unknown>,\n\t\t\trawArguments: { text: match.body.trim() },\n\t\t\tsource: \"text-protocol\",\n\t\t\terrorMessage: textToolErrorMessage(name, names),\n\t\t};\n\t}\n\n\tconst nameValue = parsed.name ?? parsed.tool;\n\tif (typeof nameValue !== \"string\") return undefined;\n\tconst argsValue = parsed.arguments ?? parsed.args ?? {};\n\tconst args = coerceArguments(argsValue);\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: nameValue,\n\t\targuments: args.arguments,\n\t\trawArguments: args.rawArguments,\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(nameValue, names),\n\t};\n}\n\nexport function normalizeTextToolProtocolOptions(\n\toption: boolean | TextToolProtocolOptions | undefined,\n): TextToolProtocolOptions | undefined {\n\tif (!option) return undefined;\n\tif (option === true) return { variant: DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n\treturn { variant: option.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n}\n\nfunction formatVariantEnvelope(variant: TextToolProtocolVariant, toolName: string, argsJson: string): string {\n\tif (variant === \"tool-call\") return `<tool_call>{\"name\":\"${toolName}\",\"arguments\":${argsJson}}</tool_call>`;\n\tif (variant === \"fenced-json\") return `\\`\\`\\`tool_call\\n{\"name\":\"${toolName}\",\"arguments\":${argsJson}}\\n\\`\\`\\``;\n\treturn `<pi:call name=\"${escapeAttribute(toolName)}\">${argsJson}</pi:call>`;\n}\n\nexport function generateTextToolProtocolPrimer(tools: readonly Tool[], options?: TextToolProtocolOptions): string {\n\tif (tools.length === 0) return \"\";\n\tconst variant = options?.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT;\n\tconst lines = [\n\t\t\"Text tool-call protocol is enabled.\",\n\t\t\"When calling tools, output only one or more envelopes and no prose:\",\n\t\tformatVariantEnvelope(variant, \"TOOL_NAME\", '{\"argument\":\"value\"}'),\n\t\t\"Available tools:\",\n\t];\n\tfor (const tool of tools) {\n\t\tlines.push(`- ${escapeAttribute(tool.name)}: ${tool.description}; args schema ${compactJson(tool.parameters)}`);\n\t}\n\tconst exampleTool = tools[0];\n\tlines.push(\"Examples:\", formatVariantEnvelope(variant, exampleTool.name, \"{}\"));\n\treturn lines.join(\"\\n\");\n}\n\nexport function parseTextToolCalls(text: string, knownTools: readonly Tool[]): ParsedTextToolCalls {\n\tif (knownTools.length === 0) return { calls: [], text, attempted: false };\n\tconst matches = findToolEnvelopes(text);\n\tif (matches.length === 0) return { calls: [], text, attempted: false };\n\tif (hasOverlap(matches)) return { calls: [], text, attempted: true, failure: \"overlap\" };\n\tconst remainder = remainingText(text, matches);\n\tconst names = [...knownToolNames(knownTools)];\n\tconst calls = matches\n\t\t.map((match, index) => parseEnvelope(match, names, index + 1))\n\t\t.filter((call): call is ToolCall => call !== undefined);\n\treturn calls.length > 0\n\t\t? { calls, text: remainder.trim(), attempted: true }\n\t\t: { calls: [], text, attempted: true, failure: \"unrecognized\" };\n}\n"]}
1
+ {"version":3,"file":"text-protocol.js","sourceRoot":"","sources":["../../../src/utils/tool-repair/text-protocol.ts"],"names":[],"mappings":"AAgCA,MAAM,kCAAkC,GAA4B,UAAU,CAAC;AAE/E,SAAS,QAAQ,CAAC,KAAc,EAAoC;IACnE,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E;AAED,SAAS,eAAe,CAAC,KAAa,EAAU;IAC/C,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAAA,CACxG;AAED,SAAS,iBAAiB,CAAC,KAAa,EAAU;IACjD,OAAO,KAAK;SACV,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC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AAI,EAAE,OAAO,EAAE,cAAc,EAAE,CAAC;AAAA,CACjE","sourcesContent":["import type { Tool, ToolCall } from \"../../types.ts\";\n\nexport type TextToolProtocolParseFailure =\n\t| \"overlap\"\n\t| \"mixed-prose\"\n\t| \"unrecognized\"\n\t| \"unknown-tool\"\n\t| \"validation-failed\";\n\nexport interface ParsedTextToolCalls {\n\tcalls: ToolCall[];\n\ttext: string;\n\tattempted: boolean;\n\tfailure?: TextToolProtocolParseFailure;\n}\n\nexport type TextToolProtocolVariant = \"tool-tag\" | \"tool-call\" | \"fenced-json\" | \"function-xml\";\n\nexport interface TextToolProtocolOptions {\n\tvariant?: TextToolProtocolVariant;\n}\n\ntype EnvelopeKind = \"pi_call\" | \"tool_call\" | \"fenced_json\" | \"function_xml\";\n\ninterface EnvelopeMatch {\n\tkind: EnvelopeKind;\n\tstart: number;\n\tend: number;\n\tname?: string;\n\tbody: string;\n}\n\nconst DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT: TextToolProtocolVariant = \"tool-tag\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction escapeAttribute(value: string): string {\n\treturn value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction unescapeAttribute(value: string): string {\n\treturn value\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&apos;/g, \"'\")\n\t\t.replace(/&lt;/g, \"<\")\n\t\t.replace(/&gt;/g, \">\")\n\t\t.replace(/&amp;/g, \"&\");\n}\n\nfunction escapeXmlText(value: string): string {\n\treturn value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction unescapeXmlText(value: string): string {\n\treturn value\n\t\t.replace(/&lt;/g, \"<\")\n\t\t.replace(/&gt;/g, \">\")\n\t\t.replace(/&apos;/g, \"'\")\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&amp;/g, \"&\");\n}\n\nfunction knownToolNames(tools: readonly Tool[]): Set<string> {\n\treturn new Set(tools.map((tool) => tool.name));\n}\n\nfunction findJsonObjectEnd(text: string, start: number): number | undefined {\n\tlet index = start;\n\twhile (/\\s/.test(text[index] ?? \"\")) index++;\n\tif (text[index] !== \"{\") return undefined;\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (; index < text.length; index++) {\n\t\tconst char = text[index];\n\t\tif (inString) {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"') {\n\t\t\tinString = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"{\") depth++;\n\t\tif (char === \"}\") {\n\t\t\tdepth--;\n\t\t\tif (depth === 0) return index + 1;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isInsideMatch(index: number, matches: readonly EnvelopeMatch[]): boolean {\n\treturn matches.some((match) => index >= match.start && index < match.end);\n}\n\nfunction findToolEnvelopes(text: string): EnvelopeMatch[] {\n\tconst matches: EnvelopeMatch[] = [];\n\tconst piCallEnvelope = /<pi:call\\s+name=([\"'])(.*?)\\1\\s*>([\\s\\S]*?)<\\/pi:call\\s*>/g;\n\tfor (const match of text.matchAll(piCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"pi_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: match[3] ?? \"\",\n\t\t});\n\t}\n\n\tconst openPiCallEnvelope = /<pi:call\\s+name=([\"'])(.*?)\\1\\s*>/g;\n\tfor (const match of text.matchAll(openPiCallEnvelope)) {\n\t\tif (isInsideMatch(match.index, matches)) continue;\n\t\tconst bodyStart = match.index + match[0].length;\n\t\tconst bodyEnd = findJsonObjectEnd(text, bodyStart);\n\t\tif (bodyEnd === undefined) continue;\n\t\tmatches.push({\n\t\t\tkind: \"pi_call\",\n\t\t\tstart: match.index,\n\t\t\tend: bodyEnd,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: text.slice(bodyStart, bodyEnd),\n\t\t});\n\t}\n\n\tconst toolCallEnvelope = /<tool_call>([\\s\\S]*?)<\\/tool_call>/g;\n\tfor (const match of text.matchAll(toolCallEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"tool_call\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\tconst fence = /```(?:tool|tool_call|json)\\s*\\n([\\s\\S]*?)\\n?```/gi;\n\tfor (const match of text.matchAll(fence)) {\n\t\tmatches.push({\n\t\t\tkind: \"fenced_json\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tbody: match[1] ?? \"\",\n\t\t});\n\t}\n\n\tconst functionEnvelope = /<function\\s+name=([\"'])(.*?)\\1\\s*>([\\s\\S]*?)<\\/function\\s*>/g;\n\tfor (const match of text.matchAll(functionEnvelope)) {\n\t\tmatches.push({\n\t\t\tkind: \"function_xml\",\n\t\t\tstart: match.index,\n\t\t\tend: match.index + match[0].length,\n\t\t\tname: unescapeAttribute(match[2] ?? \"\"),\n\t\t\tbody: match[3] ?? \"\",\n\t\t});\n\t}\n\n\treturn matches.sort((a, b) => a.start - b.start);\n}\n\nfunction hasOverlap(matches: readonly EnvelopeMatch[]): boolean {\n\tlet previousEnd = -1;\n\tfor (const match of matches) {\n\t\tif (match.start < previousEnd) return true;\n\t\tpreviousEnd = match.end;\n\t}\n\treturn false;\n}\n\nfunction remainingText(text: string, matches: readonly EnvelopeMatch[]): string {\n\tlet cursor = 0;\n\tconst pieces: string[] = [];\n\tfor (const match of matches) {\n\t\tpieces.push(text.slice(cursor, match.start));\n\t\tcursor = match.end;\n\t}\n\tpieces.push(text.slice(cursor));\n\treturn pieces.join(\"\");\n}\n\nfunction coerceArguments(value: unknown): {\n\targuments: Record<string, unknown>;\n\trawArguments?: Record<string, unknown>;\n} {\n\tif (isRecord(value)) return { arguments: value };\n\treturn { arguments: value as Record<string, unknown>, rawArguments: { value } };\n}\n\nfunction normalizeSingleQuotedJson(raw: string): string | undefined {\n\tconst trimmed = raw.trim();\n\tif (!/^\\{[\\s\\S]*\\}$/.test(trimmed)) return undefined;\n\tif (!/'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'/.test(trimmed)) return undefined;\n\treturn trimmed.replace(/'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'/g, (_match, inner: string) => {\n\t\treturn JSON.stringify(inner.replace(/\\\\'/g, \"'\"));\n\t});\n}\n\nfunction normalizeBareJsonObject(raw: string): string | undefined {\n\tconst trimmed = raw.trim();\n\tif (!/^\\{[\\s\\S]*\\}$/.test(trimmed)) return undefined;\n\tlet changed = false;\n\tlet normalized = trimmed.replace(\n\t\t/([{,]\\s*)([A-Za-z_][A-Za-z0-9_-]*)(\\s*:)/g,\n\t\t(_match, prefix: string, key: string, suffix: string) => {\n\t\t\tchanged = true;\n\t\t\treturn `${prefix}${JSON.stringify(key)}${suffix}`;\n\t\t},\n\t);\n\tnormalized = normalized.replace(/:\\s*([A-Za-z_./-][A-Za-z0-9_./:-]*)(?=\\s*[,}])/g, (_match, value: string) => {\n\t\tif ([\"true\", \"false\", \"null\"].includes(value)) return `:${value}`;\n\t\tchanged = true;\n\t\treturn `:${JSON.stringify(value)}`;\n\t});\n\treturn changed ? normalized : undefined;\n}\n\nfunction normalizedJsonCandidates(raw: string): string[] {\n\tconst candidates: string[] = [];\n\tconst objectEnd = findJsonObjectEnd(raw, 0);\n\tif (objectEnd !== undefined && raw.slice(objectEnd).trim()) candidates.push(raw.slice(0, objectEnd));\n\tconst singleQuoted = normalizeSingleQuotedJson(raw);\n\tif (singleQuoted) candidates.push(singleQuoted);\n\tconst bare = normalizeBareJsonObject(raw);\n\tif (bare) candidates.push(bare);\n\tconst singleQuotedBare = singleQuoted ? normalizeBareJsonObject(singleQuoted) : undefined;\n\tif (singleQuotedBare) candidates.push(singleQuotedBare);\n\treturn candidates;\n}\n\nfunction parseJsonValue(raw: string): { ok: true; value: unknown } | { ok: false } {\n\ttry {\n\t\treturn { ok: true, value: JSON.parse(raw) as unknown };\n\t} catch {\n\t\tfor (const normalized of normalizedJsonCandidates(raw)) {\n\t\t\ttry {\n\t\t\t\treturn { ok: true, value: JSON.parse(normalized) as unknown };\n\t\t\t} catch {\n\t\t\t\t// Try the next bounded normalization candidate.\n\t\t\t}\n\t\t}\n\t\treturn { ok: false };\n\t}\n}\n\nfunction parseJsonObject(raw: string): Record<string, unknown> | undefined {\n\tconst parsed = parseJsonValue(raw);\n\treturn parsed.ok && isRecord(parsed.value) ? parsed.value : undefined;\n}\n\nfunction textToolErrorMessage(name: string, names: readonly string[]): string | undefined {\n\tif (names.includes(name)) return undefined;\n\treturn `Unknown tool \"${name}\". Valid tools: ${names.join(\", \")}.`;\n}\n\nfunction extractNameFromMalformedJson(raw: string): string | undefined {\n\tconst match = /\"(?:name|tool)\"\\s*:\\s*\"([^\"]+)\"/.exec(raw);\n\treturn match?.[1];\n}\n\nfunction parsePiCallEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (!match.name) return undefined;\n\tconst parsed = parseJsonValue(match.body);\n\tconst args = parsed.ok ? coerceArguments(parsed.value) : coerceArguments(match.body.trim());\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: match.name,\n\t\targuments: args.arguments,\n\t\trawArguments: parsed.ok ? args.rawArguments : { text: match.body.trim() },\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(match.name, names),\n\t};\n}\n\nfunction parseFunctionXmlEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (!match.name) return undefined;\n\tif (/<\\/?function\\b/i.test(match.body)) return undefined;\n\tconst params: Record<string, string> = {};\n\tlet cursor = 0;\n\tlet sawParam = false;\n\tconst paramPattern = /<param\\s+name=([\"'])(.*?)\\1\\s*>([\\s\\S]*?)<\\/param\\s*>/g;\n\tfor (const param of match.body.matchAll(paramPattern)) {\n\t\tif (match.body.slice(cursor, param.index).trim()) return undefined;\n\t\tconst name = unescapeAttribute(param[2] ?? \"\");\n\t\tif (!name || name in params) return undefined;\n\t\tparams[name] = unescapeXmlText((param[3] ?? \"\").trim());\n\t\tcursor = param.index + param[0].length;\n\t\tsawParam = true;\n\t}\n\tif (match.body.slice(cursor).trim()) return undefined;\n\tif (!sawParam) return undefined;\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: match.name,\n\t\targuments: params,\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(match.name, names),\n\t};\n}\n\nfunction parseEnvelope(match: EnvelopeMatch, names: readonly string[], index: number): ToolCall | undefined {\n\tif (match.kind === \"pi_call\") return parsePiCallEnvelope(match, names, index);\n\tif (match.kind === \"function_xml\") return parseFunctionXmlEnvelope(match, names, index);\n\n\tconst parsed = parseJsonObject(match.body);\n\tif (!parsed) {\n\t\tconst name = extractNameFromMalformedJson(match.body);\n\t\tif (!name) return undefined;\n\t\treturn {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: `text-tool-${index}`,\n\t\t\tname,\n\t\t\targuments: match.body.trim() as unknown as Record<string, unknown>,\n\t\t\trawArguments: { text: match.body.trim() },\n\t\t\tsource: \"text-protocol\",\n\t\t\terrorMessage: textToolErrorMessage(name, names),\n\t\t};\n\t}\n\n\tconst wrappedTool = isRecord(parsed.tool) ? parsed.tool : undefined;\n\tconst nameValue = parsed.name ?? (typeof parsed.tool === \"string\" ? parsed.tool : undefined) ?? wrappedTool?.name;\n\tif (typeof nameValue !== \"string\") return undefined;\n\tconst argsValue = parsed.arguments ?? parsed.args ?? wrappedTool?.arguments ?? wrappedTool?.args ?? {};\n\tconst args = coerceArguments(argsValue);\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: `text-tool-${index}`,\n\t\tname: nameValue,\n\t\targuments: args.arguments,\n\t\trawArguments: args.rawArguments,\n\t\tsource: \"text-protocol\",\n\t\terrorMessage: textToolErrorMessage(nameValue, names),\n\t};\n}\n\nexport function normalizeTextToolProtocolOptions(\n\toption: boolean | TextToolProtocolOptions | undefined,\n): TextToolProtocolOptions | undefined {\n\tif (!option) return undefined;\n\tif (option === true) return { variant: DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n\treturn { variant: option.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT };\n}\n\nfunction functionXmlParamValue(value: unknown): string {\n\tif (typeof value === \"string\") return value;\n\tconst json = JSON.stringify(value);\n\treturn json ?? String(value);\n}\n\nfunction formatFunctionXmlEnvelope(toolName: string, argsJson: string): string {\n\tconst args = parseJsonObject(argsJson) ?? {};\n\tconst params = Object.entries(args)\n\t\t.map(\n\t\t\t([name, value]) =>\n\t\t\t\t`<param name=\"${escapeAttribute(name)}\">${escapeXmlText(functionXmlParamValue(value))}</param>`,\n\t\t)\n\t\t.join(\"\");\n\treturn `<function name=\"${escapeAttribute(toolName)}\">${params}</function>`;\n}\n\nfunction formatVariantEnvelope(variant: TextToolProtocolVariant, toolName: string, argsJson: string): string {\n\tif (variant === \"tool-call\") return `<tool_call>{\"name\":\"${toolName}\",\"arguments\":${argsJson}}</tool_call>`;\n\tif (variant === \"fenced-json\") return `\\`\\`\\`tool_call\\n{\"name\":\"${toolName}\",\"arguments\":${argsJson}}\\n\\`\\`\\``;\n\tif (variant === \"function-xml\") return formatFunctionXmlEnvelope(toolName, argsJson);\n\treturn `<pi:call name=\"${escapeAttribute(toolName)}\">${argsJson}</pi:call>`;\n}\n\nfunction schemaRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn isRecord(value) ? value : undefined;\n}\n\nfunction firstString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction schemaType(schema: Record<string, unknown>): string | undefined {\n\tconst type = schema.type;\n\tif (typeof type === \"string\") return type;\n\tif (!Array.isArray(type)) return undefined;\n\treturn type.filter(firstString).find((entry) => entry !== \"null\");\n}\n\nfunction stringExampleForProperty(propertyName: string | undefined): string {\n\tif (propertyName === \"path\") return \"src/index.ts\";\n\tif (propertyName === \"command\") return \"echo ok\";\n\tif (propertyName === \"oldText\") return \"foo\";\n\tif (propertyName === \"newText\") return \"bar\";\n\tif (propertyName === \"content\") return \"text\";\n\treturn \"value\";\n}\n\nfunction exampleValueForSchema(schemaValue: unknown, propertyName?: string): unknown {\n\tconst schema = schemaRecord(schemaValue);\n\tif (!schema) return stringExampleForProperty(propertyName);\n\tconst constValue = schema.const;\n\tif (constValue !== undefined) return constValue;\n\tconst enumValues = Array.isArray(schema.enum) ? schema.enum : [];\n\tif (enumValues.length > 0) return enumValues[0];\n\tconst defaultValue = schema.default;\n\tif (defaultValue !== undefined) return defaultValue;\n\tconst type = schemaType(schema);\n\tif (type === \"number\" || type === \"integer\") return 1;\n\tif (type === \"boolean\") return true;\n\tif (type === \"array\") return [exampleValueForSchema(schema.items, propertyName)];\n\tif (type === \"object\") return exampleArgumentsForParameters(schema);\n\treturn stringExampleForProperty(propertyName);\n}\n\nfunction requiredPropertyNames(parameters: Record<string, unknown> | undefined): string[] {\n\treturn Array.isArray(parameters?.required) ? parameters.required.filter(firstString) : [];\n}\n\nfunction exampleArgumentsForParameters(parametersValue: unknown): Record<string, unknown> {\n\tconst parameters = schemaRecord(parametersValue);\n\tconst properties = schemaRecord(parameters?.properties);\n\tif (!properties) return {};\n\tconst args: Record<string, unknown> = {};\n\tfor (const name of requiredPropertyNames(parameters)) {\n\t\targs[name] = exampleValueForSchema(properties[name], name);\n\t}\n\treturn args;\n}\n\nfunction typeLabel(schemaValue: unknown): string {\n\tconst schema = schemaRecord(schemaValue);\n\tif (!schema) return \"string\";\n\tconst enumValues = Array.isArray(schema.enum) ? schema.enum : [];\n\tif (enumValues.length > 0 && enumValues.every((entry) => [\"string\", \"number\", \"boolean\"].includes(typeof entry))) {\n\t\treturn enumValues.map(String).join(\"|\");\n\t}\n\tconst type = schemaType(schema);\n\tif (type === \"integer\" || type === \"number\") return \"number\";\n\tif (type === \"boolean\") return \"bool\";\n\tif (type === \"array\") return `${typeLabel(schema.items)}[]`;\n\tif (type === \"object\") {\n\t\tconst properties = schemaRecord(schema.properties);\n\t\tif (!properties) return \"{}\";\n\t\tconst entries = Object.entries(properties)\n\t\t\t.slice(0, 4)\n\t\t\t.map(([name, value]) => `${name}:${typeLabel(value)}`);\n\t\tconst suffix = Object.keys(properties).length > entries.length ? \",...\" : \"\";\n\t\treturn `{${entries.join(\",\")}${suffix}}`;\n\t}\n\treturn \"string\";\n}\n\nfunction orderedPropertyNames(properties: Record<string, unknown>, required: readonly string[]): string[] {\n\tconst requiredSet = new Set(required);\n\treturn [\n\t\t...required.filter((name) => name in properties),\n\t\t...Object.keys(properties).filter((name) => !requiredSet.has(name)),\n\t];\n}\n\nfunction formatDefault(value: unknown): string {\n\tconst json = JSON.stringify(value);\n\treturn json ? `=${json}` : \"\";\n}\n\nfunction formatToolProjection(tool: Tool): string {\n\tconst parameters = schemaRecord(tool.parameters);\n\tconst properties = schemaRecord(parameters?.properties);\n\tconst required = requiredPropertyNames(parameters);\n\tconst requiredSet = new Set(required);\n\tconst args = properties\n\t\t? orderedPropertyNames(properties, required)\n\t\t\t\t.map((name) => {\n\t\t\t\t\tconst schema = schemaRecord(properties[name]);\n\t\t\t\t\tconst optional = requiredSet.has(name) ? \"\" : \"?\";\n\t\t\t\t\tconst defaultText = schema && \"default\" in schema ? formatDefault(schema.default) : \"\";\n\t\t\t\t\treturn `${name}:${typeLabel(schema)}${optional}${defaultText}`;\n\t\t\t\t})\n\t\t\t\t.join(\", \")\n\t\t: \"\";\n\tconst description = tool.description.replace(/\\s+/g, \" \").trim();\n\treturn `${tool.name}(${args}) - ${description}`;\n}\n\nfunction toolHasArrayParameter(tool: Tool): boolean {\n\tconst parameters = schemaRecord(tool.parameters);\n\tconst properties = schemaRecord(parameters?.properties);\n\tif (!properties) return false;\n\treturn Object.values(properties).some((schemaValue) => schemaType(schemaRecord(schemaValue) ?? {}) === \"array\");\n}\n\nfunction exampleTools(tools: readonly Tool[]): Tool[] {\n\tconst examples: Tool[] = [];\n\tconst readTool = tools.find((tool) => tool.name === \"read\");\n\tif (readTool) examples.push(readTool);\n\tif (examples.length === 0) examples.push(tools[0]);\n\tconst editTool = tools.find((tool) => tool.name === \"edit\" && !examples.includes(tool));\n\tconst arrayTool = editTool ?? tools.find((tool) => !examples.includes(tool) && toolHasArrayParameter(tool));\n\tif (arrayTool) examples.push(arrayTool);\n\treturn examples;\n}\n\nfunction protocolHeader(variant: TextToolProtocolVariant): string[] {\n\treturn [\n\t\t\"Text tool-call protocol is enabled.\",\n\t\t\"When calling tools, output only one or more envelopes and no prose:\",\n\t\tformatVariantEnvelope(variant, \"TOOL\", '{\"arg\":\"value\"}'),\n\t\t\"Arguments must be valid JSON objects. Use double quotes for JSON keys and string values. Arrays are JSON arrays [ ], never quoted strings. Omit optional args you do not need - do not send null.\",\n\t\t\"User requests about files, directories, searches, edits, writes, or shell commands require a tool envelope first; do not describe results yourself.\",\n\t\t'If the user asks to read /tmp/example.txt, output exactly: <pi:call name=\"read\">{\"path\":\"/tmp/example.txt\"}</pi:call>',\n\t\t'For any request to read a file path, call read with {\"path\":\"THE_PATH\"}; never output {\"file_path\":..., \"content\":...} or invented file contents.',\n\t\t\"Never write raw shell commands such as read -t PATH, cat PATH, or ls PATH; use a tool-call envelope instead.\",\n\t\t\"Never output markdown code blocks, raw shell commands, file paths, or invented tool results instead of a tool call; use the envelope and wait for the real result.\",\n\t];\n}\n\nexport function generateTextToolProtocolPrimer(tools: readonly Tool[], options?: TextToolProtocolOptions): string {\n\tif (tools.length === 0) return \"\";\n\tconst variant = options?.variant ?? DEFAULT_TEXT_TOOL_PROTOCOL_VARIANT;\n\tconst lines = [...protocolHeader(variant), \"Examples:\"];\n\tfor (const tool of exampleTools(tools)) {\n\t\tlines.push(\n\t\t\tformatVariantEnvelope(variant, tool.name, JSON.stringify(exampleArgumentsForParameters(tool.parameters))),\n\t\t);\n\t}\n\tlines.push(\"Available tools:\");\n\tfor (const tool of tools) {\n\t\tlines.push(formatToolProjection(tool));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport function parseTextToolCalls(text: string, knownTools: readonly Tool[]): ParsedTextToolCalls {\n\tif (knownTools.length === 0) return { calls: [], text, attempted: false };\n\tconst matches = findToolEnvelopes(text);\n\tif (matches.length === 0) return { calls: [], text, attempted: false };\n\tif (hasOverlap(matches)) return { calls: [], text, attempted: true, failure: \"overlap\" };\n\tconst remainder = remainingText(text, matches);\n\tconst names = [...knownToolNames(knownTools)];\n\tconst calls = matches\n\t\t.map((match, index) => parseEnvelope(match, names, index + 1))\n\t\t.filter((call): call is ToolCall => call !== undefined);\n\treturn calls.length > 0\n\t\t? { calls, text: remainder.trim(), attempted: true }\n\t\t: { calls: [], text, attempted: true, failure: \"unrecognized\" };\n}\n"]}
@@ -14,6 +14,7 @@ export interface ToolArgumentValidationTelemetryEvent {
14
14
  provider?: string;
15
15
  model?: string;
16
16
  tool: string;
17
+ source?: ToolCall["source"];
17
18
  failureModes: ToolRepairFailureModeName[];
18
19
  repairsApplied: ToolRepairModeName[];
19
20
  failureShape?: ToolArgumentFailureShapeEntry[];