@theokit/acp 4.0.2 → 4.2.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/CHANGELOG.md +46 -0
- package/README.md +32 -1
- package/dist/client.cjs +339 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +92 -0
- package/dist/client.d.ts +92 -0
- package/dist/client.js +316 -0
- package/dist/client.js.map +1 -0
- package/dist/index.cjs +176 -153
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +176 -153
- package/dist/index.js.map +1 -1
- package/package.json +13 -3
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import * as acp from '@agentclientprotocol/sdk';
|
|
2
|
+
import { TheokitAgentError } from '@theokit/sdk';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Command resolution and child-process handling for `connectAcpAgent`.
|
|
6
|
+
*
|
|
7
|
+
* @internal
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A child agent could not be started, was refused before starting, or exited before it finished
|
|
12
|
+
* what it was asked to do.
|
|
13
|
+
*
|
|
14
|
+
* @public
|
|
15
|
+
*/
|
|
16
|
+
declare class AcpAgentSpawnError extends TheokitAgentError {
|
|
17
|
+
readonly name: string;
|
|
18
|
+
/** Exit code of the child, when it exited with one. */
|
|
19
|
+
readonly exitCode?: number | null;
|
|
20
|
+
/** Signal that ended the child, when it was killed by one. */
|
|
21
|
+
readonly exitSignal?: string | null;
|
|
22
|
+
/** The last (bounded) stderr lines of the child. */
|
|
23
|
+
readonly stderrTail?: string;
|
|
24
|
+
constructor(message: string, details?: {
|
|
25
|
+
exitCode?: number | null;
|
|
26
|
+
exitSignal?: string | null;
|
|
27
|
+
stderrTail?: string;
|
|
28
|
+
cause?: unknown;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* `@theokit/acp/client` — drive another ACP agent over stdio.
|
|
34
|
+
*
|
|
35
|
+
* ```ts
|
|
36
|
+
* import { connectAcpAgent } from "@theokit/acp/client";
|
|
37
|
+
*
|
|
38
|
+
* const agent = await connectAcpAgent({
|
|
39
|
+
* command: "/usr/local/bin/my-agent",
|
|
40
|
+
* cwd: process.cwd(),
|
|
41
|
+
* env: { PATH: "/usr/bin" },
|
|
42
|
+
* onPermission: async (req) => ({ outcome: { outcome: "cancelled" } }),
|
|
43
|
+
* });
|
|
44
|
+
* for await (const update of agent.prompt("hello")) console.log(update.update);
|
|
45
|
+
* await agent.close();
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* @packageDocumentation
|
|
49
|
+
*/
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Options for {@link connectAcpAgent}.
|
|
53
|
+
*
|
|
54
|
+
* @public
|
|
55
|
+
*/
|
|
56
|
+
interface ConnectAcpAgentOptions {
|
|
57
|
+
/** Absolute path, or a bare name resolved on absolute `PATH` entries of `env` only. */
|
|
58
|
+
command: string;
|
|
59
|
+
args?: readonly string[];
|
|
60
|
+
cwd: string;
|
|
61
|
+
/** Passed to the child as is. Nothing is inherited from `process.env`. */
|
|
62
|
+
env: Record<string, string>;
|
|
63
|
+
/** Answers the agent's `session/request_permission`. */
|
|
64
|
+
onPermission(request: acp.RequestPermissionRequest): Promise<acp.RequestPermissionResponse>;
|
|
65
|
+
/** Budget for the `initialize` + `session/new` handshake. Default 10_000. */
|
|
66
|
+
initializeTimeoutMs?: number;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* A live connection to a spawned ACP agent with one open session.
|
|
70
|
+
*
|
|
71
|
+
* @public
|
|
72
|
+
*/
|
|
73
|
+
interface AcpAgentConnection {
|
|
74
|
+
/**
|
|
75
|
+
* Send one prompt and stream the session updates it produces. Only one prompt may be in flight.
|
|
76
|
+
* Aborting `signal` sends `session/cancel`. A child exiting mid-prompt ends the iterator with
|
|
77
|
+
* `AcpAgentSpawnError`.
|
|
78
|
+
*/
|
|
79
|
+
prompt(text: string, signal?: AbortSignal): AsyncIterable<acp.SessionNotification>;
|
|
80
|
+
/** Ends the session and kills the child (its process group on POSIX). Idempotent. */
|
|
81
|
+
close(): Promise<void>;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Spawn an ACP agent as a child process, complete the handshake and open one session.
|
|
85
|
+
*
|
|
86
|
+
* @throws AcpAgentSpawnError when the command is refused, cannot be started, or exits or stalls
|
|
87
|
+
* during initialize.
|
|
88
|
+
* @public
|
|
89
|
+
*/
|
|
90
|
+
declare function connectAcpAgent(options: ConnectAcpAgentOptions): Promise<AcpAgentConnection>;
|
|
91
|
+
|
|
92
|
+
export { type AcpAgentConnection, AcpAgentSpawnError, type ConnectAcpAgentOptions, connectAcpAgent };
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { Writable, Readable } from 'stream';
|
|
2
|
+
import * as acp from '@agentclientprotocol/sdk';
|
|
3
|
+
import { spawn } from 'child_process';
|
|
4
|
+
import { statSync, accessSync, constants } from 'fs';
|
|
5
|
+
import { isAbsolute, delimiter, join } from 'path';
|
|
6
|
+
import { TheokitAgentError } from '@theokit/sdk';
|
|
7
|
+
|
|
8
|
+
// src/client.ts
|
|
9
|
+
var STDERR_MAX_LINES = 20;
|
|
10
|
+
var STDERR_MAX_LINE_CHARS = 500;
|
|
11
|
+
var KILL_GRACE_MS = 2e3;
|
|
12
|
+
var AcpAgentSpawnError = class extends TheokitAgentError {
|
|
13
|
+
name = "AcpAgentSpawnError";
|
|
14
|
+
/** Exit code of the child, when it exited with one. */
|
|
15
|
+
exitCode;
|
|
16
|
+
/** Signal that ended the child, when it was killed by one. */
|
|
17
|
+
exitSignal;
|
|
18
|
+
/** The last (bounded) stderr lines of the child. */
|
|
19
|
+
stderrTail;
|
|
20
|
+
constructor(message, details = {}) {
|
|
21
|
+
super(message, {
|
|
22
|
+
...details.cause !== void 0 ? { cause: details.cause } : {}
|
|
23
|
+
});
|
|
24
|
+
if (details.exitCode !== void 0) this.exitCode = details.exitCode;
|
|
25
|
+
if (details.exitSignal !== void 0) this.exitSignal = details.exitSignal;
|
|
26
|
+
if (details.stderrTail !== void 0) this.stderrTail = details.stderrTail;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
function isExecutableFile(path) {
|
|
30
|
+
try {
|
|
31
|
+
if (!statSync(path).isFile()) return false;
|
|
32
|
+
accessSync(path, constants.X_OK);
|
|
33
|
+
return true;
|
|
34
|
+
} catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function resolveCommand(command, env) {
|
|
39
|
+
if (command.length === 0) throw new AcpAgentSpawnError("ACP agent command is empty");
|
|
40
|
+
if (isAbsolute(command)) {
|
|
41
|
+
if (isExecutableFile(command)) return command;
|
|
42
|
+
throw new AcpAgentSpawnError(`ACP agent command not found or not executable: ${command}`);
|
|
43
|
+
}
|
|
44
|
+
if (command.includes("/") || command.includes("\\")) {
|
|
45
|
+
throw new AcpAgentSpawnError(
|
|
46
|
+
`ACP agent command "${command}" is a relative path; use an absolute path or a bare command name`
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
return resolveOnPath(command, env.PATH ?? "");
|
|
50
|
+
}
|
|
51
|
+
function resolveOnPath(command, pathValue) {
|
|
52
|
+
const entries = pathValue.split(delimiter);
|
|
53
|
+
if (entries.some((entry) => entry === "" || !isAbsolute(entry))) {
|
|
54
|
+
throw new AcpAgentSpawnError(
|
|
55
|
+
`refusing to resolve "${command}": PATH has a relative or empty entry`
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
const found = entries.map((entry) => join(entry, command)).find(isExecutableFile);
|
|
59
|
+
if (found === void 0) {
|
|
60
|
+
throw new AcpAgentSpawnError(`ACP agent command not found on PATH: ${command}`);
|
|
61
|
+
}
|
|
62
|
+
return found;
|
|
63
|
+
}
|
|
64
|
+
function trackStderr(child) {
|
|
65
|
+
const lines = [];
|
|
66
|
+
let partial = "";
|
|
67
|
+
const push = (line) => {
|
|
68
|
+
lines.push(line.slice(0, STDERR_MAX_LINE_CHARS));
|
|
69
|
+
if (lines.length > STDERR_MAX_LINES) lines.shift();
|
|
70
|
+
};
|
|
71
|
+
child.stderr?.setEncoding("utf8");
|
|
72
|
+
child.stderr?.on("data", (chunk) => {
|
|
73
|
+
const parts = (partial + chunk).split("\n");
|
|
74
|
+
partial = (parts.pop() ?? "").slice(-STDERR_MAX_LINE_CHARS);
|
|
75
|
+
for (const part of parts) push(part);
|
|
76
|
+
});
|
|
77
|
+
return () => (partial.length > 0 ? [...lines, partial] : lines).slice(-STDERR_MAX_LINES).join("\n");
|
|
78
|
+
}
|
|
79
|
+
function signalGroup(child, signal) {
|
|
80
|
+
try {
|
|
81
|
+
if (process.platform !== "win32" && child.pid !== void 0) process.kill(-child.pid, signal);
|
|
82
|
+
else child.kill(signal);
|
|
83
|
+
} catch {
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function spawnAgentChild(file, args, options) {
|
|
87
|
+
return new Promise((resolve, reject) => {
|
|
88
|
+
const child = spawn(file, [...args], {
|
|
89
|
+
cwd: options.cwd,
|
|
90
|
+
env: options.env,
|
|
91
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
92
|
+
detached: process.platform !== "win32"
|
|
93
|
+
});
|
|
94
|
+
const stderrTail = trackStderr(child);
|
|
95
|
+
let exitedFlag = false;
|
|
96
|
+
const exited = new Promise((done) => {
|
|
97
|
+
child.once("close", (code, signal) => {
|
|
98
|
+
exitedFlag = true;
|
|
99
|
+
done({ code, signal });
|
|
100
|
+
});
|
|
101
|
+
child.once("error", () => {
|
|
102
|
+
if (child.pid === void 0) {
|
|
103
|
+
exitedFlag = true;
|
|
104
|
+
done({ code: null, signal: null });
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
child.once("error", (err) => {
|
|
109
|
+
if (child.pid === void 0) {
|
|
110
|
+
reject(new AcpAgentSpawnError(`failed to spawn ${file}: ${err.message}`, { cause: err }));
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
child.once("spawn", () => {
|
|
114
|
+
child.stdin?.on("error", () => {
|
|
115
|
+
});
|
|
116
|
+
resolve({
|
|
117
|
+
process: child,
|
|
118
|
+
exited,
|
|
119
|
+
stderrTail,
|
|
120
|
+
hasExited: () => exitedFlag,
|
|
121
|
+
async kill() {
|
|
122
|
+
if (!exitedFlag) {
|
|
123
|
+
signalGroup(child, "SIGTERM");
|
|
124
|
+
const timer = setTimeout(() => signalGroup(child, "SIGKILL"), KILL_GRACE_MS);
|
|
125
|
+
await exited;
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
}
|
|
128
|
+
signalGroup(child, "SIGKILL");
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// src/client.ts
|
|
136
|
+
var DEFAULT_INITIALIZE_TIMEOUT_MS = 1e4;
|
|
137
|
+
var EXIT_SETTLE_MS = 1e3;
|
|
138
|
+
var UpdateQueue = class {
|
|
139
|
+
items = [];
|
|
140
|
+
waiter;
|
|
141
|
+
done = false;
|
|
142
|
+
failure;
|
|
143
|
+
push(item) {
|
|
144
|
+
this.items.push(item);
|
|
145
|
+
this.wake();
|
|
146
|
+
}
|
|
147
|
+
end(failure) {
|
|
148
|
+
if (this.done) return;
|
|
149
|
+
this.done = true;
|
|
150
|
+
this.failure = failure;
|
|
151
|
+
this.wake();
|
|
152
|
+
}
|
|
153
|
+
wake() {
|
|
154
|
+
const w = this.waiter;
|
|
155
|
+
this.waiter = void 0;
|
|
156
|
+
w?.();
|
|
157
|
+
}
|
|
158
|
+
async *drain() {
|
|
159
|
+
for (; ; ) {
|
|
160
|
+
const next = this.items.shift();
|
|
161
|
+
if (next !== void 0) {
|
|
162
|
+
yield next;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (this.done) {
|
|
166
|
+
if (this.failure !== void 0) throw this.failure;
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
await new Promise((resolve) => {
|
|
170
|
+
this.waiter = resolve;
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
var delay = (ms) => new Promise((resolve) => {
|
|
176
|
+
setTimeout(resolve, ms).unref();
|
|
177
|
+
});
|
|
178
|
+
async function exitError(child, phase, cause) {
|
|
179
|
+
const result = await Promise.race([child.exited, delay(EXIT_SETTLE_MS)]);
|
|
180
|
+
const tail = child.stderrTail();
|
|
181
|
+
const stderrPart = tail.length > 0 ? `; stderr:
|
|
182
|
+
${tail}` : "";
|
|
183
|
+
if (result === void 0) {
|
|
184
|
+
return new AcpAgentSpawnError(`ACP agent connection failed ${phase}${stderrPart}`, {
|
|
185
|
+
stderrTail: tail,
|
|
186
|
+
cause
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
const how = result.signal !== null ? `signal ${result.signal}` : `code ${result.code}`;
|
|
190
|
+
return new AcpAgentSpawnError(`ACP agent exited ${phase} (${how})${stderrPart}`, {
|
|
191
|
+
exitCode: result.code,
|
|
192
|
+
exitSignal: result.signal,
|
|
193
|
+
stderrTail: tail,
|
|
194
|
+
cause
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
var Connection = class {
|
|
198
|
+
constructor(child, conn, sessionId) {
|
|
199
|
+
this.child = child;
|
|
200
|
+
this.conn = conn;
|
|
201
|
+
this.sessionId = sessionId;
|
|
202
|
+
}
|
|
203
|
+
child;
|
|
204
|
+
conn;
|
|
205
|
+
sessionId;
|
|
206
|
+
active;
|
|
207
|
+
closing;
|
|
208
|
+
closed = false;
|
|
209
|
+
/** @internal */
|
|
210
|
+
dispatch(update) {
|
|
211
|
+
if (update.sessionId === this.sessionId) this.active?.push(update);
|
|
212
|
+
}
|
|
213
|
+
prompt(text, signal) {
|
|
214
|
+
return this.run(text, signal);
|
|
215
|
+
}
|
|
216
|
+
async *run(text, signal) {
|
|
217
|
+
if (this.closed) throw new AcpAgentSpawnError("ACP agent connection is closed");
|
|
218
|
+
if (this.active !== void 0)
|
|
219
|
+
throw new Error("a prompt is already in flight on this connection");
|
|
220
|
+
const queue = new UpdateQueue();
|
|
221
|
+
this.active = queue;
|
|
222
|
+
const onAbort = () => {
|
|
223
|
+
this.conn.cancel({ sessionId: this.sessionId }).catch(() => {
|
|
224
|
+
});
|
|
225
|
+
};
|
|
226
|
+
if (signal?.aborted) onAbort();
|
|
227
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
228
|
+
this.child.exited.then(async () => {
|
|
229
|
+
if (this.closed) return;
|
|
230
|
+
queue.end(await exitError(this.child, "during prompt"));
|
|
231
|
+
});
|
|
232
|
+
this.conn.prompt({ sessionId: this.sessionId, prompt: [{ type: "text", text }] }).then(
|
|
233
|
+
// Let notifications already read from the pipe reach the queue first.
|
|
234
|
+
() => new Promise((resolve) => setImmediate(resolve)).then(() => queue.end()),
|
|
235
|
+
async (err) => {
|
|
236
|
+
queue.end(this.closed ? void 0 : await exitError(this.child, "during prompt", err));
|
|
237
|
+
}
|
|
238
|
+
);
|
|
239
|
+
try {
|
|
240
|
+
yield* queue.drain();
|
|
241
|
+
} finally {
|
|
242
|
+
signal?.removeEventListener("abort", onAbort);
|
|
243
|
+
if (this.active === queue) this.active = void 0;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
close() {
|
|
247
|
+
this.closed = true;
|
|
248
|
+
this.closing ??= this.child.kill().then(() => this.active?.end());
|
|
249
|
+
return this.closing;
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
async function handshake(conn, cwd) {
|
|
253
|
+
await conn.initialize({ protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });
|
|
254
|
+
const session = await conn.newSession({ cwd, mcpServers: [] });
|
|
255
|
+
return session.sessionId;
|
|
256
|
+
}
|
|
257
|
+
async function initialize(child, conn, options) {
|
|
258
|
+
const timeoutMs = options.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS;
|
|
259
|
+
let timer;
|
|
260
|
+
const timeout = new Promise((_, reject) => {
|
|
261
|
+
timer = setTimeout(
|
|
262
|
+
() => reject(new AcpAgentSpawnError(`ACP agent did not initialize within ${timeoutMs}ms`)),
|
|
263
|
+
timeoutMs
|
|
264
|
+
);
|
|
265
|
+
});
|
|
266
|
+
const exit = child.exited.then(
|
|
267
|
+
() => exitError(child, "during initialize").then((e) => Promise.reject(e))
|
|
268
|
+
);
|
|
269
|
+
try {
|
|
270
|
+
return await Promise.race([handshake(conn, options.cwd), timeout, exit]);
|
|
271
|
+
} catch (err) {
|
|
272
|
+
if (err instanceof AcpAgentSpawnError) throw err;
|
|
273
|
+
throw await exitError(child, "during initialize", err);
|
|
274
|
+
} finally {
|
|
275
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
async function connectAcpAgent(options) {
|
|
279
|
+
const file = resolveCommand(options.command, options.env);
|
|
280
|
+
const child = await spawnAgentChild(file, options.args ?? [], {
|
|
281
|
+
cwd: options.cwd,
|
|
282
|
+
env: options.env
|
|
283
|
+
});
|
|
284
|
+
const stdin = child.process.stdin;
|
|
285
|
+
const stdout = child.process.stdout;
|
|
286
|
+
if (stdin === null || stdout === null) {
|
|
287
|
+
await child.kill();
|
|
288
|
+
throw new AcpAgentSpawnError("ACP agent child has no stdio pipes");
|
|
289
|
+
}
|
|
290
|
+
const stream = acp.ndJsonStream(
|
|
291
|
+
Writable.toWeb(stdin),
|
|
292
|
+
Readable.toWeb(stdout)
|
|
293
|
+
);
|
|
294
|
+
let connection;
|
|
295
|
+
const conn = new acp.ClientSideConnection(
|
|
296
|
+
() => ({
|
|
297
|
+
requestPermission: (request) => options.onPermission(request),
|
|
298
|
+
sessionUpdate: async (update) => {
|
|
299
|
+
connection?.dispatch(update);
|
|
300
|
+
}
|
|
301
|
+
}),
|
|
302
|
+
stream
|
|
303
|
+
);
|
|
304
|
+
try {
|
|
305
|
+
const sessionId = await initialize(child, conn, options);
|
|
306
|
+
connection = new Connection(child, conn, sessionId);
|
|
307
|
+
return connection;
|
|
308
|
+
} catch (err) {
|
|
309
|
+
await child.kill();
|
|
310
|
+
throw err;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export { AcpAgentSpawnError, connectAcpAgent };
|
|
315
|
+
//# sourceMappingURL=client.js.map
|
|
316
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client-spawn.ts","../src/client.ts"],"names":[],"mappings":";;;;;;;;AAYA,IAAM,gBAAA,GAAmB,EAAA;AAEzB,IAAM,qBAAA,GAAwB,GAAA;AAC9B,IAAM,aAAA,GAAgB,GAAA;AAQf,IAAM,kBAAA,GAAN,cAAiC,iBAAA,CAAkB;AAAA,EACtC,IAAA,GAAe,oBAAA;AAAA;AAAA,EAExB,QAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,UAAA;AAAA,EAET,WAAA,CACE,OAAA,EACA,OAAA,GAKI,EAAC,EACL;AACA,IAAA,KAAA,CAAM,OAAA,EAAS;AAAA,MACb,GAAI,QAAQ,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI;AAAC,KAC/D,CAAA;AACD,IAAA,IAAI,OAAA,CAAQ,QAAA,KAAa,MAAA,EAAW,IAAA,CAAK,WAAW,OAAA,CAAQ,QAAA;AAC5D,IAAA,IAAI,OAAA,CAAQ,UAAA,KAAe,MAAA,EAAW,IAAA,CAAK,aAAa,OAAA,CAAQ,UAAA;AAChE,IAAA,IAAI,OAAA,CAAQ,UAAA,KAAe,MAAA,EAAW,IAAA,CAAK,aAAa,OAAA,CAAQ,UAAA;AAAA,EAClE;AACF;AAEA,SAAS,iB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5B,EAAA,MAAM,MAAA,GAAS,MAAM,OAAA,CAAQ,MAAA;AAC7B,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,MAAA,KAAW,IAAA,EAAM;AACrC,IAAA,MAAM,MAAM,IAAA,EAAK;AACjB,IAAA,MAAM,IAAI,mBAAmB,oCAAoC,CAAA;AAAA,EACnE;AACA,EAAA,MAAM,MAAA,GAAa,GAAA,CAAA,YAAA;AAAA,IACjB,QAAA,CAAS,MAAM,KAAK,CAAA;AAAA,IACpB,QAAA,CAAS,MAAM,MAAM;AAAA,GACvB;AACA,EAAA,IAAI,UAAA;AACJ,EAAA,MAAM,OAAO,IAAQ,GAAA,CAAA,oBAAA;AAAA,IACnB,OAAO;AAAA,MACL,iBAAA,EAAmB,CAAC,OAAA,KAAY,OAAA,CAAQ,aAAa,OAAO,CAAA;AAAA,MAC5D,aAAA,EAAe,OAAO,MAAA,KAAW;AAC/B,QAAA,UAAA,EAAY,SAAS,MAAM,CAAA;AAAA,MAC7B;AAAA,KACF,CAAA;AAAA,IACA;AAAA,GACF;AACA,EAAA,IAAI;AACF,IAAA,MAAM,SAAA,GAAY,MAAM,UAAA,CAAW,KAAA,EAAO,MAAM,OAAO,CAAA;AACvD,IAAA,UAAA,GAAa,IAAI,UAAA,CAAW,KAAA,EAAO,IAAA,EAAM,SAAS,CAAA;AAClD,IAAA,OAAO,UAAA;AAAA,EACT,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,MAAM,IAAA,EAAK;AACjB,IAAA,MAAM,GAAA;AAAA,EACR;AACF","file":"client.js","sourcesContent":["/**\n * Command resolution and child-process handling for `connectAcpAgent`.\n *\n * @internal\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { accessSync, constants, statSync } from \"node:fs\";\nimport { delimiter, isAbsolute, join } from \"node:path\";\nimport { TheokitAgentError } from \"@theokit/sdk\";\n\n/** Number of trailing stderr lines kept for diagnostics. */\nconst STDERR_MAX_LINES = 20;\n/** Cap on one kept stderr line, in characters. */\nconst STDERR_MAX_LINE_CHARS = 500;\nconst KILL_GRACE_MS = 2_000;\n\n/**\n * A child agent could not be started, was refused before starting, or exited before it finished\n * what it was asked to do.\n *\n * @public\n */\nexport class AcpAgentSpawnError extends TheokitAgentError {\n override readonly name: string = \"AcpAgentSpawnError\";\n /** Exit code of the child, when it exited with one. */\n readonly exitCode?: number | null;\n /** Signal that ended the child, when it was killed by one. */\n readonly exitSignal?: string | null;\n /** The last (bounded) stderr lines of the child. */\n readonly stderrTail?: string;\n\n constructor(\n message: string,\n details: {\n exitCode?: number | null;\n exitSignal?: string | null;\n stderrTail?: string;\n cause?: unknown;\n } = {},\n ) {\n super(message, {\n ...(details.cause !== undefined ? { cause: details.cause } : {}),\n });\n if (details.exitCode !== undefined) this.exitCode = details.exitCode;\n if (details.exitSignal !== undefined) this.exitSignal = details.exitSignal;\n if (details.stderrTail !== undefined) this.stderrTail = details.stderrTail;\n }\n}\n\nfunction isExecutableFile(path: string): boolean {\n try {\n if (!statSync(path).isFile()) return false;\n accessSync(path, constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve `command` to an absolute executable path. Throws `AcpAgentSpawnError` before anything is\n * spawned when the command is a relative path, when `PATH` holds a relative or empty entry, or when\n * nothing executable is found. Only the `PATH` of the supplied `env` is read, never `process.env`.\n */\nexport function resolveCommand(command: string, env: Record<string, string>): string {\n if (command.length === 0) throw new AcpAgentSpawnError(\"ACP agent command is empty\");\n if (isAbsolute(command)) {\n if (isExecutableFile(command)) return command;\n throw new AcpAgentSpawnError(`ACP agent command not found or not executable: ${command}`);\n }\n if (command.includes(\"/\") || command.includes(\"\\\\\")) {\n throw new AcpAgentSpawnError(\n `ACP agent command \"${command}\" is a relative path; use an absolute path or a bare command name`,\n );\n }\n return resolveOnPath(command, env.PATH ?? \"\");\n}\n\nfunction resolveOnPath(command: string, pathValue: string): string {\n const entries = pathValue.split(delimiter);\n if (entries.some((entry) => entry === \"\" || !isAbsolute(entry))) {\n throw new AcpAgentSpawnError(\n `refusing to resolve \"${command}\": PATH has a relative or empty entry`,\n );\n }\n const found = entries.map((entry) => join(entry, command)).find(isExecutableFile);\n if (found === undefined) {\n throw new AcpAgentSpawnError(`ACP agent command not found on PATH: ${command}`);\n }\n return found;\n}\n\n/** A spawned child with bounded stderr capture and an exit promise. */\nexport interface AgentChild {\n readonly process: ChildProcess;\n /** Resolves once, when the child has exited. Never rejects. */\n readonly exited: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;\n /** The last stderr lines, joined by newlines. */\n stderrTail(): string;\n /** Terminate the child (its process group on POSIX) and wait for it to exit. */\n kill(): Promise<void>;\n hasExited(): boolean;\n}\n\nfunction trackStderr(child: ChildProcess): () => string {\n const lines: string[] = [];\n let partial = \"\";\n const push = (line: string): void => {\n lines.push(line.slice(0, STDERR_MAX_LINE_CHARS));\n if (lines.length > STDERR_MAX_LINES) lines.shift();\n };\n child.stderr?.setEncoding(\"utf8\");\n child.stderr?.on(\"data\", (chunk: string) => {\n const parts = (partial + chunk).split(\"\\n\");\n partial = (parts.pop() ?? \"\").slice(-STDERR_MAX_LINE_CHARS);\n for (const part of parts) push(part);\n });\n return () =>\n (partial.length > 0 ? [...lines, partial] : lines).slice(-STDERR_MAX_LINES).join(\"\\n\");\n}\n\nfunction signalGroup(child: ChildProcess, signal: NodeJS.Signals): void {\n try {\n if (process.platform !== \"win32\" && child.pid !== undefined) process.kill(-child.pid, signal);\n else child.kill(signal);\n } catch {\n // the group or process is already gone\n }\n}\n\n/** Spawn the resolved command. Rejects with `AcpAgentSpawnError` when the OS refuses to start it. */\nexport function spawnAgentChild(\n file: string,\n args: readonly string[],\n options: { cwd: string; env: Record<string, string> },\n): Promise<AgentChild> {\n return new Promise((resolve, reject) => {\n const child = spawn(file, [...args], {\n cwd: options.cwd,\n env: options.env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n const stderrTail = trackStderr(child);\n let exitedFlag = false;\n const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((done) => {\n child.once(\"close\", (code, signal) => {\n exitedFlag = true;\n done({ code, signal });\n });\n child.once(\"error\", () => {\n if (child.pid === undefined) {\n exitedFlag = true;\n done({ code: null, signal: null });\n }\n });\n });\n child.once(\"error\", (err) => {\n if (child.pid === undefined) {\n reject(new AcpAgentSpawnError(`failed to spawn ${file}: ${err.message}`, { cause: err }));\n }\n });\n child.once(\"spawn\", () => {\n child.stdin?.on(\"error\", () => {});\n resolve({\n process: child,\n exited,\n stderrTail,\n hasExited: () => exitedFlag,\n async kill() {\n if (!exitedFlag) {\n signalGroup(child, \"SIGTERM\");\n const timer = setTimeout(() => signalGroup(child, \"SIGKILL\"), KILL_GRACE_MS);\n await exited;\n clearTimeout(timer);\n }\n // Descendants may outlive the leader; sweep the group once more.\n signalGroup(child, \"SIGKILL\");\n },\n });\n });\n });\n}\n","/**\n * `@theokit/acp/client` — drive another ACP agent over stdio.\n *\n * ```ts\n * import { connectAcpAgent } from \"@theokit/acp/client\";\n *\n * const agent = await connectAcpAgent({\n * command: \"/usr/local/bin/my-agent\",\n * cwd: process.cwd(),\n * env: { PATH: \"/usr/bin\" },\n * onPermission: async (req) => ({ outcome: { outcome: \"cancelled\" } }),\n * });\n * for await (const update of agent.prompt(\"hello\")) console.log(update.update);\n * await agent.close();\n * ```\n *\n * @packageDocumentation\n */\n\nimport { Readable, Writable } from \"node:stream\";\nimport * as acp from \"@agentclientprotocol/sdk\";\nimport {\n AcpAgentSpawnError,\n type AgentChild,\n resolveCommand,\n spawnAgentChild,\n} from \"./client-spawn.js\";\n\nexport { AcpAgentSpawnError } from \"./client-spawn.js\";\n\nconst DEFAULT_INITIALIZE_TIMEOUT_MS = 10_000;\n/** How long to wait for the child's exit event after a broken pipe, to learn its exit code. */\nconst EXIT_SETTLE_MS = 1_000;\n\n/**\n * Options for {@link connectAcpAgent}.\n *\n * @public\n */\nexport interface ConnectAcpAgentOptions {\n /** Absolute path, or a bare name resolved on absolute `PATH` entries of `env` only. */\n command: string;\n args?: readonly string[];\n cwd: string;\n /** Passed to the child as is. Nothing is inherited from `process.env`. */\n env: Record<string, string>;\n /** Answers the agent's `session/request_permission`. */\n onPermission(request: acp.RequestPermissionRequest): Promise<acp.RequestPermissionResponse>;\n /** Budget for the `initialize` + `session/new` handshake. Default 10_000. */\n initializeTimeoutMs?: number;\n}\n\n/**\n * A live connection to a spawned ACP agent with one open session.\n *\n * @public\n */\nexport interface AcpAgentConnection {\n /**\n * Send one prompt and stream the session updates it produces. Only one prompt may be in flight.\n * Aborting `signal` sends `session/cancel`. A child exiting mid-prompt ends the iterator with\n * `AcpAgentSpawnError`.\n */\n prompt(text: string, signal?: AbortSignal): AsyncIterable<acp.SessionNotification>;\n /** Ends the session and kills the child (its process group on POSIX). Idempotent. */\n close(): Promise<void>;\n}\n\nclass UpdateQueue {\n private items: acp.SessionNotification[] = [];\n private waiter: (() => void) | undefined;\n private done = false;\n private failure: unknown;\n\n push(item: acp.SessionNotification): void {\n this.items.push(item);\n this.wake();\n }\n\n end(failure?: unknown): void {\n if (this.done) return;\n this.done = true;\n this.failure = failure;\n this.wake();\n }\n\n private wake(): void {\n const w = this.waiter;\n this.waiter = undefined;\n w?.();\n }\n\n async *drain(): AsyncGenerator<acp.SessionNotification> {\n for (;;) {\n const next = this.items.shift();\n if (next !== undefined) {\n yield next;\n continue;\n }\n if (this.done) {\n if (this.failure !== undefined) throw this.failure;\n return;\n }\n await new Promise<void>((resolve) => {\n this.waiter = resolve;\n });\n }\n }\n}\n\nconst delay = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, ms).unref();\n });\n\nasync function exitError(child: AgentChild, phase: string, cause?: unknown): Promise<Error> {\n const result = await Promise.race([child.exited, delay(EXIT_SETTLE_MS)]);\n const tail = child.stderrTail();\n const stderrPart = tail.length > 0 ? `; stderr:\\n${tail}` : \"\";\n if (result === undefined) {\n return new AcpAgentSpawnError(`ACP agent connection failed ${phase}${stderrPart}`, {\n stderrTail: tail,\n cause,\n });\n }\n const how = result.signal !== null ? `signal ${result.signal}` : `code ${result.code}`;\n return new AcpAgentSpawnError(`ACP agent exited ${phase} (${how})${stderrPart}`, {\n exitCode: result.code,\n exitSignal: result.signal,\n stderrTail: tail,\n cause,\n });\n}\n\nclass Connection implements AcpAgentConnection {\n private active: UpdateQueue | undefined;\n private closing: Promise<void> | undefined;\n private closed = false;\n\n constructor(\n private readonly child: AgentChild,\n private readonly conn: acp.ClientSideConnection,\n private readonly sessionId: string,\n ) {}\n\n /** @internal */\n dispatch(update: acp.SessionNotification): void {\n if (update.sessionId === this.sessionId) this.active?.push(update);\n }\n\n prompt(text: string, signal?: AbortSignal): AsyncIterable<acp.SessionNotification> {\n return this.run(text, signal);\n }\n\n private async *run(text: string, signal?: AbortSignal): AsyncGenerator<acp.SessionNotification> {\n if (this.closed) throw new AcpAgentSpawnError(\"ACP agent connection is closed\");\n if (this.active !== undefined)\n throw new Error(\"a prompt is already in flight on this connection\");\n const queue = new UpdateQueue();\n this.active = queue;\n const onAbort = (): void => {\n this.conn.cancel({ sessionId: this.sessionId }).catch(() => {});\n };\n if (signal?.aborted) onAbort();\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const exitWatch = this.child.exited.then(async () => {\n if (this.closed) return;\n queue.end(await exitError(this.child, \"during prompt\"));\n });\n void exitWatch;\n this.conn.prompt({ sessionId: this.sessionId, prompt: [{ type: \"text\", text }] }).then(\n // Let notifications already read from the pipe reach the queue first.\n () => new Promise<void>((resolve) => setImmediate(resolve)).then(() => queue.end()),\n async (err: unknown) => {\n queue.end(this.closed ? undefined : await exitError(this.child, \"during prompt\", err));\n },\n );\n try {\n yield* queue.drain();\n } finally {\n signal?.removeEventListener(\"abort\", onAbort);\n if (this.active === queue) this.active = undefined;\n }\n }\n\n close(): Promise<void> {\n this.closed = true;\n this.closing ??= this.child.kill().then(() => this.active?.end());\n return this.closing;\n }\n}\n\nasync function handshake(conn: acp.ClientSideConnection, cwd: string): Promise<string> {\n await conn.initialize({ protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });\n const session = await conn.newSession({ cwd, mcpServers: [] });\n return session.sessionId;\n}\n\nasync function initialize(\n child: AgentChild,\n conn: acp.ClientSideConnection,\n options: ConnectAcpAgentOptions,\n): Promise<string> {\n const timeoutMs = options.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS;\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new AcpAgentSpawnError(`ACP agent did not initialize within ${timeoutMs}ms`)),\n timeoutMs,\n );\n });\n const exit = child.exited.then(() =>\n exitError(child, \"during initialize\").then((e) => Promise.reject(e)),\n );\n try {\n return await Promise.race([handshake(conn, options.cwd), timeout, exit]);\n } catch (err) {\n if (err instanceof AcpAgentSpawnError) throw err;\n throw await exitError(child, \"during initialize\", err);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\n/**\n * Spawn an ACP agent as a child process, complete the handshake and open one session.\n *\n * @throws AcpAgentSpawnError when the command is refused, cannot be started, or exits or stalls\n * during initialize.\n * @public\n */\nexport async function connectAcpAgent(\n options: ConnectAcpAgentOptions,\n): Promise<AcpAgentConnection> {\n const file = resolveCommand(options.command, options.env);\n const child = await spawnAgentChild(file, options.args ?? [], {\n cwd: options.cwd,\n env: options.env,\n });\n const stdin = child.process.stdin;\n const stdout = child.process.stdout;\n if (stdin === null || stdout === null) {\n await child.kill();\n throw new AcpAgentSpawnError(\"ACP agent child has no stdio pipes\");\n }\n const stream = acp.ndJsonStream(\n Writable.toWeb(stdin) as WritableStream<Uint8Array>,\n Readable.toWeb(stdout) as ReadableStream<Uint8Array>,\n );\n let connection: Connection | undefined;\n const conn = new acp.ClientSideConnection(\n () => ({\n requestPermission: (request) => options.onPermission(request),\n sessionUpdate: async (update) => {\n connection?.dispatch(update);\n },\n }),\n stream,\n );\n try {\n const sessionId = await initialize(child, conn, options);\n connection = new Connection(child, conn, sessionId);\n return connection;\n } catch (err) {\n await child.kill();\n throw err;\n }\n}\n"]}
|