@qlairoslabs/acp-client 0.4.3 → 0.6.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/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,
@@ -20,6 +19,7 @@ import {
20
19
  import { parseConfigOptions, type ConfigOptions } from "./config-options.ts";
21
20
  import { extractResponseChunk, toActivityEvent, toAvailableCommands } from "./updates.ts";
22
21
  import { ResponseAccumulator } from "./response.ts";
22
+ import { normalizeTokenUsage } from "./metering/usage.ts";
23
23
  import { TerminalRegistry } from "./terminals.ts";
24
24
  import { readTextFile, writeTextFile } from "./fs-access.ts";
25
25
  import { NotConnectedError } from "./errors.ts";
@@ -41,11 +41,16 @@ import type {
41
41
  export interface AcpClientConfig {
42
42
  /** How to launch the agent binary. */
43
43
  adapter: Adapter;
44
- /** Prefix merged before the adapter command, e.g. ["docker","exec","-i","<ctr>"]. */
44
+ /** Runtime-specific launcher for exact ACP/PTY host process preparation. */
45
+ launcher?: AcpLauncher;
46
+ /**
47
+ * Prefix merged before the adapter command, e.g. ["docker","exec","-i","<ctr>"].
48
+ * @deprecated Use launcher.
49
+ */
45
50
  execPrefix?: string[];
46
- /** Extra env vars injected at spawn time (never sent over the protocol). */
51
+ /** @deprecated Use launcher and its exact spawnEnv. */
47
52
  env?: Record<string, string>;
48
- /** Agent workspace — passed to session/new. Also the spawn cwd unless using docker exec. */
53
+ /** Workspace visible to the ACP target and sent in session requests. */
49
54
  cwd?: string;
50
55
  /** Resume this session id when startSession() is called. */
51
56
  sessionId?: string;
@@ -59,8 +64,14 @@ export interface AcpClientConfig {
59
64
  * What we let the agent do through us: filesystem reads/writes and terminals. All
60
65
  * enabled by default. Disabling one stops us advertising it, so the agent falls back
61
66
  * to its own implementation instead of calling a method we won't answer.
67
+ * @deprecated Use clientHandlers; when a new handler selection is present it wins.
62
68
  */
63
69
  clientCapabilities?: ClientCapabilityConfig;
70
+ /**
71
+ * Client-side ACP implementations. Omitted selects the built-in host implementation;
72
+ * false disables implementation and advertisement; custom handlers are advertised.
73
+ */
74
+ clientHandlers?: AcpClientHandlers;
64
75
  /** Diagnostics sink. Omit for a silent library. */
65
76
  logger?: Logger;
66
77
  /**
@@ -71,6 +82,51 @@ export interface AcpClientConfig {
71
82
  wire?: (entry: WireEntry) => void;
72
83
  }
73
84
 
85
+ export interface FilesystemHandlers {
86
+ readTextFile?: (
87
+ params: schema.ReadTextFileRequest,
88
+ ) => Promise<schema.ReadTextFileResponse>;
89
+ writeTextFile?: (
90
+ params: schema.WriteTextFileRequest,
91
+ ) => Promise<schema.WriteTextFileResponse>;
92
+ }
93
+
94
+ export interface AcpClientHandlers {
95
+ terminal?: TerminalHandlers | false;
96
+ filesystem?: FilesystemHandlers | false;
97
+ }
98
+
99
+ interface ResolvedClientHandlers {
100
+ terminal: "builtin" | TerminalHandlers | false;
101
+ readTextFile: "builtin" | NonNullable<FilesystemHandlers["readTextFile"]> | false;
102
+ writeTextFile: "builtin" | NonNullable<FilesystemHandlers["writeTextFile"]> | false;
103
+ }
104
+
105
+ function resolveClientHandlers(
106
+ handlers: AcpClientHandlers | undefined,
107
+ legacy: ClientCapabilityConfig | undefined,
108
+ ): ResolvedClientHandlers {
109
+ const terminal = handlers?.terminal !== undefined
110
+ ? handlers.terminal
111
+ : legacy?.terminal === false ? false : "builtin";
112
+
113
+ if (handlers?.filesystem === false) {
114
+ return { terminal, readTextFile: false, writeTextFile: false };
115
+ }
116
+ if (handlers?.filesystem) {
117
+ return {
118
+ terminal,
119
+ readTextFile: handlers.filesystem.readTextFile ?? false,
120
+ writeTextFile: handlers.filesystem.writeTextFile ?? false,
121
+ };
122
+ }
123
+ return {
124
+ terminal,
125
+ readTextFile: legacy?.fs?.readTextFile === false ? false : "builtin",
126
+ writeTextFile: legacy?.fs?.writeTextFile === false ? false : "builtin",
127
+ };
128
+ }
129
+
74
130
  export interface StartSessionOptions {
75
131
  /** Resume this session. Defaults to config.sessionId. */
76
132
  sessionId?: string;
@@ -114,6 +170,15 @@ interface QueueItem {
114
170
 
115
171
  export type AvailableCommandsListener = (commands: readonly InternalSessionCommand[]) => void;
116
172
 
173
+ /**
174
+ * A raw ACP `usage_update`, with the session it named.
175
+ *
176
+ * Delivered raw rather than as an ActivityEvent because metering needs two things the
177
+ * folded event discards: ACP's absent-versus-null `cost`, and un-coerced counters (the
178
+ * activity projection defaults them to zero).
179
+ */
180
+ export type UsageUpdateListener = (update: unknown, sessionId: string | null) => void;
181
+
117
182
  interface CommandTransition {
118
183
  previous: readonly InternalSessionCommand[];
119
184
  bySession: Map<string, readonly InternalSessionCommand[]>;
@@ -125,6 +190,15 @@ export class AcpClient implements AgentClient {
125
190
  private _configOptions: ConfigOptions = new Map();
126
191
  private _availableCommands: readonly InternalSessionCommand[] = Object.freeze([]);
127
192
  private readonly availableCommandListeners = new Set<AvailableCommandsListener>();
193
+ private readonly usageUpdateListeners = new Set<UsageUpdateListener>();
194
+ /**
195
+ * Latest usage_update seen, replayed to a late subscriber.
196
+ *
197
+ * Listeners are attached after connect + session/new, so a harness that notifies during
198
+ * startup would otherwise be unobserved. Mirrors how `availableCommands` is cached and
199
+ * re-emitted on attach.
200
+ */
201
+ private lastUsageUpdate: { update: unknown; sessionId: string | null } | null = null;
128
202
  private commandTransition: CommandTransition | null = null;
129
203
  private _sessionId: string | null = null;
130
204
 
@@ -154,10 +228,18 @@ export class AcpClient implements AgentClient {
154
228
 
155
229
  private readonly log: Logger;
156
230
  private readonly clientCapabilities: ClientCapabilities;
231
+ private readonly handlers: ResolvedClientHandlers;
157
232
 
158
233
  constructor(private config: AcpClientConfig) {
159
234
  this.log = config.logger ?? noopLogger;
160
- this.clientCapabilities = buildClientCapabilities(config.clientCapabilities);
235
+ this.handlers = resolveClientHandlers(config.clientHandlers, config.clientCapabilities);
236
+ this.clientCapabilities = {
237
+ fs: {
238
+ readTextFile: this.handlers.readTextFile !== false,
239
+ writeTextFile: this.handlers.writeTextFile !== false,
240
+ },
241
+ terminal: this.handlers.terminal !== false,
242
+ };
161
243
  }
162
244
 
163
245
  // --- introspection (populated by connect) -------------------------------------
@@ -182,6 +264,26 @@ export class AcpClient implements AgentClient {
182
264
  this.availableCommandListeners.add(listener);
183
265
  return () => this.availableCommandListeners.delete(listener);
184
266
  }
267
+ /**
268
+ * Observe `usage_update` notifications — context window and provider cost.
269
+ *
270
+ * Session-scoped rather than per-turn: ACP gives no ordering guarantee between a
271
+ * prompt response and the usage update describing it, so an update can arrive well
272
+ * after the turn's handlers are gone. Routing these only through PromptHandlers would
273
+ * drop exactly the observations metering needs.
274
+ */
275
+ subscribeUsageUpdate(listener: UsageUpdateListener): () => void {
276
+ this.usageUpdateListeners.add(listener);
277
+ const buffered = this.lastUsageUpdate;
278
+ if (buffered) {
279
+ try {
280
+ listener(buffered.update, buffered.sessionId);
281
+ } catch (err) {
282
+ this.log.warn("usage_update_listener_failed", { error: String(err) });
283
+ }
284
+ }
285
+ return () => this.usageUpdateListeners.delete(listener);
286
+ }
185
287
  get currentSessionId(): string | null {
186
288
  return this._sessionId;
187
289
  }
@@ -204,13 +306,9 @@ export class AcpClient implements AgentClient {
204
306
  async connect(): Promise<Capabilities> {
205
307
  if (this.transport) return this.capabilities;
206
308
 
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
-
309
+ const launch = await prepareLaunch("acp", this.config.launcher, this.config);
212
310
  const caps = this.clientCapabilities;
213
- this.terminals = caps.terminal
311
+ this.terminals = this.handlers.terminal === "builtin"
214
312
  ? new TerminalRegistry({
215
313
  cwd: this.config.cwd,
216
314
  env: this.config.env,
@@ -218,29 +316,34 @@ export class AcpClient implements AgentClient {
218
316
  })
219
317
  : null;
220
318
 
319
+ const terminalHandlers = this.handlers.terminal === "builtin"
320
+ ? this.terminalHandlers(this.terminals!)
321
+ : this.handlers.terminal || undefined;
322
+ const readHandler = this.handlers.readTextFile === "builtin"
323
+ ? async (p: schema.ReadTextFileRequest) => ({ content: await readTextFile(p) })
324
+ : this.handlers.readTextFile || undefined;
325
+ const writeHandler = this.handlers.writeTextFile === "builtin"
326
+ ? async (p: schema.WriteTextFileRequest) => {
327
+ await writeTextFile(p);
328
+ return {};
329
+ }
330
+ : this.handlers.writeTextFile || undefined;
331
+
221
332
  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,
333
+ launch,
226
334
  onUpdate: (n) => this.handleUpdate(n),
227
335
  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,
336
+ onReadTextFile: readHandler,
337
+ onWriteTextFile: writeHandler,
338
+ terminals: terminalHandlers,
238
339
  onWire: this.config.wire,
239
340
  onStderr: (line) => {
240
341
  this.log.debug("agent_stderr", { line });
241
342
  this.authStderrSink?.(line);
242
343
  },
243
344
  onCrash: (code) => {
345
+ this.terminals?.releaseAll();
346
+ this.terminals = null;
244
347
  this.transport = null;
245
348
  this._sessionId = null;
246
349
  this.commandTransition = null;
@@ -248,28 +351,37 @@ export class AcpClient implements AgentClient {
248
351
  this.log.error("process_exit", { code });
249
352
  },
250
353
  });
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;
354
+ try {
355
+ this.log.info("connect", { command: launch.command });
356
+ await transport.start();
357
+ this.transport = transport;
358
+
359
+ const init = await transport.raceExit(
360
+ transport.initialize({
361
+ protocolVersion: PROTOCOL_VERSION,
362
+ clientCapabilities: caps as unknown as schema.ClientCapabilities,
363
+ clientInfo: this.config.clientInfo ?? {
364
+ name: "acp-lib",
365
+ title: "ACP Lib",
366
+ version: "0.1.0",
367
+ },
368
+ } as schema.InitializeRequest),
369
+ );
370
+ this._capabilities = parseCapabilities(init, caps);
371
+ this.log.info("initialized", {
372
+ agent: this._capabilities.agentInfo?.name,
373
+ protocolVersion: this._capabilities.protocolVersion,
374
+ loadSession: this._capabilities.agent.loadSession,
375
+ });
376
+ this.log.debug("initialize_response", { response: init });
377
+ return this._capabilities;
378
+ } catch (error) {
379
+ this.transport = null;
380
+ await transport.stop().catch((cleanupError) => {
381
+ this.log.warn("launch_cleanup_failed", { error: String(cleanupError) });
382
+ });
383
+ throw error;
384
+ }
273
385
  }
274
386
 
275
387
  /**
@@ -611,6 +723,10 @@ export class AcpClient implements AgentClient {
611
723
  const cancelled = this.active.cancelled;
612
724
  const text = this.active.response.text;
613
725
  const messages = this.active.response.snapshot();
726
+ // ACP usage is optional and experimental: validate rather than cast. An
727
+ // unavailable report is logged and surfaced as null — never zero-filled.
728
+ const usage = normalizeTokenUsage(res.usage);
729
+ if (!usage.ok) this.log.debug("prompt_usage_unavailable", { reason: usage.reason });
614
730
  this.log[text.length === 0 && !cancelled ? "warn" : "info"]("prompt_end", {
615
731
  stopReason: res.stopReason,
616
732
  status: cancelled ? "cancelled" : "completed",
@@ -622,7 +738,7 @@ export class AcpClient implements AgentClient {
622
738
  messages,
623
739
  stopReason: res.stopReason,
624
740
  status: cancelled ? "cancelled" : "completed",
625
- usage: (res.usage ?? null) as PromptResult["usage"],
741
+ usage: usage.ok ? usage.usage : null,
626
742
  };
627
743
  } finally {
628
744
  this.active = null;
@@ -690,6 +806,19 @@ export class AcpClient implements AgentClient {
690
806
  }
691
807
  }
692
808
 
809
+ if (kind === "usage_update") {
810
+ // Fired before the active-turn gate: a usage update is session state, and dropping
811
+ // it between turns would lose the context/cost observation entirely.
812
+ this.lastUsageUpdate = { update, sessionId: notification.sessionId ?? null };
813
+ for (const listener of [...this.usageUpdateListeners]) {
814
+ try {
815
+ listener(update, notification.sessionId ?? null);
816
+ } catch (err) {
817
+ this.log.warn("usage_update_listener_failed", { error: String(err) });
818
+ }
819
+ }
820
+ }
821
+
693
822
  if (!this.active) {
694
823
  if (this.replay && (!notification.sessionId || notification.sessionId === this.replay.sessionId)) {
695
824
  this.replay.onUpdate?.(notification);
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;
@@ -104,6 +111,10 @@ export class AgentController implements AgentClient {
104
111
  (commands: readonly InternalSessionCommand[]) => void
105
112
  >();
106
113
  private detachAvailableCommands: (() => void) | null = null;
114
+ private readonly usageUpdateListeners = new Set<
115
+ (update: unknown, sessionId: string | null) => void
116
+ >();
117
+ private detachUsageUpdates: (() => void) | null = null;
107
118
 
108
119
  constructor(private readonly config: AgentControllerConfig) {
109
120
  this.mode = config.mode ?? "normal";
@@ -158,6 +169,16 @@ export class AgentController implements AgentClient {
158
169
  return () => this.availableCommandListeners.delete(listener);
159
170
  }
160
171
 
172
+ /**
173
+ * Observe raw ACP `usage_update` notifications (context window, provider cost).
174
+ *
175
+ * Degraded (pty) mode has no ACP notifications, so this simply never fires there.
176
+ */
177
+ subscribeUsageUpdate(listener: (update: unknown, sessionId: string | null) => void): () => void {
178
+ this.usageUpdateListeners.add(listener);
179
+ return () => this.usageUpdateListeners.delete(listener);
180
+ }
181
+
161
182
  async start(): Promise<ConnectResult> {
162
183
  if (this.current) {
163
184
  return { sessionId: this.currentSessionId ?? "", resumed: this.acp?.hasSession ?? false };
@@ -196,6 +217,7 @@ export class AgentController implements AgentClient {
196
217
  const { PtyClient } = await import("./degraded/index.ts");
197
218
  const pty = new PtyClient({
198
219
  adapter: this.config.adapter,
220
+ launcher: this.config.launcher,
199
221
  execPrefix: this.config.execPrefix,
200
222
  env: this.config.env,
201
223
  cwd: this.config.cwd,
@@ -215,6 +237,8 @@ export class AgentController implements AgentClient {
215
237
  this.acp = null;
216
238
  this.detachAvailableCommands?.();
217
239
  this.detachAvailableCommands = null;
240
+ this.detachUsageUpdates?.();
241
+ this.detachUsageUpdates = null;
218
242
  this.emitAvailableCommands(NO_AVAILABLE_COMMANDS);
219
243
  if (client) await client.stop();
220
244
  }
@@ -379,6 +403,7 @@ export class AgentController implements AgentClient {
379
403
  const { PtyClient } = await import("./degraded/index.ts");
380
404
  const client = new PtyClient({
381
405
  adapter,
406
+ launcher: this.config.launcher,
382
407
  execPrefix: this.config.execPrefix,
383
408
  env: this.config.env,
384
409
  cwd: this.config.cwd,
@@ -395,6 +420,7 @@ export class AgentController implements AgentClient {
395
420
 
396
421
  const client = new AcpClient({
397
422
  adapter,
423
+ launcher: this.config.launcher,
398
424
  execPrefix: this.config.execPrefix,
399
425
  env: this.config.env,
400
426
  cwd: this.config.cwd,
@@ -403,6 +429,7 @@ export class AgentController implements AgentClient {
403
429
  defaultPermission: this.config.defaultPermission,
404
430
  clientInfo: this.config.clientInfo,
405
431
  clientCapabilities: this.config.clientCapabilities,
432
+ clientHandlers: this.config.clientHandlers,
406
433
  logger: this.config.logger,
407
434
  wire: this.config.wire,
408
435
  });
@@ -450,6 +477,20 @@ export class AgentController implements AgentClient {
450
477
  this.detachAvailableCommands = this.acp?.subscribeAvailableCommands((commands) =>
451
478
  this.emitAvailableCommands(commands)) ?? null;
452
479
  this.emitAvailableCommands(this.acp?.availableCommands ?? NO_AVAILABLE_COMMANDS);
480
+
481
+ this.detachUsageUpdates?.();
482
+ this.detachUsageUpdates =
483
+ this.acp?.subscribeUsageUpdate((update, sessionId) => {
484
+ for (const listener of [...this.usageUpdateListeners]) {
485
+ try {
486
+ listener(update, sessionId);
487
+ } catch (err) {
488
+ this.config.logger?.warn("controller_usage_update_listener_failed", {
489
+ error: String(err),
490
+ });
491
+ }
492
+ }
493
+ }) ?? null;
453
494
  }
454
495
 
455
496
  private emitAvailableCommands(commands: readonly InternalSessionCommand[]): void {
@@ -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 {