@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.
package/src/acp/client.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import type { ChildProcessWithoutNullStreams } from 'node:child_process';
3
+ import fs from 'node:fs/promises';
4
+ import path from 'node:path';
3
5
  import {
4
6
  ACP_ERROR_CODES,
5
7
  ACP_METHODS,
@@ -18,7 +20,13 @@ import type {
18
20
  RequestPermissionRequest,
19
21
  RequestPermissionResponse,
20
22
  SessionNotification,
21
- SessionUpdate
23
+ SessionUpdate,
24
+ AgentCapabilities,
25
+ AgentInfo,
26
+ ReadTextFileRequest,
27
+ ReadTextFileResponse,
28
+ WriteTextFileRequest,
29
+ WriteTextFileResponse
22
30
  } from './protocol.js';
23
31
 
24
32
  export interface AcpClientOptions {
@@ -29,6 +37,9 @@ export interface AcpClientOptions {
29
37
  clientVersion?: string;
30
38
  promptTimeoutMs?: number;
31
39
  permissionHandler?: (request: RequestPermissionRequest) => Promise<RequestPermissionResponse['outcome']>;
40
+ onUpdate?: (sessionId: string, update: SessionUpdate) => void;
41
+ fsReadHandler?: (filePath: string, options?: { line?: number; limit?: number }) => Promise<string>;
42
+ fsWriteHandler?: (filePath: string, content: string) => Promise<void>;
32
43
  }
33
44
 
34
45
  export interface AcpPromptResult {
@@ -55,6 +66,7 @@ export class AcpClient {
55
66
  private nextId = 1;
56
67
  private closed = false;
57
68
  private exitError: Error | null = null;
69
+ private initResult: InitializeResult | null = null;
58
70
 
59
71
  constructor(options: AcpClientOptions) {
60
72
  this.options = options;
@@ -64,6 +76,18 @@ export class AcpClient {
64
76
  return this.options.command;
65
77
  }
66
78
 
79
+ get agentInfo(): AgentInfo | undefined {
80
+ return this.initResult?.agentInfo;
81
+ }
82
+
83
+ get agentCapabilities(): AgentCapabilities | undefined {
84
+ return this.initResult?.agentCapabilities;
85
+ }
86
+
87
+ get authMethods(): unknown[] | undefined {
88
+ return this.initResult?.authMethods;
89
+ }
90
+
67
91
  async start(): Promise<InitializeResult> {
68
92
  if (this.child) throw new Error('client already started');
69
93
  const args = this.options.args ?? [];
@@ -90,16 +114,22 @@ export class AcpClient {
90
114
  this.failAll(new Error(`agent process exited: ${detail}`));
91
115
  });
92
116
 
117
+ const hasFsRead = Boolean(this.options.fsReadHandler || this.options.cwd);
118
+ const hasFsWrite = Boolean(this.options.fsWriteHandler || this.options.cwd);
119
+
93
120
  const params: InitializeRequest = {
94
121
  protocolVersion: ACP_PROTOCOL_VERSION,
95
122
  clientCapabilities: {
96
- fs: { readTextFile: false, writeTextFile: false },
123
+ fs: { readTextFile: hasFsRead, writeTextFile: hasFsWrite },
97
124
  terminal: false,
98
- session: { notices: false }
125
+ session: { notices: true }
99
126
  },
100
127
  clientInfo: { name: 'Causyne Agent', version: this.options.clientVersion ?? '0.0.0' }
101
128
  };
102
- return await this.request<InitializeResult>(ACP_METHODS.INITIALIZE, params, 30_000);
129
+
130
+ const result = await this.request<InitializeResult>(ACP_METHODS.INITIALIZE, params, 30_000);
131
+ this.initResult = result;
132
+ return result;
103
133
  }
104
134
 
105
135
  async newSession(cwd: string, mcpServers: unknown[] = []): Promise<string> {
@@ -113,10 +143,39 @@ export class AcpClient {
113
143
  return result.sessionId;
114
144
  }
115
145
 
146
+ async authenticate(methodId: string, params: Record<string, unknown> = {}): Promise<unknown> {
147
+ return await this.request<unknown>(ACP_METHODS.AUTHENTICATE, {
148
+ methodId,
149
+ params
150
+ }, 30_000);
151
+ }
152
+
153
+ async setSessionModel(sessionId: string, modelId: string): Promise<void> {
154
+ await this.request<void>(ACP_METHODS.SET_MODEL, {
155
+ sessionId,
156
+ modelId
157
+ }, 30_000);
158
+ }
159
+
160
+ async setSessionMode(sessionId: string, modeId: string): Promise<void> {
161
+ await this.request<void>(ACP_METHODS.SET_MODE, {
162
+ sessionId,
163
+ modeId
164
+ }, 30_000);
165
+ }
166
+
167
+ async loadSession(sessionId: string, cwd?: string): Promise<unknown> {
168
+ return await this.request<unknown>(ACP_METHODS.LOAD, {
169
+ sessionId,
170
+ cwd: cwd || this.options.cwd
171
+ }, 30_000);
172
+ }
173
+
116
174
  async prompt(sessionId: string, text: string): Promise<AcpPromptResult> {
117
175
  const blocks: ContentBlock[] = [{ type: 'text', text }];
118
176
  let collected = '';
119
177
  const collector = (update: SessionUpdate): void => {
178
+ this.options.onUpdate?.(sessionId, update);
120
179
  if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
121
180
  collected = `${collected}${update.content.text}`.slice(0, MAX_UPDATE_CHARS);
122
181
  }
@@ -209,6 +268,7 @@ export class AcpClient {
209
268
  const params = (parsed as { params?: SessionNotification }).params;
210
269
  if (params && typeof params.sessionId === 'string' && params.update) {
211
270
  this.updateListener?.(params.sessionId, params.update);
271
+ this.options.onUpdate?.(params.sessionId, params.update);
212
272
  }
213
273
  }
214
274
  }
@@ -232,6 +292,83 @@ export class AcpClient {
232
292
  }
233
293
  return;
234
294
  }
295
+
296
+ if (request.method === ACP_METHODS.READ_TEXT_FILE) {
297
+ const params = request.params as unknown as ReadTextFileRequest | undefined;
298
+ const targetPath = params?.path;
299
+ if (!targetPath || typeof targetPath !== 'string') {
300
+ this.write({
301
+ jsonrpc: '2.0',
302
+ id: request.id,
303
+ error: { code: ACP_ERROR_CODES.INVALID_PARAMS, message: 'Missing file path' }
304
+ });
305
+ return;
306
+ }
307
+
308
+ try {
309
+ let content: string;
310
+ if (this.options.fsReadHandler) {
311
+ const readOpts: { line?: number; limit?: number } = {};
312
+ if (params?.line !== undefined) readOpts.line = params.line;
313
+ if (params?.limit !== undefined) readOpts.limit = params.limit;
314
+ content = await this.options.fsReadHandler(targetPath, readOpts);
315
+ } else {
316
+ const resolved = path.resolve(this.options.cwd, targetPath);
317
+ content = await fs.readFile(resolved, 'utf8');
318
+ }
319
+ this.write({
320
+ jsonrpc: '2.0',
321
+ id: request.id,
322
+ result: { content } satisfies ReadTextFileResponse
323
+ });
324
+ } catch (err: unknown) {
325
+ const msg = err instanceof Error ? err.message : String(err);
326
+ this.write({
327
+ jsonrpc: '2.0',
328
+ id: request.id,
329
+ error: { code: ACP_ERROR_CODES.RESOURCE_NOT_FOUND, message: `Could not read file: ${msg}` }
330
+ });
331
+ }
332
+ return;
333
+ }
334
+
335
+ if (request.method === ACP_METHODS.WRITE_TEXT_FILE) {
336
+ const params = request.params as unknown as WriteTextFileRequest | undefined;
337
+ const targetPath = params?.path;
338
+ const content = params?.content;
339
+ if (!targetPath || typeof targetPath !== 'string' || typeof content !== 'string') {
340
+ this.write({
341
+ jsonrpc: '2.0',
342
+ id: request.id,
343
+ error: { code: ACP_ERROR_CODES.INVALID_PARAMS, message: 'Missing file path or content' }
344
+ });
345
+ return;
346
+ }
347
+
348
+ try {
349
+ if (this.options.fsWriteHandler) {
350
+ await this.options.fsWriteHandler(targetPath, content);
351
+ } else {
352
+ const resolved = path.resolve(this.options.cwd, targetPath);
353
+ await fs.mkdir(path.dirname(resolved), { recursive: true });
354
+ await fs.writeFile(resolved, content, 'utf8');
355
+ }
356
+ this.write({
357
+ jsonrpc: '2.0',
358
+ id: request.id,
359
+ result: {} satisfies WriteTextFileResponse
360
+ });
361
+ } catch (err: unknown) {
362
+ const msg = err instanceof Error ? err.message : String(err);
363
+ this.write({
364
+ jsonrpc: '2.0',
365
+ id: request.id,
366
+ error: { code: ACP_ERROR_CODES.INTERNAL_ERROR, message: `Could not write file: ${msg}` }
367
+ });
368
+ }
369
+ return;
370
+ }
371
+
235
372
  this.write({
236
373
  jsonrpc: '2.0',
237
374
  id: request.id,
@@ -246,7 +383,10 @@ export class AcpClient {
246
383
  clearTimeout(pending.timer);
247
384
  this.pending.delete(response.id);
248
385
  if (response.error) {
249
- pending.reject(new Error(`${pending.method} failed: ${response.error.message}`));
386
+ const err = new Error(`${pending.method} failed: ${response.error.message}`);
387
+ (err as unknown as { code?: number }).code = response.error.code;
388
+ (err as unknown as { data?: unknown }).data = response.error.data;
389
+ pending.reject(err);
250
390
  return;
251
391
  }
252
392
  pending.resolve(response.result);
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { causyneHome } from '../utils/paths.js';
4
+ import { getPresetProfile, BUILTIN_PEER_PRESETS } from './agentCatalog.js';
4
5
  const PROFILE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
5
6
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
6
7
  const MAX_PEERS = 20;
@@ -66,7 +67,9 @@ function parseProfile(raw) {
66
67
  return null;
67
68
  }
68
69
  }
69
- const policy = record.policy === 'workspace' ? 'workspace' : 'read-only';
70
+ const policy = record.policy === 'workspace'
71
+ ? 'workspace'
72
+ : (record.policy === 'ask' ? 'ask' : 'read-only');
70
73
  const timeoutSeconds = typeof record.timeoutSeconds === 'number' && Number.isFinite(record.timeoutSeconds)
71
74
  ? Math.max(5, Math.min(1800, Math.round(record.timeoutSeconds)))
72
75
  : 120;
@@ -106,12 +109,87 @@ export function loadPeerProfiles() {
106
109
  }
107
110
  return profiles;
108
111
  }
112
+ export function savePeerProfiles(profiles) {
113
+ const file = peerProfilesPath();
114
+ const dir = path.dirname(file);
115
+ if (!fs.existsSync(dir)) {
116
+ fs.mkdirSync(dir, { recursive: true });
117
+ }
118
+ const content = {
119
+ schemaVersion: 1,
120
+ peers: profiles
121
+ };
122
+ fs.writeFileSync(file, JSON.stringify(content, null, 2), 'utf8');
123
+ }
124
+ export function addPeerProfile(profile) {
125
+ const current = loadPeerProfiles();
126
+ const idx = current.findIndex((p) => p.id === profile.id);
127
+ if (idx >= 0) {
128
+ current[idx] = profile;
129
+ }
130
+ else {
131
+ if (current.length >= MAX_PEERS) {
132
+ return { ok: false, error: `Maximum of ${MAX_PEERS} peer profiles exceeded.` };
133
+ }
134
+ current.push(profile);
135
+ }
136
+ try {
137
+ savePeerProfiles(current);
138
+ return { ok: true };
139
+ }
140
+ catch (err) {
141
+ const msg = err instanceof Error ? err.message : String(err);
142
+ return { ok: false, error: msg };
143
+ }
144
+ }
145
+ export function removePeerProfile(id) {
146
+ const current = loadPeerProfiles();
147
+ const filtered = current.filter((p) => p.id !== id);
148
+ if (filtered.length === current.length) {
149
+ return { ok: false, error: `Peer profile "${id}" is not configured.` };
150
+ }
151
+ try {
152
+ savePeerProfiles(filtered);
153
+ return { ok: true };
154
+ }
155
+ catch (err) {
156
+ const msg = err instanceof Error ? err.message : String(err);
157
+ return { ok: false, error: msg };
158
+ }
159
+ }
160
+ /**
161
+ * Resolves a peer profile by ID. Checks user configuration first;
162
+ * if not found, falls back to built-in agent presets.
163
+ */
109
164
  export function getPeerProfile(id) {
110
- return loadPeerProfiles().find((profile) => profile.id === id) ?? null;
165
+ const normalizedId = String(id || '').trim().toLowerCase();
166
+ const configured = loadPeerProfiles().find((profile) => profile.id.toLowerCase() === normalizedId);
167
+ if (configured)
168
+ return configured;
169
+ // Fallback to built-in presets (e.g. opencode, claude, codex, hermes, cursor, gemini)
170
+ return getPresetProfile(normalizedId);
171
+ }
172
+ /**
173
+ * Returns all available peers: user configured peers plus all built-in presets
174
+ * that are not already shadowed by a user profile.
175
+ */
176
+ export function listAllPeers() {
177
+ const userPeers = loadPeerProfiles();
178
+ const userIds = new Set(userPeers.map((p) => p.id.toLowerCase()));
179
+ const all = [...userPeers];
180
+ for (const presetId of Object.keys(BUILTIN_PEER_PRESETS)) {
181
+ if (!userIds.has(presetId)) {
182
+ const presetProfile = getPresetProfile(presetId);
183
+ if (presetProfile) {
184
+ all.push(presetProfile);
185
+ }
186
+ }
187
+ }
188
+ return all;
111
189
  }
112
190
  export function peerEnvironment(profile) {
113
191
  const env = {};
114
- for (const name of ['PATH', 'HOME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL', 'SYSTEMROOT']) {
192
+ for (const name of ['PATH', 'HOME', 'USER', 'LOGNAME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL', 'SYSTEMROOT']) {
115
193
  const value = process.env[name];
116
194
  if (typeof value === 'string')
117
195
  env[name] = value;
@@ -1,8 +1,9 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { causyneHome } from '../utils/paths.js';
4
+ import { getPresetProfile, BUILTIN_PEER_PRESETS } from './agentCatalog.js';
4
5
 
5
- export type PeerPolicy = 'read-only' | 'workspace';
6
+ export type PeerPolicy = 'read-only' | 'ask' | 'workspace';
6
7
 
7
8
  export interface PeerProfile {
8
9
  id: string;
@@ -76,7 +77,9 @@ function parseProfile(raw: unknown): PeerProfile | null {
76
77
  return null;
77
78
  }
78
79
  }
79
- const policy: PeerPolicy = record.policy === 'workspace' ? 'workspace' : 'read-only';
80
+ const policy: PeerPolicy = record.policy === 'workspace'
81
+ ? 'workspace'
82
+ : (record.policy === 'ask' ? 'ask' : 'read-only');
80
83
  const timeoutSeconds = typeof record.timeoutSeconds === 'number' && Number.isFinite(record.timeoutSeconds)
81
84
  ? Math.max(5, Math.min(1800, Math.round(record.timeoutSeconds)))
82
85
  : 120;
@@ -113,13 +116,91 @@ export function loadPeerProfiles(): PeerProfile[] {
113
116
  return profiles;
114
117
  }
115
118
 
119
+ export function savePeerProfiles(profiles: PeerProfile[]): void {
120
+ const file = peerProfilesPath();
121
+ const dir = path.dirname(file);
122
+ if (!fs.existsSync(dir)) {
123
+ fs.mkdirSync(dir, { recursive: true });
124
+ }
125
+ const content: PeerProfilesFile = {
126
+ schemaVersion: 1,
127
+ peers: profiles
128
+ };
129
+ fs.writeFileSync(file, JSON.stringify(content, null, 2), 'utf8');
130
+ }
131
+
132
+ export function addPeerProfile(profile: PeerProfile): { ok: boolean; error?: string } {
133
+ const current = loadPeerProfiles();
134
+ const idx = current.findIndex((p) => p.id === profile.id);
135
+ if (idx >= 0) {
136
+ current[idx] = profile;
137
+ } else {
138
+ if (current.length >= MAX_PEERS) {
139
+ return { ok: false, error: `Maximum of ${MAX_PEERS} peer profiles exceeded.` };
140
+ }
141
+ current.push(profile);
142
+ }
143
+ try {
144
+ savePeerProfiles(current);
145
+ return { ok: true };
146
+ } catch (err: unknown) {
147
+ const msg = err instanceof Error ? err.message : String(err);
148
+ return { ok: false, error: msg };
149
+ }
150
+ }
151
+
152
+ export function removePeerProfile(id: string): { ok: boolean; error?: string } {
153
+ const current = loadPeerProfiles();
154
+ const filtered = current.filter((p) => p.id !== id);
155
+ if (filtered.length === current.length) {
156
+ return { ok: false, error: `Peer profile "${id}" is not configured.` };
157
+ }
158
+ try {
159
+ savePeerProfiles(filtered);
160
+ return { ok: true };
161
+ } catch (err: unknown) {
162
+ const msg = err instanceof Error ? err.message : String(err);
163
+ return { ok: false, error: msg };
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Resolves a peer profile by ID. Checks user configuration first;
169
+ * if not found, falls back to built-in agent presets.
170
+ */
116
171
  export function getPeerProfile(id: string): PeerProfile | null {
117
- return loadPeerProfiles().find((profile) => profile.id === id) ?? null;
172
+ const normalizedId = String(id || '').trim().toLowerCase();
173
+ const configured = loadPeerProfiles().find((profile) => profile.id.toLowerCase() === normalizedId);
174
+ if (configured) return configured;
175
+
176
+ // Fallback to built-in presets (e.g. opencode, claude, codex, hermes, cursor, gemini)
177
+ return getPresetProfile(normalizedId);
178
+ }
179
+
180
+ /**
181
+ * Returns all available peers: user configured peers plus all built-in presets
182
+ * that are not already shadowed by a user profile.
183
+ */
184
+ export function listAllPeers(): PeerProfile[] {
185
+ const userPeers = loadPeerProfiles();
186
+ const userIds = new Set(userPeers.map((p) => p.id.toLowerCase()));
187
+ const all: PeerProfile[] = [...userPeers];
188
+
189
+ for (const presetId of Object.keys(BUILTIN_PEER_PRESETS)) {
190
+ if (!userIds.has(presetId)) {
191
+ const presetProfile = getPresetProfile(presetId);
192
+ if (presetProfile) {
193
+ all.push(presetProfile);
194
+ }
195
+ }
196
+ }
197
+
198
+ return all;
118
199
  }
119
200
 
120
201
  export function peerEnvironment(profile: PeerProfile): NodeJS.ProcessEnv {
121
202
  const env: NodeJS.ProcessEnv = {};
122
- for (const name of ['PATH', 'HOME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL', 'SYSTEMROOT']) {
203
+ for (const name of ['PATH', 'HOME', 'USER', 'LOGNAME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL', 'SYSTEMROOT']) {
123
204
  const value = process.env[name];
124
205
  if (typeof value === 'string') env[name] = value;
125
206
  }
@@ -17,6 +17,8 @@ export const ACP_METHODS = {
17
17
  LIST: 'session/list',
18
18
  CLOSE: 'session/close',
19
19
  SET_MODE: 'session/set_mode',
20
+ SET_MODEL: 'session/set_model',
21
+ AUTHENTICATE: 'authenticate',
20
22
  REQUEST_PERMISSION: 'session/request_permission',
21
23
  READ_TEXT_FILE: 'fs/read_text_file',
22
24
  WRITE_TEXT_FILE: 'fs/write_text_file'
@@ -19,6 +19,8 @@ export const ACP_METHODS = {
19
19
  LIST: 'session/list',
20
20
  CLOSE: 'session/close',
21
21
  SET_MODE: 'session/set_mode',
22
+ SET_MODEL: 'session/set_model',
23
+ AUTHENTICATE: 'authenticate',
22
24
  REQUEST_PERMISSION: 'session/request_permission',
23
25
  READ_TEXT_FILE: 'fs/read_text_file',
24
26
  WRITE_TEXT_FILE: 'fs/write_text_file'
@@ -224,6 +226,23 @@ export interface SetSessionModeRequest {
224
226
 
225
227
  export type SetSessionModeResponse = Record<string, never>;
226
228
 
229
+ export interface SetSessionModelRequest {
230
+ sessionId: string;
231
+ modelId: string;
232
+ }
233
+
234
+ export type SetSessionModelResponse = Record<string, never>;
235
+
236
+ export interface AuthenticateRequest {
237
+ methodId: string;
238
+ params?: Record<string, unknown>;
239
+ }
240
+
241
+ export interface AuthenticateResponse {
242
+ authenticated: boolean;
243
+ message?: string;
244
+ }
245
+
227
246
  export interface CancelNotification {
228
247
  sessionId: string;
229
248
  }
package/src/agentLoop.js CHANGED
@@ -5,6 +5,7 @@ import { WorkspacePerception } from './perception.js';
5
5
  import { audioFormatForMimeType } from './providers/base.js';
6
6
  import { TaskBuffer } from './taskBuffer.js';
7
7
  import { TOOL_DEFINITIONS, getDynamicTools, resolveTool, canonicalToolName } from './tools/registry.js';
8
+ import { selfRepairToolCall, generateSelfRepairDiagnostic } from './tools/toolSelfRepair.js';
8
9
  import { Sandbox } from './sandbox.js';
9
10
  import { auditLog } from './auditLog.js';
10
11
  import { hasMatchingHook, runConfiguredHooks } from './hooks.js';
@@ -137,6 +138,11 @@ If asked to perform ANY harmful task, politely decline, state that Causyne exist
137
138
  - **Prefer REST APIs (curl)**: When interacting with external services (like web, email, chat), prioritize finding and using official REST APIs via \`curl\` or simple scripts.
138
139
  - **Avoid UI/Browser Automation**: Automating a browser (e.g., Puppeteer/Playwright) is noisy, expensive, and fragile. ONLY use browser automation if a site genuinely has no API. Reading JSON is always better than reading DOM.
139
140
 
141
+ # Universal Tool Calling & Registry Discipline
142
+ 1. **Strict Registry Adherence**: Use ONLY the tools declared in the catalogue. Invoke tools using exact parameter names specified in the schema. Do not invent or rename parameters.
143
+ 2. **Valid JSON Formatting**: All tool call arguments must be valid JSON objects. Never include raw unescaped newlines or trailing commas inside argument strings.
144
+ 3. **Automated Buffer & Self-Correction**: Causyne runs a Universal Tool Buffer with self-repair capabilities. If a tool returns a \`selfRepairGuidance\` result indicating missing or invalid parameters, immediately read the \`expectedParameters\` and re-invoke the tool with the corrected arguments.
145
+
140
146
  # UNIVERSAL CRITICAL DIRECTIVE (APPLIES TO ALL TASKS)
141
147
  **DO NOT OUTPUT CONVERSATIONAL TEXT WITHOUT INVOKING A TOOL CALL SIMULTANEOUSLY.**
142
148
  If the task is not 100% finished, you MUST invoke a tool (like web_search, fs_read, sysRun, etc.) in the exact same response as your text. If you output text without a tool call, the system will assume you are completely done and immediately terminate the task!
@@ -1789,20 +1795,33 @@ export class AgentLoop {
1789
1795
  // matches on this string, so if it is not the catalogue name those
1790
1796
  // checks silently never fire.
1791
1797
  const functionName = canonicalToolName(toolCall.function.name);
1792
- let args = {};
1793
- try {
1794
- args = typeof toolCall.function.arguments === 'string'
1795
- ? JSON.parse(toolCall.function.arguments || '{}')
1796
- : (toolCall.function.arguments || {});
1797
- } catch (parseErr) {
1798
+ const tool = resolveTool(functionName);
1799
+ const toolSchema = tool?.schema?.parameters || tool?.schema?.input_schema;
1800
+ const repair = selfRepairToolCall(toolCall, toolSchema, {
1801
+ cwd: this.workspaceRoot || process.cwd()
1802
+ });
1803
+
1804
+ if (repair.error) {
1798
1805
  this.messages.push({
1799
1806
  role: 'tool',
1800
1807
  tool_call_id: toolCall.id,
1801
1808
  name: functionName,
1802
- content: JSON.stringify({ success: false, error: `Invalid JSON in arguments: ${parseErr.message}` })
1809
+ content: JSON.stringify({
1810
+ success: false,
1811
+ error: `Invalid JSON in arguments: ${repair.error}`,
1812
+ selfRepairGuidance: {
1813
+ tool: functionName,
1814
+ instruction: 'Ensure arguments are passed as a valid JSON object without unescaped control characters or trailing commas.'
1815
+ }
1816
+ })
1803
1817
  });
1804
1818
  continue;
1805
1819
  }
1820
+
1821
+ let args = repair.args;
1822
+ if (repair.repaired && repair.repairs.length > 0) {
1823
+ this.debugLog(`[TOOL SELF-REPAIR] Healed tool call '${functionName}': ${repair.repairs.join(', ')}`);
1824
+ }
1806
1825
 
1807
1826
  this.emitEvent({ type: 'step_start', tool: functionName, args: args, toolCallId: toolCall.id });
1808
1827
  this.consecutiveCommands++;
@@ -1929,7 +1948,6 @@ export class AgentLoop {
1929
1948
 
1930
1949
  // Resolve and validate before asking the user for approval. Unknown or
1931
1950
  // malformed calls should self-correct without creating approval fatigue.
1932
- const tool = resolveTool(functionName);
1933
1951
  if (!tool || typeof tool.execute !== 'function') {
1934
1952
  this.messages.push({
1935
1953
  role: 'tool',
@@ -1953,14 +1971,17 @@ export class AgentLoop {
1953
1971
 
1954
1972
  const validationErrors = this.validateToolArgs(functionName, args);
1955
1973
  if (validationErrors) {
1974
+ const diagnostic = generateSelfRepairDiagnostic(
1975
+ functionName,
1976
+ args,
1977
+ validationErrors,
1978
+ tool?.schema?.parameters || tool?.schema?.input_schema
1979
+ );
1956
1980
  this.messages.push({
1957
1981
  role: 'tool',
1958
1982
  tool_call_id: toolCall.id,
1959
1983
  name: functionName,
1960
- content: JSON.stringify({
1961
- success: false,
1962
- error: `Invalid arguments: ${validationErrors}. Please fix and retry.`
1963
- })
1984
+ content: JSON.stringify(diagnostic)
1964
1985
  });
1965
1986
  continue;
1966
1987
  }