opencode-acp-provider 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -229,6 +229,8 @@ token per ACP session. Every tool is a 1:1 wrapper:
229
229
  | `session_context` | `session.context` (defaults to the calling session; bounded to recent items) |
230
230
  | `session_wait` | `session.wait` (timeout does not cancel the session) |
231
231
  | `session_interrupt` | `session.interrupt` |
232
+ | `worktree_create` | `worktree.create` for the calling session's project (returns the actual directory) |
233
+ | `worktree_remove` | `worktree.remove` |
232
234
 
233
235
  The wrapped builtins (`subagent`, `question`, `todowrite`) assert their own permissions. The
234
236
  `session_*` tools are normally client-only, so they assert a `session` permission on the target id:
@@ -240,6 +242,12 @@ resource `*`:
240
242
  { "action": "session", "resource": "*", "effect": "allow" }
241
243
  ```
242
244
 
245
+ `worktree_create` asserts a `worktree` permission on resource `*`, and `worktree_remove` on the worktree directory:
246
+
247
+ ```jsonc
248
+ { "action": "worktree", "resource": "*", "effect": "allow" }
249
+ ```
250
+
243
251
  MCP transport defaults to stdio, which runs `mcp-bridge.mjs` with `node` from `PATH`; set
244
252
  `mcpRuntime` for another runtime, or `mcpTransport: "http"` for an agent that accepts injected HTTP
245
253
  servers.
@@ -286,6 +294,20 @@ them would duplicate every OpenCode skill. A command list is per location, not p
286
294
  agents' commands are visible at once; running one on the wrong provider fails with a message naming
287
295
  the agent to switch to. Set `"commands": false` to turn this off.
288
296
 
297
+ ## Agent processes
298
+
299
+ One process per agent is shared by every OpenCode directory (Claude, Codex, Antigravity, and any
300
+ agent that takes the session `cwd`), so opening another directory does not start them again. Shared
301
+ processes start in the home directory (or `cwd`), and each session uses its own directory. After the
302
+ last directory releases an agent it keeps running for 60 s, so a reload reuses it. During a reload, a
303
+ conversation that the old plugin instance is still running is handed to the new one when its turn
304
+ ends.
305
+
306
+ Command Code (`cmd`) binds a process to one directory, so it keeps one process per directory. The
307
+ plugin keeps one pre-started spare `cmd` process (about 180 MB) that the next new directory adopts,
308
+ skipping its ~3 s startup, with its skills linked in on adoption. Set `"share": false` for other
309
+ agents that serve one directory per process.
310
+
289
311
  ## Server options
290
312
 
291
313
  | Option | Type | Meaning |
@@ -294,8 +316,9 @@ the agent to switch to. Set `"commands": false` to turn this off.
294
316
  | `name` | `string` | Provider display name. Defaults to `<id> (ACP)`. |
295
317
  | `command` | `string \| string[]` | Required. Command that starts the ACP agent, e.g. `["cmd", "acp"]`. |
296
318
  | `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. |
319
+ | `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
320
  | `env` | `object` | Extra environment variables for the agent process, including any API key the agent reads. |
321
+ | `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
322
  | `models` | `string[]` | Optional allowlist of model ids to expose. An agent without a model selector only exposes `default`. |
300
323
  | `model` | `string` | Default ACP model for the server. If the agent has no ACP model selector, omit this or use `default`. |
301
324
  | `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. |
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.0",
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": {
package/src/acp-client.ts CHANGED
@@ -181,8 +181,21 @@ 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 object that opened this session, usually the server manager. A call
186
+ * matches the session when it passes no owner, when the session has no
187
+ * owner, or when both are the same object; a mismatched call is refused.
188
+ */
189
+ owner?: object
190
+ /**
191
+ * The session's running prompt request, with rejections swallowed, so a new
192
+ * owner can wait for the turn to end before taking the session over.
193
+ */
194
+ turn?: Promise<unknown>
184
195
  onUpdate?: (update: SessionUpdate) => void
185
196
  requestPermission?: PermissionHandler
197
+ /** Called when this session's command list is advertised. */
198
+ onCommands?: (commands: AcpCommand[]) => void
186
199
  }
187
200
 
188
201
  interface RequestOptions {
@@ -224,6 +237,12 @@ export class AcpError extends Error {
224
237
  }
225
238
  }
226
239
 
240
+ /** True for an AcpError, including one built by another evaluation of this module. */
241
+ export function isAcpError(error: unknown): error is AcpError {
242
+ return error instanceof AcpError ||
243
+ (error instanceof Error && error.name === "AcpError" && typeof (error as { code?: unknown }).code === "number")
244
+ }
245
+
227
246
  export class AcpClient {
228
247
  private child?: ChildProcessWithoutNullStreams
229
248
  private buffer = ""
@@ -231,10 +250,14 @@ export class AcpClient {
231
250
  private nextID = 1
232
251
  private pending = new Map<number | string, Pending>()
233
252
  private sessions = new Map<string, SessionState>()
253
+ /** Restores in flight per session id, so a takeover runs before the next restore. */
254
+ private restoring = new Map<string, Promise<unknown>>()
234
255
  /** Slash commands each session advertised in `available_commands_update`. */
235
256
  private commands = new Map<string, AcpCommand[]>()
236
257
  /** Callers waiting for a session's first command list. */
237
258
  private commandWaiters = new Map<string, (commands: AcpCommand[] | undefined) => void>()
259
+ /** Children signalled by `stop()` that have not reported `exit` yet. */
260
+ private stopping = new Set<ChildProcessWithoutNullStreams>()
238
261
  private started?: Promise<AgentHandshake>
239
262
  private handshake?: AgentHandshake
240
263
  private closed = false
@@ -249,6 +272,15 @@ export class AcpClient {
249
272
  this.options.onLog?.(level, message)
250
273
  }
251
274
 
275
+ /**
276
+ * A call may touch a session when it passes no owner, when the session has
277
+ * no owner, or when it passes the session's owner.
278
+ */
279
+ private matchesOwner(session: SessionState | undefined, owner: object | undefined) {
280
+ if (!session) return true
281
+ return owner === undefined || session.owner === undefined || session.owner === owner
282
+ }
283
+
252
284
  /** Spawn the agent and run the ACP initialize handshake, restarting if it died. */
253
285
  start(): Promise<AgentHandshake> {
254
286
  if (this.disposed) return Promise.reject(new AcpError("ACP client stopped"))
@@ -349,6 +381,9 @@ export class AcpClient {
349
381
  this.buffer = ""
350
382
  this.stderrBuffer = ""
351
383
  this.sessions.clear()
384
+ this.commands.clear()
385
+ for (const finish of [...this.commandWaiters.values()]) finish(undefined)
386
+ this.commandWaiters.clear()
352
387
  const pending = [...this.pending.values()]
353
388
  this.pending.clear()
354
389
  for (const entry of pending) entry.reject(error)
@@ -442,6 +477,7 @@ export class AcpClient {
442
477
  this.commands.set(sessionId, commands)
443
478
  this.commandWaiters.get(sessionId)?.(commands)
444
479
  this.options.onCommands?.(sessionId, commands)
480
+ this.sessions.get(sessionId)?.onCommands?.(commands)
445
481
  } else if (update.sessionUpdate === "usage_update") {
446
482
  this.log(
447
483
  "debug",
@@ -453,6 +489,7 @@ export class AcpClient {
453
489
 
454
490
  private async onRequest(message: RpcMessage) {
455
491
  const method = message.method!
492
+ const child = this.child
456
493
  try {
457
494
  if (method === "session/request_permission") {
458
495
  const params = message.params ?? {}
@@ -464,7 +501,7 @@ export class AcpClient {
464
501
  // MCP `question` tool. Never auto-approve one: the first option is an
465
502
  // answer, not permission.
466
503
  this.log("debug", `declining native ACP question: ${question}`)
467
- this.reply(message.id!, { outcome: { outcome: "cancelled" } })
504
+ this.reply(message.id!, { outcome: { outcome: "cancelled" } }, undefined, undefined, child)
468
505
  return
469
506
  }
470
507
 
@@ -486,36 +523,52 @@ export class AcpClient {
486
523
  ? await handler(info).catch(() => false)
487
524
  : false
488
525
  if (!approved || !allow?.optionId) {
489
- this.reply(message.id!, { outcome: { outcome: "cancelled" } })
526
+ this.reply(message.id!, { outcome: { outcome: "cancelled" } }, undefined, undefined, child)
490
527
  return
491
528
  }
492
529
  this.log("debug", `approving ACP permission: ${info.title}`)
493
- this.reply(message.id!, { outcome: { outcome: "selected", optionId: allow.optionId } })
530
+ this.reply(
531
+ message.id!,
532
+ { outcome: { outcome: "selected", optionId: allow.optionId } },
533
+ undefined,
534
+ undefined,
535
+ child,
536
+ )
494
537
  return
495
538
  }
496
539
 
497
540
  if (method === "fs/read_text_file") {
498
541
  const content = await this.readTextFile(message.params ?? {})
499
- this.reply(message.id!, { content })
542
+ this.reply(message.id!, { content }, undefined, undefined, child)
500
543
  return
501
544
  }
502
545
 
503
546
  if (method === "fs/write_text_file") {
504
547
  await this.writeTextFile(message.params ?? {})
505
- this.reply(message.id!, {})
548
+ this.reply(message.id!, {}, undefined, undefined, child)
506
549
  return
507
550
  }
508
551
 
509
552
  this.log("warn", `unsupported ACP client method: ${method}`)
510
- this.reply(message.id!, undefined, -32601, `Method not supported by client: ${method}`)
553
+ this.reply(message.id!, undefined, -32601, `Method not supported by client: ${method}`, child)
511
554
  } catch (error) {
512
555
  const text = errorMessage(error)
513
- const code = error instanceof AcpError ? error.code : -32603
514
- this.reply(message.id!, undefined, code, text)
556
+ const code = isAcpError(error) ? error.code : -32603
557
+ this.reply(message.id!, undefined, code, text, child)
515
558
  }
516
559
  }
517
560
 
518
- private reply(id: number | string, result: any, errorCode?: number, errorMessage?: string) {
561
+ private reply(
562
+ id: number | string,
563
+ result: any,
564
+ errorCode?: number,
565
+ errorMessage?: string,
566
+ child?: ChildProcessWithoutNullStreams,
567
+ ) {
568
+ if (child && this.child !== child) {
569
+ this.log("debug", "dropping reply to a request from a previous agent process")
570
+ return
571
+ }
519
572
  try {
520
573
  if (errorCode !== undefined) {
521
574
  this.write({ jsonrpc: "2.0", id, error: { code: errorCode, message: errorMessage ?? "error" } })
@@ -617,6 +670,10 @@ export class AcpClient {
617
670
  mcpServers?: AcpMcpServer[]
618
671
  additionalDirectories?: string[]
619
672
  meta?: Record<string, unknown>
673
+ /** The object that owns this session, e.g. the server manager that opened it. */
674
+ owner?: object
675
+ /** Called when this session's command list is advertised, including one that arrived before registration. */
676
+ onCommands?: (commands: AcpCommand[]) => void
620
677
  } = {},
621
678
  ) {
622
679
  await this.start()
@@ -636,7 +693,16 @@ export class AcpClient {
636
693
  }))
637
694
  const effort = readEffortConfig(configOptions)
638
695
 
639
- this.sessions.set(sessionId, { cwd, additionalDirectories: options.additionalDirectories, configOptions })
696
+ this.sessions.set(sessionId, {
697
+ cwd,
698
+ additionalDirectories: options.additionalDirectories,
699
+ configOptions,
700
+ owner: options.owner,
701
+ onCommands: options.onCommands,
702
+ })
703
+ // The notification can arrive before the response that names the session.
704
+ const advertised = this.commands.get(sessionId)
705
+ if (advertised) options.onCommands?.(advertised)
640
706
 
641
707
  try {
642
708
  if (options.model && !modelOption) throw new AcpError("Agent does not expose an ACP model selector", -32602)
@@ -679,12 +745,53 @@ export class AcpClient {
679
745
  mcpServers?: AcpMcpServer[]
680
746
  additionalDirectories?: string[]
681
747
  meta?: Record<string, unknown>
748
+ /** The object that owns this session now, e.g. the server manager that restored it. */
749
+ owner?: object
750
+ /** Called when this session's command list is advertised, including one that arrived before registration. */
751
+ onCommands?: (commands: AcpCommand[]) => void
752
+ },
753
+ ): Promise<"resumed" | "loaded" | undefined> {
754
+ // Restores of one session run one at a time, so a takeover cannot interleave
755
+ // with another caller's resume.
756
+ const previous = this.restoring.get(sessionId)
757
+ const restore = (async () => {
758
+ if (previous) await previous.catch(() => {})
759
+ return await this.doRestoreSession(sessionId, options)
760
+ })()
761
+ this.restoring.set(sessionId, restore)
762
+ restore
763
+ .catch(() => {})
764
+ .finally(() => {
765
+ if (this.restoring.get(sessionId) === restore) this.restoring.delete(sessionId)
766
+ })
767
+ return await restore
768
+ }
769
+
770
+ private async doRestoreSession(
771
+ sessionId: string,
772
+ options: {
773
+ cwd: string
774
+ mcpServers?: AcpMcpServer[]
775
+ additionalDirectories?: string[]
776
+ meta?: Record<string, unknown>
777
+ owner?: object
778
+ onCommands?: (commands: AcpCommand[]) => void
682
779
  },
683
780
  ): Promise<"resumed" | "loaded" | undefined> {
684
781
  const capabilities = (await this.start()).agentCapabilities
685
782
  const resume = capabilities?.sessionCapabilities?.resume !== undefined
686
783
  const load = capabilities?.loadSession === true
687
784
  if (!resume && !load) return undefined
785
+
786
+ // Whoever holds the session may still be draining a turn: let that turn end,
787
+ // then close the session so the old owner's later calls are no-ops. The
788
+ // agent persists the conversation, and the resume below reattaches it.
789
+ const existing = this.sessions.get(sessionId)
790
+ if (existing && existing.owner !== options.owner) {
791
+ await existing.turn
792
+ if (this.sessions.get(sessionId) === existing) await this.closeSession(sessionId).catch(() => {})
793
+ }
794
+
688
795
  const timeout = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
689
796
  const result = await this.request(
690
797
  resume ? "session/resume" : "session/load",
@@ -696,13 +803,29 @@ export class AcpClient {
696
803
  cwd: options.cwd,
697
804
  additionalDirectories: options.additionalDirectories,
698
805
  configOptions: result.configOptions ?? [],
806
+ owner: options.owner,
807
+ onCommands: options.onCommands,
699
808
  })
809
+ // The notification can arrive before the response that names the session.
810
+ const advertised = this.commands.get(sessionId)
811
+ if (advertised) options.onCommands?.(advertised)
700
812
  return resume ? "resumed" : "loaded"
701
813
  }
702
814
 
703
815
  /** Whether this client still holds the ACP session and can take another prompt. */
704
- hasSession(sessionId: string) {
705
- return this.sessions.has(sessionId)
816
+ hasSession(sessionId: string, owner?: object) {
817
+ const session = this.sessions.get(sessionId)
818
+ if (!session) return false
819
+ return this.matchesOwner(session, owner)
820
+ }
821
+
822
+ /** Ids of the sessions whose owner is exactly this object. */
823
+ sessionsOwnedBy(owner: object): string[] {
824
+ const owned: string[] = []
825
+ for (const [sessionId, session] of this.sessions) {
826
+ if (session.owner === owner) owned.push(sessionId)
827
+ }
828
+ return owned
706
829
  }
707
830
 
708
831
  /** Whether the agent process is running and usable. */
@@ -752,6 +875,8 @@ export class AcpClient {
752
875
  sessionId: string,
753
876
  prompt: string | ContentBlock[],
754
877
  handlers: {
878
+ /** The object that owns the session; a mismatched call is refused. */
879
+ owner?: object
755
880
  onUpdate?: (update: SessionUpdate) => void
756
881
  signal?: AbortSignal
757
882
  requestPermission?: PermissionHandler
@@ -761,6 +886,9 @@ export class AcpClient {
761
886
  const blocks: ContentBlock[] = typeof prompt === "string" ? [{ type: "text", text: prompt }] : prompt
762
887
  const session = this.sessions.get(sessionId)
763
888
  if (!session) throw new AcpError(`Unknown ACP session: ${sessionId}`)
889
+ if (!this.matchesOwner(session, handlers.owner)) {
890
+ throw new AcpError("ACP session is owned by another client", -32003)
891
+ }
764
892
  session.requestPermission = handlers.requestPermission
765
893
 
766
894
  let text = ""
@@ -773,16 +901,21 @@ export class AcpClient {
773
901
  session.onUpdate = onUpdate
774
902
 
775
903
  const promptTimeout = this.options.promptTimeoutMs ?? DEFAULT_PROMPT_TIMEOUT_MS
904
+ const request = this.request(
905
+ "session/prompt",
906
+ { sessionId, prompt: blocks },
907
+ {
908
+ timeout: promptTimeout,
909
+ signal: handlers.signal,
910
+ onAbort: () => this.cancelTurn(sessionId, handlers.owner),
911
+ },
912
+ )
913
+ // A new owner waits on this turn to know the session is free; it must never
914
+ // reject, or a taken-over turn would surface as an unhandled rejection.
915
+ const turn = request.catch(() => {})
916
+ session.turn = turn
776
917
  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
- )
918
+ const result = await request
786
919
  // Usage stays in the debug log: no ACP number is right for both of the
787
920
  // ways OpenCode reads a step's tokens (context size and spend).
788
921
  if (result?.usage || result?._meta?.usage) {
@@ -793,6 +926,7 @@ export class AcpClient {
793
926
  }
794
927
  return { stopReason: result?.stopReason ?? "end_turn", text }
795
928
  } finally {
929
+ if (session.turn === turn) session.turn = undefined
796
930
  const current = this.sessions.get(sessionId)
797
931
  if (current?.onUpdate === onUpdate) {
798
932
  current.onUpdate = undefined
@@ -802,7 +936,8 @@ export class AcpClient {
802
936
  }
803
937
 
804
938
  /** Ask the agent to end the running turn; `session/prompt` then resolves with `cancelled`. */
805
- cancelTurn(sessionId: string) {
939
+ cancelTurn(sessionId: string, owner?: object) {
940
+ if (!this.matchesOwner(this.sessions.get(sessionId), owner)) return
806
941
  try {
807
942
  this.notify("session/cancel", { sessionId })
808
943
  } catch {
@@ -839,7 +974,8 @@ export class AcpClient {
839
974
  })
840
975
  }
841
976
 
842
- async closeSession(sessionId: string) {
977
+ async closeSession(sessionId: string, owner?: object) {
978
+ if (!this.matchesOwner(this.sessions.get(sessionId), owner)) return
843
979
  this.sessions.delete(sessionId)
844
980
  this.commands.delete(sessionId)
845
981
  this.commandWaiters.delete(sessionId)
@@ -871,6 +1007,9 @@ export class AcpClient {
871
1007
  const child = this.child
872
1008
  this.child = undefined
873
1009
  if (child) {
1010
+ this.stopping.add(child)
1011
+ child.once("exit", () => this.stopping.delete(child))
1012
+ if (child.exitCode !== null || child.signalCode !== null) this.stopping.delete(child)
874
1013
  this.killChild(child, "SIGTERM")
875
1014
  const timer = setTimeout(() => {
876
1015
  if (child.exitCode === null && child.signalCode === null) this.killChild(child, "SIGKILL")
@@ -879,6 +1018,13 @@ export class AcpClient {
879
1018
  }
880
1019
  }
881
1020
 
1021
+ /** SIGKILL the agent (and its process group) right away, including one still stopping. Safe to call repeatedly; for `process.on("exit")`. */
1022
+ killSync() {
1023
+ for (const child of [this.child, ...this.stopping]) {
1024
+ if (child && child.exitCode === null && child.signalCode === null) this.killChild(child, "SIGKILL")
1025
+ }
1026
+ }
1027
+
882
1028
  /** Kill the agent and, on POSIX, any wrapper it launched in its process group. */
883
1029
  private killChild(child: ChildProcessWithoutNullStreams, signal: NodeJS.Signals) {
884
1030
  if (process.platform !== "win32" && child.pid) {