@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,489 @@
1
+ /**
2
+ * Causyne Agent — ACP Agent Catalog & Zero-Token Discovery
3
+ *
4
+ * Provides built-in profiles, auth probing, and zero-token discovery for
5
+ * common external coding agents that support the Agent Client Protocol (ACP),
6
+ * such as Claude Code, Codex, OpenCode, Gemini CLI, Hermes, Cursor CLI,
7
+ * Qwen, Copilot, Kimi, and Goose.
8
+ */
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { execFile } from 'node:child_process';
13
+ import { promisify } from 'node:util';
14
+ import { AcpClient } from './client.js';
15
+ import type { PeerProfile } from './peerProfiles.js';
16
+
17
+ const execFileAsync = promisify(execFile);
18
+
19
+ export interface BuiltinPeerPreset {
20
+ id: string;
21
+ label: string;
22
+ description: string;
23
+ command: string;
24
+ args: string[];
25
+ binaryName: string;
26
+ fallbackCommand?: string;
27
+ fallbackArgs?: string[];
28
+ authType: 'subscription' | 'oauth' | 'api_key' | 'none';
29
+ authProbe?: {
30
+ type: 'json' | 'output_match' | 'file_exists';
31
+ command?: string;
32
+ args?: string[];
33
+ filePath?: string;
34
+ positiveMatch?: string;
35
+ negativeMatch?: string;
36
+ jsonField?: string;
37
+ };
38
+ setupInstruction?: string;
39
+ timeoutSeconds?: number;
40
+ }
41
+
42
+ export interface PeerDetectionResult {
43
+ id: string;
44
+ label: string;
45
+ status: 'ready' | 'needs_auth' | 'not_installed' | 'error';
46
+ command: string;
47
+ args: string[];
48
+ details?: string;
49
+ agentInfo?: { name: string; version: string };
50
+ authMethods?: string[];
51
+ setupInstruction?: string;
52
+ }
53
+
54
+ export const BUILTIN_PEER_PRESETS: Record<string, BuiltinPeerPreset> = {
55
+ antigravity: {
56
+ id: 'antigravity',
57
+ label: 'Google Antigravity (AGY)',
58
+ description: 'Google Antigravity agent CLI with Gemini and Claude frontier models',
59
+ command: 'agy',
60
+ args: ['--output-format', 'json'],
61
+ binaryName: 'agy',
62
+ authType: 'none',
63
+ setupInstruction: 'Install Antigravity IDE or CLI to enable Google AGY models',
64
+ timeoutSeconds: 180
65
+ },
66
+ opencode: {
67
+ id: 'opencode',
68
+ label: 'OpenCode',
69
+ description: 'OpenCode AI coding agent with support for free and local models',
70
+ command: 'opencode',
71
+ args: ['acp'],
72
+ binaryName: 'opencode',
73
+ fallbackCommand: 'npx',
74
+ fallbackArgs: ['-y', 'opencode-ai', 'acp'],
75
+ authType: 'none',
76
+ setupInstruction: 'Run "opencode auth login" or configure a model in ~/.config/opencode',
77
+ timeoutSeconds: 180
78
+ },
79
+ claude: {
80
+ id: 'claude',
81
+ label: 'Claude Code',
82
+ description: 'Anthropic Claude Code CLI via official ACP bridge adapter',
83
+ command: 'npx',
84
+ args: ['-y', '@agentclientprotocol/claude-agent-acp@0.70.0'],
85
+ binaryName: 'claude',
86
+ authType: 'subscription',
87
+ authProbe: {
88
+ type: 'json',
89
+ command: 'claude',
90
+ args: ['auth', 'status', '--json'],
91
+ jsonField: 'loggedIn'
92
+ },
93
+ setupInstruction: 'Run "claude login" to authenticate with your Anthropic subscription or set ANTHROPIC_API_KEY',
94
+ timeoutSeconds: 300
95
+ },
96
+ codex: {
97
+ id: 'codex',
98
+ label: 'Codex CLI',
99
+ description: 'OpenAI Codex CLI coding agent via ACP adapter',
100
+ command: 'npx',
101
+ args: ['-y', '@agentclientprotocol/codex-acp@1.6.0'],
102
+ binaryName: 'codex',
103
+ authType: 'subscription',
104
+ authProbe: {
105
+ type: 'output_match',
106
+ command: 'codex',
107
+ args: ['login', 'status'],
108
+ positiveMatch: 'logged in',
109
+ negativeMatch: 'not logged in'
110
+ },
111
+ setupInstruction: 'Run "codex login" or set OPENAI_API_KEY in your environment',
112
+ timeoutSeconds: 300
113
+ },
114
+ gemini: {
115
+ id: 'gemini',
116
+ label: 'Gemini CLI',
117
+ description: 'Google Gemini CLI agent with free tier model support',
118
+ command: 'gemini',
119
+ args: ['--acp'],
120
+ binaryName: 'gemini',
121
+ fallbackCommand: 'npx',
122
+ fallbackArgs: ['-y', '@google/gemini-cli', '--acp'],
123
+ authType: 'oauth',
124
+ authProbe: {
125
+ type: 'file_exists',
126
+ filePath: path.join(process.env.HOME || '', '.gemini', 'oauth_creds.json')
127
+ },
128
+ setupInstruction: 'Run "gemini auth" or set GEMINI_API_KEY in your environment',
129
+ timeoutSeconds: 240
130
+ },
131
+ hermes: {
132
+ id: 'hermes',
133
+ label: 'Hermes Agent',
134
+ description: 'Nous Research Hermes autonomous AI agent',
135
+ command: 'hermes',
136
+ args: ['acp'],
137
+ binaryName: 'hermes',
138
+ authType: 'api_key',
139
+ setupInstruction: 'Run "hermes acp --setup" to configure provider credentials',
140
+ timeoutSeconds: 240
141
+ },
142
+ cursor: {
143
+ id: 'cursor',
144
+ label: 'Cursor CLI',
145
+ description: 'Cursor CLI coding agent over ACP',
146
+ command: 'cursor-agent',
147
+ args: ['acp'],
148
+ binaryName: 'cursor-agent',
149
+ authType: 'subscription',
150
+ setupInstruction: 'Run "cursor-agent login" to sign in to your Cursor account',
151
+ timeoutSeconds: 180
152
+ },
153
+ qwen: {
154
+ id: 'qwen',
155
+ label: 'Qwen Code',
156
+ description: 'Alibaba Qwen Code AI assistant over ACP',
157
+ command: 'qwen',
158
+ args: ['--acp'],
159
+ binaryName: 'qwen',
160
+ authType: 'api_key',
161
+ setupInstruction: 'Set DASHSCOPE_API_KEY or run "qwen login"',
162
+ timeoutSeconds: 180
163
+ },
164
+ copilot: {
165
+ id: 'copilot',
166
+ label: 'GitHub Copilot CLI',
167
+ description: 'GitHub Copilot CLI agent over ACP',
168
+ command: 'copilot',
169
+ args: ['--acp', '--stdio'],
170
+ binaryName: 'copilot',
171
+ authType: 'subscription',
172
+ setupInstruction: 'Run "copilot auth" to link your GitHub Copilot subscription',
173
+ timeoutSeconds: 180
174
+ },
175
+ kimi: {
176
+ id: 'kimi',
177
+ label: 'Kimi CLI',
178
+ description: 'Moonshot AI Kimi coding assistant via ACP',
179
+ command: 'kimi',
180
+ args: ['acp'],
181
+ binaryName: 'kimi',
182
+ authType: 'api_key',
183
+ setupInstruction: 'Set MOONSHOT_API_KEY in your environment',
184
+ timeoutSeconds: 180
185
+ },
186
+ goose: {
187
+ id: 'goose',
188
+ label: 'Goose CLI',
189
+ description: 'Block Goose extensible AI coding agent',
190
+ command: 'goose',
191
+ args: ['acp'],
192
+ binaryName: 'goose',
193
+ authType: 'api_key',
194
+ setupInstruction: 'Run "goose configure" to set up providers',
195
+ timeoutSeconds: 180
196
+ }
197
+ };
198
+
199
+ /**
200
+ * Check if a command or binary exists in PATH.
201
+ */
202
+ export function isBinaryOnPath(binaryName: string): boolean {
203
+ if (path.isAbsolute(binaryName)) {
204
+ return fs.existsSync(binaryName);
205
+ }
206
+ const envPath = process.env.PATH || '';
207
+ const delimiter = process.platform === 'win32' ? ';' : ':';
208
+ const home = process.env.HOME || '';
209
+ const fallbackDirs = [
210
+ path.join(home, '.local', 'bin'),
211
+ path.join(home, '.antigravity', 'antigravity', 'bin'),
212
+ path.join(home, '.gemini', 'antigravity-ide', 'bin'),
213
+ path.join(home, '.opencode', 'bin'),
214
+ '/Applications/Antigravity.app/Contents/Resources/app/bin',
215
+ '/Applications/Antigravity IDE.app/Contents/Resources/app/bin'
216
+ ];
217
+ const dirs = [...envPath.split(delimiter), ...fallbackDirs];
218
+ const extensions = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
219
+
220
+ for (const dir of dirs) {
221
+ if (!dir) continue;
222
+ for (const ext of extensions) {
223
+ const full = path.join(dir, `${binaryName}${ext}`);
224
+ try {
225
+ if (fs.existsSync(full) && fs.statSync(full).isFile()) {
226
+ return true;
227
+ }
228
+ } catch {
229
+ // Skip inaccessible path segments
230
+ }
231
+ }
232
+ }
233
+ return false;
234
+ }
235
+
236
+ /**
237
+ * Probe authorization state without spending model tokens.
238
+ */
239
+ export async function probePresetAuth(preset: BuiltinPeerPreset): Promise<{ authenticated: boolean; reason?: string }> {
240
+ if (!preset.authProbe) {
241
+ return { authenticated: true };
242
+ }
243
+
244
+ const probe = preset.authProbe;
245
+
246
+ if (probe.type === 'file_exists' && probe.filePath) {
247
+ const exists = fs.existsSync(probe.filePath);
248
+ return {
249
+ authenticated: exists,
250
+ reason: exists ? 'OAuth credentials file detected' : `Credentials file not found at ${probe.filePath}`
251
+ };
252
+ }
253
+
254
+ if (probe.type === 'json' && probe.command) {
255
+ if (!isBinaryOnPath(probe.command)) {
256
+ return { authenticated: false, reason: `${probe.command} CLI not found on PATH` };
257
+ }
258
+ try {
259
+ const { stdout } = await execFileAsync(probe.command, probe.args || [], { timeout: 8000 });
260
+ const parsed = JSON.parse(stdout.trim());
261
+ if (probe.jsonField && typeof parsed === 'object' && parsed !== null) {
262
+ const val = (parsed as Record<string, unknown>)[probe.jsonField];
263
+ const isAuth = Boolean(val);
264
+ return {
265
+ authenticated: isAuth,
266
+ reason: isAuth ? 'Valid CLI login session active' : 'CLI reports not logged in'
267
+ };
268
+ }
269
+ return { authenticated: true, reason: 'CLI auth responded' };
270
+ } catch {
271
+ return { authenticated: false, reason: `Failed to probe ${probe.command} auth status` };
272
+ }
273
+ }
274
+
275
+ if (probe.type === 'output_match' && probe.command) {
276
+ if (!isBinaryOnPath(probe.command)) {
277
+ return { authenticated: false, reason: `${probe.command} CLI not found on PATH` };
278
+ }
279
+ try {
280
+ const result = await execFileAsync(probe.command, probe.args || [], { timeout: 8000 }).catch((e) => e);
281
+ const combined = `${result?.stdout || ''}\n${result?.stderr || ''}`.toLowerCase();
282
+ if (probe.negativeMatch && combined.includes(probe.negativeMatch.toLowerCase())) {
283
+ return { authenticated: false, reason: 'CLI reported not logged in' };
284
+ }
285
+ if (probe.positiveMatch && combined.includes(probe.positiveMatch.toLowerCase())) {
286
+ return { authenticated: true, reason: 'CLI login detected' };
287
+ }
288
+ return { authenticated: false, reason: 'No active login detected' };
289
+ } catch {
290
+ return { authenticated: false, reason: `Failed to probe ${probe.command} auth` };
291
+ }
292
+ }
293
+
294
+ return { authenticated: true };
295
+ }
296
+
297
+ /**
298
+ * Execute a zero-token ACP handshake (initialize + session/new) with strict timeout.
299
+ * Never sends session/prompt, ensuring $0 token consumption.
300
+ */
301
+ export async function testPeerHandshake(
302
+ options: {
303
+ command: string;
304
+ args?: string[];
305
+ cwd?: string;
306
+ timeoutMs?: number;
307
+ }
308
+ ): Promise<{
309
+ ready: boolean;
310
+ agentInfo?: { name: string; version: string };
311
+ authMethods?: string[];
312
+ error?: string;
313
+ }> {
314
+ const cwd = options.cwd || process.cwd();
315
+ const clientOptions: { command: string; args?: string[]; cwd: string; promptTimeoutMs: number } = {
316
+ command: options.command,
317
+ cwd,
318
+ promptTimeoutMs: options.timeoutMs || 15000
319
+ };
320
+ if (options.args) {
321
+ clientOptions.args = options.args;
322
+ }
323
+ const client = new AcpClient(clientOptions);
324
+
325
+ const timeoutMs = options.timeoutMs || 12000;
326
+ try {
327
+ const init = await Promise.race([
328
+ client.start(),
329
+ new Promise<never>((_, reject) =>
330
+ setTimeout(() => reject(new Error(`ACP initialization timed out after ${timeoutMs}ms`)), timeoutMs)
331
+ )
332
+ ]);
333
+
334
+ const agentInfo = init.agentInfo ? { name: init.agentInfo.name, version: init.agentInfo.version } : undefined;
335
+ const authMethods = Array.isArray(init.authMethods)
336
+ ? init.authMethods.map((m) => (typeof m === 'object' && m !== null && 'id' in m ? String((m as { id: unknown }).id) : String(m)))
337
+ : [];
338
+
339
+ // Attempt session/new to ensure agent is fully operational
340
+ try {
341
+ await client.newSession(cwd);
342
+ return {
343
+ ready: true,
344
+ ...(agentInfo ? { agentInfo } : {}),
345
+ authMethods
346
+ };
347
+ } catch (sessionErr: unknown) {
348
+ const msg = sessionErr instanceof Error ? sessionErr.message : String(sessionErr);
349
+ return {
350
+ ready: false,
351
+ ...(agentInfo ? { agentInfo } : {}),
352
+ authMethods,
353
+ error: `Session creation failed: ${msg}`
354
+ };
355
+ }
356
+ } catch (initErr: unknown) {
357
+ const msg = initErr instanceof Error ? initErr.message : String(initErr);
358
+ return { ready: false, error: msg };
359
+ } finally {
360
+ await client.close().catch(() => {});
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Detect all built-in ACP presets available on this machine and report their readiness.
366
+ */
367
+ export async function detectAllPeers(cwd: string = process.cwd()): Promise<PeerDetectionResult[]> {
368
+ const results: PeerDetectionResult[] = [];
369
+
370
+ for (const preset of Object.values(BUILTIN_PEER_PRESETS)) {
371
+ const hasDirectBinary = isBinaryOnPath(preset.binaryName);
372
+ const hasRunner = isBinaryOnPath(preset.command);
373
+
374
+ if (!hasDirectBinary && !hasRunner) {
375
+ results.push({
376
+ id: preset.id,
377
+ label: preset.label,
378
+ status: 'not_installed',
379
+ command: preset.command,
380
+ args: preset.args,
381
+ details: `Binary "${preset.binaryName}" and runner "${preset.command}" not found on PATH.`,
382
+ ...(preset.setupInstruction ? { setupInstruction: preset.setupInstruction } : {})
383
+ });
384
+ continue;
385
+ }
386
+
387
+ // Determine actual command to execute
388
+ let activeCommand = preset.command;
389
+ let activeArgs = preset.args;
390
+
391
+ if (!hasDirectBinary && preset.fallbackCommand && isBinaryOnPath(preset.fallbackCommand)) {
392
+ activeCommand = preset.fallbackCommand;
393
+ activeArgs = preset.fallbackArgs || [];
394
+ }
395
+
396
+ // Run auth probe
397
+ const auth = await probePresetAuth(preset);
398
+ if (!auth.authenticated) {
399
+ results.push({
400
+ id: preset.id,
401
+ label: preset.label,
402
+ status: 'needs_auth',
403
+ command: activeCommand,
404
+ args: activeArgs,
405
+ details: auth.reason || 'Authentication required.',
406
+ ...(preset.setupInstruction ? { setupInstruction: preset.setupInstruction } : {})
407
+ });
408
+ continue;
409
+ }
410
+
411
+ // Antigravity communicates natively via CLI JSON mode
412
+ if (preset.id === 'antigravity') {
413
+ results.push({
414
+ id: preset.id,
415
+ label: preset.label,
416
+ status: 'ready',
417
+ command: activeCommand,
418
+ args: activeArgs,
419
+ agentInfo: { name: 'Google Antigravity', version: '2.0' },
420
+ details: 'Operational via local AGY CLI with Gemini & Claude frontier models.'
421
+ });
422
+ continue;
423
+ }
424
+
425
+ // Run zero-token handshake
426
+ const handshake = await testPeerHandshake({
427
+ command: activeCommand,
428
+ args: activeArgs,
429
+ cwd,
430
+ timeoutMs: 8000
431
+ });
432
+
433
+ if (handshake.ready) {
434
+ results.push({
435
+ id: preset.id,
436
+ label: preset.label,
437
+ status: 'ready',
438
+ command: activeCommand,
439
+ args: activeArgs,
440
+ ...(handshake.agentInfo ? { agentInfo: handshake.agentInfo } : {}),
441
+ ...(handshake.authMethods ? { authMethods: handshake.authMethods } : {}),
442
+ details: 'Operational and ready for delegation.'
443
+ });
444
+ } else if (handshake.error && /auth/i.test(handshake.error)) {
445
+ results.push({
446
+ id: preset.id,
447
+ label: preset.label,
448
+ status: 'needs_auth',
449
+ command: activeCommand,
450
+ args: activeArgs,
451
+ ...(handshake.agentInfo ? { agentInfo: handshake.agentInfo } : {}),
452
+ ...(handshake.authMethods ? { authMethods: handshake.authMethods } : {}),
453
+ details: handshake.error,
454
+ ...(preset.setupInstruction ? { setupInstruction: preset.setupInstruction } : {})
455
+ });
456
+ } else {
457
+ results.push({
458
+ id: preset.id,
459
+ label: preset.label,
460
+ status: hasDirectBinary ? 'error' : 'not_installed',
461
+ command: activeCommand,
462
+ args: activeArgs,
463
+ details: handshake.error || 'ACP handshake did not complete.',
464
+ ...(preset.setupInstruction ? { setupInstruction: preset.setupInstruction } : {})
465
+ });
466
+ }
467
+ }
468
+
469
+ return results;
470
+ }
471
+
472
+ /**
473
+ * Convert a preset to a runnable PeerProfile.
474
+ */
475
+ export function getPresetProfile(id: string): PeerProfile | null {
476
+ const preset = BUILTIN_PEER_PRESETS[id.toLowerCase()];
477
+ if (!preset) return null;
478
+
479
+ return {
480
+ id: preset.id,
481
+ label: preset.label,
482
+ command: preset.command,
483
+ args: preset.args,
484
+ cwd: null,
485
+ policy: 'read-only',
486
+ timeoutSeconds: preset.timeoutSeconds || 180,
487
+ env: {}
488
+ };
489
+ }
package/src/acp/client.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
2
4
  import { ACP_ERROR_CODES, ACP_METHODS, ACP_PROTOCOL_VERSION, isJsonRpcRequest, isJsonRpcResponse } from './protocol.js';
3
5
  const MAX_STDERR_CHARS = 4000;
4
6
  const MAX_UPDATE_CHARS = 200_000;
@@ -11,12 +13,22 @@ export class AcpClient {
11
13
  nextId = 1;
12
14
  closed = false;
13
15
  exitError = null;
16
+ initResult = null;
14
17
  constructor(options) {
15
18
  this.options = options;
16
19
  }
17
20
  get command() {
18
21
  return this.options.command;
19
22
  }
23
+ get agentInfo() {
24
+ return this.initResult?.agentInfo;
25
+ }
26
+ get agentCapabilities() {
27
+ return this.initResult?.agentCapabilities;
28
+ }
29
+ get authMethods() {
30
+ return this.initResult?.authMethods;
31
+ }
20
32
  async start() {
21
33
  if (this.child)
22
34
  throw new Error('client already started');
@@ -42,16 +54,20 @@ export class AcpClient {
42
54
  const detail = this.stderrTail.trim() || `exit code ${code ?? 'null'}${signal ? ` signal ${signal}` : ''}`;
43
55
  this.failAll(new Error(`agent process exited: ${detail}`));
44
56
  });
57
+ const hasFsRead = Boolean(this.options.fsReadHandler || this.options.cwd);
58
+ const hasFsWrite = Boolean(this.options.fsWriteHandler || this.options.cwd);
45
59
  const params = {
46
60
  protocolVersion: ACP_PROTOCOL_VERSION,
47
61
  clientCapabilities: {
48
- fs: { readTextFile: false, writeTextFile: false },
62
+ fs: { readTextFile: hasFsRead, writeTextFile: hasFsWrite },
49
63
  terminal: false,
50
- session: { notices: false }
64
+ session: { notices: true }
51
65
  },
52
66
  clientInfo: { name: 'Causyne Agent', version: this.options.clientVersion ?? '0.0.0' }
53
67
  };
54
- return await this.request(ACP_METHODS.INITIALIZE, params, 30_000);
68
+ const result = await this.request(ACP_METHODS.INITIALIZE, params, 30_000);
69
+ this.initResult = result;
70
+ return result;
55
71
  }
56
72
  async newSession(cwd, mcpServers = []) {
57
73
  const result = await this.request(ACP_METHODS.NEW_SESSION, {
@@ -63,10 +79,35 @@ export class AcpClient {
63
79
  }
64
80
  return result.sessionId;
65
81
  }
66
- async prompt(sessionId, text) {
67
- const blocks = [{ type: 'text', text }];
82
+ async authenticate(methodId, params = {}) {
83
+ return await this.request(ACP_METHODS.AUTHENTICATE, {
84
+ methodId,
85
+ params
86
+ }, 30_000);
87
+ }
88
+ async setSessionModel(sessionId, modelId) {
89
+ await this.request(ACP_METHODS.SET_MODEL, {
90
+ sessionId,
91
+ modelId
92
+ }, 30_000);
93
+ }
94
+ async setSessionMode(sessionId, modeId) {
95
+ await this.request(ACP_METHODS.SET_MODE, {
96
+ sessionId,
97
+ modeId
98
+ }, 30_000);
99
+ }
100
+ async loadSession(sessionId, cwd) {
101
+ return await this.request(ACP_METHODS.LOAD, {
102
+ sessionId,
103
+ cwd: cwd || this.options.cwd
104
+ }, 30_000);
105
+ }
106
+ async prompt(sessionId, input) {
107
+ const blocks = typeof input === 'string' ? [{ type: 'text', text: input }] : input;
68
108
  let collected = '';
69
109
  const collector = (update) => {
110
+ this.options.onUpdate?.(sessionId, update);
70
111
  if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
71
112
  collected = `${collected}${update.content.text}`.slice(0, MAX_UPDATE_CHARS);
72
113
  }
@@ -161,6 +202,7 @@ export class AcpClient {
161
202
  const params = parsed.params;
162
203
  if (params && typeof params.sessionId === 'string' && params.update) {
163
204
  this.updateListener?.(params.sessionId, params.update);
205
+ this.options.onUpdate?.(params.sessionId, params.update);
164
206
  }
165
207
  }
166
208
  }
@@ -184,6 +226,84 @@ export class AcpClient {
184
226
  }
185
227
  return;
186
228
  }
229
+ if (request.method === ACP_METHODS.READ_TEXT_FILE) {
230
+ const params = request.params;
231
+ const targetPath = params?.path;
232
+ if (!targetPath || typeof targetPath !== 'string') {
233
+ this.write({
234
+ jsonrpc: '2.0',
235
+ id: request.id,
236
+ error: { code: ACP_ERROR_CODES.INVALID_PARAMS, message: 'Missing file path' }
237
+ });
238
+ return;
239
+ }
240
+ try {
241
+ let content;
242
+ if (this.options.fsReadHandler) {
243
+ const readOpts = {};
244
+ if (params?.line !== undefined)
245
+ readOpts.line = params.line;
246
+ if (params?.limit !== undefined)
247
+ readOpts.limit = params.limit;
248
+ content = await this.options.fsReadHandler(targetPath, readOpts);
249
+ }
250
+ else {
251
+ const resolved = path.resolve(this.options.cwd, targetPath);
252
+ content = await fs.readFile(resolved, 'utf8');
253
+ }
254
+ this.write({
255
+ jsonrpc: '2.0',
256
+ id: request.id,
257
+ result: { content }
258
+ });
259
+ }
260
+ catch (err) {
261
+ const msg = err instanceof Error ? err.message : String(err);
262
+ this.write({
263
+ jsonrpc: '2.0',
264
+ id: request.id,
265
+ error: { code: ACP_ERROR_CODES.RESOURCE_NOT_FOUND, message: `Could not read file: ${msg}` }
266
+ });
267
+ }
268
+ return;
269
+ }
270
+ if (request.method === ACP_METHODS.WRITE_TEXT_FILE) {
271
+ const params = request.params;
272
+ const targetPath = params?.path;
273
+ const content = params?.content;
274
+ if (!targetPath || typeof targetPath !== 'string' || typeof content !== 'string') {
275
+ this.write({
276
+ jsonrpc: '2.0',
277
+ id: request.id,
278
+ error: { code: ACP_ERROR_CODES.INVALID_PARAMS, message: 'Missing file path or content' }
279
+ });
280
+ return;
281
+ }
282
+ try {
283
+ if (this.options.fsWriteHandler) {
284
+ await this.options.fsWriteHandler(targetPath, content);
285
+ }
286
+ else {
287
+ const resolved = path.resolve(this.options.cwd, targetPath);
288
+ await fs.mkdir(path.dirname(resolved), { recursive: true });
289
+ await fs.writeFile(resolved, content, 'utf8');
290
+ }
291
+ this.write({
292
+ jsonrpc: '2.0',
293
+ id: request.id,
294
+ result: {}
295
+ });
296
+ }
297
+ catch (err) {
298
+ const msg = err instanceof Error ? err.message : String(err);
299
+ this.write({
300
+ jsonrpc: '2.0',
301
+ id: request.id,
302
+ error: { code: ACP_ERROR_CODES.INTERNAL_ERROR, message: `Could not write file: ${msg}` }
303
+ });
304
+ }
305
+ return;
306
+ }
187
307
  this.write({
188
308
  jsonrpc: '2.0',
189
309
  id: request.id,
@@ -199,7 +319,10 @@ export class AcpClient {
199
319
  clearTimeout(pending.timer);
200
320
  this.pending.delete(response.id);
201
321
  if (response.error) {
202
- pending.reject(new Error(`${pending.method} failed: ${response.error.message}`));
322
+ const err = new Error(`${pending.method} failed: ${response.error.message}`);
323
+ err.code = response.error.code;
324
+ err.data = response.error.data;
325
+ pending.reject(err);
203
326
  return;
204
327
  }
205
328
  pending.resolve(response.result);