@qlairoslabs/acp-client 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG-consumer-fixes.md +62 -0
  2. package/CHANGELOG-operation-lifecycle.md +64 -0
  3. package/CONSUMER_GUIDE.md +288 -12
  4. package/MIGRATION-0.10-to-0.12.md +189 -0
  5. package/README.md +6 -3
  6. package/package.json +5 -2
  7. package/src/adapters.ts +8 -1
  8. package/src/agent/adoption/replay.ts +1 -0
  9. package/src/agent/config.ts +4 -0
  10. package/src/agent/conversation-manager.ts +178 -150
  11. package/src/agent/error-record-writer.ts +77 -0
  12. package/src/agent/persisted-lifecycle.ts +152 -35
  13. package/src/agent/record-capture.ts +18 -18
  14. package/src/agent-adapter-registry.ts +2 -0
  15. package/src/agent-client.ts +9 -3
  16. package/src/agent-conversation-contracts.ts +6 -0
  17. package/src/agent-conversation-owner.ts +31 -6
  18. package/src/agent-conversation-presentation.ts +12 -1
  19. package/src/agent-conversation-queue.ts +3 -2
  20. package/src/agent-session.ts +535 -94
  21. package/src/agent.ts +46 -23
  22. package/src/audit/config.ts +4 -0
  23. package/src/audit/projection.ts +3 -0
  24. package/src/checkpointing/recovery.ts +12 -0
  25. package/src/checkpointing/strategy.ts +2 -0
  26. package/src/client.ts +132 -30
  27. package/src/controller.ts +116 -7
  28. package/src/degraded/pty-client.ts +25 -1
  29. package/src/index.ts +17 -0
  30. package/src/internal-inference/config.ts +7 -0
  31. package/src/internal-inference/contracts.ts +3 -0
  32. package/src/internal-inference/coordination/handles.ts +11 -2
  33. package/src/internal-inference/coordination/manager.ts +20 -3
  34. package/src/internal-inference/index.ts +2 -0
  35. package/src/internal-inference/persistence/records.ts +3 -1
  36. package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
  37. package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
  38. package/src/internal-inference/runtime/harness-runtime.ts +19 -2
  39. package/src/media/acp.ts +118 -0
  40. package/src/media/capture.ts +15 -0
  41. package/src/media/content.ts +142 -0
  42. package/src/media/files.ts +28 -0
  43. package/src/media/parts.ts +145 -0
  44. package/src/media/pending.ts +51 -0
  45. package/src/media/redact.ts +14 -0
  46. package/src/media/store.ts +127 -0
  47. package/src/metering/provider.ts +8 -1
  48. package/src/operations/activity-tracker.ts +31 -0
  49. package/src/operations/contracts.ts +63 -0
  50. package/src/operations/errors.ts +31 -0
  51. package/src/operations/index.ts +6 -0
  52. package/src/operations/stale-policy.ts +51 -0
  53. package/src/operations/supervisor.ts +209 -0
  54. package/src/operations/timers.ts +12 -0
  55. package/src/out-of-band-messages.ts +49 -32
  56. package/src/persistence/audit-runtime.ts +14 -2
  57. package/src/persistence/backend.ts +108 -12
  58. package/src/persistence/error-records.ts +27 -0
  59. package/src/persistence/index.ts +8 -0
  60. package/src/persistence/presentation.ts +9 -1
  61. package/src/persistence/projection.ts +20 -0
  62. package/src/persistence/records.ts +45 -6
  63. package/src/persistence/sqlite-backend.ts +207 -16
  64. package/src/persistence/sqlite-conversation-records.ts +31 -4
  65. package/src/persistence/sqlite-files.ts +95 -0
  66. package/src/persistence/sqlite-media-store.ts +67 -0
  67. package/src/persistence/sqlite-schema.ts +86 -10
  68. package/src/persistence/state-runtime.ts +2 -0
  69. package/src/persistence/timeline-reconcile.ts +21 -4
  70. package/src/persistence/transcript-reader.ts +11 -4
  71. package/src/persistence/transcript-runtime.ts +105 -12
  72. package/src/repl/repl.ts +1 -1
  73. package/src/response.ts +40 -8
  74. package/src/steering/combine.ts +11 -4
  75. package/src/steering/contracts.ts +14 -4
  76. package/src/steering/controller.ts +96 -21
  77. package/src/steering/index.ts +1 -0
  78. package/src/transport/acp-transport.ts +18 -7
  79. package/src/types.ts +7 -0
  80. package/src/updates.ts +4 -4
package/src/agent.ts CHANGED
@@ -40,6 +40,7 @@ import type {
40
40
  } from "./internal-inference/contracts.ts";
41
41
  import { DefaultInternalInferenceManager } from "./internal-inference/coordination/manager.ts";
42
42
  import { HarnessInternalInferenceRuntime } from "./internal-inference/runtime/harness-runtime.ts";
43
+ import { withoutHarnessBackgroundWork } from "./internal-inference/runtime/disposable-session-env.ts";
43
44
  import {
44
45
  ConversationCheckpointCoordinator,
45
46
  ConversationCheckpointStrategy,
@@ -57,6 +58,9 @@ import type {
57
58
  AgentConfig,
58
59
  AgentConversationManager,
59
60
  } from "./agent/config.ts";
61
+ import { forgetPendingParts } from "./media/pending.ts";
62
+ import type { AgentConversationId } from "./agent-ids.ts";
63
+ import type { MediaConfig } from "./media/store.ts";
60
64
 
61
65
  export type {
62
66
  AdoptProviderSessionConfig,
@@ -88,6 +92,7 @@ export type {
88
92
 
89
93
  /** Durable owner of one agent identity, its adapters, identity runtime, and conversations. */
90
94
  export class Agent {
95
+ readonly media: MediaConfig;
91
96
  readonly id: AgentSessionId;
92
97
  readonly persistence: PersistenceBackend;
93
98
  readonly identity: AgentIdentityRuntime;
@@ -106,6 +111,18 @@ export class Agent {
106
111
  private detachInternalInferenceAudit?: () => void;
107
112
  private closed = false;
108
113
 
114
+ /** Remove a kept copy's bytes. Records keep its metadata and a ref that now resolves to nothing. */
115
+ async deleteMedia(ref: string): Promise<void> {
116
+ await (this.media.store ?? this.persistence.media)?.delete(ref);
117
+ }
118
+
119
+ /** Remove the bytes of every copy one conversation kept, and its waiting out-of-band parts. */
120
+ async deleteMediaForConversation(owner: AgentConversationId): Promise<void> {
121
+ forgetPendingParts(this, owner);
122
+ const store = this.media.store ?? this.persistence.media;
123
+ if (store) for (const media of await store.list(owner)) await store.delete(media.ref);
124
+ }
125
+
109
126
  private constructor(
110
127
  id: AgentSessionId,
111
128
  persistence: PersistenceBackend,
@@ -115,6 +132,7 @@ export class Agent {
115
132
  private readonly auditLog: ResolvedAgentAuditLogConfig | null,
116
133
  audit: AgentAuditRuntime | undefined,
117
134
  ) {
135
+ this.media = config.media ?? {};
118
136
  this.id = id;
119
137
  this.persistence = persistence;
120
138
  this.adapters = adapters;
@@ -169,7 +187,10 @@ export class Agent {
169
187
  ...(config.capture ? { captureConfig: config.capture } : {}),
170
188
  ...(config.auditLog && config.auditLog.capture ? { auditCaptureConfig: config.auditLog.capture } : {}),
171
189
  ...(config.conversationPersistence ? { conversationPersistence: config.conversationPersistence } : {}),
172
- defaults: config.conversationDefaults ?? {},
190
+ defaults: {
191
+ ...config.conversationDefaults,
192
+ ...(config.operationLifecycle ? { operationLifecycle: config.operationLifecycle } : {}),
193
+ },
173
194
  meteringRecords: config.meteringPersistence?.meteringRecords ?? "all",
174
195
  checkpointing,
175
196
  auditLog,
@@ -197,29 +218,31 @@ export class Agent {
197
218
  if (!persistence.internalInferences) {
198
219
  throw new Error("persistence backend does not support internal inference");
199
220
  }
221
+ const suppressBackgroundWork = inferenceConfig.suppressHarnessBackgroundWork !== false;
200
222
  const runtime = settings.runtime ?? new HarnessInternalInferenceRuntime({
201
- controllerConfig: (request) => ({
202
- adapter: adapters.require(request.adapterId),
203
- adapterId: request.adapterId,
204
- ...(config.conversationDefaults?.launcher
205
- ? { launcher: config.conversationDefaults.launcher }
206
- : {}),
207
- ...(config.conversationDefaults?.execPrefix
208
- ? { execPrefix: config.conversationDefaults.execPrefix }
209
- : {}),
210
- ...(config.conversationDefaults?.env ? { env: config.conversationDefaults.env } : {}),
211
- ...(config.conversationDefaults?.cwd ? { cwd: config.conversationDefaults.cwd } : {}),
212
- ...(config.conversationDefaults?.clientInfo
213
- ? { clientInfo: config.conversationDefaults.clientInfo }
214
- : {}),
215
- ...(config.conversationDefaults?.clientCapabilities
216
- ? { clientCapabilities: config.conversationDefaults.clientCapabilities }
217
- : {}),
218
- ...(config.conversationDefaults?.logger
219
- ? { logger: config.conversationDefaults.logger }
220
- : {}),
221
- ...(config.conversationDefaults?.wire ? { wire: config.conversationDefaults.wire } : {}),
222
- }),
223
+ controllerConfig: (request) => {
224
+ const adapter = adapters.require(request.adapterId);
225
+ const defaults = config.conversationDefaults;
226
+ const launch = suppressBackgroundWork
227
+ ? withoutHarnessBackgroundWork(request.adapterId, adapter, {
228
+ ...(defaults?.env ? { env: defaults.env } : {}),
229
+ ...(defaults?.launcher ? { launcher: defaults.launcher } : {}),
230
+ })
231
+ : { env: defaults?.env, launcher: defaults?.launcher };
232
+ return {
233
+ adapter,
234
+ adapterId: request.adapterId,
235
+ operationLifecycle: config.operationLifecycle ?? defaults?.operationLifecycle,
236
+ ...(launch.launcher ? { launcher: launch.launcher } : {}),
237
+ ...(defaults?.execPrefix ? { execPrefix: defaults.execPrefix } : {}),
238
+ ...(launch.env ? { env: launch.env } : {}),
239
+ ...(defaults?.cwd ? { cwd: defaults.cwd } : {}),
240
+ ...(defaults?.clientInfo ? { clientInfo: defaults.clientInfo } : {}),
241
+ ...(defaults?.clientCapabilities ? { clientCapabilities: defaults.clientCapabilities } : {}),
242
+ ...(defaults?.logger ? { logger: defaults.logger } : {}),
243
+ ...(defaults?.wire ? { wire: defaults.wire } : {}),
244
+ };
245
+ },
223
246
  });
224
247
  const strategies = [...(inferenceConfig.strategies ?? [])];
225
248
  if (checkpointing?.enabled) {
@@ -20,6 +20,7 @@ export interface AgentAuditCaptureConfig {
20
20
  readonly thinking?: RecordCaptureLevel;
21
21
  readonly activity?: RecordCaptureLevel;
22
22
  readonly error?: RecordCaptureLevel;
23
+ readonly cancellation?: RecordCaptureLevel;
23
24
  readonly metering?: "none" | "metadata" | "summary" | "raw";
24
25
  readonly agent_lifecycle?: RecordCaptureLevel;
25
26
  readonly identity?: RecordCaptureLevel;
@@ -56,6 +57,7 @@ export interface ResolvedAgentAuditCapturePolicy {
56
57
  readonly thinking: RecordCaptureLevel;
57
58
  readonly activity: RecordCaptureLevel;
58
59
  readonly error: RecordCaptureLevel;
60
+ readonly cancellation: RecordCaptureLevel;
59
61
  readonly metering: "none" | "metadata" | "summary" | "raw";
60
62
  readonly agent_lifecycle: RecordCaptureLevel;
61
63
  readonly identity: RecordCaptureLevel;
@@ -83,6 +85,7 @@ export const DEFAULT_AGENT_AUDIT_CAPTURE: ResolvedAgentAuditCapturePolicy = Obje
83
85
  thinking: "none",
84
86
  activity: "metadata",
85
87
  error: "content",
88
+ cancellation: "metadata",
86
89
  metering: "summary",
87
90
  agent_lifecycle: "metadata",
88
91
  identity: "metadata",
@@ -170,6 +173,7 @@ export function resolveAgentAuditCapture(
170
173
  thinking: general("thinking"),
171
174
  activity: general("activity"),
172
175
  error: general("error"),
176
+ cancellation: general("cancellation"),
173
177
  metering: specialized("metering", ["none", "metadata", "summary", "raw"]),
174
178
  agent_lifecycle: general("agent_lifecycle"),
175
179
  identity: general("identity"),
@@ -101,6 +101,9 @@ function projectRecordPayload(
101
101
  ...(level !== "metadata" && record.message ? { message: record.message } : {}),
102
102
  ...(level === "raw" && record.details ? { details: json(record.details) } : {}),
103
103
  };
104
+ case "cancellation":
105
+ return { ...base, cancellationId: record.cancellationId, state: record.state, reason: record.reason,
106
+ ...(record.outcome ? { outcome: record.outcome } : {}) };
104
107
  case "metering": {
105
108
  const metering = observation.meteringRecord;
106
109
  if (level === "raw" && metering) return json(metering);
@@ -35,6 +35,16 @@ export function isMissingProviderSessionError(
35
35
  && message.toLowerCase() === "internal error: opencode service failure"
36
36
  && data?.service === "session"
37
37
  ) return true;
38
+ // Grok Build reports a session file it cannot find as a generic internal error; its error code
39
+ // `FS_NOT_FOUND` is the machine-readable signal, so match it exactly, with the message.
40
+ if (
41
+ value?.code === -32603
42
+ && message === "Path not found."
43
+ && data?.code === "FS_NOT_FOUND"
44
+ ) return true;
45
+ // ACP's standard "resource not found". This classifier only sees `session/load` failures, so the
46
+ // resource is the session (Claude reports a missing session this way).
47
+ if (value?.code === -32002) return true;
38
48
  const text = [
39
49
  message,
40
50
  safeJson(value?.data),
@@ -42,6 +52,8 @@ export function isMissingProviderSessionError(
42
52
  return [
43
53
  "failed to resolve rollout path",
44
54
  "no rollout found for thread id",
55
+ // Codex archives a deleted session; it cannot be loaded until unarchived outside the library.
56
+ "is archived. run `codex unarchive",
45
57
  "session not found",
46
58
  "unknown session",
47
59
  "no such session",
@@ -105,6 +105,8 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
105
105
  agentConversationId: conversationId,
106
106
  kind: "native_action" as const,
107
107
  timestamp: checkpoint.createdAt,
108
+ // The internal inference that wrote the summary is the operation this action belongs to.
109
+ operationId: result.internalInferenceId,
108
110
  action: "conversation_checkpoint",
109
111
  state: "completed" as const,
110
112
  output: {
package/src/client.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  // session/new|load) → prompt(). Capabilities and configOptions are populated by
6
6
  // connect() so callers can inspect them BEFORE prompting.
7
7
 
8
+ import type { OutputListener, ProviderOutput } from "./operations/contracts.ts";
8
9
  import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
9
10
  import type * as schema from "@agentclientprotocol/sdk";
10
11
  import type { Adapter } from "./adapters.ts";
@@ -37,6 +38,11 @@ import type {
37
38
  ToolContent,
38
39
  WireEntry,
39
40
  } from "./types.ts";
41
+ import { promptParts } from "./media/parts.ts";
42
+ import { resolveParts } from "./media/store.ts";
43
+ import { assertPartCapabilities, attachmentParts, partsToAcp } from "./media/acp.ts";
44
+ import { redactMedia } from "./media/redact.ts";
45
+ import type { ClientPrompt } from "./agent-client.ts";
40
46
 
41
47
  export interface AcpClientConfig {
42
48
  /** How to launch the agent binary. */
@@ -52,6 +58,8 @@ export interface AcpClientConfig {
52
58
  env?: Record<string, string>;
53
59
  /** Workspace visible to the ACP target and sent in session requests. */
54
60
  cwd?: string;
61
+ /** Additional workspace roots passed to ACP session creation and loading. */
62
+ additionalDirectories?: string[];
55
63
  /** Resume this session id when startSession() is called. */
56
64
  sessionId?: string;
57
65
  /** Policy when config.sessionId cannot be loaded. Default "new" for compatibility. */
@@ -128,6 +136,7 @@ function resolveClientHandlers(
128
136
  }
129
137
 
130
138
  export interface StartSessionOptions {
139
+ additionalDirectories?: string[];
131
140
  /** Resume this session. Defaults to config.sessionId. */
132
141
  sessionId?: string;
133
142
  /** What to do when the requested session cannot be loaded. Default config policy, then "new". */
@@ -165,7 +174,7 @@ export interface SwitchSessionOptions {
165
174
  onUpdate?: (notification: unknown) => void;
166
175
  }
167
176
 
168
- interface QueueItem {
177
+ interface QueueItem extends ClientPrompt {
169
178
  text: string;
170
179
  handlers?: PromptHandlers;
171
180
  attachments?: Attachment[];
@@ -196,6 +205,12 @@ export class AcpClient implements AgentClient {
196
205
  private _availableCommands: readonly InternalSessionCommand[] = Object.freeze([]);
197
206
  private readonly availableCommandListeners = new Set<AvailableCommandsListener>();
198
207
  private readonly usageUpdateListeners = new Set<UsageUpdateListener>();
208
+ /** The stop in progress; later operations wait on it before reconnecting. */
209
+ private stopPromise: Promise<void> | null = null;
210
+ private readonly disconnectListeners = new Set<() => void>();
211
+ /** Answers `cancelled` to each permission request still waiting on the consumer's handler. */
212
+ private readonly pendingPermissions = new Set<() => void>();
213
+ private readonly outputListeners = new Set<OutputListener>();
199
214
  /**
200
215
  * Latest usage_update seen, replayed to a late subscriber.
201
216
  *
@@ -289,12 +304,34 @@ export class AcpClient implements AgentClient {
289
304
  }
290
305
  return () => this.usageUpdateListeners.delete(listener);
291
306
  }
307
+ subscribeDisconnect(listener: () => void): () => void {
308
+ this.disconnectListeners.add(listener);
309
+ return () => this.disconnectListeners.delete(listener);
310
+ }
311
+ subscribeOutput(listener: OutputListener): () => void {
312
+ this.outputListeners.add(listener);
313
+ return () => this.outputListeners.delete(listener);
314
+ }
315
+ private notifyDisconnected(): void {
316
+ for (const listener of [...this.disconnectListeners]) {
317
+ try { listener(); } catch (error) { this.log.warn("disconnect_listener_failed", { error: String(error) }); }
318
+ }
319
+ }
320
+ private cancelPendingPermissions(): void {
321
+ for (const cancel of [...this.pendingPermissions]) cancel();
322
+ }
323
+ private emitOutput(output: ProviderOutput): void {
324
+ for (const listener of [...this.outputListeners]) {
325
+ try { listener(output); }
326
+ catch (error) { this.log.warn("output_listener_failed", { error: String(error) }); }
327
+ }
328
+ }
292
329
  get currentSessionId(): string | null {
293
330
  return this._sessionId;
294
331
  }
295
332
  /** True once connect() has spawned + initialized (a session may not exist yet). */
296
333
  get isConnected(): boolean {
297
- return this.transport !== null;
334
+ return this.transport?.isConnected ?? false;
298
335
  }
299
336
  /** True once a session has been created or loaded. */
300
337
  get hasSession(): boolean {
@@ -336,6 +373,7 @@ export class AcpClient implements AgentClient {
336
373
 
337
374
  const transport = new AcpTransport({
338
375
  launch,
376
+ onRequest: (sessionId) => this.emitOutput({ kind: "request", sessionId }),
339
377
  onUpdate: (n) => this.handleUpdate(n),
340
378
  onPermissionRequest: (p) => this.handlePermission(p),
341
379
  onReadTextFile: readHandler,
@@ -346,7 +384,12 @@ export class AcpClient implements AgentClient {
346
384
  this.log.debug("agent_stderr", { line });
347
385
  this.authStderrSink?.(line);
348
386
  },
387
+ onDisconnect: () => {
388
+ this.cancelPendingPermissions();
389
+ this.notifyDisconnected();
390
+ },
349
391
  onCrash: (code) => {
392
+ this.cancelPendingPermissions();
350
393
  this.terminals?.releaseAll();
351
394
  this.terminals = null;
352
395
  this.transport = null;
@@ -354,6 +397,7 @@ export class AcpClient implements AgentClient {
354
397
  this.commandTransition = null;
355
398
  this.setAvailableCommands([]);
356
399
  this.log.error("process_exit", { code });
400
+ this.notifyDisconnected();
357
401
  },
358
402
  });
359
403
  try {
@@ -397,6 +441,7 @@ export class AcpClient implements AgentClient {
397
441
  async startSession(options: StartSessionOptions = {}): Promise<ConnectResult> {
398
442
  const transport = this.requireTransport();
399
443
  const mcpServers = options.mcpServers ?? [];
444
+ const additionalDirectories = options.additionalDirectories ?? this.config.additionalDirectories;
400
445
  const cwd = this.config.cwd ?? process.cwd();
401
446
  const resumeId = options.sessionId ?? this.config.sessionId;
402
447
  const loadFailure = options.loadFailure ?? this.config.sessionLoadFailure ?? "new";
@@ -408,6 +453,7 @@ export class AcpClient implements AgentClient {
408
453
  try {
409
454
  const result = await this.loadSessionInternal(transport, resumeId, {
410
455
  mcpServers,
456
+ additionalDirectories,
411
457
  ...(options.onReplayUpdate ? { onUpdate: options.onReplayUpdate } : {}),
412
458
  });
413
459
  sessionId = result.sessionId;
@@ -415,12 +461,12 @@ export class AcpClient implements AgentClient {
415
461
  } catch (err) {
416
462
  this.log.warn("session_load_failed", { sessionId: resumeId, error: String(err) });
417
463
  if (loadFailure === "error") throw err;
418
- sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
464
+ sessionId = await this.newSessionInternal(transport, cwd, mcpServers, additionalDirectories);
419
465
  }
420
466
  } else if (resumeId && loadFailure === "error") {
421
467
  throw new Error("agent does not advertise session/load for the requested internal session");
422
468
  } else {
423
- sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
469
+ sessionId = await this.newSessionInternal(transport, cwd, mcpServers, additionalDirectories);
424
470
  }
425
471
 
426
472
  return { sessionId, resumed };
@@ -451,7 +497,7 @@ export class AcpClient implements AgentClient {
451
497
  sessionId,
452
498
  cwd: this.config.cwd ?? process.cwd(),
453
499
  mcpServers: options.mcpServers ?? [],
454
- additionalDirectories: options.additionalDirectories,
500
+ ...this.additionalDirectoriesParam(options.additionalDirectories ?? this.config.additionalDirectories),
455
501
  } as schema.LoadSessionRequest);
456
502
  } catch (err) {
457
503
  this.abortCommandTransition();
@@ -488,7 +534,7 @@ export class AcpClient implements AgentClient {
488
534
  sessionId,
489
535
  cwd: this.config.cwd ?? process.cwd(),
490
536
  mcpServers: options.mcpServers ?? [],
491
- additionalDirectories: options.additionalDirectories,
537
+ ...this.additionalDirectoriesParam(options.additionalDirectories ?? this.config.additionalDirectories),
492
538
  } as schema.ResumeSessionRequest);
493
539
  } catch (err) {
494
540
  this.abortCommandTransition();
@@ -537,7 +583,7 @@ export class AcpClient implements AgentClient {
537
583
  sessionId,
538
584
  cwd: this.config.cwd ?? process.cwd(),
539
585
  mcpServers: options.mcpServers ?? [],
540
- additionalDirectories: options.additionalDirectories,
586
+ ...this.additionalDirectoriesParam(options.additionalDirectories ?? this.config.additionalDirectories),
541
587
  } as schema.ForkSessionRequest);
542
588
  } catch (err) {
543
589
  this.abortCommandTransition();
@@ -611,22 +657,42 @@ export class AcpClient implements AgentClient {
611
657
  }
612
658
 
613
659
  /** Force a brand-new session, ignoring config.sessionId. Useful after authenticating. */
614
- async newSession(options: { mcpServers?: schema.McpServer[] } = {}): Promise<ConnectResult> {
660
+ async newSession(
661
+ options: { mcpServers?: schema.McpServer[]; additionalDirectories?: string[] } = {},
662
+ ): Promise<ConnectResult> {
615
663
  const transport = this.requireTransport();
616
664
  const cwd = this.config.cwd ?? process.cwd();
617
- const sessionId = await this.newSessionInternal(transport, cwd, options.mcpServers ?? []);
665
+ const additionalDirectories = options.additionalDirectories ?? this.config.additionalDirectories;
666
+ const sessionId = await this.newSessionInternal(transport, cwd, options.mcpServers ?? [], additionalDirectories);
618
667
  return { sessionId, resumed: false };
619
668
  }
620
669
 
670
+ /**
671
+ * ACP only allows `additionalDirectories` when the agent advertises it. Sending it anyway can make the
672
+ * agent refuse the whole session request (Grok answers "Invalid params"), so unadvertised directories
673
+ * are left out, with a warning: the agent then sees only its working directory.
674
+ */
675
+ private additionalDirectoriesParam(directories: string[] | undefined): { additionalDirectories?: string[] } {
676
+ if (!directories?.length) return {};
677
+ if (this._capabilities?.agent.sessionCapabilities.additionalDirectories) return { additionalDirectories: directories };
678
+ this.log.warn("additional_directories_unsupported", { directories: directories.length });
679
+ return {};
680
+ }
681
+
621
682
  private async newSessionInternal(
622
683
  transport: AcpTransport,
623
684
  cwd: string,
624
685
  mcpServers: schema.McpServer[],
686
+ additionalDirectories?: string[],
625
687
  ): Promise<string> {
626
688
  this.beginCommandTransition();
627
689
  let res: schema.NewSessionResponse;
628
690
  try {
629
- res = await transport.newSession({ cwd, mcpServers } as schema.NewSessionRequest);
691
+ res = await transport.newSession({
692
+ cwd,
693
+ mcpServers,
694
+ ...this.additionalDirectoriesParam(additionalDirectories),
695
+ } as schema.NewSessionRequest);
630
696
  } catch (err) {
631
697
  this.abortCommandTransition();
632
698
  throw err;
@@ -652,7 +718,9 @@ export class AcpClient implements AgentClient {
652
718
  if (!this._sessionId) await this.startSession();
653
719
  }
654
720
 
655
- async stop(): Promise<void> {
721
+ stop(): Promise<void> {
722
+ if (this.stopPromise) return this.stopPromise;
723
+ this.cancelPendingPermissions();
656
724
  const t = this.transport;
657
725
  this.transport = null;
658
726
  this._sessionId = null;
@@ -660,8 +728,12 @@ export class AcpClient implements AgentClient {
660
728
  this.setAvailableCommands([]);
661
729
  this.terminals?.releaseAll();
662
730
  this.terminals = null;
663
- if (t) await t.stop();
664
- this.log.info("stopped", {});
731
+ const pending = t ? t.stop() : Promise.resolve();
732
+ this.stopPromise = pending.finally(() => {
733
+ this.stopPromise = null;
734
+ this.log.info("stopped", {});
735
+ });
736
+ return this.stopPromise;
665
737
  }
666
738
 
667
739
  /** Adapt the registry to the transport's async handler shape. */
@@ -684,12 +756,16 @@ export class AcpClient implements AgentClient {
684
756
  // --- prompting ----------------------------------------------------------------
685
757
 
686
758
  prompt(
687
- text: string,
759
+ input: string | ClientPrompt,
688
760
  handlers?: PromptHandlers,
689
761
  attachments?: Attachment[],
690
762
  ): Promise<PromptResult> {
763
+ // The positional form is the compatibility signature; the object form can carry parts.
764
+ const prompt: ClientPrompt = typeof input === "string"
765
+ ? { text: input, handlers, attachments }
766
+ : { ...input, parts: promptParts(input) };
691
767
  return new Promise<PromptResult>((resolve, reject) => {
692
- this.queue.push({ text, handlers, attachments, resolve, reject });
768
+ this.queue.push({ ...prompt, text: prompt.text ?? "", resolve, reject });
693
769
  void this.pump();
694
770
  });
695
771
  }
@@ -715,15 +791,13 @@ export class AcpClient implements AgentClient {
715
791
  if (!this.transport) throw new NotConnectedError();
716
792
  await this.ensureSession(); // lazily create a session on first prompt
717
793
 
718
- const contentBlocks: schema.ContentBlock[] = [];
719
- if (item.text) contentBlocks.push({ type: "text", text: item.text });
720
- for (const att of item.attachments ?? []) {
721
- contentBlocks.push({
722
- type: "image",
723
- data: Buffer.from(att.data).toString("base64"),
724
- mimeType: att.mimeType,
725
- } as schema.ContentBlock);
726
- }
794
+ const capabilities = this._capabilities?.agent.promptCapabilities;
795
+ const parts = await resolveParts([
796
+ ...(item.parts ?? (item.text ? [{ kind: "text" as const, text: item.text }] : [])),
797
+ ...attachmentParts(item.attachments),
798
+ ], { cwd: this.config.cwd ?? process.cwd(), capabilities });
799
+ assertPartCapabilities(parts, capabilities);
800
+ const contentBlocks = partsToAcp(parts);
727
801
  if (contentBlocks.length === 0) contentBlocks.push({ type: "text", text: "" });
728
802
 
729
803
  this.active = {
@@ -733,7 +807,7 @@ export class AcpClient implements AgentClient {
733
807
  };
734
808
  const t0 = Date.now();
735
809
  this.log.debug("prompt_start", { chars: item.text.length });
736
- this.log.debug("prompt_request", { sessionId: this._sessionId, prompt: contentBlocks });
810
+ this.log.debug("prompt_request", { sessionId: this._sessionId, prompt: redactMedia(contentBlocks) });
737
811
  try {
738
812
  const res = await this.transport.prompt({
739
813
  sessionId: this._sessionId,
@@ -769,6 +843,7 @@ export class AcpClient implements AgentClient {
769
843
  }
770
844
 
771
845
  interrupt(options: InterruptOptions = {}): void {
846
+ this.cancelPendingPermissions();
772
847
  if (options.clearQueue) {
773
848
  const dropped = this.queue.splice(0);
774
849
  for (const item of dropped) {
@@ -784,7 +859,10 @@ export class AcpClient implements AgentClient {
784
859
  if (this.active && this.transport && this._sessionId) {
785
860
  this.active.cancelled = true;
786
861
  // ACP baseline: session/cancel. The in-flight prompt() then resolves naturally.
787
- void this.transport.cancel({ sessionId: this._sessionId } as schema.CancelNotification);
862
+ try {
863
+ void this.transport.cancel({ sessionId: this._sessionId } as schema.CancelNotification)
864
+ .catch((error) => this.log.warn("cancel_notification_failed", { error: String(error) }));
865
+ } catch (error) { this.log.warn("cancel_notification_failed", { error: String(error) }); }
788
866
  }
789
867
  }
790
868
 
@@ -808,6 +886,8 @@ export class AcpClient implements AgentClient {
808
886
  // Raw protocol trace (logged even outside an active turn, e.g. session/load replay).
809
887
  this.log.debug("session_update", { notification });
810
888
 
889
+ this.emitOutput({ kind: "update", sessionId: notification.sessionId ?? null,
890
+ activity: toActivityEvent(notification.update) ?? undefined });
811
891
  const update = notification.update;
812
892
  const kind = (update as Record<string, any>).sessionUpdate;
813
893
  if (
@@ -859,6 +939,9 @@ export class AcpClient implements AgentClient {
859
939
  this.active.handlers?.onChunk?.(chunk.text);
860
940
  }
861
941
  const activity = toActivityEvent(update);
942
+ // Text after a new tool call is a new message, even when the agent sends no message ids.
943
+ // Tool updates do not split: a running tool's output can arrive while the agent writes.
944
+ if (activity?.kind === "tool") this.active.response.closeMessage();
862
945
  if (activity) this.active.handlers?.onActivity?.(this.enrich(activity));
863
946
  }
864
947
 
@@ -891,11 +974,30 @@ export class AcpClient implements AgentClient {
891
974
  const handler = this.active?.handlers?.onPermissionRequest;
892
975
  const request = toPermissionRequest(params);
893
976
 
977
+ const abort = new AbortController();
978
+ let cancel!: () => void;
979
+ const cancelled = new Promise<PermissionOutcome>((resolve) => {
980
+ cancel = () => {
981
+ abort.abort();
982
+ resolve({ outcome: "cancelled" });
983
+ };
984
+ });
985
+ this.pendingPermissions.add(cancel);
986
+ this.emitOutput({ kind: "permission_started", sessionId: params.sessionId });
894
987
  let outcome: PermissionOutcome;
895
- if (handler) {
896
- outcome = await handler(request);
897
- } else {
898
- outcome = this.defaultOutcome(request);
988
+ try {
989
+ // A stopped client may still read requests the dying process wrote; they belong to no turn.
990
+ if (this.active?.cancelled || !this.transport) cancel();
991
+ outcome = await Promise.race([
992
+ cancelled,
993
+ Promise.resolve().then(() => {
994
+ if (abort.signal.aborted) return { outcome: "cancelled" as const };
995
+ return handler ? handler(request, abort.signal) : this.defaultOutcome(request);
996
+ }),
997
+ ]);
998
+ } finally {
999
+ this.pendingPermissions.delete(cancel);
1000
+ this.emitOutput({ kind: "permission_ended", sessionId: params.sessionId });
899
1001
  }
900
1002
 
901
1003
  this.log.debug("permission_response", { outcome });