opencode-acp-provider 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -66,8 +66,8 @@ reuses the run, and a server restart runs it again.
66
66
  // any command works, e.g. preparing a config file the agent reads at startup
67
67
  {
68
68
  "id": "agy",
69
- "setup": "mkdir -p ~/.config/agy && cp ./agy.json ~/.config/agy/config.json",
70
- "command": ["agy", "acp"]
69
+ "setup": "mkdir -p ~/.gemini/config && cp ./agy-hooks.json ~/.gemini/config/hooks.json",
70
+ "command": ["agy", "acp", "--process-per-session"]
71
71
  }
72
72
  ]
73
73
  }
@@ -93,7 +93,7 @@ delegation and questions through the MCP bridge instead of a second hidden agent
93
93
  | --- | --- | --- | --- |
94
94
  | Claude Code (`claude`) | `["claude-agent-acp"]` | adapter's own login | `meta.claudeCode.options.disallowedTools` |
95
95
  | Codex (`codex`) | `["codex-acp"]` | adapter's own login | `CODEX_CONFIG` env |
96
- | Antigravity (`agy`) | `["agy", "acp"]` | `agy acp --login` or `GEMINI_API_KEY` | `PreToolUse` hook |
96
+ | Antigravity (`agy`) | `["agy", "acp", "--process-per-session"]` | `agy acp --login` or `GEMINI_API_KEY` | `PreToolUse` hook |
97
97
  | Command Code (`cmd`) | `["cmd", "acp"]` | sign in with `cmd` itself | companion mod (automatic) |
98
98
 
99
99
  ### Claude Code (`claude`)
@@ -129,15 +129,21 @@ Ships its own ACP stdio server, so it needs no adapter package:
129
129
 
130
130
  ```jsonc
131
131
  {
132
- "servers": [{ "id": "agy", "setup": "agy update", "command": ["agy", "acp"] }]
132
+ "servers": [{ "id": "agy", "setup": "agy update", "command": ["agy", "acp", "--process-per-session"] }]
133
133
  }
134
134
  ```
135
135
 
136
+ - **Session isolation.** `--process-per-session` isolates each session's worker process so the
137
+ `opencode` MCP server keeps its name across sessions (and is required for injected HTTP MCP
138
+ servers).
139
+
136
140
  - **Model ids.** The session's `model` select lists base ids without the thinking level, while
137
141
  `agy models` appends it (`<model>-high`). Use the base ids the selector lists.
138
- - **Reasoning effort.** Effort is not part of the model id: its `thought_level` select (`low`,
139
- `medium`, `high`) becomes the model variants, so `acp-agy/<base-id>#high` sets it. There is no
140
- `off` variant.
142
+ - **Reasoning effort.** Effort is not part of the model id: its `thought_level` select becomes the
143
+ model variants, so `acp-agy/<base-id>#high` sets it. The levels differ per model (some add
144
+ `xhigh`), and the orchestrator models offer none, so they show no variants and no effort is
145
+ sent. A model's own levels replace the default model's list once it is first selected, and are
146
+ cached. There is no `off` variant.
141
147
  - **Mode.** Its `mode` select (`default`, `accept-edits`, `auto`, `plan`) is not a variant; pin it
142
148
  with the server's `mode` option. Permission requests in `default` mode go through `autoApprove`.
143
149
  - **Native tools.** `agy` keeps `ask_question` plus its own subagent family (`invoke_subagent`,
@@ -220,6 +226,7 @@ token per ACP session. Every tool is a 1:1 wrapper:
220
226
  | --- | --- |
221
227
  | `models` | OpenCode's `models` tool (search, variants, pagination) |
222
228
  | `subagent` | builtin `subagent` (native child session; async with native `<subagent>` wake) |
229
+ | `subagent_list` | List available OpenCode subagents with IDs and descriptions on demand |
223
230
  | `question` | builtin `question` (native session form) |
224
231
  | `todowrite` | builtin `todowrite` (only with `experimental.todo`) |
225
232
  | `session_create` | `session.create`, then `session.prompt` when `prompt` is set (independent top-level session) |
@@ -229,6 +236,8 @@ token per ACP session. Every tool is a 1:1 wrapper:
229
236
  | `session_context` | `session.context` (defaults to the calling session; bounded to recent items) |
230
237
  | `session_wait` | `session.wait` (timeout does not cancel the session) |
231
238
  | `session_interrupt` | `session.interrupt` |
239
+ | `worktree_create` | `worktree.create` for the calling session's project (returns the actual directory) |
240
+ | `worktree_remove` | `worktree.remove` |
232
241
 
233
242
  The wrapped builtins (`subagent`, `question`, `todowrite`) assert their own permissions. The
234
243
  `session_*` tools are normally client-only, so they assert a `session` permission on the target id:
@@ -240,6 +249,12 @@ resource `*`:
240
249
  { "action": "session", "resource": "*", "effect": "allow" }
241
250
  ```
242
251
 
252
+ `worktree_create` asserts a `worktree` permission on resource `*`, and `worktree_remove` on the worktree directory:
253
+
254
+ ```jsonc
255
+ { "action": "worktree", "resource": "*", "effect": "allow" }
256
+ ```
257
+
243
258
  MCP transport defaults to stdio, which runs `mcp-bridge.mjs` with `node` from `PATH`; set
244
259
  `mcpRuntime` for another runtime, or `mcpTransport: "http"` for an agent that accepts injected HTTP
245
260
  servers.
@@ -258,7 +273,7 @@ the agent in `session/new`'s `additionalDirectories`, so each agent reads them w
258
273
 
259
274
  Skills already living in `.agents/skills` or `.claude/skills` belong to the agents and stay put.
260
275
  Skipped: no description, `opencode/autoinvoke: false`, or an ID not portable lowercase kebab-case.
261
- `"skills": false` opts a server out; `{ "skills": ["opencode"] }` allowlists specific IDs.
276
+ `"skills": false` on a server entry opts that server out; `"skills": ["opencode"]` at the plugin level allowlists specific skill IDs.
262
277
 
263
278
  `cmd` ignores `additionalDirectories` and never applies `--skill` on the ACP path, so a companion mod
264
279
  registers the directory itself; an explicit `--skill`, `--no-skills`, or `--safe-mode` wins. Native
@@ -286,6 +301,24 @@ them would duplicate every OpenCode skill. A command list is per location, not p
286
301
  agents' commands are visible at once; running one on the wrong provider fails with a message naming
287
302
  the agent to switch to. Set `"commands": false` to turn this off.
288
303
 
304
+ ## Agent processes
305
+
306
+ One process per agent is shared by every OpenCode directory (Claude, Codex, Antigravity, and any
307
+ agent that takes the session `cwd`), so opening another directory does not start them again. Shared
308
+ processes start in the home directory (or `cwd`), and each session uses its own directory. After the
309
+ last directory releases an agent it keeps running for 60 s, so a reload reuses it. During a reload, a
310
+ conversation that the old plugin instance is still running is handed to the new one when its turn
311
+ ends.
312
+
313
+ Command Code (`cmd`) binds a process to one directory, so it keeps one process per directory. The
314
+ plugin keeps one pre-started spare `cmd` process (about 180 MB) that the next new directory adopts,
315
+ skipping its ~3 s startup, with its skills linked in on adoption. Set `"share": false` for other
316
+ agents that serve one directory per process.
317
+
318
+ Model discovery runs once per agent configuration per OpenCode service process. Per-model
319
+ variants are learned on first selection and shared across locations and plugin reloads.
320
+ Restarting the service refreshes discovery. Slash commands are still discovered per location.
321
+
289
322
  ## Server options
290
323
 
291
324
  | Option | Type | Meaning |
@@ -294,8 +327,9 @@ the agent to switch to. Set `"commands": false` to turn this off.
294
327
  | `name` | `string` | Provider display name. Defaults to `<id> (ACP)`. |
295
328
  | `command` | `string \| string[]` | Required. Command that starts the ACP agent, e.g. `["cmd", "acp"]`. |
296
329
  | `setup` | `string` | Shell command run once before the agent is first spawned. See [setup](#setup). |
297
- | `cwd` | `string` | Agent working directory. Defaults to the OpenCode location. |
330
+ | `cwd` | `string` | Working directory for the agent process and its sessions. When unset, sessions use the OpenCode location, and the process starts in the home directory if it is shared across directories (else in the OpenCode location). |
298
331
  | `env` | `object` | Extra environment variables for the agent process, including any API key the agent reads. |
332
+ | `share` | `boolean` | Share one agent process across OpenCode directories. Defaults to `true`, except for Command Code (`cmd`), which binds a process to one directory and always gets its own process with a warm spare. Set `false` for other agents that serve one directory per process. See [Agent processes](#agent-processes). |
299
333
  | `models` | `string[]` | Optional allowlist of model ids to expose. An agent without a model selector only exposes `default`. |
300
334
  | `model` | `string` | Default ACP model for the server. If the agent has no ACP model selector, omit this or use `default`. |
301
335
  | `effort` | `string` | Default ACP reasoning effort for sessions without a `#variant`. `cmd` accepts `off`, `low`, `high`, `max`, or `default`. Lower is faster; `off` disables thinking. Per-model variants override this. |
@@ -310,7 +344,7 @@ the agent to switch to. Set `"commands": false` to turn this off.
310
344
  | Option | Meaning |
311
345
  | --- | --- |
312
346
  | `logLevel` | `debug`, `info` (default), `warn`, or `error`. Debug logs also go to `$OPENCODE_ACP_PROVIDER_LOG` (default `opencode-acp-provider-<uid>.log` in the OS temp directory, truncated at 10 MB). |
313
- | `includeSystem` | Include OpenCode's system message in the ACP prompt. Defaults to `false`; the agent uses its own instructions. |
347
+ | `includeSystem` | Include OpenCode's system message in the ACP prompt. Defaults to `false`; the agent uses its own instructions. Either way, the `<system-*>` blocks OpenCode puts in user messages (such as `<system-reminder>` and `<system-update>`) are always removed before the prompt reaches the agent. |
314
348
  | `historyTurns` | Turns of history replayed into a brand new ACP session. Defaults to `16`. |
315
349
  | `historyChars` | Characters of history replayed into a brand new ACP session. Defaults to `8192`. Also caps the recent conversation a `/compact` summary keeps. |
316
350
  | `maxSessions` | Pooled ACP sessions per location, including opening ones. Defaults to `32`. At capacity the least recently used idle session closes; if none is idle, a new conversation retries after a turn finishes. |
@@ -322,26 +356,23 @@ the agent to switch to. Set `"commands": false` to turn this off.
322
356
  | `initTimeoutMs` | How long one agent may take to initialize. Defaults to `20000`; a failed server is retried in the background under the same bound. |
323
357
  | `requestTimeoutMs` | Timeout for the ACP handshake and control calls such as `session/new`. Defaults to `15000`; raise it for agents that start slowly. |
324
358
  | `promptTimeoutMs` | How long one ACP turn may run. Defaults to `1800000` (30 minutes); `0` disables the cap. |
325
- | `toolCallDisplay` | `inline` (default) shows finished ACP tool calls as transcript lines; `off` hides them. |
359
+ | `toolCallDisplay` | `inline` (default) shows finished ACP tool calls as transcript lines on the fallback chat-completions route when OpenCode cannot render native tool cards; `off` hides them. |
326
360
  | `mcp` | Expose OpenCode tools to ACP agents through the MCP bridge. Defaults to `true`. |
327
361
  | `commands` | Register the agents' own slash commands as namespaced OpenCode commands. Defaults to `true`. See [Commands](#commands). |
328
362
  | `skills` | Mirror OpenCode's skills into the agents' native skill discovery. Defaults to `true`; `false` disables it, and an array such as `["opencode"]` is an allowlist. |
329
363
  | `mcpTransport` | `stdio` (default) or `http`. Use `http` only for an agent that accepts injected HTTP MCP servers. |
330
364
  | `mcpRuntime` | Runtime that executes the stdio bridge, e.g. `bun`. Defaults to `node` from `PATH`. |
331
365
 
332
- ## MCP sign-ins
366
+ ## Sign-ins and external MCP servers
333
367
 
334
368
  Each agent signs in on its own; the plugin holds no credentials for it. To pass an agent a key, set
335
369
  it in that server's `env`.
336
370
 
337
- Remote MCP servers configured in OpenCode are forwarded to every ACP agent. When OpenCode holds an
338
- OAuth sign-in for one, the plugin resolves the active grant and passes it as an `Authorization:
339
- Bearer` header on `session/new`, so the agent reuses the same login, refreshing an expired grant as it
340
- resolves. A header set explicitly in the server's `headers` wins. A server not signed in to OpenCode
341
- still starts but keeps its tools unavailable; run `opencode mcp auth <name>` (or sign in through the
342
- agent's own CLI) and the next session picks the credential up. ACP cannot update headers on a live
343
- session, so a grant that expires mid-session is not replaced until that session is recycled or a new
344
- conversation starts.
371
+ In `session/new`, the plugin only supplies its own `opencode` MCP bridge; it does not forward
372
+ OpenCode's external MCP servers. Configure any additional MCP servers directly in each agent's own
373
+ MCP configuration (for example, `agy mcp add` / `~/.gemini/config/mcp_config.json`, `claude mcp add`,
374
+ `codex mcp add`, or `cmd mcp add`) so each agent handles its own credentials and tool loading (such
375
+ as Antigravity's native lazy loading).
345
376
 
346
377
  ## Limits
347
378
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-acp-provider",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "OpenCode plugin that acts as an Agent Client Protocol (ACP) client and exposes registered ACP agents as model providers.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -28,7 +28,8 @@
28
28
  "node": ">=24"
29
29
  },
30
30
  "dependencies": {
31
- "@opencode/plugin": "latest"
31
+ "@opencode/plugin": "latest",
32
+ "effect": "4.1.0"
32
33
  },
33
34
  "devDependencies": {
34
35
  "@types/node": "^26.0.0",
package/src/acp-client.ts CHANGED
@@ -119,7 +119,7 @@ function readQuestionText(params: any, options: Array<{ optionId?: string }>): s
119
119
  return question
120
120
  }
121
121
 
122
- function readEffortConfig(configOptions: AcpConfigOption[]): AcpEffortConfig | undefined {
122
+ export function readEffortConfig(configOptions: AcpConfigOption[]): AcpEffortConfig | undefined {
123
123
  const option =
124
124
  configOptions.find((candidate) => candidate.id === "effort") ??
125
125
  configOptions.find((candidate) => candidate.category === "thought_level")
@@ -181,8 +181,31 @@ interface SessionState {
181
181
  /** Extra directories granted at session/new; readable through client fs. */
182
182
  additionalDirectories?: string[]
183
183
  configOptions: AcpConfigOption[]
184
+ /**
185
+ * The agent reported the session's options after its latest model change, so
186
+ * `configOptions` reflects the selected model's effort select (or its absence).
187
+ */
188
+ optionsConfirmed: boolean
189
+ /** An effort was set in this session, so the current effort is no longer the model's default. */
190
+ effortSet: boolean
191
+ /**
192
+ * The object that opened this session, usually the server manager. A call
193
+ * matches the session when it passes no owner, when the session has no
194
+ * owner, or when both are the same object; a mismatched call is refused.
195
+ */
196
+ owner?: object
197
+ /**
198
+ * The session's running prompt request, with rejections swallowed, so a new
199
+ * owner can wait for the turn to end before taking the session over.
200
+ */
201
+ turn?: Promise<unknown>
184
202
  onUpdate?: (update: SessionUpdate) => void
203
+ onUnsolicitedUpdate?: (update: SessionUpdate) => void
185
204
  requestPermission?: PermissionHandler
205
+ defaultRequestPermission?: PermissionHandler
206
+ onPermissionChange?: (delta: 1 | -1) => void
207
+ /** Called when this session's command list is advertised. */
208
+ onCommands?: (commands: AcpCommand[]) => void
186
209
  }
187
210
 
188
211
  interface RequestOptions {
@@ -224,6 +247,12 @@ export class AcpError extends Error {
224
247
  }
225
248
  }
226
249
 
250
+ /** True for an AcpError, including one built by another evaluation of this module. */
251
+ export function isAcpError(error: unknown): error is AcpError {
252
+ return error instanceof AcpError ||
253
+ (error instanceof Error && error.name === "AcpError" && typeof (error as { code?: unknown }).code === "number")
254
+ }
255
+
227
256
  export class AcpClient {
228
257
  private child?: ChildProcessWithoutNullStreams
229
258
  private buffer = ""
@@ -231,10 +260,14 @@ export class AcpClient {
231
260
  private nextID = 1
232
261
  private pending = new Map<number | string, Pending>()
233
262
  private sessions = new Map<string, SessionState>()
263
+ /** Restores in flight per session id, so a takeover runs before the next restore. */
264
+ private restoring = new Map<string, Promise<unknown>>()
234
265
  /** Slash commands each session advertised in `available_commands_update`. */
235
266
  private commands = new Map<string, AcpCommand[]>()
236
267
  /** Callers waiting for a session's first command list. */
237
268
  private commandWaiters = new Map<string, (commands: AcpCommand[] | undefined) => void>()
269
+ /** Children signalled by `stop()` that have not reported `exit` yet. */
270
+ private stopping = new Set<ChildProcessWithoutNullStreams>()
238
271
  private started?: Promise<AgentHandshake>
239
272
  private handshake?: AgentHandshake
240
273
  private closed = false
@@ -249,6 +282,15 @@ export class AcpClient {
249
282
  this.options.onLog?.(level, message)
250
283
  }
251
284
 
285
+ /**
286
+ * A call may touch a session when it passes no owner, when the session has
287
+ * no owner, or when it passes the session's owner.
288
+ */
289
+ private matchesOwner(session: SessionState | undefined, owner: object | undefined) {
290
+ if (!session) return true
291
+ return owner === undefined || session.owner === undefined || session.owner === owner
292
+ }
293
+
252
294
  /** Spawn the agent and run the ACP initialize handshake, restarting if it died. */
253
295
  start(): Promise<AgentHandshake> {
254
296
  if (this.disposed) return Promise.reject(new AcpError("ACP client stopped"))
@@ -349,6 +391,9 @@ export class AcpClient {
349
391
  this.buffer = ""
350
392
  this.stderrBuffer = ""
351
393
  this.sessions.clear()
394
+ this.commands.clear()
395
+ for (const finish of [...this.commandWaiters.values()]) finish(undefined)
396
+ this.commandWaiters.clear()
352
397
  const pending = [...this.pending.values()]
353
398
  this.pending.clear()
354
399
  for (const entry of pending) entry.reject(error)
@@ -442,17 +487,21 @@ export class AcpClient {
442
487
  this.commands.set(sessionId, commands)
443
488
  this.commandWaiters.get(sessionId)?.(commands)
444
489
  this.options.onCommands?.(sessionId, commands)
490
+ this.sessions.get(sessionId)?.onCommands?.(commands)
445
491
  } else if (update.sessionUpdate === "usage_update") {
446
492
  this.log(
447
493
  "debug",
448
494
  `ACP context for ${sessionId}: ${update.used ?? "?"}/${update.size ?? "?"} tokens, cost ${JSON.stringify(update.cost ?? null)}`,
449
495
  )
450
496
  }
451
- this.sessions.get(sessionId)?.onUpdate?.(update)
497
+ const session = this.sessions.get(sessionId)
498
+ if (session?.onUpdate) session.onUpdate(update)
499
+ else session?.onUnsolicitedUpdate?.(update)
452
500
  }
453
501
 
454
502
  private async onRequest(message: RpcMessage) {
455
503
  const method = message.method!
504
+ const child = this.child
456
505
  try {
457
506
  if (method === "session/request_permission") {
458
507
  const params = message.params ?? {}
@@ -464,7 +513,7 @@ export class AcpClient {
464
513
  // MCP `question` tool. Never auto-approve one: the first option is an
465
514
  // answer, not permission.
466
515
  this.log("debug", `declining native ACP question: ${question}`)
467
- this.reply(message.id!, { outcome: { outcome: "cancelled" } })
516
+ this.reply(message.id!, { outcome: { outcome: "cancelled" } }, undefined, undefined, child)
468
517
  return
469
518
  }
470
519
 
@@ -478,44 +527,68 @@ export class AcpClient {
478
527
  kind: params.toolCall?.kind,
479
528
  detail: readToolCallText(params.toolCall?.content),
480
529
  }
481
- const handler = this.sessions.get(params.sessionId)?.requestPermission
530
+ const session = this.sessions.get(params.sessionId)
531
+ const handler = session?.requestPermission ?? session?.defaultRequestPermission
482
532
  const approved =
483
533
  this.options.autoApprove !== false
484
534
  ? Boolean(allow)
485
535
  : handler
486
- ? await handler(info).catch(() => false)
536
+ ? await (async () => {
537
+ session?.onPermissionChange?.(1)
538
+ try {
539
+ return await handler(info).catch(() => false)
540
+ } finally {
541
+ session?.onPermissionChange?.(-1)
542
+ }
543
+ })()
487
544
  : false
488
545
  if (!approved || !allow?.optionId) {
489
- this.reply(message.id!, { outcome: { outcome: "cancelled" } })
546
+ this.reply(message.id!, { outcome: { outcome: "cancelled" } }, undefined, undefined, child)
490
547
  return
491
548
  }
492
549
  this.log("debug", `approving ACP permission: ${info.title}`)
493
- this.reply(message.id!, { outcome: { outcome: "selected", optionId: allow.optionId } })
550
+ this.reply(
551
+ message.id!,
552
+ { outcome: { outcome: "selected", optionId: allow.optionId } },
553
+ undefined,
554
+ undefined,
555
+ child,
556
+ )
494
557
  return
495
558
  }
496
559
 
497
560
  if (method === "fs/read_text_file") {
498
561
  const content = await this.readTextFile(message.params ?? {})
499
- this.reply(message.id!, { content })
562
+ this.reply(message.id!, { content }, undefined, undefined, child)
500
563
  return
501
564
  }
502
565
 
503
566
  if (method === "fs/write_text_file") {
504
567
  await this.writeTextFile(message.params ?? {})
505
- this.reply(message.id!, {})
568
+ this.reply(message.id!, {}, undefined, undefined, child)
506
569
  return
507
570
  }
508
571
 
509
572
  this.log("warn", `unsupported ACP client method: ${method}`)
510
- this.reply(message.id!, undefined, -32601, `Method not supported by client: ${method}`)
573
+ this.reply(message.id!, undefined, -32601, `Method not supported by client: ${method}`, child)
511
574
  } catch (error) {
512
575
  const text = errorMessage(error)
513
- const code = error instanceof AcpError ? error.code : -32603
514
- this.reply(message.id!, undefined, code, text)
576
+ const code = isAcpError(error) ? error.code : -32603
577
+ this.reply(message.id!, undefined, code, text, child)
515
578
  }
516
579
  }
517
580
 
518
- private reply(id: number | string, result: any, errorCode?: number, errorMessage?: string) {
581
+ private reply(
582
+ id: number | string,
583
+ result: any,
584
+ errorCode?: number,
585
+ errorMessage?: string,
586
+ child?: ChildProcessWithoutNullStreams,
587
+ ) {
588
+ if (child && this.child !== child) {
589
+ this.log("debug", "dropping reply to a request from a previous agent process")
590
+ return
591
+ }
519
592
  try {
520
593
  if (errorCode !== undefined) {
521
594
  this.write({ jsonrpc: "2.0", id, error: { code: errorCode, message: errorMessage ?? "error" } })
@@ -617,6 +690,16 @@ export class AcpClient {
617
690
  mcpServers?: AcpMcpServer[]
618
691
  additionalDirectories?: string[]
619
692
  meta?: Record<string, unknown>
693
+ /** The object that owns this session, e.g. the server manager that opened it. */
694
+ owner?: object
695
+ /** Called when this session's command list is advertised, including one that arrived before registration. */
696
+ onCommands?: (commands: AcpCommand[]) => void
697
+ /** Persistent listener for updates emitted when no `prompt()` turn is active. */
698
+ onUnsolicitedUpdate?: (update: SessionUpdate) => void
699
+ /** Fallback permission handler for unsolicited tool calls when `autoApprove` is false. */
700
+ requestPermission?: PermissionHandler
701
+ /** Notifies listeners when an unsolicited permission prompt starts (`1`) or settles (`-1`). */
702
+ onPermissionChange?: (delta: 1 | -1) => void
620
703
  } = {},
621
704
  ) {
622
705
  await this.start()
@@ -636,7 +719,21 @@ export class AcpClient {
636
719
  }))
637
720
  const effort = readEffortConfig(configOptions)
638
721
 
639
- this.sessions.set(sessionId, { cwd, additionalDirectories: options.additionalDirectories, configOptions })
722
+ this.sessions.set(sessionId, {
723
+ cwd,
724
+ additionalDirectories: options.additionalDirectories,
725
+ configOptions,
726
+ optionsConfirmed: Array.isArray(result.configOptions),
727
+ effortSet: false,
728
+ owner: options.owner,
729
+ onCommands: options.onCommands,
730
+ onUnsolicitedUpdate: options.onUnsolicitedUpdate,
731
+ defaultRequestPermission: options.requestPermission,
732
+ onPermissionChange: options.onPermissionChange,
733
+ })
734
+ // The notification can arrive before the response that names the session.
735
+ const advertised = this.commands.get(sessionId)
736
+ if (advertised) options.onCommands?.(advertised)
640
737
 
641
738
  try {
642
739
  if (options.model && !modelOption) throw new AcpError("Agent does not expose an ACP model selector", -32602)
@@ -679,12 +776,62 @@ export class AcpClient {
679
776
  mcpServers?: AcpMcpServer[]
680
777
  additionalDirectories?: string[]
681
778
  meta?: Record<string, unknown>
779
+ /** The object that owns this session now, e.g. the server manager that restored it. */
780
+ owner?: object
781
+ /** Called when this session's command list is advertised, including one that arrived before registration. */
782
+ onCommands?: (commands: AcpCommand[]) => void
783
+ /** Persistent listener for updates emitted when no `prompt()` turn is active. */
784
+ onUnsolicitedUpdate?: (update: SessionUpdate) => void
785
+ /** Fallback permission handler for unsolicited tool calls when `autoApprove` is false. */
786
+ requestPermission?: PermissionHandler
787
+ /** Notifies listeners when an unsolicited permission prompt starts (`1`) or settles (`-1`). */
788
+ onPermissionChange?: (delta: 1 | -1) => void
789
+ },
790
+ ): Promise<"resumed" | "loaded" | undefined> {
791
+ // Restores of one session run one at a time, so a takeover cannot interleave
792
+ // with another caller's resume.
793
+ const previous = this.restoring.get(sessionId)
794
+ const restore = (async () => {
795
+ if (previous) await previous.catch(() => {})
796
+ return await this.doRestoreSession(sessionId, options)
797
+ })()
798
+ this.restoring.set(sessionId, restore)
799
+ restore
800
+ .catch(() => {})
801
+ .finally(() => {
802
+ if (this.restoring.get(sessionId) === restore) this.restoring.delete(sessionId)
803
+ })
804
+ return await restore
805
+ }
806
+
807
+ private async doRestoreSession(
808
+ sessionId: string,
809
+ options: {
810
+ cwd: string
811
+ mcpServers?: AcpMcpServer[]
812
+ additionalDirectories?: string[]
813
+ meta?: Record<string, unknown>
814
+ owner?: object
815
+ onCommands?: (commands: AcpCommand[]) => void
816
+ onUnsolicitedUpdate?: (update: SessionUpdate) => void
817
+ requestPermission?: PermissionHandler
818
+ onPermissionChange?: (delta: 1 | -1) => void
682
819
  },
683
820
  ): Promise<"resumed" | "loaded" | undefined> {
684
821
  const capabilities = (await this.start()).agentCapabilities
685
822
  const resume = capabilities?.sessionCapabilities?.resume !== undefined
686
823
  const load = capabilities?.loadSession === true
687
824
  if (!resume && !load) return undefined
825
+
826
+ // Whoever holds the session may still be draining a turn: let that turn end,
827
+ // then close the session so the old owner's later calls are no-ops. The
828
+ // agent persists the conversation, and the resume below reattaches it.
829
+ const existing = this.sessions.get(sessionId)
830
+ if (existing && existing.owner !== options.owner) {
831
+ await existing.turn
832
+ if (this.sessions.get(sessionId) === existing) await this.closeSession(sessionId).catch(() => {})
833
+ }
834
+
688
835
  const timeout = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
689
836
  const result = await this.request(
690
837
  resume ? "session/resume" : "session/load",
@@ -696,13 +843,35 @@ export class AcpClient {
696
843
  cwd: options.cwd,
697
844
  additionalDirectories: options.additionalDirectories,
698
845
  configOptions: result.configOptions ?? [],
846
+ optionsConfirmed: Array.isArray(result.configOptions),
847
+ // An earlier process may have changed the effort of a restored session.
848
+ effortSet: true,
849
+ owner: options.owner,
850
+ onCommands: options.onCommands,
851
+ onUnsolicitedUpdate: options.onUnsolicitedUpdate,
852
+ defaultRequestPermission: options.requestPermission,
853
+ onPermissionChange: options.onPermissionChange,
699
854
  })
855
+ // The notification can arrive before the response that names the session.
856
+ const advertised = this.commands.get(sessionId)
857
+ if (advertised) options.onCommands?.(advertised)
700
858
  return resume ? "resumed" : "loaded"
701
859
  }
702
860
 
703
861
  /** Whether this client still holds the ACP session and can take another prompt. */
704
- hasSession(sessionId: string) {
705
- return this.sessions.has(sessionId)
862
+ hasSession(sessionId: string, owner?: object) {
863
+ const session = this.sessions.get(sessionId)
864
+ if (!session) return false
865
+ return this.matchesOwner(session, owner)
866
+ }
867
+
868
+ /** Ids of the sessions whose owner is exactly this object. */
869
+ sessionsOwnedBy(owner: object): string[] {
870
+ const owned: string[] = []
871
+ for (const [sessionId, session] of this.sessions) {
872
+ if (session.owner === owner) owned.push(sessionId)
873
+ }
874
+ return owned
706
875
  }
707
876
 
708
877
  /** Whether the agent process is running and usable. */
@@ -717,6 +886,19 @@ export class AcpClient {
717
886
  async setModel(sessionId: string, modelId: string, configId = "model") {
718
887
  return this.setConfigOption(sessionId, this.configOption(sessionId, "model")?.id ?? configId, modelId)
719
888
  }
889
+ /**
890
+ * The effort select the session's current model offers, as last reported by
891
+ * the agent. Undefined when the agent has not reported the options since the
892
+ * last model change; `config` is undefined when the model offers no effort.
893
+ * `defaultValue` is the model's own effort, known only until one is set.
894
+ */
895
+ observedEffort(sessionId: string) {
896
+ const session = this.sessions.get(sessionId)
897
+ if (!session?.optionsConfirmed) return undefined
898
+ const config = readEffortConfig(session.configOptions)
899
+ return { config, defaultValue: session.effortSet ? undefined : config?.currentValue }
900
+ }
901
+
720
902
  /** Set the agent's reasoning effort for a session. */
721
903
  async setEffort(sessionId: string, effort: string, configId = "effort") {
722
904
  return this.setConfigOption(sessionId, this.configOption(sessionId, "thought_level")?.id ?? configId, effort)
@@ -729,6 +911,10 @@ export class AcpClient {
729
911
  if (option?.currentValue === value) return
730
912
  const result = await this.request("session/set_config_option", { sessionId, configId, value })
731
913
  if (session) {
914
+ if (option?.category === "model" || configId === "model") session.optionsConfirmed = Array.isArray(result.configOptions)
915
+ if (option?.category === "thought_level" || configId === readEffortConfig(session.configOptions)?.configId) {
916
+ session.effortSet = true
917
+ }
732
918
  session.configOptions = Array.isArray(result.configOptions)
733
919
  ? result.configOptions
734
920
  : session.configOptions.map((current) => {
@@ -752,6 +938,8 @@ export class AcpClient {
752
938
  sessionId: string,
753
939
  prompt: string | ContentBlock[],
754
940
  handlers: {
941
+ /** The object that owns the session; a mismatched call is refused. */
942
+ owner?: object
755
943
  onUpdate?: (update: SessionUpdate) => void
756
944
  signal?: AbortSignal
757
945
  requestPermission?: PermissionHandler
@@ -761,6 +949,9 @@ export class AcpClient {
761
949
  const blocks: ContentBlock[] = typeof prompt === "string" ? [{ type: "text", text: prompt }] : prompt
762
950
  const session = this.sessions.get(sessionId)
763
951
  if (!session) throw new AcpError(`Unknown ACP session: ${sessionId}`)
952
+ if (!this.matchesOwner(session, handlers.owner)) {
953
+ throw new AcpError("ACP session is owned by another client", -32003)
954
+ }
764
955
  session.requestPermission = handlers.requestPermission
765
956
 
766
957
  let text = ""
@@ -773,16 +964,21 @@ export class AcpClient {
773
964
  session.onUpdate = onUpdate
774
965
 
775
966
  const promptTimeout = this.options.promptTimeoutMs ?? DEFAULT_PROMPT_TIMEOUT_MS
967
+ const request = this.request(
968
+ "session/prompt",
969
+ { sessionId, prompt: blocks },
970
+ {
971
+ timeout: promptTimeout,
972
+ signal: handlers.signal,
973
+ onAbort: () => this.cancelTurn(sessionId, handlers.owner),
974
+ },
975
+ )
976
+ // A new owner waits on this turn to know the session is free; it must never
977
+ // reject, or a taken-over turn would surface as an unhandled rejection.
978
+ const turn = request.catch(() => {})
979
+ session.turn = turn
776
980
  try {
777
- const result = await this.request(
778
- "session/prompt",
779
- { sessionId, prompt: blocks },
780
- {
781
- timeout: promptTimeout,
782
- signal: handlers.signal,
783
- onAbort: () => this.cancelTurn(sessionId),
784
- },
785
- )
981
+ const result = await request
786
982
  // Usage stays in the debug log: no ACP number is right for both of the
787
983
  // ways OpenCode reads a step's tokens (context size and spend).
788
984
  if (result?.usage || result?._meta?.usage) {
@@ -793,6 +989,7 @@ export class AcpClient {
793
989
  }
794
990
  return { stopReason: result?.stopReason ?? "end_turn", text }
795
991
  } finally {
992
+ if (session.turn === turn) session.turn = undefined
796
993
  const current = this.sessions.get(sessionId)
797
994
  if (current?.onUpdate === onUpdate) {
798
995
  current.onUpdate = undefined
@@ -802,7 +999,8 @@ export class AcpClient {
802
999
  }
803
1000
 
804
1001
  /** Ask the agent to end the running turn; `session/prompt` then resolves with `cancelled`. */
805
- cancelTurn(sessionId: string) {
1002
+ cancelTurn(sessionId: string, owner?: object) {
1003
+ if (!this.matchesOwner(this.sessions.get(sessionId), owner)) return
806
1004
  try {
807
1005
  this.notify("session/cancel", { sessionId })
808
1006
  } catch {
@@ -839,7 +1037,8 @@ export class AcpClient {
839
1037
  })
840
1038
  }
841
1039
 
842
- async closeSession(sessionId: string) {
1040
+ async closeSession(sessionId: string, owner?: object) {
1041
+ if (!this.matchesOwner(this.sessions.get(sessionId), owner)) return
843
1042
  this.sessions.delete(sessionId)
844
1043
  this.commands.delete(sessionId)
845
1044
  this.commandWaiters.delete(sessionId)
@@ -871,6 +1070,9 @@ export class AcpClient {
871
1070
  const child = this.child
872
1071
  this.child = undefined
873
1072
  if (child) {
1073
+ this.stopping.add(child)
1074
+ child.once("exit", () => this.stopping.delete(child))
1075
+ if (child.exitCode !== null || child.signalCode !== null) this.stopping.delete(child)
874
1076
  this.killChild(child, "SIGTERM")
875
1077
  const timer = setTimeout(() => {
876
1078
  if (child.exitCode === null && child.signalCode === null) this.killChild(child, "SIGKILL")
@@ -879,6 +1081,13 @@ export class AcpClient {
879
1081
  }
880
1082
  }
881
1083
 
1084
+ /** SIGKILL the agent (and its process group) right away, including one still stopping. Safe to call repeatedly; for `process.on("exit")`. */
1085
+ killSync() {
1086
+ for (const child of [this.child, ...this.stopping]) {
1087
+ if (child && child.exitCode === null && child.signalCode === null) this.killChild(child, "SIGKILL")
1088
+ }
1089
+ }
1090
+
882
1091
  /** Kill the agent and, on POSIX, any wrapper it launched in its process group. */
883
1092
  private killChild(child: ChildProcessWithoutNullStreams, signal: NodeJS.Signals) {
884
1093
  if (process.platform !== "win32" && child.pid) {