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