@causyne/agent 1.13.0 → 1.14.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.
@@ -0,0 +1,759 @@
1
+ /**
2
+ * Causyne Agent — Universal Tool Self-Repair & Healing Buffer (toolsSelfRepair)
3
+ *
4
+ * Intercepts, sanitizes, heals, and type-coerces LLM tool calls at runtime.
5
+ * Automatically recovers from malformed JSON, unescaped newlines, trailing
6
+ * commas, single quotes, parameter name hallucinations, and type mismatches
7
+ * without degrading tool functionality or throwing unhandled errors.
8
+ */
9
+ import path from 'node:path';
10
+ /**
11
+ * Universal tool name alias dictionary. Maps hallucinations from OpenAI,
12
+ * Anthropic, DeepSeek, Qwen, Ollama, etc. to Causyne Agent canonical tool names.
13
+ */
14
+ export const TOOL_NAME_ALIASES = {
15
+ // Core filesystem
16
+ read_file: 'fs_read',
17
+ readFile: 'fs_read',
18
+ view_file: 'fs_read',
19
+ cat: 'fs_read',
20
+ write_file: 'fs_write',
21
+ writeFile: 'fs_write',
22
+ write_to_file: 'fs_write',
23
+ create_file: 'fs_write',
24
+ edit_file: 'fs_edit',
25
+ editFile: 'fs_edit',
26
+ replace_file_content: 'fs_edit',
27
+ modify_file: 'fs_edit',
28
+ delete_file: 'fs_delete',
29
+ deleteFile: 'fs_delete',
30
+ remove_file: 'fs_delete',
31
+ rm: 'fs_delete',
32
+ list_dir: 'fs_list',
33
+ listDir: 'fs_list',
34
+ list_files: 'fs_list',
35
+ listFiles: 'fs_list',
36
+ list_directory: 'fs_list',
37
+ ls: 'fs_list',
38
+ find_files: 'fs_find',
39
+ findFiles: 'fs_find',
40
+ find_file: 'fs_find',
41
+ glob: 'fs_find',
42
+ search_files: 'fs_search',
43
+ grep: 'fs_search',
44
+ grep_search: 'fs_search',
45
+ move_file: 'fs_move',
46
+ moveFile: 'fs_move',
47
+ rename_file: 'fs_move',
48
+ mv: 'fs_move',
49
+ patch: 'MultiEdit',
50
+ multi_edit: 'MultiEdit',
51
+ multiedit: 'MultiEdit',
52
+ diff_edit: 'MultiEdit',
53
+ // Execution & shell
54
+ sys_run: 'sysRun',
55
+ sysrun: 'sysRun',
56
+ run_command: 'sysRun',
57
+ runCommand: 'sysRun',
58
+ bash: 'sysRun',
59
+ sh: 'sysRun',
60
+ terminal: 'sysRun',
61
+ exec_command: 'sysRun',
62
+ execute_command: 'sysRun',
63
+ shell: 'sysRun',
64
+ sys_run_bg: 'sysRunBg',
65
+ sysrunbg: 'sysRunBg',
66
+ sysRun_bg: 'sysRunBg',
67
+ run_bg: 'sysRunBg',
68
+ run_background: 'sysRunBg',
69
+ background_run: 'sysRunBg',
70
+ git_op: 'gitOp',
71
+ gitop: 'gitOp',
72
+ git: 'gitOp',
73
+ gitExec: 'gitOp',
74
+ procTerm: 'proc_term',
75
+ persistent_shell: 'terminal_persistent_shell',
76
+ terminal_shell: 'terminal_persistent_shell',
77
+ // Web & search
78
+ search_web: 'web_search',
79
+ searchWeb: 'web_search',
80
+ google_search: 'web_search',
81
+ search_internet: 'web_search',
82
+ fetch_url: 'web_fetch',
83
+ fetchUrl: 'web_fetch',
84
+ read_url: 'web_fetch',
85
+ read_url_content: 'web_fetch',
86
+ http_get: 'web_fetch',
87
+ // Specialized engines & capabilities
88
+ nativeEngine: 'native_engine',
89
+ 'native-engine': 'native_engine',
90
+ creativeApps: 'creative_apps',
91
+ 'creative-apps': 'creative_apps',
92
+ astryxOracle: 'astryx_oracle',
93
+ pdfRead: 'pdf_read',
94
+ codeVerifySyntax: 'code_verify_syntax',
95
+ codeListSymbols: 'code_list_symbols',
96
+ codeSearchAst: 'code_search_ast',
97
+ codeSearcher: 'code_search_ripgrep',
98
+ blenderAutomator: 'blender_act',
99
+ resolveAutomator: 'resolve_act',
100
+ palmierAutomator: 'palmier_act',
101
+ godotAutomator: 'godot_act',
102
+ visionInspector: 'vision_inspect_ui',
103
+ vision_inspector: 'vision_inspect_ui',
104
+ vision_inspect: 'vision_inspect_ui',
105
+ computerUse: 'computer_use',
106
+ uiForge: 'ui_forge',
107
+ documentForge: 'document_forge',
108
+ documentForgeTool: 'document_forge',
109
+ peerAgent: 'peer_agent_delegate',
110
+ peer_agent: 'peer_agent_delegate',
111
+ openSourceToolProvisioner: 'open_source_tool_provisioner',
112
+ open_source_tool: 'open_source_tool_provisioner',
113
+ subagent: 'agent_subagent_orchestrate',
114
+ subagent_orchestrator: 'agent_subagent_orchestrate',
115
+ spawn_subagent: 'agent_subagent_orchestrate',
116
+ agent_orchestrator: 'agent_subagent_orchestrate',
117
+ printer_status: 'printer_get_status',
118
+ printer_list: 'printer_list_printers',
119
+ create_skill: 'skill_create',
120
+ read_skill: 'fs_read_skill',
121
+ readNativeSkill: 'fs_read_skill',
122
+ take_screenshot: 'screenshot',
123
+ capture_screenshot: 'screenshot',
124
+ open_file: 'desktop_open',
125
+ open_desktop: 'desktop_open',
126
+ TodoWrite: 'update_plan',
127
+ manage_local_ai_dependencies: 'manage_local_dependencies',
128
+ tool_deferred_mcp_search: 'tool_search'
129
+ };
130
+ function stripDelimiters(str) {
131
+ return String(str || '').toLowerCase().replace(/[-_.]/g, '');
132
+ }
133
+ const DELIMITER_FREE_TOOL_INDEX = {};
134
+ for (const [alias, canonical] of Object.entries(TOOL_NAME_ALIASES)) {
135
+ DELIMITER_FREE_TOOL_INDEX[stripDelimiters(alias)] = canonical;
136
+ DELIMITER_FREE_TOOL_INDEX[stripDelimiters(canonical)] = canonical;
137
+ }
138
+ /**
139
+ * Resolve any raw tool name (including hallucinated or camelCased names) to its canonical tool name.
140
+ */
141
+ export function canonicalizeToolName(rawName) {
142
+ const normalized = String(rawName || '').replace(/\./g, '_');
143
+ if (TOOL_NAME_ALIASES[normalized]) {
144
+ return TOOL_NAME_ALIASES[normalized];
145
+ }
146
+ const stripped = stripDelimiters(rawName);
147
+ if (DELIMITER_FREE_TOOL_INDEX[stripped]) {
148
+ return DELIMITER_FREE_TOOL_INDEX[stripped];
149
+ }
150
+ return normalized;
151
+ }
152
+ /**
153
+ * Universal parameter alias dictionary mapping common LLM hallucinated
154
+ * parameter names to their canonical schema counterparts.
155
+ */
156
+ const PARAMETER_ALIASES = {
157
+ path: [
158
+ 'filepath', 'file_path', 'filePath', 'targetFile', 'target_file',
159
+ 'fileName', 'file_name', 'file', 'target', 'dir', 'folder',
160
+ 'src_path', 'source_file', 'target_path'
161
+ ],
162
+ file_path: [
163
+ 'path', 'filepath', 'filePath', 'targetFile', 'target_file',
164
+ 'fileName', 'file_name', 'file', 'target'
165
+ ],
166
+ command: [
167
+ 'cmd', 'bash', 'sh', 'script', 'shell', 'exec',
168
+ 'terminalCommand', 'run', 'instruction'
169
+ ],
170
+ query: [
171
+ 'q', 'search', 'term', 'pattern', 'search_term',
172
+ 'searchQuery', 'find', 'prompt'
173
+ ],
174
+ pattern: [
175
+ 'query', 'q', 'search', 'regex', 'term', 'filter'
176
+ ],
177
+ content: [
178
+ 'contents', 'data', 'text', 'body', 'code', 'payload', 'input'
179
+ ],
180
+ destination: [
181
+ 'dest', 'to', 'targetPath', 'destPath', 'destination_path', 'target_path'
182
+ ],
183
+ source: [
184
+ 'src', 'from', 'sourcePath', 'source_path', 'source_file'
185
+ ],
186
+ action: [
187
+ 'act', 'operation', 'op', 'mode', 'method'
188
+ ],
189
+ message: [
190
+ 'msg', 'prompt', 'text', 'note'
191
+ ],
192
+ reason: [
193
+ 'why', 'justification', 'details', 'explanation'
194
+ ],
195
+ filter: [
196
+ 'pattern', 'glob', 'regex', 'matching'
197
+ ],
198
+ options: [
199
+ 'opts', 'config', 'settings', 'params'
200
+ ],
201
+ timeout: [
202
+ 'timeoutMs', 'timeout_ms', 'timeoutSec', 'duration'
203
+ ],
204
+ url: [
205
+ 'link', 'href', 'endpoint', 'uri', 'target_url'
206
+ ]
207
+ };
208
+ /**
209
+ * Attempt to repair and parse potentially malformed JSON argument strings.
210
+ */
211
+ export function repairJsonArguments(rawInput) {
212
+ const repairs = [];
213
+ // 1. If already an object, return as-is
214
+ if (rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)) {
215
+ return {
216
+ args: { ...rawInput },
217
+ repaired: false,
218
+ repairs: []
219
+ };
220
+ }
221
+ if (typeof rawInput !== 'string') {
222
+ return {
223
+ args: {},
224
+ repaired: false,
225
+ repairs: []
226
+ };
227
+ }
228
+ let text = rawInput.trim();
229
+ if (text === '' || text === '{}') {
230
+ return {
231
+ args: {},
232
+ repaired: false,
233
+ repairs: []
234
+ };
235
+ }
236
+ // 2. Fast path: native parse
237
+ try {
238
+ const parsed = JSON.parse(text);
239
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
240
+ return { args: parsed, repaired: false, repairs: [] };
241
+ }
242
+ if (Array.isArray(parsed)) {
243
+ return { args: { items: parsed }, repaired: true, repairs: ['Wrapped array payload into items property'] };
244
+ }
245
+ }
246
+ catch {
247
+ // Proceed to healing pipeline
248
+ }
249
+ let healed = text;
250
+ // 3. Strip Markdown code fences: ```json ... ``` or ``` ... ```
251
+ if (healed.includes('```')) {
252
+ const fenceMatch = healed.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
253
+ if (fenceMatch && fenceMatch[1]) {
254
+ healed = fenceMatch[1].trim();
255
+ repairs.push('Stripped markdown code fence block');
256
+ }
257
+ }
258
+ // 4. Extract first balanced JSON object if surrounded by conversational filler
259
+ if (!healed.startsWith('{')) {
260
+ const startIdx = healed.indexOf('{');
261
+ const endIdx = healed.lastIndexOf('}');
262
+ if (startIdx !== -1 && endIdx > startIdx) {
263
+ healed = healed.slice(startIdx, endIdx + 1).trim();
264
+ repairs.push('Extracted JSON object substring from conversational output');
265
+ }
266
+ }
267
+ // 5. Native parse retry after stripping markdown/filler
268
+ try {
269
+ const parsed = JSON.parse(healed);
270
+ if (parsed && typeof parsed === 'object') {
271
+ return { args: parsed, repaired: true, repairs };
272
+ }
273
+ }
274
+ catch {
275
+ // Proceed to syntax healing
276
+ }
277
+ // 6. Fix unescaped control characters & newlines inside strings
278
+ healed = sanitizeUnescapedStringLiterals(healed);
279
+ // 7. Remove trailing commas before } or ]
280
+ const trailingCommaFixed = healed.replace(/,\s*([}\]])/g, '$1');
281
+ if (trailingCommaFixed !== healed) {
282
+ healed = trailingCommaFixed;
283
+ repairs.push('Removed trailing commas');
284
+ }
285
+ // 8. Convert single-quoted keys/values to double-quoted keys/values
286
+ if (healed.includes("'")) {
287
+ const doubleQuoted = convertSingleQuotesToJson(healed);
288
+ if (doubleQuoted !== healed) {
289
+ healed = doubleQuoted;
290
+ repairs.push('Converted single quotes to valid JSON double quotes');
291
+ }
292
+ }
293
+ // 9. Recover truncated JSON by balancing braces/brackets
294
+ healed = balanceTruncatedJson(healed, repairs);
295
+ // 10. Final parse attempt
296
+ try {
297
+ const parsed = JSON.parse(healed);
298
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
299
+ return { args: parsed, repaired: true, repairs };
300
+ }
301
+ if (Array.isArray(parsed)) {
302
+ return { args: { items: parsed }, repaired: true, repairs: [...repairs, 'Wrapped array payload into items'] };
303
+ }
304
+ }
305
+ catch (err) {
306
+ const errorMsg = err instanceof Error ? err.message : String(err);
307
+ return {
308
+ args: {},
309
+ repaired: false,
310
+ repairs,
311
+ error: `JSON parse recovery failed: ${errorMsg}`
312
+ };
313
+ }
314
+ return { args: {}, repaired: false, repairs };
315
+ }
316
+ /**
317
+ * Handle unescaped newlines/tabs inside string literals without breaking valid JSON escapes.
318
+ */
319
+ function sanitizeUnescapedStringLiterals(input) {
320
+ let result = '';
321
+ let inString = false;
322
+ let escapeNext = false;
323
+ for (let i = 0; i < input.length; i++) {
324
+ const char = input[i];
325
+ if (escapeNext) {
326
+ result += char;
327
+ escapeNext = false;
328
+ continue;
329
+ }
330
+ if (char === '\\') {
331
+ escapeNext = true;
332
+ result += char;
333
+ continue;
334
+ }
335
+ if (char === '"') {
336
+ inString = !inString;
337
+ result += char;
338
+ continue;
339
+ }
340
+ if (inString) {
341
+ if (char === '\n') {
342
+ result += '\\n';
343
+ continue;
344
+ }
345
+ if (char === '\r') {
346
+ result += '\\r';
347
+ continue;
348
+ }
349
+ if (char === '\t') {
350
+ result += '\\t';
351
+ continue;
352
+ }
353
+ }
354
+ result += char;
355
+ }
356
+ return result;
357
+ }
358
+ /**
359
+ * Convert simple single-quoted JSON objects to valid double-quoted JSON.
360
+ */
361
+ function convertSingleQuotesToJson(input) {
362
+ return input.replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g, (_match, inner) => {
363
+ const escaped = inner.replace(/"/g, '\\"');
364
+ return `"${escaped}"`;
365
+ });
366
+ }
367
+ /**
368
+ * Balance unmatched brackets/braces if the LLM output was truncated.
369
+ */
370
+ function balanceTruncatedJson(input, repairs) {
371
+ let str = input.trim();
372
+ const stack = [];
373
+ let inString = false;
374
+ let escapeNext = false;
375
+ for (let i = 0; i < str.length; i++) {
376
+ const char = str[i];
377
+ if (escapeNext) {
378
+ escapeNext = false;
379
+ continue;
380
+ }
381
+ if (char === '\\') {
382
+ escapeNext = true;
383
+ continue;
384
+ }
385
+ if (char === '"') {
386
+ inString = !inString;
387
+ continue;
388
+ }
389
+ if (inString)
390
+ continue;
391
+ if (char === '{' || char === '[') {
392
+ stack.push(char);
393
+ }
394
+ else if (char === '}') {
395
+ if (stack.length > 0 && stack[stack.length - 1] === '{') {
396
+ stack.pop();
397
+ }
398
+ }
399
+ else if (char === ']') {
400
+ if (stack.length > 0 && stack[stack.length - 1] === '[') {
401
+ stack.pop();
402
+ }
403
+ }
404
+ }
405
+ // If a string was left open, close it
406
+ if (inString) {
407
+ str += '"';
408
+ repairs.push('Closed unclosed string literal');
409
+ }
410
+ // Balance remaining open brackets/braces in reverse order
411
+ if (stack.length > 0) {
412
+ while (stack.length > 0) {
413
+ const open = stack.pop();
414
+ if (open === '{')
415
+ str += '}';
416
+ if (open === '[')
417
+ str += ']';
418
+ }
419
+ repairs.push('Balanced unclosed braces/brackets on truncated JSON');
420
+ }
421
+ return str;
422
+ }
423
+ /**
424
+ * Map hallucinated parameter aliases to the canonical parameter names expected by the tool schema,
425
+ * with deep structural healing for complex tools (fs_edit, MultiEdit, native_engine, creative_apps).
426
+ */
427
+ export function resolveParameterAliases(toolName, args, schema) {
428
+ const repairs = [];
429
+ const modified = { ...args };
430
+ const canonicalName = canonicalizeToolName(toolName);
431
+ // 1. Specialized structural healing: fs_edit vs MultiEdit
432
+ if (canonicalName === 'fs_edit') {
433
+ // If edits is missing, synthesize from top-level fields
434
+ if (!modified.edits && (modified.searchContent || modified.old_string || modified.oldText || modified.find)) {
435
+ const search = (modified.searchContent || modified.old_string || modified.oldText || modified.find || '');
436
+ const replace = (modified.replaceContent || modified.new_string || modified.newText || modified.replacement || '');
437
+ modified.edits = [{ searchContent: search, replaceContent: replace }];
438
+ delete modified.searchContent;
439
+ delete modified.old_string;
440
+ delete modified.oldText;
441
+ delete modified.find;
442
+ delete modified.replaceContent;
443
+ delete modified.new_string;
444
+ delete modified.newText;
445
+ delete modified.replacement;
446
+ repairs.push("Synthesized 'edits' array from top-level edit parameters for 'fs_edit'");
447
+ }
448
+ else if (Array.isArray(modified.edits)) {
449
+ modified.edits = modified.edits.map((item) => {
450
+ if (!item || typeof item !== 'object')
451
+ return item;
452
+ const normalizedItem = { ...item };
453
+ if (!normalizedItem.searchContent && (normalizedItem.old_string || normalizedItem.oldText || normalizedItem.find)) {
454
+ normalizedItem.searchContent = normalizedItem.old_string || normalizedItem.oldText || normalizedItem.find;
455
+ }
456
+ if (!normalizedItem.replaceContent && (normalizedItem.new_string || normalizedItem.newText || normalizedItem.replace)) {
457
+ normalizedItem.replaceContent = normalizedItem.new_string || normalizedItem.newText || normalizedItem.replace;
458
+ }
459
+ return normalizedItem;
460
+ });
461
+ }
462
+ }
463
+ else if (canonicalName === 'MultiEdit') {
464
+ if (!modified.edits && (modified.old_string || modified.searchContent || modified.oldText || modified.find)) {
465
+ const search = (modified.old_string || modified.searchContent || modified.oldText || modified.find || '');
466
+ const replace = (modified.new_string || modified.replaceContent || modified.newText || modified.replacement || '');
467
+ modified.edits = [{ old_string: search, new_string: replace }];
468
+ delete modified.searchContent;
469
+ delete modified.old_string;
470
+ delete modified.oldText;
471
+ delete modified.find;
472
+ delete modified.replaceContent;
473
+ delete modified.new_string;
474
+ delete modified.newText;
475
+ delete modified.replacement;
476
+ repairs.push("Synthesized 'edits' array from top-level edit parameters for 'MultiEdit'");
477
+ }
478
+ else if (Array.isArray(modified.edits)) {
479
+ modified.edits = modified.edits.map((item) => {
480
+ if (!item || typeof item !== 'object')
481
+ return item;
482
+ const normalizedItem = { ...item };
483
+ if (!normalizedItem.old_string && (normalizedItem.searchContent || normalizedItem.oldText || normalizedItem.find)) {
484
+ normalizedItem.old_string = normalizedItem.searchContent || normalizedItem.oldText || normalizedItem.find;
485
+ }
486
+ if (!normalizedItem.new_string && (normalizedItem.replaceContent || normalizedItem.newText || normalizedItem.replace)) {
487
+ normalizedItem.new_string = normalizedItem.replaceContent || normalizedItem.newText || normalizedItem.replace;
488
+ }
489
+ return normalizedItem;
490
+ });
491
+ }
492
+ }
493
+ else if (canonicalName === 'native_engine') {
494
+ if (Array.isArray(modified.steps)) {
495
+ modified.steps = modified.steps.map((item) => {
496
+ if (!item || typeof item !== 'object')
497
+ return item;
498
+ const norm = { ...item };
499
+ if (!norm.id && (norm.name || norm.action || norm.command || norm.task)) {
500
+ norm.id = norm.name || norm.action || norm.command || norm.task;
501
+ }
502
+ if (!norm.params && (norm.args || norm.arguments || norm.options || norm.data)) {
503
+ norm.params = norm.args || norm.arguments || norm.options || norm.data;
504
+ }
505
+ return norm;
506
+ });
507
+ }
508
+ }
509
+ else if (canonicalName === 'creative_apps') {
510
+ if (Array.isArray(modified.actions)) {
511
+ modified.actions = modified.actions.map((item) => {
512
+ if (!item || typeof item !== 'object')
513
+ return item;
514
+ const norm = { ...item };
515
+ if (!norm.action && (norm.command || norm.name || norm.operation)) {
516
+ norm.action = norm.command || norm.name || norm.operation;
517
+ }
518
+ if (!norm.parameters && (norm.params || norm.args || norm.arguments)) {
519
+ norm.parameters = norm.params || norm.args || norm.arguments;
520
+ }
521
+ return norm;
522
+ });
523
+ }
524
+ }
525
+ // 2. Identify expected parameters from schema or default aliases
526
+ const expectedKeys = new Set();
527
+ if (schema && schema.properties) {
528
+ for (const key of Object.keys(schema.properties)) {
529
+ expectedKeys.add(key);
530
+ }
531
+ }
532
+ // 3. Resolve top-level parameter aliases
533
+ for (const [canonicalParam, aliases] of Object.entries(PARAMETER_ALIASES)) {
534
+ const isExpected = expectedKeys.size === 0 || expectedKeys.has(canonicalParam);
535
+ if (!isExpected)
536
+ continue;
537
+ if (modified[canonicalParam] === undefined || modified[canonicalParam] === null || modified[canonicalParam] === '') {
538
+ for (const alias of aliases) {
539
+ if (modified[alias] !== undefined && modified[alias] !== null && modified[alias] !== '') {
540
+ modified[canonicalParam] = modified[alias];
541
+ repairs.push(`Mapped hallucinated parameter alias '${alias}' -> '${canonicalParam}' for tool '${canonicalName}'`);
542
+ break;
543
+ }
544
+ }
545
+ }
546
+ }
547
+ return {
548
+ args: modified,
549
+ repaired: repairs.length > 0,
550
+ repairs
551
+ };
552
+ }
553
+ /**
554
+ * Automatically coerce argument types according to the tool's parameter schema.
555
+ */
556
+ export function coerceArgumentTypes(toolName, args, schema) {
557
+ const repairs = [];
558
+ const modified = { ...args };
559
+ if (!schema || !schema.properties) {
560
+ return { args: modified, repaired: false, repairs: [] };
561
+ }
562
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
563
+ if (!(key in modified))
564
+ continue;
565
+ const val = modified[key];
566
+ const expectedType = propSchema.type;
567
+ // 1. Number / Integer coercion
568
+ if (expectedType === 'number' || expectedType === 'integer') {
569
+ if (typeof val === 'string') {
570
+ const trimmed = val.trim();
571
+ if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
572
+ const num = expectedType === 'integer' ? parseInt(trimmed, 10) : parseFloat(trimmed);
573
+ if (!isNaN(num)) {
574
+ modified[key] = num;
575
+ repairs.push(`Coerced string "${val}" -> number ${num} for parameter '${key}'`);
576
+ }
577
+ }
578
+ }
579
+ else if (Array.isArray(val) && val.length === 1) {
580
+ const item = val[0];
581
+ if (typeof item === 'number') {
582
+ modified[key] = item;
583
+ repairs.push(`Unwrapped single-element array to number for parameter '${key}'`);
584
+ }
585
+ else if (typeof item === 'string' && /^-?\d+(\.\d+)?$/.test(item.trim())) {
586
+ modified[key] = expectedType === 'integer' ? parseInt(item.trim(), 10) : parseFloat(item.trim());
587
+ repairs.push(`Unwrapped single-element array to number for parameter '${key}'`);
588
+ }
589
+ }
590
+ }
591
+ // 2. Boolean coercion
592
+ if (expectedType === 'boolean') {
593
+ if (typeof val === 'string') {
594
+ const lower = val.trim().toLowerCase();
595
+ if (lower === 'true' || lower === '1') {
596
+ modified[key] = true;
597
+ repairs.push(`Coerced string "${val}" -> boolean true for parameter '${key}'`);
598
+ }
599
+ else if (lower === 'false' || lower === '0') {
600
+ modified[key] = false;
601
+ repairs.push(`Coerced string "${val}" -> boolean false for parameter '${key}'`);
602
+ }
603
+ }
604
+ else if (typeof val === 'number') {
605
+ modified[key] = val !== 0;
606
+ repairs.push(`Coerced number ${val} -> boolean ${modified[key]} for parameter '${key}'`);
607
+ }
608
+ }
609
+ // 3. Array coercion (auto-wraps single objects and parses strings)
610
+ if (expectedType === 'array') {
611
+ if (typeof val === 'string') {
612
+ const trimmed = val.trim();
613
+ if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
614
+ try {
615
+ const parsed = JSON.parse(trimmed);
616
+ if (Array.isArray(parsed)) {
617
+ modified[key] = parsed;
618
+ repairs.push(`Parsed stringified array for parameter '${key}'`);
619
+ }
620
+ }
621
+ catch {
622
+ // Passthrough
623
+ }
624
+ }
625
+ else if (trimmed.includes(',')) {
626
+ modified[key] = trimmed.split(',').map((s) => s.trim());
627
+ repairs.push(`Split comma-separated string into array for parameter '${key}'`);
628
+ }
629
+ else if (trimmed.length > 0) {
630
+ modified[key] = [trimmed];
631
+ repairs.push(`Wrapped single string into array for parameter '${key}'`);
632
+ }
633
+ }
634
+ else if (val && typeof val === 'object' && !Array.isArray(val)) {
635
+ modified[key] = [val];
636
+ repairs.push(`Wrapped single object into array for parameter '${key}'`);
637
+ }
638
+ }
639
+ // 4. Object coercion
640
+ if (expectedType === 'object') {
641
+ if (typeof val === 'string') {
642
+ const trimmed = val.trim();
643
+ if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
644
+ try {
645
+ const parsed = JSON.parse(trimmed);
646
+ if (parsed && typeof parsed === 'object') {
647
+ modified[key] = parsed;
648
+ repairs.push(`Parsed stringified JSON object for parameter '${key}'`);
649
+ }
650
+ }
651
+ catch {
652
+ // Passthrough
653
+ }
654
+ }
655
+ }
656
+ }
657
+ // 5. String coercion (unwrapping single-element arrays)
658
+ if (expectedType === 'string') {
659
+ if (Array.isArray(val) && val.length === 1 && typeof val[0] === 'string') {
660
+ modified[key] = val[0];
661
+ repairs.push(`Unwrapped single-element array to string for parameter '${key}'`);
662
+ }
663
+ }
664
+ }
665
+ return {
666
+ args: modified,
667
+ repaired: repairs.length > 0,
668
+ repairs
669
+ };
670
+ }
671
+ /**
672
+ * Automatically normalize relative file paths to absolute paths using cwd.
673
+ */
674
+ export function normalizePaths(args, cwd = process.cwd()) {
675
+ const repairs = [];
676
+ const modified = { ...args };
677
+ const pathKeys = ['path', 'file_path', 'source', 'destination', 'targetFile'];
678
+ for (const key of pathKeys) {
679
+ const val = modified[key];
680
+ if (typeof val === 'string' && val.trim() !== '') {
681
+ const trimmed = val.trim();
682
+ if (!path.isAbsolute(trimmed) && !trimmed.startsWith('~')) {
683
+ modified[key] = path.resolve(cwd, trimmed);
684
+ repairs.push(`Normalized relative path '${trimmed}' -> '${modified[key]}' for parameter '${key}'`);
685
+ }
686
+ }
687
+ }
688
+ return {
689
+ args: modified,
690
+ repaired: repairs.length > 0,
691
+ repairs
692
+ };
693
+ }
694
+ /**
695
+ * Master self-repair entrypoint: heals raw tool call JSON, canonicalizes tool names,
696
+ * resolves aliases, coerces argument types, and normalizes paths.
697
+ */
698
+ export function selfRepairToolCall(toolCall, toolSchema, options = {}) {
699
+ const rawName = toolCall.function?.name || toolCall.name || '';
700
+ const canonicalName = canonicalizeToolName(rawName);
701
+ const rawArgs = toolCall.function?.arguments !== undefined
702
+ ? toolCall.function.arguments
703
+ : toolCall.arguments;
704
+ const allRepairs = [];
705
+ if (canonicalName !== rawName) {
706
+ allRepairs.push(`Canonicalized tool name '${rawName}' -> '${canonicalName}'`);
707
+ }
708
+ // 1. Repair JSON parsing
709
+ const jsonResult = repairJsonArguments(rawArgs);
710
+ if (jsonResult.error) {
711
+ return {
712
+ name: canonicalName,
713
+ args: {},
714
+ repaired: false,
715
+ repairs: [...allRepairs, ...jsonResult.repairs],
716
+ error: jsonResult.error
717
+ };
718
+ }
719
+ allRepairs.push(...jsonResult.repairs);
720
+ // 2. Resolve parameter aliases & structural transforms
721
+ const aliasResult = resolveParameterAliases(canonicalName, jsonResult.args, toolSchema);
722
+ allRepairs.push(...aliasResult.repairs);
723
+ // 3. Coerce argument types
724
+ const typeResult = coerceArgumentTypes(canonicalName, aliasResult.args, toolSchema);
725
+ allRepairs.push(...typeResult.repairs);
726
+ // 4. Normalize filesystem paths
727
+ const pathResult = normalizePaths(typeResult.args, options.cwd || process.cwd());
728
+ allRepairs.push(...pathResult.repairs);
729
+ return {
730
+ name: canonicalName,
731
+ args: pathResult.args,
732
+ repaired: allRepairs.length > 0,
733
+ repairs: allRepairs
734
+ };
735
+ }
736
+ /**
737
+ * Generate a rich, non-crashing self-repair diagnostic message for the agent loop
738
+ * when required tool parameters are missing and cannot be automatically inferred.
739
+ */
740
+ export function generateSelfRepairDiagnostic(toolName, args, errorMessage, schema) {
741
+ const required = schema?.required || [];
742
+ const properties = schema?.properties || {};
743
+ const expectedFields = {};
744
+ for (const req of required) {
745
+ const prop = properties[req];
746
+ expectedFields[req] = prop?.description || (typeof prop?.type === 'string' ? prop.type : 'required');
747
+ }
748
+ return {
749
+ success: false,
750
+ error: `Validation error for tool '${toolName}': ${errorMessage}`,
751
+ selfRepairGuidance: {
752
+ tool: toolName,
753
+ missingOrInvalid: errorMessage,
754
+ expectedParameters: expectedFields,
755
+ receivedArguments: args,
756
+ instruction: `Please re-invoke '${toolName}' supplying the valid required parameters.`
757
+ }
758
+ };
759
+ }