@qlairoslabs/acp-client 0.4.3 → 0.5.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/README.md CHANGED
@@ -28,8 +28,8 @@ assumptions that don't fit when you orchestrate **many** agents across **many**
28
28
  environments:
29
29
 
30
30
  - **No forced `cwd` discovery.** Other libraries crawl up to the git root and impose a
31
- working directory. This one takes `cwd` (and an `execPrefix` like `docker exec -i …`) as
32
- plain config, so you can talk to agents inside containers or arbitrary runtimes.
31
+ working directory. This one keeps target-visible `cwd` separate from an optional
32
+ runtime `launcher` that prepares the exact host process.
33
33
  - **Introspection over hardcoding.** Models, auth methods, capabilities, and config
34
34
  options are all *discovered* from the protocol at runtime, never baked in. The library
35
35
  surfaces raw protocol facts and lets you decide what they mean.
@@ -273,16 +273,26 @@ shell line and run through `bash` (or `/bin/sh`), because that is how agents use
273
273
  `claude-code-acp` puts its whole Bash command line, redirections and all, in `command`.
274
274
  Set `ACP_TERMINAL_SHELL` to choose a different shell.
275
275
 
276
- To opt out — letting the agent fall back to its own implementation — turn the capability
277
- off, which also stops us advertising it:
276
+ The built-in handlers operate in the library process's host namespace. For a container,
277
+ VM, SSH session, or other runtime boundary, disable them or provide runtime-aware handlers.
278
+ Handler presence is the source of truth for capability advertisement:
278
279
 
279
280
  ```ts
280
281
  new AcpClient({
281
282
  adapter: ADAPTERS.codex,
282
- clientCapabilities: { terminal: false, fs: { writeTextFile: false } },
283
+ clientHandlers: {
284
+ terminal: false,
285
+ filesystem: {
286
+ readTextFile: async (request) => containerFs.read(request),
287
+ // write omitted: writeTextFile is not advertised
288
+ },
289
+ },
283
290
  });
284
291
  ```
285
292
 
293
+ `clientCapabilities` remains as a compatibility option. New `clientHandlers` selections
294
+ take precedence and cannot advertise an operation without installing its implementation.
295
+
286
296
  ### Durable sessions with a catalog
287
297
 
288
298
  `AgentSession` gives a conversation a stable id that persists across reconnects, and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.4.3",
3
+ "version": "0.5.0",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -191,7 +191,11 @@ export interface AgentSessionConfig {
191
191
  adapterId: string;
192
192
  /** Talk over ACP ("normal") or scrape a pty ("degraded"). Default "normal". */
193
193
  mode?: AgentMode;
194
+ /** Runtime-specific launcher shared by normal ACP and degraded PTY modes. */
195
+ launcher?: AgentControllerConfig["launcher"];
196
+ /** @deprecated Use launcher. */
194
197
  execPrefix?: string[];
198
+ /** @deprecated Use launcher and its exact spawnEnv. */
195
199
  env?: Record<string, string>;
196
200
  cwd?: string;
197
201
  /** Default MCP servers bound at session creation/switch, unless a call overrides them. */
@@ -200,6 +204,8 @@ export interface AgentSessionConfig {
200
204
  clientInfo?: { name: string; title?: string; version?: string };
201
205
  /** What we let the agent do through us (terminals, filesystem). All on by default. */
202
206
  clientCapabilities?: AgentControllerConfig["clientCapabilities"];
207
+ /** Client-side ACP implementations; their presence determines advertisement. */
208
+ clientHandlers?: AgentControllerConfig["clientHandlers"];
203
209
  logger?: Logger;
204
210
  /** Raw protocol traffic for debugging — see `AcpClientConfig.wire`. */
205
211
  wire?: (entry: WireEntry) => void;
@@ -321,6 +327,7 @@ export class AgentSession implements AgentClient, Bridgeable {
321
327
  adapter: config.adapter,
322
328
  adapterId: config.adapterId,
323
329
  mode: this._mode,
330
+ launcher: config.launcher,
324
331
  execPrefix: config.execPrefix,
325
332
  env: config.env,
326
333
  cwd: config.cwd,
@@ -332,6 +339,7 @@ export class AgentSession implements AgentClient, Bridgeable {
332
339
  defaultPermission: config.defaultPermission,
333
340
  clientInfo: config.clientInfo,
334
341
  clientCapabilities: config.clientCapabilities,
342
+ clientHandlers: config.clientHandlers,
335
343
  logger: config.logger,
336
344
  wire: config.wire,
337
345
  });
@@ -348,8 +356,13 @@ export class AgentSession implements AgentClient, Bridgeable {
348
356
  */
349
357
  static async create(config: AgentSessionConfig): Promise<AgentSession> {
350
358
  const session = new AgentSession(config);
351
- await session.start();
352
- return session;
359
+ try {
360
+ await session.start();
361
+ return session;
362
+ } catch (error) {
363
+ await session.stop().catch(() => {});
364
+ throw error;
365
+ }
353
366
  }
354
367
 
355
368
  private async start(): Promise<void> {
package/src/client.ts CHANGED
@@ -8,11 +8,10 @@
8
8
  import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
9
9
  import type * as schema from "@agentclientprotocol/sdk";
10
10
  import type { Adapter } from "./adapters.ts";
11
- import { buildSpawnCommand } from "./adapters.ts";
12
- import { AcpTransport } from "./transport/acp-transport.ts";
11
+ import { AcpTransport, type TerminalHandlers } from "./transport/acp-transport.ts";
12
+ import { prepareLaunch, type AcpLauncher } from "./launcher.ts";
13
13
  import {
14
14
  parseCapabilities,
15
- buildClientCapabilities,
16
15
  type Capabilities,
17
16
  type ClientCapabilities,
18
17
  type ClientCapabilityConfig,
@@ -41,11 +40,16 @@ import type {
41
40
  export interface AcpClientConfig {
42
41
  /** How to launch the agent binary. */
43
42
  adapter: Adapter;
44
- /** Prefix merged before the adapter command, e.g. ["docker","exec","-i","<ctr>"]. */
43
+ /** Runtime-specific launcher for exact ACP/PTY host process preparation. */
44
+ launcher?: AcpLauncher;
45
+ /**
46
+ * Prefix merged before the adapter command, e.g. ["docker","exec","-i","<ctr>"].
47
+ * @deprecated Use launcher.
48
+ */
45
49
  execPrefix?: string[];
46
- /** Extra env vars injected at spawn time (never sent over the protocol). */
50
+ /** @deprecated Use launcher and its exact spawnEnv. */
47
51
  env?: Record<string, string>;
48
- /** Agent workspace — passed to session/new. Also the spawn cwd unless using docker exec. */
52
+ /** Workspace visible to the ACP target and sent in session requests. */
49
53
  cwd?: string;
50
54
  /** Resume this session id when startSession() is called. */
51
55
  sessionId?: string;
@@ -59,8 +63,14 @@ export interface AcpClientConfig {
59
63
  * What we let the agent do through us: filesystem reads/writes and terminals. All
60
64
  * enabled by default. Disabling one stops us advertising it, so the agent falls back
61
65
  * to its own implementation instead of calling a method we won't answer.
66
+ * @deprecated Use clientHandlers; when a new handler selection is present it wins.
62
67
  */
63
68
  clientCapabilities?: ClientCapabilityConfig;
69
+ /**
70
+ * Client-side ACP implementations. Omitted selects the built-in host implementation;
71
+ * false disables implementation and advertisement; custom handlers are advertised.
72
+ */
73
+ clientHandlers?: AcpClientHandlers;
64
74
  /** Diagnostics sink. Omit for a silent library. */
65
75
  logger?: Logger;
66
76
  /**
@@ -71,6 +81,51 @@ export interface AcpClientConfig {
71
81
  wire?: (entry: WireEntry) => void;
72
82
  }
73
83
 
84
+ export interface FilesystemHandlers {
85
+ readTextFile?: (
86
+ params: schema.ReadTextFileRequest,
87
+ ) => Promise<schema.ReadTextFileResponse>;
88
+ writeTextFile?: (
89
+ params: schema.WriteTextFileRequest,
90
+ ) => Promise<schema.WriteTextFileResponse>;
91
+ }
92
+
93
+ export interface AcpClientHandlers {
94
+ terminal?: TerminalHandlers | false;
95
+ filesystem?: FilesystemHandlers | false;
96
+ }
97
+
98
+ interface ResolvedClientHandlers {
99
+ terminal: "builtin" | TerminalHandlers | false;
100
+ readTextFile: "builtin" | NonNullable<FilesystemHandlers["readTextFile"]> | false;
101
+ writeTextFile: "builtin" | NonNullable<FilesystemHandlers["writeTextFile"]> | false;
102
+ }
103
+
104
+ function resolveClientHandlers(
105
+ handlers: AcpClientHandlers | undefined,
106
+ legacy: ClientCapabilityConfig | undefined,
107
+ ): ResolvedClientHandlers {
108
+ const terminal = handlers?.terminal !== undefined
109
+ ? handlers.terminal
110
+ : legacy?.terminal === false ? false : "builtin";
111
+
112
+ if (handlers?.filesystem === false) {
113
+ return { terminal, readTextFile: false, writeTextFile: false };
114
+ }
115
+ if (handlers?.filesystem) {
116
+ return {
117
+ terminal,
118
+ readTextFile: handlers.filesystem.readTextFile ?? false,
119
+ writeTextFile: handlers.filesystem.writeTextFile ?? false,
120
+ };
121
+ }
122
+ return {
123
+ terminal,
124
+ readTextFile: legacy?.fs?.readTextFile === false ? false : "builtin",
125
+ writeTextFile: legacy?.fs?.writeTextFile === false ? false : "builtin",
126
+ };
127
+ }
128
+
74
129
  export interface StartSessionOptions {
75
130
  /** Resume this session. Defaults to config.sessionId. */
76
131
  sessionId?: string;
@@ -154,10 +209,18 @@ export class AcpClient implements AgentClient {
154
209
 
155
210
  private readonly log: Logger;
156
211
  private readonly clientCapabilities: ClientCapabilities;
212
+ private readonly handlers: ResolvedClientHandlers;
157
213
 
158
214
  constructor(private config: AcpClientConfig) {
159
215
  this.log = config.logger ?? noopLogger;
160
- this.clientCapabilities = buildClientCapabilities(config.clientCapabilities);
216
+ this.handlers = resolveClientHandlers(config.clientHandlers, config.clientCapabilities);
217
+ this.clientCapabilities = {
218
+ fs: {
219
+ readTextFile: this.handlers.readTextFile !== false,
220
+ writeTextFile: this.handlers.writeTextFile !== false,
221
+ },
222
+ terminal: this.handlers.terminal !== false,
223
+ };
161
224
  }
162
225
 
163
226
  // --- introspection (populated by connect) -------------------------------------
@@ -204,13 +267,9 @@ export class AcpClient implements AgentClient {
204
267
  async connect(): Promise<Capabilities> {
205
268
  if (this.transport) return this.capabilities;
206
269
 
207
- const command = buildSpawnCommand(this.config.adapter, this.config.execPrefix);
208
- const isDockerExec = command[0] === "docker";
209
-
210
- this.log.info("connect", { command, dockerExec: isDockerExec });
211
-
270
+ const launch = await prepareLaunch("acp", this.config.launcher, this.config);
212
271
  const caps = this.clientCapabilities;
213
- this.terminals = caps.terminal
272
+ this.terminals = this.handlers.terminal === "builtin"
214
273
  ? new TerminalRegistry({
215
274
  cwd: this.config.cwd,
216
275
  env: this.config.env,
@@ -218,29 +277,34 @@ export class AcpClient implements AgentClient {
218
277
  })
219
278
  : null;
220
279
 
280
+ const terminalHandlers = this.handlers.terminal === "builtin"
281
+ ? this.terminalHandlers(this.terminals!)
282
+ : this.handlers.terminal || undefined;
283
+ const readHandler = this.handlers.readTextFile === "builtin"
284
+ ? async (p: schema.ReadTextFileRequest) => ({ content: await readTextFile(p) })
285
+ : this.handlers.readTextFile || undefined;
286
+ const writeHandler = this.handlers.writeTextFile === "builtin"
287
+ ? async (p: schema.WriteTextFileRequest) => {
288
+ await writeTextFile(p);
289
+ return {};
290
+ }
291
+ : this.handlers.writeTextFile || undefined;
292
+
221
293
  const transport = new AcpTransport({
222
- command,
223
- // docker exec resolves paths inside the container's namespace — don't pass a host cwd.
224
- cwd: isDockerExec ? undefined : this.config.cwd,
225
- env: this.config.env,
294
+ launch,
226
295
  onUpdate: (n) => this.handleUpdate(n),
227
296
  onPermissionRequest: (p) => this.handlePermission(p),
228
- onReadTextFile: caps.fs.readTextFile
229
- ? async (p) => ({ content: await readTextFile(p) })
230
- : undefined,
231
- onWriteTextFile: caps.fs.writeTextFile
232
- ? async (p) => {
233
- await writeTextFile(p);
234
- return {};
235
- }
236
- : undefined,
237
- terminals: this.terminals ? this.terminalHandlers(this.terminals) : undefined,
297
+ onReadTextFile: readHandler,
298
+ onWriteTextFile: writeHandler,
299
+ terminals: terminalHandlers,
238
300
  onWire: this.config.wire,
239
301
  onStderr: (line) => {
240
302
  this.log.debug("agent_stderr", { line });
241
303
  this.authStderrSink?.(line);
242
304
  },
243
305
  onCrash: (code) => {
306
+ this.terminals?.releaseAll();
307
+ this.terminals = null;
244
308
  this.transport = null;
245
309
  this._sessionId = null;
246
310
  this.commandTransition = null;
@@ -248,28 +312,37 @@ export class AcpClient implements AgentClient {
248
312
  this.log.error("process_exit", { code });
249
313
  },
250
314
  });
251
- await transport.start();
252
- this.transport = transport;
253
-
254
- const init = await transport.raceExit(
255
- transport.initialize({
256
- protocolVersion: PROTOCOL_VERSION,
257
- clientCapabilities: caps as unknown as schema.ClientCapabilities,
258
- clientInfo: this.config.clientInfo ?? {
259
- name: "acp-lib",
260
- title: "ACP Lib",
261
- version: "0.1.0",
262
- },
263
- } as schema.InitializeRequest),
264
- );
265
- this._capabilities = parseCapabilities(init, caps);
266
- this.log.info("initialized", {
267
- agent: this._capabilities.agentInfo?.name,
268
- protocolVersion: this._capabilities.protocolVersion,
269
- loadSession: this._capabilities.agent.loadSession,
270
- });
271
- this.log.debug("initialize_response", { response: init });
272
- return this._capabilities;
315
+ try {
316
+ this.log.info("connect", { command: launch.command });
317
+ await transport.start();
318
+ this.transport = transport;
319
+
320
+ const init = await transport.raceExit(
321
+ transport.initialize({
322
+ protocolVersion: PROTOCOL_VERSION,
323
+ clientCapabilities: caps as unknown as schema.ClientCapabilities,
324
+ clientInfo: this.config.clientInfo ?? {
325
+ name: "acp-lib",
326
+ title: "ACP Lib",
327
+ version: "0.1.0",
328
+ },
329
+ } as schema.InitializeRequest),
330
+ );
331
+ this._capabilities = parseCapabilities(init, caps);
332
+ this.log.info("initialized", {
333
+ agent: this._capabilities.agentInfo?.name,
334
+ protocolVersion: this._capabilities.protocolVersion,
335
+ loadSession: this._capabilities.agent.loadSession,
336
+ });
337
+ this.log.debug("initialize_response", { response: init });
338
+ return this._capabilities;
339
+ } catch (error) {
340
+ this.transport = null;
341
+ await transport.stop().catch((cleanupError) => {
342
+ this.log.warn("launch_cleanup_failed", { error: String(cleanupError) });
343
+ });
344
+ throw error;
345
+ }
273
346
  }
274
347
 
275
348
  /**
package/src/controller.ts CHANGED
@@ -11,6 +11,7 @@ import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from ".
11
11
  import type { Capabilities } from "./capabilities.ts";
12
12
  import type { ConfigOption, ConfigOptions } from "./config-options.ts";
13
13
  import type { Logger } from "./logger.ts";
14
+ import type { AcpLauncher } from "./launcher.ts";
14
15
  import type {
15
16
  InternalSessionCommand,
16
17
  Attachment,
@@ -38,7 +39,11 @@ export interface AgentControllerConfig {
38
39
  adapterId: string;
39
40
  /** How to talk to the agent on start(). Default "normal". */
40
41
  mode?: AgentMode;
42
+ /** Runtime-specific launcher shared by normal ACP and degraded PTY modes. */
43
+ launcher?: AcpLauncher;
44
+ /** @deprecated Use launcher. */
41
45
  execPrefix?: string[];
46
+ /** @deprecated Use launcher and its exact spawnEnv. */
42
47
  env?: Record<string, string>;
43
48
  cwd?: string;
44
49
  /** Session id to load on start(). */
@@ -51,6 +56,8 @@ export interface AgentControllerConfig {
51
56
  clientInfo?: AcpClientConfig["clientInfo"];
52
57
  /** What we let the agent do through us (terminals, filesystem). All on by default. */
53
58
  clientCapabilities?: AcpClientConfig["clientCapabilities"];
59
+ /** Client-side ACP implementations; their presence determines advertisement. */
60
+ clientHandlers?: AcpClientConfig["clientHandlers"];
54
61
  logger?: Logger;
55
62
  /** Raw protocol traffic for debugging — see `AcpClientConfig.wire`. */
56
63
  wire?: (entry: WireEntry) => void;
@@ -196,6 +203,7 @@ export class AgentController implements AgentClient {
196
203
  const { PtyClient } = await import("./degraded/index.ts");
197
204
  const pty = new PtyClient({
198
205
  adapter: this.config.adapter,
206
+ launcher: this.config.launcher,
199
207
  execPrefix: this.config.execPrefix,
200
208
  env: this.config.env,
201
209
  cwd: this.config.cwd,
@@ -379,6 +387,7 @@ export class AgentController implements AgentClient {
379
387
  const { PtyClient } = await import("./degraded/index.ts");
380
388
  const client = new PtyClient({
381
389
  adapter,
390
+ launcher: this.config.launcher,
382
391
  execPrefix: this.config.execPrefix,
383
392
  env: this.config.env,
384
393
  cwd: this.config.cwd,
@@ -395,6 +404,7 @@ export class AgentController implements AgentClient {
395
404
 
396
405
  const client = new AcpClient({
397
406
  adapter,
407
+ launcher: this.config.launcher,
398
408
  execPrefix: this.config.execPrefix,
399
409
  env: this.config.env,
400
410
  cwd: this.config.cwd,
@@ -403,6 +413,7 @@ export class AgentController implements AgentClient {
403
413
  defaultPermission: this.config.defaultPermission,
404
414
  clientInfo: this.config.clientInfo,
405
415
  clientCapabilities: this.config.clientCapabilities,
416
+ clientHandlers: this.config.clientHandlers,
406
417
  logger: this.config.logger,
407
418
  wire: this.config.wire,
408
419
  });
@@ -12,7 +12,7 @@
12
12
 
13
13
  import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "../agent-client.ts";
14
14
  import type { Adapter } from "../adapters.ts";
15
- import { buildPtyCommand } from "../adapters.ts";
15
+ import { prepareLaunch, type AcpLauncher } from "../launcher.ts";
16
16
  import type { ScreenParser } from "../parser/types.ts";
17
17
  import type { PromptResult, PromptHandlers, Attachment } from "../types.ts";
18
18
  import { noopLogger, type Logger } from "../logger.ts";
@@ -26,7 +26,11 @@ const ESC = "\x1b";
26
26
 
27
27
  export interface PtyClientOptions {
28
28
  adapter: Adapter;
29
+ /** Runtime-specific launcher for exact ACP/PTY host process preparation. */
30
+ launcher?: AcpLauncher;
31
+ /** @deprecated Use launcher. */
29
32
  execPrefix?: string[];
33
+ /** @deprecated Use launcher and its exact spawnEnv. */
30
34
  env?: Record<string, string>;
31
35
  cwd?: string;
32
36
  /** Optional smart parser (SML/heuristic). Absent → deterministic extractReply. */
@@ -80,14 +84,9 @@ export class PtyClient implements AgentClient, Bridgeable {
80
84
  /** Spawn the interactive CLI and wait for its banner/prompt to settle. */
81
85
  async start(): Promise<void> {
82
86
  if (this.transport) return;
83
- const command = buildPtyCommand(this.opts.adapter, this.opts.execPrefix);
84
- this.log.info("pty_connect", { command });
85
-
86
- this.screen = new EmulatorScreen({ cols: this.cols, rows: this.rows });
87
+ const launch = await prepareLaunch("pty", this.opts.launcher, this.opts);
87
88
  const transport = new PtyTransport({
88
- command,
89
- cwd: this.opts.cwd,
90
- env: this.opts.env,
89
+ launch,
91
90
  cols: this.cols,
92
91
  rows: this.rows,
93
92
  onData: (data) => this.onData(data),
@@ -97,12 +96,21 @@ export class PtyClient implements AgentClient, Bridgeable {
97
96
  void this.finishTurn("end_turn");
98
97
  },
99
98
  });
100
- await transport.start();
101
- this.transport = transport;
102
-
103
- // Drain the startup banner so the first prompt's response isn't polluted by it.
104
- await this.waitIdle();
105
- this.log.debug("pty_ready", {});
99
+ try {
100
+ this.log.info("pty_connect", { command: launch.command });
101
+ this.screen = new EmulatorScreen({ cols: this.cols, rows: this.rows });
102
+ await transport.start();
103
+ this.transport = transport;
104
+
105
+ // Drain the startup banner so the first prompt's response isn't polluted by it.
106
+ await this.waitIdle();
107
+ this.log.debug("pty_ready", {});
108
+ } catch (error) {
109
+ await transport.stop().catch((cleanupError) => {
110
+ this.log.warn("pty_launch_cleanup_failed", { error: String(cleanupError) });
111
+ });
112
+ throw error;
113
+ }
106
114
  }
107
115
 
108
116
  prompt(
@@ -8,11 +8,16 @@
8
8
  // event callbacks. Everything above stays pty-plumbing-agnostic.
9
9
 
10
10
  import { ProcessCrashError } from "../errors.ts";
11
+ import { onceDispose, type PreparedLaunch } from "../launcher.ts";
11
12
 
12
13
  export interface PtyTransportOptions {
13
- /** The interactive command (argv) to run inside the pty, e.g. ["codex"] (exec-prefixed). */
14
- command: string[];
14
+ /** Exact host-side process launch, already resolved by the caller's launcher. */
15
+ launch?: PreparedLaunch;
16
+ /** @deprecated Pass launch. */
17
+ command?: string[];
18
+ /** @deprecated Pass launch.spawnCwd. */
15
19
  cwd?: string;
20
+ /** @deprecated Pass launch.spawnEnv. Legacy values overlay process.env. */
16
21
  env?: Record<string, string>;
17
22
  cols?: number;
18
23
  rows?: number;
@@ -35,40 +40,68 @@ export class PtyTransport {
35
40
  private proc: ReturnType<typeof Bun.spawn> | null = null;
36
41
  private terminal: BunTerminal | null = null;
37
42
  private stopping = false;
43
+ private readonly disposeLaunch: () => Promise<void>;
44
+ private readonly launch: PreparedLaunch;
38
45
 
39
- constructor(private opts: PtyTransportOptions) {}
46
+ constructor(private opts: PtyTransportOptions) {
47
+ if (opts.launch) {
48
+ this.launch = opts.launch;
49
+ } else {
50
+ if (!opts.command?.length) throw new Error("PtyTransport requires launch or command");
51
+ this.launch = {
52
+ command: opts.command,
53
+ spawnCwd: opts.cwd,
54
+ spawnEnv: {
55
+ ...(process.env as Record<string, string>),
56
+ ...(opts.env ?? {}),
57
+ TERM: opts.env?.TERM ?? "xterm-color",
58
+ },
59
+ };
60
+ }
61
+ this.disposeLaunch = onceDispose(this.launch.dispose);
62
+ }
40
63
 
41
64
  async start(): Promise<void> {
42
65
  if (this.proc) return;
43
66
  const dec = new TextDecoder();
44
67
 
45
- const proc = Bun.spawn(this.opts.command, {
46
- cwd: this.opts.cwd,
47
- env: {
48
- ...process.env,
49
- ...(this.opts.env ?? {}),
50
- TERM: this.opts.env?.TERM ?? "xterm-color",
51
- },
52
- terminal: {
53
- cols: this.opts.cols ?? 80,
54
- rows: this.opts.rows ?? 24,
55
- data: (_term: unknown, data: Uint8Array) => {
56
- const text = dec.decode(data, { stream: true });
57
- if (text) this.opts.onData?.(text);
68
+ let proc: ReturnType<typeof Bun.spawn>;
69
+ try {
70
+ proc = Bun.spawn(this.launch.command, {
71
+ cwd: this.launch.spawnCwd,
72
+ env: this.launch.spawnEnv,
73
+ terminal: {
74
+ cols: this.opts.cols ?? 80,
75
+ rows: this.opts.rows ?? 24,
76
+ data: (_term: unknown, data: Uint8Array) => {
77
+ const text = dec.decode(data, { stream: true });
78
+ if (text) this.opts.onData?.(text);
79
+ },
58
80
  },
59
- },
60
- } as Parameters<typeof Bun.spawn>[1]);
81
+ } as Parameters<typeof Bun.spawn>[1]);
82
+ } catch (error) {
83
+ await this.disposeLaunch().catch(() => {});
84
+ throw error;
85
+ }
61
86
 
62
87
  this.proc = proc;
63
88
  this.terminal = (proc as unknown as { terminal: BunTerminal }).terminal ?? null;
64
89
 
65
90
  proc.exited
66
- .then((code) => {
91
+ .then(async (code) => {
67
92
  if (this.proc === proc && !this.stopping) {
68
93
  this.proc = null;
69
94
  this.terminal = null;
95
+ await this.disposeLaunch().catch(() => {});
70
96
  this.opts.onExit?.(code ?? null);
71
97
  }
98
+ }, async () => {
99
+ if (this.proc === proc && !this.stopping) {
100
+ this.proc = null;
101
+ this.terminal = null;
102
+ await this.disposeLaunch().catch(() => {});
103
+ this.opts.onExit?.(null);
104
+ }
72
105
  })
73
106
  .catch(() => {});
74
107
  }
@@ -120,8 +153,10 @@ export class PtyTransport {
120
153
  } catch {
121
154
  /* gone */
122
155
  }
156
+ await proc.exited.catch(() => {});
123
157
  }
124
158
  }
159
+ await this.disposeLaunch();
125
160
  }
126
161
 
127
162
  get running(): boolean {
package/src/index.ts CHANGED
@@ -11,8 +11,12 @@ export type {
11
11
  SwitchSessionOptions,
12
12
  ConnectResult,
13
13
  SessionLoadFailure,
14
+ AcpClientHandlers,
15
+ FilesystemHandlers,
14
16
  } from "./client.ts";
15
17
 
18
+ export type { AcpLauncher, PreparedLaunch, LaunchKind } from "./launcher.ts";
19
+
16
20
  export {
17
21
  AgentController,
18
22
  parseConfigValue,
@@ -68,6 +72,7 @@ export type {
68
72
  TerminalOutput,
69
73
  TerminalRegistryOptions,
70
74
  } from "./terminals.ts";
75
+ export type { TerminalHandlers } from "./transport/acp-transport.ts";
71
76
 
72
77
  export { extractChunkText, extractResponseChunk, toActivityEvent } from "./updates.ts";
73
78
 
@@ -0,0 +1,86 @@
1
+ import type { Adapter } from "./adapters.ts";
2
+ import { buildPtyCommand, buildSpawnCommand } from "./adapters.ts";
3
+
4
+ export type LaunchKind = "acp" | "pty";
5
+
6
+ /** A fully resolved host process launch. The environment is exact, not an overlay. */
7
+ export interface PreparedLaunch {
8
+ command: string[];
9
+ spawnCwd?: string;
10
+ /** Complete environment for the directly spawned process. */
11
+ spawnEnv: Record<string, string>;
12
+ /** Release resources created while preparing this launch. Called exactly once. */
13
+ dispose?: () => void | Promise<void>;
14
+ }
15
+
16
+ /** Translates an adapter command into a runtime-specific host process launch. */
17
+ export interface AcpLauncher {
18
+ prepare(request: {
19
+ kind: LaunchKind;
20
+ targetCommand: readonly string[];
21
+ }): Promise<PreparedLaunch>;
22
+ }
23
+
24
+ export interface LegacyLaunchOptions {
25
+ adapter: Adapter;
26
+ execPrefix?: string[];
27
+ env?: Record<string, string>;
28
+ cwd?: string;
29
+ }
30
+
31
+ /**
32
+ * Resolve the new launcher contract, or reproduce the historical adapter/execPrefix
33
+ * behavior for callers that have not migrated yet.
34
+ */
35
+ export async function prepareLaunch(
36
+ kind: LaunchKind,
37
+ launcher: AcpLauncher | undefined,
38
+ legacy: LegacyLaunchOptions,
39
+ ): Promise<PreparedLaunch> {
40
+ const targetCommand = kind === "acp" ? legacy.adapter.command : legacy.adapter.ptyCommand;
41
+ if (!targetCommand?.length) {
42
+ // Preserve buildPtyCommand's established error for adapters without a PTY command.
43
+ if (kind === "pty") buildPtyCommand(legacy.adapter);
44
+ throw new Error("adapter command cannot be empty");
45
+ }
46
+
47
+ if (launcher) {
48
+ const prepared = await launcher.prepare({ kind, targetCommand: [...targetCommand] });
49
+ if (!prepared.command.length) {
50
+ await prepared.dispose?.();
51
+ throw new Error("launcher returned an empty command");
52
+ }
53
+ if (prepared.spawnEnv == null) {
54
+ await prepared.dispose?.();
55
+ throw new Error("launcher must return a complete spawnEnv");
56
+ }
57
+ return prepared;
58
+ }
59
+
60
+ const command = kind === "acp"
61
+ ? buildSpawnCommand(legacy.adapter, legacy.execPrefix)
62
+ : buildPtyCommand(legacy.adapter, legacy.execPrefix);
63
+ const env = {
64
+ ...(process.env as Record<string, string>),
65
+ ...(legacy.env ?? {}),
66
+ };
67
+ if (kind === "pty") env.TERM = legacy.env?.TERM ?? "xterm-color";
68
+
69
+ return {
70
+ command,
71
+ // This inference exists only in the compatibility adapter. Explicit launchers own cwd.
72
+ spawnCwd: kind === "acp" && command[0] === "docker" ? undefined : legacy.cwd,
73
+ spawnEnv: env,
74
+ };
75
+ }
76
+
77
+ /** Wrap a prepared launch's cleanup in an exactly-once async operation. */
78
+ export function onceDispose(dispose?: PreparedLaunch["dispose"]): () => Promise<void> {
79
+ let result: Promise<void> | null = null;
80
+ return () => {
81
+ result ??= Promise.resolve().then(async () => {
82
+ await dispose?.();
83
+ });
84
+ return result;
85
+ };
86
+ }
@@ -6,6 +6,7 @@
6
6
  import * as acp from "@agentclientprotocol/sdk";
7
7
  import type * as schema from "@agentclientprotocol/sdk";
8
8
  import { ProcessCrashError } from "../errors.ts";
9
+ import { onceDispose, type PreparedLaunch } from "../launcher.ts";
9
10
  import type { WireEntry } from "../types.ts";
10
11
 
11
12
  /** The five `terminal/*` methods a client that advertises `terminal: true` must serve. */
@@ -20,11 +21,8 @@ export interface TerminalHandlers {
20
21
  }
21
22
 
22
23
  export interface AcpTransportOptions {
23
- /** Full command to spawn: [...execPrefix, ...adapter.command]. */
24
- command: string[];
25
- /** cwd for the spawned process. Omit for `docker exec` (host path won't resolve in-container). */
26
- cwd?: string;
27
- env?: Record<string, string>;
24
+ /** Exact host-side process launch, already resolved by the caller's launcher. */
25
+ launch: PreparedLaunch;
28
26
 
29
27
  /**
30
28
  * A session/update notification arrived, exactly as the agent sent it — the transport
@@ -67,8 +65,11 @@ export class AcpTransport {
67
65
  private connection: acp.ClientSideConnection | null = null;
68
66
  private stopping = false;
69
67
  private tap?: (dir: WireEntry["dir"], line: string) => void;
68
+ private readonly disposeLaunch: () => Promise<void>;
70
69
 
71
- constructor(private opts: AcpTransportOptions) {}
70
+ constructor(private opts: AcpTransportOptions) {
71
+ this.disposeLaunch = onceDispose(opts.launch.dispose);
72
+ }
72
73
 
73
74
  async start(): Promise<void> {
74
75
  if (this.proc) return;
@@ -77,54 +78,90 @@ export class AcpTransport {
77
78
  // Bun's FileSink (from stdin:"pipe") lacks getWriter().
78
79
  const stdinTransform = new TransformStream<Uint8Array, Uint8Array>();
79
80
 
80
- const proc = Bun.spawn(this.opts.command, {
81
- cwd: this.opts.cwd,
82
- env: { ...process.env, ...(this.opts.env ?? {}) },
83
- stdin: stdinTransform.readable,
84
- stdout: "pipe",
85
- stderr: "pipe",
86
- });
81
+ let proc: ReturnType<typeof Bun.spawn>;
82
+ try {
83
+ proc = Bun.spawn(this.opts.launch.command, {
84
+ cwd: this.opts.launch.spawnCwd,
85
+ env: this.opts.launch.spawnEnv,
86
+ stdin: stdinTransform.readable,
87
+ stdout: "pipe",
88
+ stderr: "pipe",
89
+ });
90
+ } catch (error) {
91
+ await this.disposeLaunch().catch(() => {});
92
+ throw error;
93
+ }
87
94
  this.proc = proc;
88
95
 
89
- const wire = this.opts.onWire;
90
- const tap = wire ? (dir: WireEntry["dir"], line: string) => wire({ dir, ts: Date.now(), line }) : undefined;
96
+ try {
97
+ const wire = this.opts.onWire;
98
+ const tap = wire ? (dir: WireEntry["dir"], line: string) => wire({ dir, ts: Date.now(), line }) : undefined;
91
99
 
92
- const stream = acp.ndJsonStream(
93
- // Outgoing bytes are forwarded untouched; the tap only reads them on the way past.
94
- tap ? tapOutgoing(stdinTransform.writable, (line) => tap("out", line)) : stdinTransform.writable,
95
- interceptUpdates(
96
- proc.stdout as ReadableStream<Uint8Array>,
97
- (m) => this.opts.onUpdate?.(m.params as schema.SessionNotification),
98
- tap && ((line) => tap("in", line)),
99
- ),
100
- );
101
- this.tap = tap;
102
- const handler = new ClientHandler(this.opts);
103
- this.connection = new acp.ClientSideConnection(() => handler, stream);
100
+ const stream = acp.ndJsonStream(
101
+ // Outgoing bytes are forwarded untouched; the tap only reads them on the way past.
102
+ tap ? tapOutgoing(stdinTransform.writable, (line) => tap("out", line)) : stdinTransform.writable,
103
+ interceptUpdates(
104
+ proc.stdout as ReadableStream<Uint8Array>,
105
+ (m) => this.opts.onUpdate?.(m.params as schema.SessionNotification),
106
+ tap && ((line) => tap("in", line)),
107
+ ),
108
+ );
109
+ this.tap = tap;
110
+ const handler = new ClientHandler(this.opts);
111
+ this.connection = new acp.ClientSideConnection(() => handler, stream);
104
112
 
105
- if (proc.stderr) this.pumpStderr(proc.stderr as ReadableStream<Uint8Array>);
113
+ if (proc.stderr) this.pumpStderr(proc.stderr as ReadableStream<Uint8Array>);
106
114
 
107
- proc.exited
108
- .then((code) => {
109
- if (this.proc === proc && !this.stopping) {
110
- this.proc = null;
111
- this.connection = null;
112
- this.opts.onCrash?.(code ?? null);
113
- }
114
- })
115
- .catch(() => {});
115
+ proc.exited
116
+ .then(async (code) => {
117
+ if (this.proc === proc && !this.stopping) {
118
+ this.proc = null;
119
+ this.connection = null;
120
+ await this.disposeLaunch().catch(() => {});
121
+ this.opts.onCrash?.(code ?? null);
122
+ }
123
+ }, async () => {
124
+ if (this.proc === proc && !this.stopping) {
125
+ this.proc = null;
126
+ this.connection = null;
127
+ await this.disposeLaunch().catch(() => {});
128
+ this.opts.onCrash?.(null);
129
+ }
130
+ })
131
+ .catch(() => {});
132
+ } catch (error) {
133
+ await this.stop().catch(() => {});
134
+ throw error;
135
+ }
116
136
  }
117
137
 
118
138
  async stop(): Promise<void> {
119
139
  this.stopping = true;
120
- if (!this.proc) return;
140
+ const proc = this.proc;
141
+ this.proc = null;
142
+ this.connection = null;
143
+ if (!proc) {
144
+ await this.disposeLaunch();
145
+ return;
146
+ }
121
147
  try {
122
- this.proc.kill("SIGTERM");
148
+ proc.kill("SIGTERM");
123
149
  } catch {
124
150
  /* already exited */
125
151
  }
126
- this.proc = null;
127
- this.connection = null;
152
+ const exited = await Promise.race([
153
+ proc.exited.then(() => true, () => true),
154
+ new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 500)),
155
+ ]);
156
+ if (!exited) {
157
+ try {
158
+ proc.kill("SIGKILL");
159
+ } catch {
160
+ /* already exited */
161
+ }
162
+ await proc.exited.catch(() => {});
163
+ }
164
+ await this.disposeLaunch();
128
165
  }
129
166
 
130
167
  private conn(): acp.ClientSideConnection {