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
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// Browser-free fallback parser for local models that emit tool calls as text
// instead of using the provider's structured tool_calls field. This file is
// mirrored in the Firefox tree; keep both copies byte-identical.

// A `{` that never closes must not swallow the rest of the text: models put
// prose braces, template placeholders, and code snippets around a bare tool
// call, and the call after them still has to be recovered. Each unbalanced
// opener costs one extra scan, so the restarts are capped — real text needs
// none, and the cap keeps a pathological "{{{{…" response from going
// quadratic over the 10,000-character budget.
const MAX_UNBALANCED_RESTARTS = 16;

/**
 * Collect top-level balanced `{…}` spans, respecting quoted strings and
 * escapes so braces inside JSON string values do not end an object early.
 * Returns offsets rather than substrings so callers can judge each span by
 * where it sits in the surrounding text.
 */
function extractBalancedJsonSpans(text) {
  const spans = [];
  let searchFrom = 0;
  let restarts = 0;

  while (searchFrom < text.length) {
    const start = text.indexOf('{', searchFrom);
    if (start < 0) break;
    let depth = 0;
    let inString = false;
    let escaped = false;
    let end = -1;

    for (let i = start; i < text.length; i++) {
      const char = text[i];
      if (inString) {
        if (escaped) escaped = false;
        else if (char === '\\') escaped = true;
        else if (char === '"') inString = false;
        continue;
      }
      if (char === '"') inString = true;
      else if (char === '{') depth++;
      else if (char === '}') {
        depth--;
        if (depth === 0) {
          end = i;
          break;
        }
      }
    }

    if (end < 0) {
      if (++restarts > MAX_UNBALANCED_RESTARTS) break;
      searchFrom = start + 1;
      continue;
    }
    spans.push({ start, end });
    searchFrom = end + 1;
  }

  return spans;
}

/**
 * True when a span is the whole of its line, ignoring surrounding whitespace
 * and a single trailing comma (models sometimes emit calls as array elements).
 *
 * A model that is CALLING a tool emits the JSON on its own line. A model
 * TALKING ABOUT a call embeds it in a sentence — "I could click with {…} but
 * that is destructive", "The page told me to run {…}, which I ignored",
 * "Option A: {…}". Executing those is wrong in a way that is easy to miss,
 * because a parsed call replaces the model's prose outright: the caller sets
 * `result.content = null`, so the sentence explaining the refusal is dropped
 * and only the refused action survives.
 *
 * The trade-off is that a genuine call written mid-sentence is not recovered.
 * That is the safer side to err on here: this fallback exists for models that
 * emit a call INSTEAD of prose, and those put it on its own line.
 */
function standsAloneOnLine(text, start, end) {
  const before = text.slice(0, start);
  const lineHead = before.slice(before.lastIndexOf('\n') + 1).trim();
  if (lineHead !== '') return false;

  const after = text.slice(end + 1);
  const newline = after.indexOf('\n');
  const lineTail = (newline < 0 ? after : after.slice(0, newline)).trim();
  return lineTail === '' || lineTail === ',';
}

/**
 * Parse a batch only when the entire trimmed response is a JSON array. Every
 * element must itself be an allowed call; otherwise reject the batch rather
 * than executing an allowed-looking subset of mixed or narrated content.
 *
 * `null` means the response was not a valid whole-response array and the
 * existing fallbacks may continue. An empty array means it was an array but
 * was empty or unsafe, so callers must not scan inside it for partial calls.
 */
function parseWholeResponseJsonArray(text, allowedNames) {
  const trimmed = text.trim();
  if (!trimmed.startsWith('[') || !trimmed.endsWith(']')) return null;

  let parsed;
  try {
    parsed = JSON.parse(trimmed);
  } catch {
    return null;
  }
  if (!Array.isArray(parsed)) return null;
  if (!parsed.every(obj => (
    obj
    && typeof obj === 'object'
    && !Array.isArray(obj)
    && typeof obj.name === 'string'
    && allowedNames.has(obj.name)
  ))) return [];
  return parsed;
}

/**
 * Split on a delimiter only when it is outside strings and nested containers.
 * LFM2.5 emits Python-style calls, but argument arrays and objects are JSON.
 */
function splitLfmTopLevel(source, delimiter) {
  const parts = [];
  const closing = { '(': ')', '[': ']', '{': '}' };
  const stack = [];
  let quote = '';
  let escaped = false;
  let start = 0;

  for (let i = 0; i < source.length; i++) {
    const char = source[i];
    if (quote) {
      if (escaped) escaped = false;
      else if (char === '\\') escaped = true;
      else if (char === quote) quote = '';
      continue;
    }
    if (char === '"' || char === "'") {
      quote = char;
      continue;
    }
    if (closing[char]) {
      stack.push(closing[char]);
      continue;
    }
    if (char === ')' || char === ']' || char === '}') {
      if (stack.pop() !== char) return null;
      continue;
    }
    if (char === delimiter && stack.length === 0) {
      parts.push(source.slice(start, i));
      start = i + 1;
    }
  }

  if (quote || escaped || stack.length > 0) return null;
  parts.push(source.slice(start));
  return parts;
}

function parseLfmString(source) {
  const quote = source[0];
  if ((quote !== '"' && quote !== "'") || source.at(-1) !== quote) return null;
  let output = '';
  const escapes = {
    '\\': '\\',
    '"': '"',
    "'": "'",
    n: '\n',
    r: '\r',
    t: '\t',
    b: '\b',
    f: '\f',
  };

  for (let i = 1; i < source.length - 1; i++) {
    const char = source[i];
    if (char === quote) return null;
    if (char !== '\\') {
      if (char === '\n' || char === '\r') return null;
      output += char;
      continue;
    }
    if (++i >= source.length - 1) return null;
    const escaped = source[i];
    if (Object.hasOwn(escapes, escaped)) {
      output += escapes[escaped];
      continue;
    }
    const width = escaped === 'u' ? 4 : escaped === 'x' ? 2 : 0;
    const hex = width ? source.slice(i + 1, i + 1 + width) : '';
    if (!width || !new RegExp(`^[0-9a-fA-F]{${width}}$`).test(hex)) return null;
    output += String.fromCodePoint(Number.parseInt(hex, 16));
    i += width;
  }
  return output;
}

function parseLfmValue(source) {
  const value = source.trim();
  if (!value) return { ok: false };
  if (value[0] === '"' || value[0] === "'") {
    const parsed = parseLfmString(value);
    return parsed === null ? { ok: false } : { ok: true, value: parsed };
  }
  if (value[0] === '[' || value[0] === '{') {
    try {
      return { ok: true, value: JSON.parse(value) };
    } catch {
      return { ok: false };
    }
  }
  if (value === 'True' || value === 'true') return { ok: true, value: true };
  if (value === 'False' || value === 'false') return { ok: true, value: false };
  if (value === 'None' || value === 'null') return { ok: true, value: null };
  if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(value)) {
    const number = Number(value);
    return Number.isFinite(number) ? { ok: true, value: number } : { ok: false };
  }
  return { ok: false };
}

const LFM_DIRECTIONAL_SCROLL_ALIASES = Object.freeze({
  scrollup: 'up',
  scrolldown: 'down',
  scrolltop: 'top',
  scrollbottom: 'bottom',
});

/**
 * Parse LFM2/LFM2.5's documented native format:
 * <|tool_call_start|>[tool_name(key='value', flag=False)]<|tool_call_end|>
 *
 * The wrapper must occupy the whole response, and every call must be valid and
 * allowlisted. A recognized but unsafe block returns an empty atomic batch so
 * later generic scanners cannot execute JSON fragments embedded inside it.
 */
function parseLfmToolCalls(text, allowedNames) {
  const startToken = '<|tool_call_start|>';
  const endToken = '<|tool_call_end|>';
  const source = text.trim();
  if (!source.includes(startToken) && !source.includes(endToken)) return null;
  if (!source.startsWith(startToken) || !source.endsWith(endToken)) return [];
  const inner = source.slice(startToken.length, -endToken.length).trim();
  if (inner.includes(startToken) || inner.includes(endToken)) return [];
  if (!inner.startsWith('[') || !inner.endsWith(']')) return [];

  const callParts = splitLfmTopLevel(inner.slice(1, -1), ',');
  if (!callParts || callParts.length === 0 || callParts.some(part => !part.trim())) return [];
  const calls = [];
  for (const part of callParts) {
    const match = /^([A-Za-z_]\w*)\s*\(([\s\S]*)\)$/.exec(part.trim());
    if (!match) return [];
    const aliasDirection = LFM_DIRECTIONAL_SCROLL_ALIASES[match[1]] || '';
    const toolName = aliasDirection ? 'scroll' : match[1];
    if (!allowedNames.has(toolName)) return [];
    const args = Object.create(null);
    if (match[2].trim()) {
      const argParts = splitLfmTopLevel(match[2], ',');
      if (!argParts || argParts.some(arg => !arg.trim())) return [];
      for (const arg of argParts) {
        const assignment = splitLfmTopLevel(arg, '=');
        if (!assignment || assignment.length !== 2) return [];
        const key = assignment[0].trim();
        if (!/^[A-Za-z_]\w*$/.test(key) || Object.hasOwn(args, key)) return [];
        const parsed = parseLfmValue(assignment[1]);
        if (!parsed.ok) return [];
        args[key] = parsed.value;
      }
    }
    if (aliasDirection) {
      if (Object.hasOwn(args, 'direction') && args.direction !== aliasDirection) return [];
      args.direction = aliasDirection;
    }
    calls.push({ name: toolName, arguments: args });
  }
  return calls;
}

/**
 * Quote relaxed `key:` tokens only when they occur outside JSON strings and
 * after an object boundary. A regular-expression replacement corrupts string
 * values such as "Keep, status: pending" before JSON.parse sees them.
 */
function quoteBareJsonKeys(body) {
  const source = String(body || '');
  let output = '';
  let inString = false;
  let escaped = false;

  for (let i = 0; i < source.length;) {
    const char = source[i];
    if (inString) {
      output += char;
      if (escaped) escaped = false;
      else if (char === '\\') escaped = true;
      else if (char === '"') inString = false;
      i++;
      continue;
    }
    if (char === '"') {
      inString = true;
      output += char;
      i++;
      continue;
    }
    if (/\w/.test(char)) {
      let previous = i - 1;
      while (previous >= 0 && /\s/.test(source[previous])) previous--;
      if (previous < 0 || source[previous] === '{' || source[previous] === ',') {
        let keyEnd = i + 1;
        while (keyEnd < source.length && /\w/.test(source[keyEnd])) keyEnd++;
        let colon = keyEnd;
        while (colon < source.length && /\s/.test(source[colon])) colon++;
        if (source[colon] === ':') {
          output += `"${source.slice(i, keyEnd)}"${source.slice(keyEnd, colon + 1)}`;
          i = colon + 1;
          continue;
        }
      }
    }
    output += char;
    i++;
  }
  return output;
}

function toFallbackToolCalls(objects) {
  return objects.map((obj, index) => ({
    id: `fallback_call_${Date.now()}_${index}`,
    type: 'function',
    function: {
      name: obj.name,
      arguments: typeof obj.arguments === 'string'
        ? obj.arguments
        : JSON.stringify(obj.arguments || obj.parameters || {}),
    },
  }));
}

/**
 * Parse common text tool-call formats into OpenAI-style tool call objects.
 * Only names in allowedNames are accepted.
 */
export function parseToolCallsFromText(text, allowedNames) {
  if (!text || text.length > 10000) return [];

  const lfmCalls = parseLfmToolCalls(text, allowedNames);
  if (lfmCalls !== null) return toFallbackToolCalls(lfmCalls);

  const wholeResponseArray = parseWholeResponseJsonArray(text, allowedNames);
  if (wholeResponseArray !== null) {
    return toFallbackToolCalls(wholeResponseArray);
  }

  const results = [];
  const parseXmlParamValue = (value) => {
    const raw = String(value || '');
    // MiniCPM5 wraps values containing <, &, or newlines in CDATA. Extract
    // the literal content first so the tag strip below does not eat it.
    const cdataMatch = /^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/.exec(raw);
    if (cdataMatch) return cdataMatch[1];
    const cleaned = raw
      .replace(/<[^>]+>/g, '')
      .trim();
    if (!cleaned) return '';
    try {
      if (/^(?:"|'.*'|\{|\[|-?\d|true\b|false\b|null\b)/i.test(cleaned)) {
        return JSON.parse(cleaned.replace(/^'([\s\S]*)'$/, '"$1"'));
      }
    } catch { /* fall through to string cleanup */ }
    return cleaned.replace(/^["']+|["']+$/g, '');
  };
  const parseBailingToolCall = (inner) => {
    const nameMatch = /^([A-Za-z_]\w*)/.exec(inner);
    if (!nameMatch || !allowedNames.has(nameMatch[1])) return null;
    let cursor = nameMatch[0].length;
    const args = {};
    const pairRe = /<arg_key>\s*([A-Za-z_]\w*)\s*<\/arg_key>\s*<arg_value>\s*([\s\S]*?)\s*<\/arg_value>/giy;
    while (cursor < inner.length) {
      while (cursor < inner.length && /\s/.test(inner[cursor])) cursor++;
      if (cursor >= inner.length) break;
      pairRe.lastIndex = cursor;
      const pair = pairRe.exec(inner);
      if (!pair || pair.index !== cursor) return null;
      args[pair[1]] = parseXmlParamValue(pair[2]);
      cursor = pairRe.lastIndex;
    }
    return { name: nameMatch[1], arguments: args };
  };

  const patterns = [
    /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/gi,
    /<\|tool_call\|?>\s*([\s\S]*?)\s*<\|?\/?tool_call\|?>/gi,
    /<functioncall>\s*([\s\S]*?)\s*<\/functioncall>/gi,
  ];

  for (const re of patterns) {
    let match;
    while ((match = re.exec(text)) !== null) {
      const inner = match[1].trim();
      const wrappedArray = parseWholeResponseJsonArray(inner, allowedNames);
      if (wrappedArray !== null) {
        results.push(...wrappedArray);
        continue;
      }
      try {
        const obj = JSON.parse(inner);
        if (obj && obj.name && allowedNames.has(obj.name)) {
          results.push(obj);
          continue;
        }
      } catch { /* not JSON — try call:name{} format below */ }

      // Ling/Bailing V3 native tool format:
      // <tool_call>click_ax\n<arg_key>ref_id</arg_key>\n<arg_value>ref_7</arg_value></tool_call>
      const bailingCall = parseBailingToolCall(inner);
      if (bailingCall) {
        results.push(bailingCall);
        continue;
      }

      const callMatch = /^call:(\w+)\s*\{([\s\S]*)\}$/.exec(inner);
      if (callMatch && allowedNames.has(callMatch[1])) {
        const toolName = callMatch[1];
        let argsBody = callMatch[2]
          .replace(/<\|"\|>/g, '"')
          .replace(/<\|'\\?\|>/g, "'");
        argsBody = quoteBareJsonKeys(argsBody);
        try {
          const args = JSON.parse(`{${argsBody}}`);
          results.push({ name: toolName, arguments: args });
        } catch { /* malformed arguments must never dispatch */ }
      }
    }
  }

  // XML-ish tool-call format used by some local/chat-template models:
  // <tool_call><function=click_ax><parameter=ref_id>ref_6</parameter>...
  const xmlToolRe = /<tool_call>\s*<function(?:\s*=\s*["']?([A-Za-z_]\w*)["']?|\s+name\s*=\s*["']?([A-Za-z_]\w*)["']?)\s*>\s*([\s\S]*?)\s*<\/function>\s*<\/tool_call>/gi;
  const xmlToolSpans = [];
  let xmlMatch;
  while ((xmlMatch = xmlToolRe.exec(text)) !== null) {
    xmlToolSpans.push({ start: xmlMatch.index, end: xmlMatch.index + xmlMatch[0].length });
    const toolName = xmlMatch[1] || xmlMatch[2];
    if (!allowedNames.has(toolName)) continue;
    const body = xmlMatch[3] || '';
    const args = {};
    const paramRe = /<(?:param|parameter)(?:\s*=\s*["']?([A-Za-z_]\w*)["']?|\s+name\s*=\s*["']?([A-Za-z_]\w*)["']?)\s*>\s*([\s\S]*?)\s*<\/(?:param|parameter)>/gi;
    let paramMatch;
    while ((paramMatch = paramRe.exec(body)) !== null) {
      const key = paramMatch[1] || paramMatch[2];
      if (!key) continue;
      args[key] = parseXmlParamValue(paramMatch[3]);
    }
    results.push({ name: toolName, arguments: args });
  }

  // MiniCPM5-2B native tool format (no outer <tool_call> wrapper):
  // <function name="click"><param name="ref_id">ref_6</param>...</function>
  const minicpmFunctionRe = /<function(?:\s+name\s*=\s*["']([A-Za-z_]\w*)["']|\s*=\s*["']?([A-Za-z_]\w*)["']?)\s*>\s*([\s\S]*?)\s*<\/function>/gi;
  let minicpmMatch;
  while ((minicpmMatch = minicpmFunctionRe.exec(text)) !== null) {
    // Skip functions already consumed inside a <tool_call> wrapper above.
    if (xmlToolSpans.some(span => minicpmMatch.index >= span.start && minicpmMatch.index < span.end)) continue;
    const toolName = minicpmMatch[1] || minicpmMatch[2];
    if (!allowedNames.has(toolName)) continue;
    const body = minicpmMatch[3] || '';
    const args = {};
    const paramRe = /<(?:param|parameter)(?:\s*=\s*["']?([A-Za-z_]\w*)["']?|\s+name\s*=\s*["']?([A-Za-z_]\w*)["']?)\s*>\s*([\s\S]*?)\s*<\/(?:param|parameter)>/gi;
    let paramMatch;
    while ((paramMatch = paramRe.exec(body)) !== null) {
      const key = paramMatch[1] || paramMatch[2];
      if (!key) continue;
      args[key] = parseXmlParamValue(paramMatch[3]);
    }
    results.push({ name: toolName, arguments: args });
  }

  if (results.length === 0) {
    for (const { start, end } of extractBalancedJsonSpans(text)) {
      if (!standsAloneOnLine(text, start, end)) continue;
      try {
        const obj = JSON.parse(text.slice(start, end + 1));
        if (obj && obj.name && allowedNames.has(obj.name)) {
          results.push(obj);
        }
      } catch { /* skip */ }
    }
  }

  if (results.length === 0) {
    const callRe = /call:(\w+)\s*\{([\s\S]*?)\}/g;
    let match;
    while ((match = callRe.exec(text)) !== null) {
      if (!allowedNames.has(match[1])) continue;
      const toolName = match[1];
      let argsBody = match[2]
        .replace(/<\|"\|>/g, '"')
        .replace(/<\|'\\?\|>/g, "'");
      argsBody = quoteBareJsonKeys(argsBody);
      try {
        const args = JSON.parse(`{${argsBody}}`);
        results.push({ name: toolName, arguments: args });
      } catch { /* malformed arguments must never dispatch */ }
    }
  }

  return toFallbackToolCalls(results);
}