@acryldev/driver-acp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,440 @@
1
+ import { existsSync } from "node:fs";
2
+ import { isAbsolute } from "node:path";
3
+ import { onPath } from "@acryldev/agent-panel/headless";
4
+ import { spawn, spawnSync } from "node:child_process";
5
+ //#region connection.ts
6
+ /**
7
+ * One ACP agent process and the JSON-RPC 2.0 connection to it: newline-delimited messages over its stdin and stdout (the ACP stdio transport). The driver needs a handful of
8
+ * calls, so this is the whole client: requests with their answers, notifications both ways, and the agent's own requests answered by a handler. `close()` ends the process
9
+ * the way an ACP agent expects: stdin closed first, then SIGTERM, then a hard kill, and it resolves only once the process is gone.
10
+ */
11
+ /** An error the agent answered with, or the reason the connection ended. */
12
+ var AcpError = class extends Error {
13
+ /** The JSON-RPC error code, for an error the agent answered with. */
14
+ code;
15
+ constructor(message, code) {
16
+ super(message);
17
+ this.name = "AcpError";
18
+ this.code = code;
19
+ }
20
+ };
21
+ /** How long each step of `close()` waits before the next, harder one. */
22
+ const GRACE_MS = 2e3;
23
+ var AcpConnection = class {
24
+ #child;
25
+ #pending = /* @__PURE__ */ new Map();
26
+ #listeners = /* @__PURE__ */ new Set();
27
+ #nextId = 1;
28
+ #buffer = "";
29
+ #stderr = "";
30
+ #ended;
31
+ /** Resolves with the reason once the process is gone. */
32
+ ended;
33
+ constructor(agent, cwd, handle) {
34
+ this.#child = spawn(agent.command, [...agent.args], {
35
+ cwd,
36
+ env: {
37
+ ...process.env,
38
+ ...agent.env
39
+ },
40
+ stdio: [
41
+ "pipe",
42
+ "pipe",
43
+ "pipe"
44
+ ],
45
+ shell: process.platform === "win32",
46
+ detached: process.platform !== "win32",
47
+ windowsHide: true
48
+ });
49
+ this.ended = new Promise((resolve) => {
50
+ const end = (reason) => {
51
+ if (this.#ended) return;
52
+ this.#ended = reason;
53
+ for (const pending of this.#pending.values()) pending.reject(reason);
54
+ this.#pending.clear();
55
+ resolve(reason);
56
+ };
57
+ this.#child.on("error", (error) => end(new AcpError(`${agent.command} could not be started: ${error.message}`)));
58
+ this.#child.on("exit", (code, signal) => {
59
+ const tail = this.#stderr.trim().split("\n").slice(-3).join(" ").slice(-500);
60
+ end(new AcpError(`${agent.command} ended (${signal ?? `exit code ${String(code)}`})${tail ? `: ${tail}` : ""}`));
61
+ });
62
+ });
63
+ this.#child.stderr.setEncoding("utf8");
64
+ this.#child.stderr.on("data", (chunk) => {
65
+ this.#stderr = (this.#stderr + chunk).slice(-4e3);
66
+ });
67
+ this.#child.stdout.setEncoding("utf8");
68
+ this.#child.stdout.on("data", (chunk) => {
69
+ this.#buffer += chunk;
70
+ for (let end = this.#buffer.indexOf("\n"); end !== -1; end = this.#buffer.indexOf("\n")) {
71
+ const line = this.#buffer.slice(0, end).trim();
72
+ this.#buffer = this.#buffer.slice(end + 1);
73
+ if (line) this.#receive(line, handle);
74
+ }
75
+ });
76
+ this.#child.stdin.on("error", () => {});
77
+ }
78
+ /** Sends a request and resolves with its result; rejects with the agent's error, or when the process ends first. */
79
+ request(method, params) {
80
+ if (this.#ended) return Promise.reject(this.#ended);
81
+ const id = this.#nextId++;
82
+ return new Promise((resolve, reject) => {
83
+ this.#pending.set(id, {
84
+ resolve,
85
+ reject
86
+ });
87
+ this.#send({
88
+ jsonrpc: "2.0",
89
+ id,
90
+ method,
91
+ params
92
+ });
93
+ });
94
+ }
95
+ notify(method, params) {
96
+ if (!this.#ended) this.#send({
97
+ jsonrpc: "2.0",
98
+ method,
99
+ params
100
+ });
101
+ }
102
+ /** Hears every notification the agent sends; returns the function that stops listening. */
103
+ onNotification(listener) {
104
+ this.#listeners.add(listener);
105
+ return () => void this.#listeners.delete(listener);
106
+ }
107
+ /**
108
+ * Ends the process and what it started: stdin closed, then SIGTERM, then a hard kill, each to the whole process group on POSIX (the tree, with `taskkill /T`, on Windows).
109
+ * Resolves once they are gone. Safe to call again, and after the agent ended on its own (its leftovers are still cleared).
110
+ */
111
+ async close() {
112
+ if (!this.#ended) {
113
+ const gone = (ms) => Promise.race([this.ended.then(() => true), new Promise((done) => setTimeout(() => done(false), ms).unref())]);
114
+ this.#child.stdin.end();
115
+ if (!await gone(GRACE_MS)) {
116
+ this.#signal("SIGTERM");
117
+ if (!await gone(GRACE_MS)) this.#signal("SIGKILL");
118
+ await this.ended;
119
+ }
120
+ }
121
+ await this.#reapGroup();
122
+ }
123
+ /** A signal to the agent and, on POSIX, everything in its group. */
124
+ #signal(signal) {
125
+ const pid = this.#child.pid;
126
+ if (pid === void 0) return;
127
+ if (process.platform === "win32") {
128
+ if (signal === "SIGKILL") spawnSync("taskkill", [
129
+ "/pid",
130
+ String(pid),
131
+ "/T",
132
+ "/F"
133
+ ], { windowsHide: true });
134
+ else this.#child.kill(signal);
135
+ return;
136
+ }
137
+ try {
138
+ process.kill(-pid, signal);
139
+ } catch {
140
+ this.#child.kill(signal);
141
+ }
142
+ }
143
+ /** On POSIX, processes the agent left in its group are ended too: SIGTERM, then SIGKILL after the grace. */
144
+ async #reapGroup() {
145
+ const pid = this.#child.pid;
146
+ if (process.platform === "win32" || pid === void 0) return;
147
+ const groupAlive = () => {
148
+ try {
149
+ process.kill(-pid, 0);
150
+ return true;
151
+ } catch (error) {
152
+ return error.code === "EPERM";
153
+ }
154
+ };
155
+ for (const signal of ["SIGTERM", "SIGKILL"]) {
156
+ if (!groupAlive()) return;
157
+ try {
158
+ process.kill(-pid, signal);
159
+ } catch {
160
+ return;
161
+ }
162
+ for (let waited = 0; waited < GRACE_MS && groupAlive(); waited += 25) await new Promise((done) => setTimeout(done, 25));
163
+ }
164
+ }
165
+ #send(message) {
166
+ this.#child.stdin.write(`${JSON.stringify(message)}\n`);
167
+ }
168
+ #receive(line, handle) {
169
+ let message;
170
+ try {
171
+ message = JSON.parse(line);
172
+ } catch {
173
+ return;
174
+ }
175
+ if (typeof message.method === "string") {
176
+ if (message.id === void 0) {
177
+ for (const listener of this.#listeners) listener(message.method, message.params);
178
+ return;
179
+ }
180
+ const id = message.id;
181
+ Promise.resolve().then(() => handle(message.method, message.params)).then((result) => this.#answer(id, result), (error) => this.#send({
182
+ jsonrpc: "2.0",
183
+ id,
184
+ error: error instanceof AcpError && error.code !== void 0 ? {
185
+ code: error.code,
186
+ message: error.message
187
+ } : {
188
+ code: -32603,
189
+ message: error instanceof Error ? error.message : String(error)
190
+ }
191
+ }));
192
+ return;
193
+ }
194
+ const pending = typeof message.id === "number" ? this.#pending.get(message.id) : void 0;
195
+ if (!pending) return;
196
+ this.#pending.delete(message.id);
197
+ if (message.error) pending.reject(new AcpError(message.error.message ?? "the agent answered with an error", message.error.code));
198
+ else pending.resolve(message.result);
199
+ }
200
+ #answer(id, result) {
201
+ if (!this.#ended) this.#send({
202
+ jsonrpc: "2.0",
203
+ id,
204
+ result: result ?? null
205
+ });
206
+ }
207
+ };
208
+ //#endregion
209
+ //#region chat.ts
210
+ /** The ACP version this client speaks. */
211
+ const PROTOCOL_VERSION = 1;
212
+ /** Why a turn stopped short, in the panel's words; `undefined` for a turn that ended normally or was cancelled. */
213
+ function stopMessage(name, stopReason) {
214
+ switch (stopReason) {
215
+ case "end_turn":
216
+ case "cancelled": return;
217
+ case "refusal": return `${name} refused to continue`;
218
+ case "max_tokens": return `${name} stopped at its token limit`;
219
+ case "max_turn_requests": return `${name} stopped at its limit of model requests for one message`;
220
+ default: return `${name} stopped (${String(stopReason)})`;
221
+ }
222
+ }
223
+ /** The text an ACP tool call produced, when it reports text content and no raw output. */
224
+ function toolText(update) {
225
+ return (update.content ?? []).map((item) => item.type === "content" && item.content?.type === "text" ? item.content.text : void 0).filter((part) => typeof part === "string").join("\n") || void 0;
226
+ }
227
+ /** The answer to `session/request_permission`: the agent's option of the wanted kind, or `cancelled` when it offers none or the turn was cancelled. */
228
+ function permissionAnswer(params, permissions, cancelled) {
229
+ const options = params.options ?? [];
230
+ const option = cancelled ? void 0 : (permissions === "allow" ? ["allow_once", "allow_always"] : ["reject_once", "reject_always"]).map((kind) => options.find((o) => o.kind === kind)).find(Boolean);
231
+ return { outcome: option ? {
232
+ outcome: "selected",
233
+ optionId: option.optionId
234
+ } : { outcome: "cancelled" } };
235
+ }
236
+ function acpDriver(options) {
237
+ const { name, agent, cwd, permissions, open } = options;
238
+ let session;
239
+ /** The connection `session` belongs to, so only its own end clears it. */
240
+ let live;
241
+ let turnCancelled = false;
242
+ let queue = Promise.resolve();
243
+ const startSession = async () => {
244
+ const { connection, close } = open(agent, (method, params) => {
245
+ if (method === "session/request_permission") return permissionAnswer(params, permissions, turnCancelled);
246
+ throw new AcpError(`${method} is not offered by this client`, -32601);
247
+ });
248
+ live = connection;
249
+ connection.ended.then(() => {
250
+ if (live !== connection) return;
251
+ live = void 0;
252
+ session = void 0;
253
+ });
254
+ try {
255
+ await connection.request("initialize", {
256
+ protocolVersion: PROTOCOL_VERSION,
257
+ clientCapabilities: {
258
+ fs: {
259
+ readTextFile: false,
260
+ writeTextFile: false
261
+ },
262
+ terminal: false
263
+ },
264
+ clientInfo: {
265
+ name: "acrylblends-driver-acp",
266
+ version: "1"
267
+ }
268
+ });
269
+ return {
270
+ connection,
271
+ id: (await connection.request("session/new", {
272
+ cwd,
273
+ mcpServers: []
274
+ })).sessionId
275
+ };
276
+ } catch (error) {
277
+ await close();
278
+ throw error;
279
+ }
280
+ };
281
+ return {
282
+ kind: "chat",
283
+ name,
284
+ async *start({ message, signal }) {
285
+ const previous = queue;
286
+ let finished;
287
+ queue = new Promise((resolve) => finished = resolve);
288
+ try {
289
+ await previous;
290
+ if (signal.aborted) return;
291
+ let current;
292
+ try {
293
+ session ??= startSession();
294
+ current = await session;
295
+ } catch (error) {
296
+ session = void 0;
297
+ yield {
298
+ event: "error",
299
+ data: { message: error instanceof Error ? error.message : String(error) }
300
+ };
301
+ return;
302
+ }
303
+ yield* turn(current, message, signal);
304
+ } finally {
305
+ finished();
306
+ }
307
+ }
308
+ };
309
+ async function* turn(current, message, signal) {
310
+ const events = [];
311
+ let wake;
312
+ let settled = false;
313
+ const push = (event) => {
314
+ events.push(event);
315
+ wake?.();
316
+ };
317
+ /** What earlier updates said about each tool call: its title and its input arrive before its result. */
318
+ const calls = /* @__PURE__ */ new Map();
319
+ const off = current.connection.onNotification((method, params) => {
320
+ const { sessionId, update } = params;
321
+ if (method !== "session/update" || sessionId !== current.id || !update) return;
322
+ if (update.sessionUpdate === "agent_message_chunk") {
323
+ const content = update.content;
324
+ if (content?.type === "text" && content.text) push({
325
+ event: "text",
326
+ data: { text: content.text }
327
+ });
328
+ return;
329
+ }
330
+ if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") return;
331
+ const call = calls.get(update.toolCallId) ?? {};
332
+ if (update.title) call.title = update.title;
333
+ if (update.rawInput !== void 0) call.input = update.rawInput;
334
+ calls.set(update.toolCallId, call);
335
+ if (update.status !== "completed" && update.status !== "failed") return;
336
+ const tool = call.title ?? update.toolCallId;
337
+ const output = update.rawOutput ?? toolText(update);
338
+ push({
339
+ event: "tool",
340
+ data: {
341
+ tool,
342
+ ...call.input === void 0 ? {} : { input: call.input },
343
+ ...update.status === "failed" ? { error: output === void 0 ? "failed" : String(typeof output === "string" ? output : JSON.stringify(output)) } : { result: output }
344
+ }
345
+ });
346
+ });
347
+ turnCancelled = false;
348
+ const cancel = () => {
349
+ turnCancelled = true;
350
+ current.connection.notify("session/cancel", { sessionId: current.id });
351
+ };
352
+ signal.addEventListener("abort", cancel, { once: true });
353
+ current.connection.request("session/prompt", {
354
+ sessionId: current.id,
355
+ prompt: [{
356
+ type: "text",
357
+ text: message
358
+ }]
359
+ }).then((result) => {
360
+ const stopped = signal.aborted ? void 0 : stopMessage(name, result.stopReason);
361
+ if (stopped) push({
362
+ event: "error",
363
+ data: { message: stopped }
364
+ });
365
+ }, (error) => {
366
+ if (!signal.aborted) push({
367
+ event: "error",
368
+ data: { message: error instanceof Error ? error.message : String(error) }
369
+ });
370
+ }).finally(() => {
371
+ settled = true;
372
+ wake?.();
373
+ });
374
+ try {
375
+ for (;;) {
376
+ const next = events.shift();
377
+ if (next) yield next;
378
+ else if (settled) return;
379
+ else await new Promise((resolve) => wake = resolve);
380
+ }
381
+ } finally {
382
+ off();
383
+ signal.removeEventListener("abort", cancel);
384
+ if (!settled) cancel();
385
+ }
386
+ }
387
+ }
388
+ //#endregion
389
+ //#region index.ts
390
+ /**
391
+ * The ACP driver (M8, spec 046 T028): any agent that speaks the Agent Client Protocol (ACP v1 over stdio) as a chat driver of the agent panel, started in the app folder.
392
+ * No agent gets code of its own here: an agent is a preset, a command line that starts its ACP server. `dsh` (DeepSeek Harness, `dsh --profile acp`) is the first preset;
393
+ * other ACP agents are added by config.
394
+ *
395
+ * - The drivers are `chat` entries of the panel's `drivers` service (`acp:dsh`, ...). A panel without this plugin lists none; this plugin without a panel is pending.
396
+ * - An agent whose command is not on the machine gets no driver, and the plugin says so in one line (as `driver-pty` does without node-pty).
397
+ * - Every agent process is acquired inside one `ctx.effect`; its disposer ends the process. Unloading or reloading the plugin leaves no agent running.
398
+ * - Development only, like the panel: with `NODE_ENV=production` (or `ACRYL_DOOR=off`) it starts nothing.
399
+ */
400
+ const name = "driver-acp";
401
+ const inject = ["drivers", "appInstance"];
402
+ /** The ACP agents this plugin knows by name: the command line that starts each one's ACP server. */
403
+ const PRESETS = { dsh: {
404
+ command: "dsh",
405
+ args: ["--profile", "acp"]
406
+ } };
407
+ function apply(ctx, config = {}) {
408
+ if (process.env.NODE_ENV === "production" || process.env.ACRYL_DOOR === "off") return;
409
+ const root = ctx.appInstance.root;
410
+ const open = (agent, handle) => {
411
+ let connection;
412
+ const close = ctx.effect(() => {
413
+ connection = new AcpConnection(agent, root, handle);
414
+ return () => connection.close();
415
+ });
416
+ connection.ended.then(() => close());
417
+ return {
418
+ connection,
419
+ close
420
+ };
421
+ };
422
+ for (const [agentName, agent] of Object.entries(config.agents ?? PRESETS)) {
423
+ if (!(isAbsolute(agent.command) ? existsSync(agent.command) : onPath(agent.command))) {
424
+ console.warn(`driver-acp: no acp:${agentName} driver, "${agent.command}" is not on the PATH`);
425
+ continue;
426
+ }
427
+ const driver = acpDriver({
428
+ name: `acp:${agentName}`,
429
+ agent,
430
+ cwd: root,
431
+ permissions: config.permissions ?? "reject",
432
+ open
433
+ });
434
+ ctx.effect(() => ctx.drivers.register(driver));
435
+ }
436
+ }
437
+ //#endregion
438
+ export { AcpConnection, AcpError, PRESETS, acpDriver, apply, inject, name };
439
+
440
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["#child","#pending","#listeners","#ended","#stderr","#buffer","#receive","#nextId","#send","#signal","#reapGroup","#answer"],"sources":["../connection.ts","../chat.ts","../index.ts"],"sourcesContent":["/**\n * One ACP agent process and the JSON-RPC 2.0 connection to it: newline-delimited messages over its stdin and stdout (the ACP stdio transport). The driver needs a handful of\n * calls, so this is the whole client: requests with their answers, notifications both ways, and the agent's own requests answered by a handler. `close()` ends the process\n * the way an ACP agent expects: stdin closed first, then SIGTERM, then a hard kill, and it resolves only once the process is gone.\n */\nimport { type ChildProcessWithoutNullStreams, spawn, spawnSync } from 'node:child_process'\n\n/** How to start an ACP agent: a program and its arguments, and what to add to the app's environment. */\nexport interface AcpAgent {\n readonly command: string\n readonly args: readonly string[]\n readonly env?: Readonly<Record<string, string>>\n}\n\n/** An error the agent answered with, or the reason the connection ended. */\nexport class AcpError extends Error {\n /** The JSON-RPC error code, for an error the agent answered with. */\n readonly code: number | undefined\n\n constructor(message: string, code?: number) {\n super(message)\n this.name = 'AcpError'\n this.code = code\n }\n}\n\n/** Answers a request the agent sends (`session/request_permission`); throwing answers with an error. */\nexport type AgentRequestHandler = (method: string, params: unknown) => unknown\n\n/** How long each step of `close()` waits before the next, harder one. */\nconst GRACE_MS = 2000\n/** The most of the agent's stderr kept, to say why it ended. */\nconst STDERR_TAIL = 4000\n\ninterface Pending {\n resolve(value: unknown): void\n reject(error: Error): void\n}\n\nexport class AcpConnection {\n readonly #child: ChildProcessWithoutNullStreams\n readonly #pending = new Map<number, Pending>()\n readonly #listeners = new Set<(method: string, params: unknown) => void>()\n #nextId = 1\n #buffer = ''\n #stderr = ''\n #ended: AcpError | undefined\n /** Resolves with the reason once the process is gone. */\n readonly ended: Promise<AcpError>\n\n constructor(agent: AcpAgent, cwd: string, handle: AgentRequestHandler) {\n this.#child = spawn(agent.command, [...agent.args], {\n cwd,\n env: { ...process.env, ...agent.env },\n stdio: ['pipe', 'pipe', 'pipe'],\n // An npm-installed agent is a `.cmd` shim on Windows, which only a shell can start.\n shell: process.platform === 'win32',\n // Its own process group on POSIX, so closing the connection also ends what the agent started (its tools, a shell): nothing is left behind when the plugin unloads.\n detached: process.platform !== 'win32',\n windowsHide: true,\n })\n this.ended = new Promise((resolve) => {\n const end = (reason: AcpError): void => {\n if (this.#ended) return\n this.#ended = reason\n for (const pending of this.#pending.values()) pending.reject(reason)\n this.#pending.clear()\n resolve(reason)\n }\n this.#child.on('error', (error) =>\n end(new AcpError(`${agent.command} could not be started: ${error.message}`)),\n )\n this.#child.on('exit', (code, signal) => {\n const tail = this.#stderr.trim().split('\\n').slice(-3).join(' ').slice(-500)\n end(\n new AcpError(\n `${agent.command} ended (${signal ?? `exit code ${String(code)}`})${tail ? `: ${tail}` : ''}`,\n ),\n )\n })\n })\n this.#child.stderr.setEncoding('utf8')\n this.#child.stderr.on('data', (chunk: string) => {\n this.#stderr = (this.#stderr + chunk).slice(-STDERR_TAIL)\n })\n this.#child.stdout.setEncoding('utf8')\n this.#child.stdout.on('data', (chunk: string) => {\n this.#buffer += chunk\n for (let end = this.#buffer.indexOf('\\n'); end !== -1; end = this.#buffer.indexOf('\\n')) {\n const line = this.#buffer.slice(0, end).trim()\n this.#buffer = this.#buffer.slice(end + 1)\n if (line) this.#receive(line, handle)\n }\n })\n // A write after the agent went away fails here instead of throwing out of the process.\n this.#child.stdin.on('error', () => {})\n }\n\n /** Sends a request and resolves with its result; rejects with the agent's error, or when the process ends first. */\n request<T>(method: string, params: unknown): Promise<T> {\n if (this.#ended) return Promise.reject(this.#ended)\n const id = this.#nextId++\n return new Promise<T>((resolve, reject) => {\n this.#pending.set(id, { resolve: resolve as (value: unknown) => void, reject })\n this.#send({ jsonrpc: '2.0', id, method, params })\n })\n }\n\n notify(method: string, params: unknown): void {\n if (!this.#ended) this.#send({ jsonrpc: '2.0', method, params })\n }\n\n /** Hears every notification the agent sends; returns the function that stops listening. */\n onNotification(listener: (method: string, params: unknown) => void): () => void {\n this.#listeners.add(listener)\n return () => void this.#listeners.delete(listener)\n }\n\n /**\n * Ends the process and what it started: stdin closed, then SIGTERM, then a hard kill, each to the whole process group on POSIX (the tree, with `taskkill /T`, on Windows).\n * Resolves once they are gone. Safe to call again, and after the agent ended on its own (its leftovers are still cleared).\n */\n async close(): Promise<void> {\n if (!this.#ended) {\n const gone = (ms: number) =>\n Promise.race([\n this.ended.then(() => true),\n new Promise<boolean>((done) => setTimeout(() => done(false), ms).unref()),\n ])\n this.#child.stdin.end()\n if (!(await gone(GRACE_MS))) {\n this.#signal('SIGTERM')\n if (!(await gone(GRACE_MS))) this.#signal('SIGKILL')\n await this.ended\n }\n }\n await this.#reapGroup()\n }\n\n /** A signal to the agent and, on POSIX, everything in its group. */\n #signal(signal: 'SIGTERM' | 'SIGKILL'): void {\n const pid = this.#child.pid\n if (pid === undefined) return\n if (process.platform === 'win32') {\n if (signal === 'SIGKILL')\n spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true })\n else this.#child.kill(signal)\n return\n }\n try {\n process.kill(-pid, signal)\n } catch {\n this.#child.kill(signal)\n }\n }\n\n /** On POSIX, processes the agent left in its group are ended too: SIGTERM, then SIGKILL after the grace. */\n async #reapGroup(): Promise<void> {\n const pid = this.#child.pid\n if (process.platform === 'win32' || pid === undefined) return\n const groupAlive = (): boolean => {\n try {\n process.kill(-pid, 0)\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n }\n for (const signal of ['SIGTERM', 'SIGKILL'] as const) {\n if (!groupAlive()) return\n try {\n process.kill(-pid, signal)\n } catch {\n return\n }\n for (let waited = 0; waited < GRACE_MS && groupAlive(); waited += 25)\n await new Promise((done) => setTimeout(done, 25))\n }\n }\n\n #send(message: unknown): void {\n this.#child.stdin.write(`${JSON.stringify(message)}\\n`)\n }\n\n #receive(line: string, handle: AgentRequestHandler): void {\n let message: {\n id?: number | string\n method?: string\n params?: unknown\n result?: unknown\n error?: { code?: number; message?: string }\n }\n try {\n message = JSON.parse(line)\n } catch {\n return // Not a protocol frame: an agent may print a stray line; it carries nothing to act on.\n }\n if (typeof message.method === 'string') {\n if (message.id === undefined) {\n for (const listener of this.#listeners) listener(message.method, message.params)\n return\n }\n const id = message.id\n Promise.resolve()\n .then(() => handle(message.method as string, message.params))\n .then(\n (result) => this.#answer(id, result),\n (error: unknown) =>\n this.#send({\n jsonrpc: '2.0',\n id,\n error:\n error instanceof AcpError && error.code !== undefined\n ? { code: error.code, message: error.message }\n : {\n code: -32603,\n message: error instanceof Error ? error.message : String(error),\n },\n }),\n )\n return\n }\n const pending = typeof message.id === 'number' ? this.#pending.get(message.id) : undefined\n if (!pending) return\n this.#pending.delete(message.id as number)\n if (message.error)\n pending.reject(\n new AcpError(\n message.error.message ?? 'the agent answered with an error',\n message.error.code,\n ),\n )\n else pending.resolve(message.result)\n }\n\n #answer(id: number | string, result: unknown): void {\n if (!this.#ended) this.#send({ jsonrpc: '2.0', id, result: result ?? null })\n }\n}\n","/**\n * An ACP agent as a chat driver of the panel. The agent process starts at the first message and keeps one ACP session, so later messages continue the same conversation;\n * an agent that ended is started again, with a new session, at the next message. One message runs at a time; a second one waits for the first.\n *\n * What the panel gets from the ACP updates: the agent's message chunks as `text`, each finished tool call as one `tool` (its title, input, and result or error), and an\n * `error` for a turn that stopped short (a refusal, a token or request limit, an agent that ended). Thoughts, plans and the rest stay out of the chat.\n */\nimport type { ChatDriver, ChatEvent } from '@acryldev/drivers'\nimport { type AcpAgent, type AcpConnection, AcpError } from './connection.ts'\n\n/** Which answer a permission request gets: the agent's own \"allow once\" or \"reject once\" option. */\nexport type AcpPermissions = 'allow' | 'reject'\n\n/** The ACP version this client speaks. */\nconst PROTOCOL_VERSION = 1\n\n/** An agent connection with its session. */\ninterface Session {\n readonly connection: AcpConnection\n readonly id: string\n}\n\n/**\n * Opens a connection to the agent and returns it with the function that closes it. The plugin acquires it inside one `ctx.effect`, so unloading the plugin ends the process.\n */\nexport type OpenAgent = (\n agent: AcpAgent,\n handle: (method: string, params: unknown) => unknown,\n) => {\n connection: AcpConnection\n close(): Promise<void>\n}\n\ninterface ToolUpdate {\n toolCallId: string\n title?: string | null\n status?: string | null\n rawInput?: unknown\n rawOutput?: unknown\n content?: Array<{ type?: string; content?: { type?: string; text?: string } }> | null\n}\n\n/** Why a turn stopped short, in the panel's words; `undefined` for a turn that ended normally or was cancelled. */\nfunction stopMessage(name: string, stopReason: unknown): string | undefined {\n switch (stopReason) {\n case 'end_turn':\n case 'cancelled':\n return undefined\n case 'refusal':\n return `${name} refused to continue`\n case 'max_tokens':\n return `${name} stopped at its token limit`\n case 'max_turn_requests':\n return `${name} stopped at its limit of model requests for one message`\n default:\n return `${name} stopped (${String(stopReason)})`\n }\n}\n\n/** The text an ACP tool call produced, when it reports text content and no raw output. */\nfunction toolText(update: ToolUpdate): string | undefined {\n const text = (update.content ?? [])\n .map((item) =>\n item.type === 'content' && item.content?.type === 'text' ? item.content.text : undefined,\n )\n .filter((part): part is string => typeof part === 'string')\n .join('\\n')\n return text || undefined\n}\n\n/** The answer to `session/request_permission`: the agent's option of the wanted kind, or `cancelled` when it offers none or the turn was cancelled. */\nfunction permissionAnswer(\n params: unknown,\n permissions: AcpPermissions,\n cancelled: boolean,\n): unknown {\n const options = ((params as { options?: Array<{ optionId: string; kind: string }> }).options ??\n []) as Array<{ optionId: string; kind: string }>\n const wanted =\n permissions === 'allow' ? ['allow_once', 'allow_always'] : ['reject_once', 'reject_always']\n const option = cancelled\n ? undefined\n : wanted.map((kind) => options.find((o) => o.kind === kind)).find(Boolean)\n return {\n outcome: option ? { outcome: 'selected', optionId: option.optionId } : { outcome: 'cancelled' },\n }\n}\n\nexport function acpDriver(options: {\n /** The driver's name in the panel (`acp:dsh`). */\n name: string\n agent: AcpAgent\n /** The app folder: the agent's working directory and its session's `cwd`. */\n cwd: string\n permissions: AcpPermissions\n open: OpenAgent\n}): ChatDriver {\n const { name, agent, cwd, permissions, open } = options\n let session: Promise<Session> | undefined\n /** The connection `session` belongs to, so only its own end clears it. */\n let live: AcpConnection | undefined\n let turnCancelled = false\n let queue: Promise<void> = Promise.resolve()\n\n const startSession = async (): Promise<Session> => {\n const { connection, close } = open(agent, (method, params) => {\n if (method === 'session/request_permission')\n return permissionAnswer(params, permissions, turnCancelled)\n throw new AcpError(`${method} is not offered by this client`, -32601)\n })\n // An agent that ends is started again at the next message.\n live = connection\n void connection.ended.then(() => {\n if (live !== connection) return\n live = undefined\n session = undefined\n })\n try {\n await connection.request('initialize', {\n protocolVersion: PROTOCOL_VERSION,\n clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },\n clientInfo: { name: 'acrylblends-driver-acp', version: '1' },\n })\n const created = await connection.request<{ sessionId: string }>('session/new', {\n cwd,\n mcpServers: [],\n })\n return { connection, id: created.sessionId }\n } catch (error) {\n await close()\n throw error\n }\n }\n\n return {\n kind: 'chat',\n name,\n async *start({ message, signal }) {\n // One message at a time: this one waits for the one before it.\n const previous = queue\n let finished!: () => void\n queue = new Promise((resolve) => (finished = resolve))\n try {\n await previous\n if (signal.aborted) return\n let current: Session\n try {\n session ??= startSession()\n current = await session\n } catch (error) {\n session = undefined\n yield {\n event: 'error',\n data: { message: error instanceof Error ? error.message : String(error) },\n }\n return\n }\n yield* turn(current, message, signal)\n } finally {\n finished()\n }\n },\n }\n\n async function* turn(\n current: Session,\n message: string,\n signal: AbortSignal,\n ): AsyncGenerator<ChatEvent> {\n const events: ChatEvent[] = []\n let wake: (() => void) | undefined\n let settled = false\n const push = (event: ChatEvent): void => {\n events.push(event)\n wake?.()\n }\n /** What earlier updates said about each tool call: its title and its input arrive before its result. */\n const calls = new Map<string, { title?: string; input?: unknown }>()\n const off = current.connection.onNotification((method, params) => {\n const { sessionId, update } = params as {\n sessionId?: string\n update?: { sessionUpdate?: string } & ToolUpdate & { content?: unknown }\n }\n if (method !== 'session/update' || sessionId !== current.id || !update) return\n if (update.sessionUpdate === 'agent_message_chunk') {\n const content = update.content as { type?: string; text?: string } | undefined\n if (content?.type === 'text' && content.text)\n push({ event: 'text', data: { text: content.text } })\n return\n }\n if (update.sessionUpdate !== 'tool_call' && update.sessionUpdate !== 'tool_call_update')\n return\n const call = calls.get(update.toolCallId) ?? {}\n if (update.title) call.title = update.title\n if (update.rawInput !== undefined) call.input = update.rawInput\n calls.set(update.toolCallId, call)\n if (update.status !== 'completed' && update.status !== 'failed') return\n const tool = call.title ?? update.toolCallId\n const output = update.rawOutput ?? toolText(update)\n push({\n event: 'tool',\n data: {\n tool,\n ...(call.input === undefined ? {} : { input: call.input }),\n ...(update.status === 'failed'\n ? {\n error:\n output === undefined\n ? 'failed'\n : String(typeof output === 'string' ? output : JSON.stringify(output)),\n }\n : { result: output }),\n },\n })\n })\n turnCancelled = false\n const cancel = (): void => {\n turnCancelled = true\n current.connection.notify('session/cancel', { sessionId: current.id })\n }\n signal.addEventListener('abort', cancel, { once: true })\n current.connection\n .request<{ stopReason?: unknown }>('session/prompt', {\n sessionId: current.id,\n prompt: [{ type: 'text', text: message }],\n })\n .then(\n (result) => {\n const stopped = signal.aborted ? undefined : stopMessage(name, result.stopReason)\n if (stopped) push({ event: 'error', data: { message: stopped } })\n },\n (error: unknown) => {\n if (!signal.aborted)\n push({\n event: 'error',\n data: { message: error instanceof Error ? error.message : String(error) },\n })\n },\n )\n .finally(() => {\n settled = true\n wake?.()\n })\n try {\n for (;;) {\n const next = events.shift()\n if (next) yield next\n else if (settled) return\n else await new Promise<void>((resolve) => (wake = resolve))\n }\n } finally {\n off()\n signal.removeEventListener('abort', cancel)\n // The panel stopped reading before the turn ended: the agent is told to stop it.\n if (!settled) cancel()\n }\n }\n}\n","/**\n * The ACP driver (M8, spec 046 T028): any agent that speaks the Agent Client Protocol (ACP v1 over stdio) as a chat driver of the agent panel, started in the app folder.\n * No agent gets code of its own here: an agent is a preset, a command line that starts its ACP server. `dsh` (DeepSeek Harness, `dsh --profile acp`) is the first preset;\n * other ACP agents are added by config.\n *\n * - The drivers are `chat` entries of the panel's `drivers` service (`acp:dsh`, ...). A panel without this plugin lists none; this plugin without a panel is pending.\n * - An agent whose command is not on the machine gets no driver, and the plugin says so in one line (as `driver-pty` does without node-pty).\n * - Every agent process is acquired inside one `ctx.effect`; its disposer ends the process. Unloading or reloading the plugin leaves no agent running.\n * - Development only, like the panel: with `NODE_ENV=production` (or `ACRYL_DOOR=off`) it starts nothing.\n */\n\nimport { existsSync } from 'node:fs'\nimport { isAbsolute } from 'node:path'\nimport { onPath } from '@acryldev/agent-panel/headless'\nimport type {} from '@acryldev/agent-panel/registry'\nimport type {} from '@acryldev/instance'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { type AcpPermissions, acpDriver, type OpenAgent } from './chat.ts'\nimport { type AcpAgent, AcpConnection } from './connection.ts'\n\nexport const name = 'driver-acp'\nexport const inject = ['drivers', 'appInstance']\n\nexport type { AcpPermissions } from './chat.ts'\nexport { acpDriver } from './chat.ts'\nexport { type AcpAgent, AcpConnection, AcpError } from './connection.ts'\n\n/** The ACP agents this plugin knows by name: the command line that starts each one's ACP server. */\nexport const PRESETS: Readonly<Record<string, AcpAgent>> = {\n dsh: { command: 'dsh', args: ['--profile', 'acp'] },\n}\n\nexport interface DriverAcpConfig {\n /** The agents to offer, by name (the driver is `acp:<name>`). Default: the presets whose command is on the machine. */\n agents?: Record<string, AcpAgent>\n /** The answer to an agent's permission request: its \"allow once\" or its \"reject once\" option. Default `reject`. */\n permissions?: AcpPermissions\n}\n\nexport function apply(ctx: Context, config: DriverAcpConfig = {}): void {\n if (process.env.NODE_ENV === 'production' || process.env.ACRYL_DOOR === 'off') return\n const root = ctx.appInstance.root\n const open: OpenAgent = (agent, handle) => {\n let connection!: AcpConnection\n const close = ctx.effect(() => {\n connection = new AcpConnection(agent, root, handle)\n return () => connection.close()\n }) as () => Promise<void>\n // An agent that ended on its own gives its effect back at once instead of at unload.\n void connection.ended.then(() => close())\n return { connection, close }\n }\n for (const [agentName, agent] of Object.entries(config.agents ?? PRESETS)) {\n if (!(isAbsolute(agent.command) ? existsSync(agent.command) : onPath(agent.command))) {\n console.warn(`driver-acp: no acp:${agentName} driver, \"${agent.command}\" is not on the PATH`)\n continue\n }\n const driver = acpDriver({\n name: `acp:${agentName}`,\n agent,\n cwd: root,\n permissions: config.permissions ?? 'reject',\n open,\n })\n ctx.effect(() => ctx.drivers.register(driver))\n }\n}\n"],"mappings":";;;;;;;;;;;AAeA,IAAa,WAAb,cAA8B,MAAM;;CAElC;CAEA,YAAY,SAAiB,MAAe;EAC1C,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;AAMA,MAAM,WAAW;AASjB,IAAa,gBAAb,MAA2B;CACzB;CACA,2BAAoB,IAAI,IAAqB;CAC7C,6BAAsB,IAAI,IAA+C;CACzE,UAAU;CACV,UAAU;CACV,UAAU;CACV;;CAEA;CAEA,YAAY,OAAiB,KAAa,QAA6B;EACrE,KAAKA,SAAS,MAAM,MAAM,SAAS,CAAC,GAAG,MAAM,IAAI,GAAG;GAClD;GACA,KAAK;IAAE,GAAG,QAAQ;IAAK,GAAG,MAAM;GAAI;GACpC,OAAO;IAAC;IAAQ;IAAQ;GAAM;GAE9B,OAAO,QAAQ,aAAa;GAE5B,UAAU,QAAQ,aAAa;GAC/B,aAAa;EACf,CAAC;EACD,KAAK,QAAQ,IAAI,SAAS,YAAY;GACpC,MAAM,OAAO,WAA2B;IACtC,IAAI,KAAKG,QAAQ;IACjB,KAAKA,SA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,OAAO;CAC/E,MAAM,OAAO,IAAI,YAAY;CAC7B,MAAM,QAAmB,OAAO,WAAW;EACzC,IAAI;EACJ,MAAM,QAAQ,IAAI,aAAa;GAC7B,aAAa,IAAI,cAAc,OAAO,MAAM,MAAM;GAClD,aAAa,WAAW,MAAM;EAChC,CAAC;EAED,WAAgB,MAAM,WAAW,MAAM,CAAC;EACxC,OAAO;GAAE;GAAY;EAAM;CAC7B;CACA,KAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,OAAO,UAAU,OAAO,GAAG;EACzE,IAAI,EAAE,WAAW,MAAM,OAAO,IAAI,WAAW,MAAM,OAAO,IAAI,OAAO,MAAM,OAAO,IAAI;GACpF,QAAQ,KAAK,sBAAsB,UAAU,YAAY,MAAM,QAAQ,qBAAqB;GAC5F;EACF;EACA,MAAM,SAAS,UAAU;GACvB,MAAM,OAAO;GACb;GACA,KAAK;GACL,aAAa,OAAO,eAAe;GACnC;EACF,CAAC;EACD,IAAI,aAAa,IAAI,QAAQ,SAAS,MAAM,CAAC;CAC/C;AACF"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * An ACP agent as a chat driver of the panel. The agent process starts at the first message and keeps one ACP session, so later messages continue the same conversation;
3
+ * an agent that ended is started again, with a new session, at the next message. One message runs at a time; a second one waits for the first.
4
+ *
5
+ * What the panel gets from the ACP updates: the agent's message chunks as `text`, each finished tool call as one `tool` (its title, input, and result or error), and an
6
+ * `error` for a turn that stopped short (a refusal, a token or request limit, an agent that ended). Thoughts, plans and the rest stay out of the chat.
7
+ */
8
+ import type { ChatDriver } from '@acryldev/drivers';
9
+ import { type AcpAgent, type AcpConnection } from './connection.ts';
10
+ /** Which answer a permission request gets: the agent's own "allow once" or "reject once" option. */
11
+ export type AcpPermissions = 'allow' | 'reject';
12
+ /**
13
+ * Opens a connection to the agent and returns it with the function that closes it. The plugin acquires it inside one `ctx.effect`, so unloading the plugin ends the process.
14
+ */
15
+ export type OpenAgent = (agent: AcpAgent, handle: (method: string, params: unknown) => unknown) => {
16
+ connection: AcpConnection;
17
+ close(): Promise<void>;
18
+ };
19
+ export declare function acpDriver(options: {
20
+ /** The driver's name in the panel (`acp:dsh`). */
21
+ name: string;
22
+ agent: AcpAgent;
23
+ /** The app folder: the agent's working directory and its session's `cwd`. */
24
+ cwd: string;
25
+ permissions: AcpPermissions;
26
+ open: OpenAgent;
27
+ }): ChatDriver;
@@ -0,0 +1,30 @@
1
+ /** How to start an ACP agent: a program and its arguments, and what to add to the app's environment. */
2
+ export interface AcpAgent {
3
+ readonly command: string;
4
+ readonly args: readonly string[];
5
+ readonly env?: Readonly<Record<string, string>>;
6
+ }
7
+ /** An error the agent answered with, or the reason the connection ended. */
8
+ export declare class AcpError extends Error {
9
+ /** The JSON-RPC error code, for an error the agent answered with. */
10
+ readonly code: number | undefined;
11
+ constructor(message: string, code?: number);
12
+ }
13
+ /** Answers a request the agent sends (`session/request_permission`); throwing answers with an error. */
14
+ export type AgentRequestHandler = (method: string, params: unknown) => unknown;
15
+ export declare class AcpConnection {
16
+ #private;
17
+ /** Resolves with the reason once the process is gone. */
18
+ readonly ended: Promise<AcpError>;
19
+ constructor(agent: AcpAgent, cwd: string, handle: AgentRequestHandler);
20
+ /** Sends a request and resolves with its result; rejects with the agent's error, or when the process ends first. */
21
+ request<T>(method: string, params: unknown): Promise<T>;
22
+ notify(method: string, params: unknown): void;
23
+ /** Hears every notification the agent sends; returns the function that stops listening. */
24
+ onNotification(listener: (method: string, params: unknown) => void): () => void;
25
+ /**
26
+ * Ends the process and what it started: stdin closed, then SIGTERM, then a hard kill, each to the whole process group on POSIX (the tree, with `taskkill /T`, on Windows).
27
+ * Resolves once they are gone. Safe to call again, and after the agent ended on its own (its leftovers are still cleared).
28
+ */
29
+ close(): Promise<void>;
30
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The ACP driver (M8, spec 046 T028): any agent that speaks the Agent Client Protocol (ACP v1 over stdio) as a chat driver of the agent panel, started in the app folder.
3
+ * No agent gets code of its own here: an agent is a preset, a command line that starts its ACP server. `dsh` (DeepSeek Harness, `dsh --profile acp`) is the first preset;
4
+ * other ACP agents are added by config.
5
+ *
6
+ * - The drivers are `chat` entries of the panel's `drivers` service (`acp:dsh`, ...). A panel without this plugin lists none; this plugin without a panel is pending.
7
+ * - An agent whose command is not on the machine gets no driver, and the plugin says so in one line (as `driver-pty` does without node-pty).
8
+ * - Every agent process is acquired inside one `ctx.effect`; its disposer ends the process. Unloading or reloading the plugin leaves no agent running.
9
+ * - Development only, like the panel: with `NODE_ENV=production` (or `ACRYL_DOOR=off`) it starts nothing.
10
+ */
11
+ import type { Context } from '@deepseek-ai/cordis';
12
+ import { type AcpPermissions } from './chat.ts';
13
+ import { type AcpAgent } from './connection.ts';
14
+ export declare const name = "driver-acp";
15
+ export declare const inject: string[];
16
+ export type { AcpPermissions } from './chat.ts';
17
+ export { acpDriver } from './chat.ts';
18
+ export { type AcpAgent, AcpConnection, AcpError } from './connection.ts';
19
+ /** The ACP agents this plugin knows by name: the command line that starts each one's ACP server. */
20
+ export declare const PRESETS: Readonly<Record<string, AcpAgent>>;
21
+ export interface DriverAcpConfig {
22
+ /** The agents to offer, by name (the driver is `acp:<name>`). Default: the presets whose command is on the machine. */
23
+ agents?: Record<string, AcpAgent>;
24
+ /** The answer to an agent's permission request: its "allow once" or its "reject once" option. Default `reject`. */
25
+ permissions?: AcpPermissions;
26
+ }
27
+ export declare function apply(ctx: Context, config?: DriverAcpConfig): void;
@@ -0,0 +1,2 @@
1
+ declare const _default: import("tsdown").UserConfig;
2
+ export default _default;
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@acryldev/driver-acp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Any agent that speaks the Agent Client Protocol (ACP) as a chat in the agent panel, started in the app folder: DeepSeek Harness (dsh --profile acp) is the first preset, other ACP agents are added by config. Development only; needs the agent panel; opt-in with acrylblends add driver-acp.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/acryldev/acryl.git",
9
+ "directory": "plugins/driver-acp"
10
+ },
11
+ "homepage": "https://github.com/acryldev/acryl/tree/main/plugins/driver-acp#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/acryldev/acryl/issues"
14
+ },
15
+ "type": "module",
16
+ "engines": {
17
+ "node": "^22.19.0 || >=24.0.0"
18
+ },
19
+ "main": "./lib/index.js",
20
+ "types": "./lib/types/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./lib/types/index.d.ts",
24
+ "default": "./lib/index.js"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "dependencies": {
29
+ "@acryldev/agent-panel": "0.1.0",
30
+ "@acryldev/instance": "0.1.0",
31
+ "@acryldev/drivers": "0.1.0"
32
+ },
33
+ "peerDependencies": {
34
+ "@deepseek-ai/cordis": "^4.0.2"
35
+ },
36
+ "devDependencies": {
37
+ "@deepseek-ai/cordis": "4.0.4",
38
+ "@types/node": "^22.20.0",
39
+ "@acryldev/agent": "0.1.0",
40
+ "@acryldev/builder": "0.1.0",
41
+ "@acryldev/extensions": "0.1.0",
42
+ "@acryldev/instance": "0.1.0",
43
+ "@acryldev/router": "0.1.0",
44
+ "@acryldev/state": "0.1.0",
45
+ "ajv": "^8.20.0",
46
+ "tsdown": "0.22.2",
47
+ "typescript": "6.0.3"
48
+ },
49
+ "scripts": {
50
+ "build": "tsdown && tsc -p tsconfig.json --emitDeclarationOnly"
51
+ }
6
52
  }