@prplkane/agentlink 0.0.0-stage → 0.3.0-beta.1

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/client.mjs ADDED
@@ -0,0 +1,309 @@
1
+ import { version } from './version.mjs';
2
+ import { spawn } from 'node:child_process';
3
+ import { isAbsolute, join } from 'node:path';
4
+ export { providers, planProvider } from './providers.mjs';
5
+
6
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
7
+ const own = (value, key) => Object.hasOwn(value, key);
8
+ const fault = (code, message) => Object.assign(new Error(message), { name: 'AcpError', code });
9
+ const stops = new Set(['end_turn', 'max_tokens', 'max_turn_requests', 'refusal', 'cancelled']);
10
+ const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
11
+
12
+ // Deliberately narrow evaluation client: one process, one session, one prompt at a time.
13
+ // This is not a full ACP implementation or a process sandbox.
14
+ export class AcpClient {
15
+ #child; #pending = new Map(); #nextId = 1; #parts = []; #lineBytes = 0;
16
+ #bytes = 0; #stderr = Buffer.alloc(0); #failure; #closing; #exit; #exited = false;
17
+ #initialized = false; #sessionId; #promptId; #onUpdate; #limits; #cwd; #setupMethod;
18
+ #onPermission; #permissions = new Map(); #initialization;
19
+
20
+ constructor({ command, args = [], cwd, env = process.env, onUpdate = () => {}, onPermission,
21
+ maxMessageBytes = 1024 * 1024, maxOutputBytes = 8 * 1024 * 1024,
22
+ stderrBytes = 8192, cancelGraceMs = 500, exitGraceMs = 1500, permissionTimeoutMs = 60000 } = {}) {
23
+ if (!isAbsolute(command ?? '') || !isAbsolute(cwd ?? '') ||
24
+ !Array.isArray(args) || args.some(value => typeof value !== 'string')) {
25
+ throw new TypeError('Use absolute executable/cwd paths and an argument array.');
26
+ }
27
+ if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(command)) {
28
+ throw new TypeError('Use the executable or node + script, not a Windows shell shim.');
29
+ }
30
+ if (typeof onUpdate !== 'function') throw new TypeError('onUpdate must be a function.');
31
+ if (onPermission !== undefined && typeof onPermission !== 'function') throw new TypeError('onPermission must be a function.');
32
+ for (const value of [maxMessageBytes, maxOutputBytes, stderrBytes, cancelGraceMs, exitGraceMs, permissionTimeoutMs]) {
33
+ if (!Number.isSafeInteger(value) || value < 1) throw new TypeError('Limits must be positive integers.');
34
+ }
35
+ this.#limits = { maxMessageBytes, maxOutputBytes, stderrBytes, cancelGraceMs, exitGraceMs, permissionTimeoutMs };
36
+ this.#onUpdate = onUpdate;
37
+ this.#onPermission = onPermission;
38
+ this.#cwd = cwd;
39
+ this.#child = spawn(command, args, {
40
+ cwd, env, shell: false, windowsHide: true,
41
+ detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe']
42
+ });
43
+ this.#exit = new Promise(resolve => {
44
+ this.#child.once('exit', (code, signal) => {
45
+ this.#exited = true;
46
+ resolve({ code, signal });
47
+ if (!this.#closing) this.#fail(fault('PROCESS_EXIT', `Agent exited (${code ?? signal}).`));
48
+ });
49
+ this.#child.once('error', () => {
50
+ this.#exited = true;
51
+ resolve({ spawnFailed: true });
52
+ this.#fail(fault('SPAWN_FAILED', 'Could not start the configured agent executable.'));
53
+ });
54
+ });
55
+ this.#child.stdin.on('error', () => this.#fail(fault('PIPE_ERROR', 'Agent input pipe failed.')));
56
+ this.#child.stdout.on('data', chunk => this.#read(chunk));
57
+ this.#child.stdout.on('error', () => this.#fail(fault('PIPE_ERROR', 'Agent output pipe failed.')));
58
+ this.#child.stderr.on('data', chunk => {
59
+ this.#stderr = Buffer.concat([this.#stderr, chunk]).subarray(-stderrBytes);
60
+ });
61
+ }
62
+
63
+ get pid() { return this.#child.pid; }
64
+ get stderrTail() { return this.#stderr.toString('utf8'); }
65
+ get sessionId() { return this.#sessionId; }
66
+ get initialization() { return structuredClone(this.#initialization); }
67
+
68
+ async initialize(options) {
69
+ if (this.#initialized || this.#setupMethod) throw fault('INVALID_STATE', 'Initialization is already started.');
70
+ this.#setupMethod = 'initialize';
71
+ let result;
72
+ try { result = await this.#request('initialize', {
73
+ protocolVersion: 1,
74
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
75
+ clientInfo: { name: 'agentlink', version }
76
+ }, options); } finally { this.#setupMethod = undefined; }
77
+ if (!object(result) || result.protocolVersion !== 1 || !object(result.agentCapabilities)) {
78
+ const error = fault('UNSUPPORTED_PROTOCOL', 'Agent did not negotiate the supported ACP v1 profile.');
79
+ this.#fail(error); throw error;
80
+ }
81
+ this.#initialized = true;
82
+ this.#initialization = structuredClone(result);
83
+ return result;
84
+ }
85
+
86
+ async authenticate(methodId, options) {
87
+ if (!this.#initialized || this.#sessionId || this.#setupMethod) throw fault('INVALID_STATE', 'Authenticate after initialization and before creating a session.');
88
+ if (typeof methodId !== 'string' || !methodId) throw new TypeError('Provide an advertised authentication method ID.');
89
+ if (!this.#initialization.authMethods?.some(method => method.id === methodId)) throw fault('UNSUPPORTED_AUTH', 'The agent did not advertise this authentication method.');
90
+ this.#setupMethod = 'authenticate';
91
+ try { return await this.#request('authenticate', { methodId }, options); }
92
+ finally { this.#setupMethod = undefined; }
93
+ }
94
+
95
+ async newSession(options) {
96
+ if (!this.#initialized || this.#sessionId || this.#setupMethod) throw fault('INVALID_STATE', 'Initialize before creating one session.');
97
+ this.#setupMethod = 'session/new';
98
+ let result;
99
+ try { result = await this.#request('session/new', { cwd: this.#cwd, mcpServers: [] }, options); }
100
+ finally { this.#setupMethod = undefined; }
101
+ if (!object(result) || typeof result.sessionId !== 'string' || !result.sessionId) {
102
+ const error = fault('PROTOCOL_ERROR', 'Missing session ID.'); this.#fail(error); throw error;
103
+ }
104
+ this.#sessionId = result.sessionId;
105
+ return result;
106
+ }
107
+
108
+ async prompt(text, options) {
109
+ if (!this.#sessionId || this.#promptId !== undefined) throw fault('INVALID_STATE', 'Create a session and wait for its active prompt.');
110
+ if (typeof text !== 'string') throw new TypeError('This prototype supports text prompts only.');
111
+ try {
112
+ const result = await this.#request('session/prompt', {
113
+ sessionId: this.#sessionId, prompt: [{ type: 'text', text }]
114
+ }, options);
115
+ if (!object(result) || !stops.has(result.stopReason)) {
116
+ const error = fault('PROTOCOL_ERROR', 'Missing or unsupported stop reason.'); this.#fail(error); throw error;
117
+ }
118
+ return result;
119
+ } finally { this.#promptId = undefined; }
120
+ }
121
+
122
+ cancel() {
123
+ if (this.#promptId === undefined) return false;
124
+ this.#cancel(this.#promptId);
125
+ return true;
126
+ }
127
+
128
+ async close() {
129
+ if (this.#closing) return this.#closing;
130
+ this.#failure ??= fault('CLOSED', 'Connection closed.');
131
+ this.#cancelPermissions();
132
+ this.#rejectAll(this.#failure);
133
+ this.#closing = this.#stopOwnedProcess();
134
+ return this.#closing;
135
+ }
136
+
137
+ #request(method, params, { timeoutMs = 30000, signal } = {}) {
138
+ if (this.#failure) return Promise.reject(this.#failure);
139
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1) return Promise.reject(new TypeError('timeoutMs must be positive.'));
140
+ if (signal?.aborted) return Promise.reject(fault('CANCELLED', 'Request cancelled before it was sent.'));
141
+ const id = this.#nextId++;
142
+ return new Promise((resolve, reject) => {
143
+ const abort = () => method === 'session/prompt'
144
+ ? this.#cancel(id, fault('CANCELLED', 'Prompt cancelled.'))
145
+ : this.#fail(fault('CANCELLED', `${method} cancelled.`));
146
+ const timer = setTimeout(() => method === 'session/prompt'
147
+ ? this.#cancel(id, fault('DEADLINE', 'Prompt deadline reached.'))
148
+ : this.#fail(fault('DEADLINE', `${method} deadline reached.`)), timeoutMs);
149
+ const entry = { resolve, reject, timer, signal, abort, method };
150
+ this.#pending.set(id, entry);
151
+ if (method === 'session/prompt') this.#promptId = id;
152
+ signal?.addEventListener('abort', abort, { once: true });
153
+ this.#send({ jsonrpc: '2.0', id, method, params });
154
+ });
155
+ }
156
+
157
+ #cancel(id, error) {
158
+ const entry = this.#pending.get(id);
159
+ if (!entry || entry.cancelSent) return;
160
+ entry.cancelSent = true;
161
+ entry.cancelError = error;
162
+ clearTimeout(entry.timer);
163
+ this.#cancelPermissions();
164
+ this.#send({ jsonrpc: '2.0', method: 'session/cancel', params: { sessionId: this.#sessionId } });
165
+ entry.grace = setTimeout(() => this.#fail(error ?? fault('CANCEL_TIMEOUT', 'Agent did not complete cancellation.')), this.#limits.cancelGraceMs);
166
+ }
167
+
168
+ #send(message) {
169
+ if (this.#failure) return;
170
+ const wire = JSON.stringify(message) + '\n';
171
+ if (Buffer.byteLength(wire) > this.#limits.maxMessageBytes) {
172
+ this.#fail(fault('MESSAGE_LIMIT', 'Outgoing message exceeds the configured limit.')); return;
173
+ }
174
+ this.#child.stdin.write(wire, error => {
175
+ if (error) this.#fail(fault('PIPE_ERROR', 'Agent input pipe failed.'));
176
+ });
177
+ }
178
+
179
+ #read(chunk) {
180
+ if (this.#failure) return;
181
+ this.#bytes += chunk.length;
182
+ if (this.#bytes > this.#limits.maxOutputBytes) {
183
+ this.#fail(fault('OUTPUT_LIMIT', 'Agent output exceeds the connection limit.')); return;
184
+ }
185
+ let start = 0;
186
+ for (let i = 0; i <= chunk.length; i++) {
187
+ if (i !== chunk.length && chunk[i] !== 10) continue;
188
+ const part = chunk.subarray(start, i);
189
+ this.#lineBytes += part.length;
190
+ if (this.#lineBytes > this.#limits.maxMessageBytes) {
191
+ this.#fail(fault('MESSAGE_LIMIT', 'Agent message exceeds the configured limit.')); return;
192
+ }
193
+ if (part.length) this.#parts.push(part);
194
+ if (i < chunk.length) {
195
+ const bytes = Buffer.concat(this.#parts, this.#lineBytes);
196
+ this.#parts = []; this.#lineBytes = 0;
197
+ try {
198
+ const line = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
199
+ this.#message(JSON.parse(line));
200
+ } catch (error) {
201
+ this.#fail(error.name === 'AcpError' ? error : fault('PROTOCOL_ERROR', 'Agent sent invalid UTF-8, JSON, or ACP data.'));
202
+ }
203
+ if (this.#failure) return;
204
+ }
205
+ start = i + 1;
206
+ }
207
+ }
208
+
209
+ #message(message) {
210
+ if (!object(message) || message.jsonrpc !== '2.0') throw fault('PROTOCOL_ERROR', 'Invalid JSON-RPC envelope.');
211
+ if (own(message, 'method')) {
212
+ if (own(message, 'result') || own(message, 'error')) throw fault('PROTOCOL_ERROR', 'Invalid JSON-RPC method envelope.');
213
+ if (typeof message.method !== 'string' || !object(message.params)) throw fault('PROTOCOL_ERROR', 'Invalid method or params.');
214
+ if (own(message, 'id')) {
215
+ if (typeof message.id !== 'string' && !Number.isSafeInteger(message.id)) throw fault('PROTOCOL_ERROR', 'Invalid request ID.');
216
+ if (message.method === 'session/request_permission') this.#permission(message);
217
+ else this.#send({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'This client does not support this method.' } });
218
+ } else if (message.method === 'session/update') {
219
+ const { sessionId, update } = message.params;
220
+ if (sessionId !== this.#sessionId || !object(update) || typeof update.sessionUpdate !== 'string') {
221
+ throw fault('PROTOCOL_ERROR', 'Invalid update or unexpected session.');
222
+ }
223
+ try { this.#onUpdate(update); }
224
+ catch { throw fault('HANDLER_ERROR', 'The update callback failed.'); }
225
+ }
226
+ return;
227
+ }
228
+ const entry = this.#pending.get(message.id);
229
+ if (!entry || own(message, 'result') === own(message, 'error')) throw fault('PROTOCOL_ERROR', 'Unexpected or invalid response.');
230
+ if (own(message, 'error') && (!object(message.error) || !Number.isInteger(message.error.code) || typeof message.error.message !== 'string')) {
231
+ throw fault('PROTOCOL_ERROR', 'Invalid remote error.');
232
+ }
233
+ if (entry.method === 'session/prompt') this.#cancelPermissions();
234
+ this.#finish(message.id);
235
+ // An update can follow this response in the same stdout chunk, before the
236
+ // newSession() promise resumes. Establish the ID at the receive boundary.
237
+ if (entry.method === 'session/new' && object(message.result) && typeof message.result.sessionId === 'string') {
238
+ this.#sessionId = message.result.sessionId;
239
+ }
240
+ if (entry.cancelError) entry.reject(entry.cancelError);
241
+ else if (message.error) entry.reject(Object.assign(fault('REMOTE_ERROR', message.error.message), { rpcCode: message.error.code }));
242
+ else entry.resolve(message.result);
243
+ }
244
+
245
+ #permission({ id, params }) {
246
+ if (!this.#sessionId || params.sessionId !== this.#sessionId || !Array.isArray(params.options) ||
247
+ !params.options.every(option => object(option) && typeof option.optionId === 'string') || this.#permissions.has(id)) {
248
+ throw fault('PROTOCOL_ERROR', 'Invalid permission request or session.');
249
+ }
250
+ const options = new Set(params.options.map(option => option.optionId));
251
+ const controller = new AbortController();
252
+ let finished = false;
253
+ const finish = optionId => {
254
+ if (finished) return;
255
+ finished = true;
256
+ clearTimeout(timer);
257
+ this.#permissions.delete(id);
258
+ const outcome = typeof optionId === 'string' && options.has(optionId)
259
+ ? { outcome: 'selected', optionId } : { outcome: 'cancelled' };
260
+ this.#send({ jsonrpc: '2.0', id, result: { outcome } });
261
+ };
262
+ const cancel = () => { controller.abort(); finish(null); };
263
+ const timer = setTimeout(cancel, this.#limits.permissionTimeoutMs);
264
+ this.#permissions.set(id, { cancel });
265
+ Promise.resolve().then(() => controller.signal.aborted ? null : this.#onPermission?.(structuredClone(params), { signal: controller.signal }))
266
+ .then(finish, () => finish(null));
267
+ }
268
+
269
+ #cancelPermissions() {
270
+ for (const request of [...this.#permissions.values()]) request.cancel();
271
+ }
272
+
273
+ #finish(id) {
274
+ const entry = this.#pending.get(id);
275
+ clearTimeout(entry.timer); clearTimeout(entry.grace);
276
+ entry.signal?.removeEventListener('abort', entry.abort);
277
+ this.#pending.delete(id);
278
+ }
279
+
280
+ #rejectAll(error) {
281
+ for (const [id, entry] of this.#pending) { this.#finish(id); entry.reject(error); }
282
+ }
283
+
284
+ #fail(error) {
285
+ if (this.#failure) return;
286
+ this.#failure = error;
287
+ void this.close().catch(() => {});
288
+ }
289
+
290
+ async #stopOwnedProcess() {
291
+ // Target only the process spawned here. Never search/kill by executable name.
292
+ if (this.#child.pid && !this.#exited) {
293
+ if (process.platform === 'win32') {
294
+ const taskkill = spawn(join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'taskkill.exe'),
295
+ ['/PID', String(this.#child.pid), '/T', '/F'], { windowsHide: true, shell: false, stdio: 'ignore' });
296
+ await Promise.race([
297
+ new Promise(resolve => { taskkill.once('exit', resolve); taskkill.once('error', resolve); }),
298
+ wait(this.#limits.exitGraceMs).then(() => { if (taskkill.exitCode === null) taskkill.kill(); })
299
+ ]);
300
+ } else {
301
+ try { process.kill(-this.#child.pid, 'SIGKILL'); }
302
+ catch (error) { if (error.code !== 'ESRCH') throw error; }
303
+ }
304
+ }
305
+ const exited = await Promise.race([this.#exit.then(() => true), wait(this.#limits.exitGraceMs).then(() => false)]);
306
+ this.#child.stdin.destroy(); this.#child.stdout.destroy(); this.#child.stderr.destroy();
307
+ if (!exited) throw fault('PROCESS_STOP_FAILED', 'Owned agent did not exit.');
308
+ }
309
+ }
@@ -0,0 +1,168 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdtemp, rm } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { basename, dirname, join, resolve } from 'node:path';
5
+ import { probeAcp } from './probe.mjs';
6
+ import { providers } from './providers.mjs';
7
+ import { error, strings } from './profiles.mjs';
8
+ import { readHelp, resolveCommand } from './process.mjs';
9
+
10
+ function knownRecipe(provider, executableName) {
11
+ if (provider !== undefined) {
12
+ if (!Object.hasOwn(providers, provider)) throw error('UNKNOWN_PROVIDER', `Unknown recipe "${provider}". Omit --provider to discover a custom CLI.`);
13
+ const recipe = providers[provider];
14
+ if (recipe.kind === 'unavailable') throw error('UNAVAILABLE_PROVIDER', recipe.note);
15
+ if (['codex', 'claude'].includes(executableName)) {
16
+ throw error('ACP_BRIDGE_REQUIRED', `Use the installed ${recipe.executableName} bridge, rather than the interactive ${executableName} CLI.`);
17
+ }
18
+ return [provider, recipe];
19
+ }
20
+ return Object.entries(providers).find(([, recipe]) => !recipe.explicitMatch && recipe.executableName === executableName);
21
+ }
22
+
23
+ // Parse only declared options/command rows. Prose, examples and shell snippets are
24
+ // not executable instructions. An unusual interface can use explicit acpArgs.
25
+ export function inspectHelp(text) {
26
+ const lines = text.split(/\r?\n/);
27
+ const candidates = [];
28
+ const subcommands = [];
29
+ let stdio = [];
30
+ for (const line of lines) {
31
+ if (/^\s*(?:-\w,\s*)?--stdio(?:\s|$)/.test(line)) stdio = ['--stdio'];
32
+ else if (/^\s*--transport\s+[<[]/.test(line) && /\bstdio\b/i.test(line)) stdio = ['--transport', 'stdio'];
33
+ }
34
+ for (const line of lines) {
35
+ const flag = /^\s*(?:-\w,\s*)?(--(?:experimental-)?acp)(?=\s|$)(.*)$/.exec(line);
36
+ if (flag && !/^\s*[<=]/.test(flag[2]) && !/^\s*\[(?!boolean\b)/i.test(flag[2])) {
37
+ candidates.push([flag[1], ...stdio]);
38
+ }
39
+ const protocol = /^\s*(--(?:protocol|mode))\s+(?:<[^>]+>|\[[^\]]+\])\s+(.+)$/.exec(line);
40
+ if (protocol && /(?:choices?|values?|one of|options?).*\bacp\b/i.test(protocol[2])) {
41
+ candidates.push([protocol[1], 'acp', ...stdio]);
42
+ }
43
+ const row = /^\s{0,8}([a-z][a-z0-9_-]*)(?:\s+(\[[^\]]*\]|<[^>]+>))?\s{2,}(.+)$/.exec(line);
44
+ if (row && (/\bacp\b|agent client protocol/i.test(row[3]) ||
45
+ (/^(serve|server|protocol)$/.test(row[1]) && /protocol|stdio/i.test(row[3]))) && !row[2]?.startsWith('<')) {
46
+ if (row[1] === 'acp' || row[1] === 'acp-server') candidates.push([row[1], ...stdio]);
47
+ else subcommands.push(row[1]);
48
+ }
49
+ // Yargs can print the executable name before a command.
50
+ if (/^\s{0,8}[\w.-]+\s+acp\s{2,}.*(?:ACP|Agent Client Protocol)/i.test(line)) candidates.push(['acp', ...stdio]);
51
+ }
52
+ return { candidates, subcommands: [...new Set(subcommands)].slice(0, 2) };
53
+ }
54
+
55
+ export async function verifyAgent(launch, { cwd, env = process.env, timeoutMs = 3000, signal } = {}) {
56
+ return probeAcp(launch, { cwd, env, timeoutMs, signal });
57
+ }
58
+
59
+ export async function inProbeDirectory(callback) {
60
+ const base = resolve(tmpdir());
61
+ const directory = await mkdtemp(join(base, 'agentlink-probe-'));
62
+ try { return await callback(directory); }
63
+ finally {
64
+ if (dirname(directory) !== base || !basename(directory).startsWith('agentlink-probe-')) throw error('INVALID_PATH', 'Unexpected probe directory.');
65
+ // Windows may retain a just-stopped descendant's cwd for a short time.
66
+ // Retry only transient filesystem errors; do not replace the probe outcome
67
+ // with a one-off EBUSY, and still surface a persistent cleanup failure.
68
+ await rm(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
69
+ }
70
+ }
71
+
72
+ export function validateDiscoveryOptions({ command, prefixArgs = [], acpArgs, provider, helpArgs,
73
+ verify = true, timeoutMs = 3000, maxHelpBytes = 65536 } = {}) {
74
+ if (typeof verify !== 'boolean' || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1) throw new TypeError('Invalid discovery options.');
75
+ if (!Number.isSafeInteger(maxHelpBytes) || maxHelpBytes < 1) throw new TypeError('Invalid help output limit.');
76
+ if (command !== undefined && (typeof command !== 'string' || !command || command.includes('\0'))) throw new TypeError('Invalid command.');
77
+ if (!strings(prefixArgs)) throw new TypeError('prefixArgs must be an array of strings.');
78
+ if (provider !== undefined && !Object.hasOwn(providers, provider)) throw error('UNKNOWN_PROVIDER', `Unknown recipe "${provider}".`);
79
+ if (acpArgs !== undefined && !strings(acpArgs)) throw new TypeError('acpArgs must be an array of strings.');
80
+ if (helpArgs !== undefined && (!strings(helpArgs) || !helpArgs.length)) throw new TypeError('helpArgs must be a nonempty argument array.');
81
+ }
82
+
83
+ export async function discoverAgent({ command, prefixArgs = [], acpArgs, provider, helpArgs,
84
+ env = process.env, verify = true, timeoutMs = 3000, maxHelpBytes = 65536, signal } = {}) {
85
+ validateDiscoveryOptions({ command, prefixArgs, acpArgs, provider, helpArgs, verify, timeoutMs, maxHelpBytes });
86
+ command ??= providers[provider]?.executableName;
87
+ const resolved = await resolveCommand(command, prefixArgs, env);
88
+ const known = acpArgs === undefined ? knownRecipe(provider, resolved.executableName) : undefined;
89
+ const base = { command: resolved.command, prefixArgs: resolved.prefixArgs, provider: provider ?? known?.[0] ?? null, protocolVersion: 1 };
90
+ const diagnostics = [];
91
+ const attempted = new Set();
92
+ return inProbeDirectory(async cwd => {
93
+ const attempt = async (args, method, help) => {
94
+ signal?.throwIfAborted();
95
+ const key = JSON.stringify(args);
96
+ if (attempted.has(key) || attempted.size >= 5) return;
97
+ attempted.add(key);
98
+ const candidate = { ...base, acpArgs: [...args], discovery: { method } };
99
+ if (helpArgs) candidate.discovery.helpArgs = [...helpArgs];
100
+ if (help) candidate.discovery.helpSha256 = createHash('sha256').update(help).digest('hex');
101
+ try {
102
+ candidate.verification = verify ? await verifyAgent(candidate, { cwd, env, timeoutMs, signal }) : { status: 'pending' };
103
+ candidate.protocolVersion = candidate.verification.protocolVersion || 1;
104
+ return candidate;
105
+ } catch (cause) {
106
+ if (signal?.aborted) throw cause;
107
+ diagnostics.push({ stage: 'initialize', args, code: cause.code || 'PROBE_FAILED', message: cause.message });
108
+ }
109
+ };
110
+ if (acpArgs !== undefined) {
111
+ const result = await attempt(acpArgs, 'manual');
112
+ if (result) return result;
113
+ throw Object.assign(error('ACP_VERIFICATION_FAILED', 'The supplied ACP command did not complete initialization.'), { diagnostics });
114
+ }
115
+ if (known) {
116
+ const result = await attempt(known[1].args, 'known');
117
+ if (result) return result;
118
+ }
119
+ const helpCalls = new Set();
120
+ const help = async args => {
121
+ signal?.throwIfAborted();
122
+ const key = JSON.stringify(args);
123
+ if (helpCalls.has(key) || helpCalls.size >= 8) return '';
124
+ helpCalls.add(key);
125
+ try {
126
+ const result = await readHelp({ command: base.command, args: [...base.prefixArgs, ...args], cwd, env, timeoutMs, maxBytes: maxHelpBytes, signal });
127
+ if (result.code !== 0) {
128
+ diagnostics.push({ stage: 'help', args, code: 'HELP_EXIT', message: `Help exited with ${result.code}.` });
129
+ }
130
+ return result.text;
131
+ } catch (cause) {
132
+ if (signal?.aborted) throw cause;
133
+ diagnostics.push({ stage: 'help', args, code: cause.code || 'HELP_FAILED', message: cause.message });
134
+ return '';
135
+ }
136
+ };
137
+ const queue = helpArgs ? [[...helpArgs]] : [['--help'], ['-h']];
138
+ for (let index = 0; index < queue.length && helpCalls.size < 8; index++) {
139
+ const text = await help(queue[index]);
140
+ const parsed = inspectHelp(text);
141
+ for (const args of parsed.candidates) {
142
+ const result = await attempt(args, 'help', text);
143
+ if (result) return result;
144
+ }
145
+ for (const subcommand of parsed.subcommands) {
146
+ const routes = [[subcommand, '--help']];
147
+ if (/^\s{0,8}help(?:\s+\[[^\]]+\])?\s{2,}/m.test(text)) routes.push(['help', subcommand]);
148
+ for (const route of routes) {
149
+ const nested = await help(route);
150
+ for (const args of inspectHelp(nested).candidates) {
151
+ const result = await attempt([subcommand, ...args], 'help', text + '\n' + nested);
152
+ if (result) return result;
153
+ }
154
+ }
155
+ }
156
+ // Only follow alternative forms advertised as actual command/option rows.
157
+ // A custom convention can always be supplied explicitly with helpArgs.
158
+ if (/^\s{0,8}help(?:\s+\[[^\]]+\])?\s{2,}/m.test(text)) queue.push(['help']);
159
+ for (const alias of ['/?', '-?', '/h']) {
160
+ if (text.split(/\r?\n/).some(line => line.trimStart().startsWith(alias + ' '))) queue.push([alias]);
161
+ }
162
+ }
163
+ const bridge = ['codex', 'claude'].includes(resolved.executableName) ? providers[resolved.executableName].executableName : undefined;
164
+ const message = bridge ? `This CLI needs an installed ${bridge} ACP bridge.` :
165
+ 'Automatic ACP discovery was inconclusive. Supply --help-args or exact --acp-args for an installed agent or bridge.';
166
+ throw Object.assign(error(bridge ? 'ACP_BRIDGE_REQUIRED' : 'DISCOVERY_INCONCLUSIVE', message), { diagnostics });
167
+ });
168
+ }
package/src/doctor.mjs ADDED
@@ -0,0 +1,63 @@
1
+ import { access, readdir, stat } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { basename, isAbsolute, join } from 'node:path';
4
+ import { readJson } from './storage.mjs';
5
+
6
+ // Read-only inspection. In particular, never start an agent, download a bridge,
7
+ // clear a lock, or infer authentication success from files on disk.
8
+ export async function doctor(runtime) {
9
+ const checks = [];
10
+ const check = async (scope, name, callback) => {
11
+ try { await callback(); checks.push({ scope, name, status: 'ok' }); }
12
+ catch (cause) { checks.push({ scope, name, status: 'error', code: cause.code || 'INVALID_METADATA', message: cause.message }); }
13
+ };
14
+ const launchFiles = async launch => {
15
+ if (!(await stat(launch.command)).isFile()) throw new Error('Configured command is not a file: ' + launch.command);
16
+ if (process.platform !== 'win32') await access(launch.command, constants.X_OK);
17
+ const script = launch.prefixArgs?.[0];
18
+ if (/^node(?:\.exe)?$/i.test(basename(launch.command)) && isAbsolute(script || '')) {
19
+ if (!(await stat(script)).isFile()) throw new Error('Configured Node entry script is not a file: ' + script);
20
+ }
21
+ };
22
+ for (const profile of await runtime.list()) {
23
+ await check('profile', profile.name, async () => {
24
+ if (profile.error) throw profile.error;
25
+ await launchFiles(await runtime.resolveProfile(profile));
26
+ });
27
+ }
28
+ for (const record of await runtime.bridges.list()) {
29
+ await check('bridge', record.id, async () => {
30
+ if (record.error) throw record.error;
31
+ const root = join(runtime.bridges.installations, record.installKey);
32
+ const metadata = await readJson(join(root, 'installation.json'));
33
+ if (metadata.installKey !== record.installKey) throw new Error('Installation metadata does not match the active bridge.');
34
+ await launchFiles(record.launch);
35
+ });
36
+ }
37
+ const lockFiles = [join(runtime.home, 'management.lock'), join(runtime.home, 'leases.lock')];
38
+ try {
39
+ for (const name of await readdir(join(runtime.home, 'locks'))) {
40
+ if (name.endsWith('.lock')) lockFiles.push(join(runtime.home, 'locks', name));
41
+ }
42
+ } catch (cause) { if (cause.code !== 'ENOENT') throw cause; }
43
+ for (const path of lockFiles) {
44
+ let owner;
45
+ try { owner = await readJson(path); }
46
+ catch (cause) {
47
+ if (cause.code !== 'ENOENT') checks.push({ scope: 'lock', name: path, status: 'error',
48
+ code: 'INVALID_LOCK', message: 'Cannot read lock owner; inspect it before recovery.' });
49
+ continue;
50
+ }
51
+ if (!Number.isSafeInteger(owner.pid) || owner.pid < 1) {
52
+ checks.push({ scope: 'lock', name: path, status: 'error', code: 'INVALID_LOCK', message: 'Lock has no valid process owner.' });
53
+ continue;
54
+ }
55
+ let stopped = false;
56
+ try { process.kill(owner.pid, 0); } catch (cause) { stopped = cause.code === 'ESRCH'; }
57
+ checks.push({ scope: 'lock', name: path, status: stopped ? 'error' : 'busy', pid: owner.pid,
58
+ code: stopped ? 'STALE_LOCK' : 'LOCK_HELD',
59
+ message: stopped ? 'Recorded process has stopped. After confirming no operation is running, remove this lock and retry.' :
60
+ 'An operation may still be running. Do not remove this lock while its owner is active.' });
61
+ }
62
+ return { ok: !checks.some(check => check.status === 'error'), home: runtime.home, checks };
63
+ }
@@ -0,0 +1,106 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { pipeline } from 'node:stream/promises';
3
+ import { AcpFrames } from './wire.mjs';
4
+ import { stopProcess } from './child-process.mjs';
5
+ import { error, strings } from './profiles.mjs';
6
+ import { authMarker, terminalAuthReply } from './terminal-auth.mjs';
7
+
8
+ // One process/connection per caller; installed bridges and profiles are shared.
9
+ // No initialize, session/new, task, approval, download or discovery is injected.
10
+ export async function runGateway(launch, { cwd = process.cwd(), env = process.env,
11
+ input = process.stdin, output = process.stdout, diagnostics = process.stderr,
12
+ signal, extraArgs = [], interactive = Boolean(process.stdin.isTTY),
13
+ maxMessageBytes = 16 * 1024 * 1024, shutdownGraceMs = 750 } = {}) {
14
+ if (!strings(extraArgs) || !Number.isSafeInteger(shutdownGraceMs) || shutdownGraceMs < 1) {
15
+ throw new TypeError('Invalid gateway arguments.');
16
+ }
17
+ signal?.throwIfAborted();
18
+ // ACP terminal-auth methods append argv to the configured launch command.
19
+ // Append those bytes to the bridge's base argv, not to management option parsing.
20
+ const terminal = interactive || extraArgs.length > 0;
21
+ const forwardedArgs = extraArgs[0] === authMarker ? extraArgs.slice(1) : extraArgs;
22
+ const child = spawn(launch.command, [...launch.prefixArgs, ...launch.acpArgs, ...forwardedArgs], {
23
+ cwd, env: terminal ? { ...launch.env, ...env } : { ...env, ...launch.env }, shell: false, windowsHide: !terminal,
24
+ detached: process.platform !== 'win32', stdio: terminal ? 'inherit' : ['pipe', 'pipe', 'pipe']
25
+ });
26
+ let failure, inputTimer, closing = false;
27
+ const pumps = new AbortController();
28
+ let stopPromise;
29
+ const stop = () => stopPromise ??= stopProcess(child).catch(cause => { failure ??= cause; });
30
+ const fail = cause => {
31
+ failure ??= cause;
32
+ pumps.abort();
33
+ if (!terminal) output.destroy(); // end:false may have settled before its last write callback.
34
+ void stop();
35
+ };
36
+ const aborted = () => fail(error('CANCELLED', 'AgentLink connection was terminated.'));
37
+ signal?.addEventListener('abort', aborted, { once: true });
38
+ const exited = new Promise(resolve => {
39
+ child.once('error', () => { failure ??= error('SPAWN_FAILED', 'Could not start the configured bridge.'); resolve(1); });
40
+ child.once('exit', code => resolve(code ?? 1));
41
+ });
42
+ let outputPump = Promise.resolve();
43
+ let inputPump = Promise.resolve();
44
+ let outputFrames;
45
+ if (!terminal) {
46
+ const initializeIds = new Set();
47
+ inputPump = pipeline(input, new AcpFrames({ maxMessageBytes, onMessage(message) {
48
+ if (message.method === 'initialize' && Object.hasOwn(message, 'id')) initializeIds.add(message.id);
49
+ } }), child.stdin, { signal: pumps.signal }).then(() => {
50
+ if (!closing) inputTimer = setTimeout(() => { void stop(); }, shutdownGraceMs);
51
+ }, cause => {
52
+ if (closing) return;
53
+ // A normally exiting bridge can close its stdin before the exit event.
54
+ // Give it time to finish and drain stdout instead of destroying its reply.
55
+ if (['EPIPE', 'ERR_STREAM_PREMATURE_CLOSE', 'ERR_STREAM_DESTROYED'].includes(cause.code)) {
56
+ if (child.exitCode === null && child.signalCode === null) inputTimer = setTimeout(() => fail(cause), shutdownGraceMs);
57
+ } else fail(cause);
58
+ });
59
+ outputFrames = new AcpFrames({ maxMessageBytes, mapMessage(message, source) {
60
+ if (message.method || !initializeIds.delete(message.id) || !Array.isArray(message.result?.authMethods)) return;
61
+ // The client relaunches AgentLink, not the underlying executable. A marker
62
+ // identifies terminal auth even when the upstream method has only env.
63
+ return terminalAuthReply(message, source);
64
+ } });
65
+ outputPump = pipeline(child.stdout, outputFrames, output, { end: false, signal: pumps.signal })
66
+ .catch(cause => { if (!closing) fail(cause); });
67
+ child.stderr.pipe(diagnostics, { end: false });
68
+ child.stderr.on('error', fail);
69
+ diagnostics.on('error', fail);
70
+ }
71
+ let flushTimer;
72
+ try {
73
+ const exitCode = await exited;
74
+ clearTimeout(inputTimer);
75
+ // Drain final responses even when the client reads slowly. The grace period
76
+ // only limits idle pipes retained by a descendant after its parent exited.
77
+ await new Promise(resolve => {
78
+ let done = false;
79
+ const finish = () => { done = true; clearTimeout(flushTimer); resolve(); };
80
+ const idle = () => {
81
+ if (done) return;
82
+ if (!failure && !output.destroyed && (output.writableLength || output.writableNeedDrain || child.stdout?.readableLength ||
83
+ outputFrames?.readableLength || outputFrames?.writableLength)) {
84
+ flushTimer = setTimeout(idle, shutdownGraceMs);
85
+ } else finish();
86
+ };
87
+ // end:false leaves the caller's stream open and may resolve before its
88
+ // final write callback; also wait for that queued output to drain.
89
+ outputPump.then(() => { if (failure || !output.writableLength || output.destroyed) finish(); });
90
+ flushTimer = setTimeout(idle, shutdownGraceMs);
91
+ });
92
+ if (failure) throw failure;
93
+ return { exitCode };
94
+ } finally {
95
+ closing = true;
96
+ clearTimeout(inputTimer); clearTimeout(flushTimer);
97
+ signal?.removeEventListener('abort', aborted);
98
+ diagnostics.off('error', fail);
99
+ await stop();
100
+ if (!terminal) {
101
+ pumps.abort();
102
+ input.destroy();
103
+ await Promise.allSettled([inputPump, outputPump]);
104
+ }
105
+ }
106
+ }