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.
@@ -0,0 +1,448 @@
1
+ import { mkdtempSync, rmSync, symlinkSync } from "node:fs"
2
+ import { createRequire } from "node:module"
3
+ import { tmpdir } from "node:os"
4
+ import { join } from "node:path"
5
+ import { AcpClient } from "./acp-client.ts"
6
+ import type { AcpCatalog } from "./inventory.ts"
7
+ import { errorMessage } from "./util.ts"
8
+
9
+ /**
10
+ * One ACP agent process per distinct launch, shared by every OpenCode location.
11
+ *
12
+ * OpenCode loads this plugin once per directory, and each copy used to spawn its
13
+ * own process per agent, paying memory and startup again for every directory.
14
+ * Claude, Codex and Antigravity accept sessions in many directories from one
15
+ * process because each `session/new` carries its own `cwd`, so those agents are
16
+ * shared: `acquire` keys a client by its launch and hands out leases to it.
17
+ *
18
+ * Command Code (`cmd acp`) instead binds a process to the directory of its first
19
+ * session and refuses the others. Such agents use `dedicated`, which keeps one
20
+ * pre-started spare per template. The expensive part (`initialize`, about three
21
+ * seconds for cmd) happens before that binding, and the skills directory passed
22
+ * at spawn is only read when a session starts, so the spare is adopted by
23
+ * symlinking the caller's skills directory into its temporary directory after
24
+ * `initialize`. The link is reported through the lease's `readRoots` so the
25
+ * caller knows it is available.
26
+ *
27
+ * The pool lives on `globalThis` because every location evaluates its own copy
28
+ * of this module; a module-level singleton would give each copy its own pool.
29
+ * The symbol is keyed by ABI and package version so copies from different
30
+ * plugin versions never share a pool whose `AcpClient` they cannot use.
31
+ */
32
+
33
+ export interface AgentLaunch {
34
+ command: string
35
+ args: string[]
36
+ cwd: string
37
+ env: Record<string, string>
38
+ /** Launches with different scopes never share a process. */
39
+ scope?: string
40
+ autoApprove?: boolean
41
+ requestTimeoutMs?: number
42
+ promptTimeoutMs?: number
43
+ allowPathsOutsideCwd?: boolean
44
+ maxFileBytes?: number
45
+ }
46
+
47
+ export interface AgentSubscriber {
48
+ onLog?: (level: "debug" | "warn" | "error", message: string) => void
49
+ onExit?: (error: Error) => void
50
+ }
51
+
52
+ export interface AgentLease {
53
+ readonly client: AcpClient
54
+ /** Extra directories this client's sessions must be allowed to read (an adopted spare's skill link). */
55
+ readonly readRoots: string[]
56
+ /** Give the client back. Idempotent. */
57
+ release(): void
58
+ }
59
+
60
+ export interface DedicatedTemplate {
61
+ /** Build the launch. `skillDir` is where the agent should read skills, or undefined when skills are off. */
62
+ launch: (skillDir: string | undefined) => AgentLaunch
63
+ /** The caller's own skills directory; undefined when skills are off. */
64
+ skillDir?: string
65
+ }
66
+
67
+ export interface AgentPoolOptions {
68
+ /** Keep a shared client running this long after its last lease is released. Default 0 (stop at once). */
69
+ lingerMs?: number
70
+ /** Keep one pre-started spare client per dedicated template. Default false. */
71
+ spares?: boolean
72
+ /** Parent directory for spare skill-link directories. Default os.tmpdir(). */
73
+ tmpDir?: string
74
+ }
75
+
76
+ /** Stands in for any skills directory when keying a template, so only skills-on vs skills-off differ. */
77
+ const SKILL_PLACEHOLDER = "\u0000skill-dir\u0000"
78
+ /** How long a stopped client stays reachable from the process exit hook. */
79
+ const RETIRED_TTL_MS = 5_000
80
+ const SPARE_PREFIX = "opencode-acp-provider-spare-"
81
+
82
+ type LogLevel = "debug" | "warn" | "error"
83
+
84
+ interface SharedEntry {
85
+ client: AcpClient
86
+ subscribers: Array<{ subscriber: AgentSubscriber }>
87
+ linger?: ReturnType<typeof setTimeout>
88
+ }
89
+
90
+ interface Spare {
91
+ client: AcpClient
92
+ dir: string
93
+ link: string
94
+ owner: { subscriber?: AgentSubscriber }
95
+ }
96
+
97
+ interface DedicatedState {
98
+ /** Live dedicated leases for this template. */
99
+ interest: number
100
+ spare?: Spare
101
+ spareStop?: ReturnType<typeof setTimeout>
102
+ }
103
+
104
+ interface Dispatch {
105
+ onLog?: (level: LogLevel, message: string) => void
106
+ onExit?: (error: Error) => void
107
+ }
108
+
109
+ /** Two launches share a client exactly when this key is equal. */
110
+ function launchKey(launch: AgentLaunch) {
111
+ const sortedEnv = Object.keys(launch.env)
112
+ .sort()
113
+ .map((name) => [name, launch.env[name]])
114
+ return JSON.stringify([
115
+ launch.scope ?? null,
116
+ launch.command,
117
+ launch.args,
118
+ launch.cwd,
119
+ sortedEnv,
120
+ launch.autoApprove ?? null,
121
+ launch.requestTimeoutMs ?? null,
122
+ launch.promptTimeoutMs ?? null,
123
+ launch.allowPathsOutsideCwd ?? null,
124
+ launch.maxFileBytes ?? null,
125
+ ])
126
+ }
127
+
128
+ export class AgentPool {
129
+ /** Discovery outlives individual clients and location leases. */
130
+ readonly catalogs = new Map<string, Promise<AcpCatalog>>()
131
+ private readonly lingerMs: number
132
+ private readonly spares: boolean
133
+ private readonly tmpDir: string
134
+ private readonly shared = new Map<string, SharedEntry>()
135
+ private readonly dedicatedStates = new Map<string, DedicatedState>()
136
+ private readonly dedicatedClients = new Set<AcpClient>()
137
+ private readonly retired = new Set<AcpClient>()
138
+ private readonly retireTimers = new Set<ReturnType<typeof setTimeout>>()
139
+ private readonly dirs = new Set<string>()
140
+ private listening = false
141
+ private halted = false
142
+
143
+ constructor(options: AgentPoolOptions = {}) {
144
+ this.lingerMs = options.lingerMs ?? 0
145
+ this.spares = options.spares ?? false
146
+ this.tmpDir = options.tmpDir ?? tmpdir()
147
+ }
148
+
149
+ get stopped() {
150
+ return this.halted
151
+ }
152
+
153
+ /** Agents are spawned detached, so a lingering one must be killed by hand. */
154
+ private readonly onProcessExit = () => {
155
+ for (const client of this.knownClients()) client.killSync()
156
+ }
157
+
158
+ acquire(launch: AgentLaunch, subscriber: AgentSubscriber): AgentLease {
159
+ if (this.halted) throw new Error("ACP agent pool is stopped")
160
+ const key = launchKey(launch)
161
+ const shared = this.shared.get(key) ?? this.createSharedEntry(key, launch)
162
+ this.clearLinger(shared)
163
+
164
+ const registration = { subscriber }
165
+ shared.subscribers.push(registration)
166
+ let released = false
167
+ return {
168
+ client: shared.client,
169
+ readRoots: [],
170
+ release: () => {
171
+ if (released) return
172
+ released = true
173
+ const index = shared.subscribers.indexOf(registration)
174
+ if (index >= 0) shared.subscribers.splice(index, 1)
175
+ // stop() already retired this client and dropped the entry.
176
+ if (this.shared.get(key) !== shared || shared.subscribers.length) return
177
+ if (this.lingerMs > 0) {
178
+ // Stay in the map so a re-acquire before the timer reuses the client.
179
+ const timer = setTimeout(() => {
180
+ shared.linger = undefined
181
+ if (shared.subscribers.length || this.shared.get(key) !== shared) return
182
+ this.shared.delete(key)
183
+ this.retire(shared.client)
184
+ }, this.lingerMs)
185
+ timer.unref?.()
186
+ shared.linger = timer
187
+ } else {
188
+ this.shared.delete(key)
189
+ this.retire(shared.client)
190
+ }
191
+ },
192
+ }
193
+ }
194
+
195
+ private createSharedEntry(key: string, launch: AgentLaunch): SharedEntry {
196
+ let entry: SharedEntry
197
+ const client = this.createClient(launch, {
198
+ onLog: (level, message) => entry.subscribers[0]?.subscriber.onLog?.(level, message),
199
+ onExit: (error) => {
200
+ for (const registration of [...entry.subscribers]) registration.subscriber.onExit?.(error)
201
+ },
202
+ })
203
+ entry = { client, subscribers: [] }
204
+ this.shared.set(key, entry)
205
+ return entry
206
+ }
207
+
208
+ dedicated(template: DedicatedTemplate, subscriber: AgentSubscriber): AgentLease {
209
+ if (this.halted) throw new Error("ACP agent pool is stopped")
210
+ const key = this.templateKey(template)
211
+ let state = this.dedicatedStates.get(key)
212
+ if (!state) {
213
+ state = { interest: 0 }
214
+ this.dedicatedStates.set(key, state)
215
+ }
216
+ if (state.spareStop) {
217
+ clearTimeout(state.spareStop)
218
+ state.spareStop = undefined
219
+ }
220
+
221
+ let adopted: Spare | undefined
222
+ if (this.spares && state.spare) {
223
+ const spare = state.spare
224
+ state.spare = undefined
225
+ if (template.skillDir === undefined) {
226
+ adopted = spare
227
+ } else {
228
+ try {
229
+ symlinkSync(template.skillDir, spare.link, "dir")
230
+ adopted = spare
231
+ } catch (error) {
232
+ subscriber.onLog?.("warn", `could not adopt a warm agent: ${errorMessage(error)}`)
233
+ this.retire(spare.client)
234
+ this.removeDir(spare.dir)
235
+ }
236
+ }
237
+ if (adopted) adopted.owner.subscriber = subscriber
238
+ }
239
+
240
+ const client =
241
+ adopted?.client ??
242
+ this.createClient(template.launch(template.skillDir), {
243
+ onLog: (level, message) => subscriber.onLog?.(level, message),
244
+ onExit: (error) => subscriber.onExit?.(error),
245
+ })
246
+ this.dedicatedClients.add(client)
247
+ state.interest++
248
+ if (this.spares) {
249
+ void client
250
+ .start()
251
+ .catch(() => {})
252
+ .finally(() => this.ensureSpare(key, template))
253
+ }
254
+
255
+ const current = state
256
+ let released = false
257
+ return {
258
+ client,
259
+ readRoots: adopted ? [adopted.dir] : [],
260
+ release: () => {
261
+ if (released) return
262
+ released = true
263
+ this.dedicatedClients.delete(client)
264
+ this.retire(client)
265
+ if (adopted) this.removeDir(adopted.dir)
266
+ current.interest = Math.max(0, current.interest - 1)
267
+ if (current.interest === 0) this.stopSpareLater(current)
268
+ },
269
+ }
270
+ }
271
+
272
+ async stop(): Promise<void> {
273
+ if (this.halted) return
274
+ this.halted = true
275
+ for (const entry of this.shared.values()) this.clearLinger(entry)
276
+ for (const state of this.dedicatedStates.values()) {
277
+ if (state.spareStop) clearTimeout(state.spareStop)
278
+ state.spareStop = undefined
279
+ }
280
+ for (const timer of this.retireTimers) clearTimeout(timer)
281
+ this.retireTimers.clear()
282
+
283
+ const clients = [...this.knownClients()]
284
+ const dirs = [...this.dirs]
285
+ this.shared.clear()
286
+ this.catalogs.clear()
287
+ for (const state of this.dedicatedStates.values()) {
288
+ state.spare = undefined
289
+ state.interest = 0
290
+ }
291
+ this.dedicatedStates.clear()
292
+ this.dedicatedClients.clear()
293
+ this.dirs.clear()
294
+
295
+ const stopping = clients.map((client) => this.retire(client))
296
+ await Promise.allSettled(stopping)
297
+
298
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true })
299
+ if (this.listening) {
300
+ process.off("exit", this.onProcessExit)
301
+ this.listening = false
302
+ }
303
+ }
304
+
305
+ private templateKey(template: DedicatedTemplate) {
306
+ return launchKey(template.launch(template.skillDir === undefined ? undefined : SKILL_PLACEHOLDER))
307
+ }
308
+
309
+ private clearLinger(entry: SharedEntry) {
310
+ if (!entry.linger) return
311
+ clearTimeout(entry.linger)
312
+ entry.linger = undefined
313
+ }
314
+
315
+ /** Stop the key's spare once nothing needs it, after the shared linger. */
316
+ private stopSpareLater(state: DedicatedState) {
317
+ if (!state.spare) return
318
+ const run = () => {
319
+ state.spareStop = undefined
320
+ if (state.interest !== 0) return
321
+ const spare = state.spare
322
+ if (!spare) return
323
+ state.spare = undefined
324
+ this.retire(spare.client)
325
+ this.removeDir(spare.dir)
326
+ }
327
+ if (this.lingerMs > 0) {
328
+ const timer = setTimeout(run, this.lingerMs)
329
+ timer.unref?.()
330
+ state.spareStop = timer
331
+ } else {
332
+ run()
333
+ }
334
+ }
335
+
336
+ private ensureSpare(key: string, template: DedicatedTemplate) {
337
+ if (!this.spares || this.halted) return
338
+ const state = this.dedicatedStates.get(key)
339
+ if (!state || state.interest === 0 || state.spare) return
340
+ let dir: string | undefined
341
+ try {
342
+ dir = mkdtempSync(join(this.tmpDir, SPARE_PREFIX))
343
+ const spareDir = dir
344
+ this.dirs.add(spareDir)
345
+ const link = join(spareDir, "skills")
346
+ const holder: { spare?: Spare } = {}
347
+ const client = this.createClient(
348
+ template.launch(template.skillDir === undefined ? undefined : link),
349
+ {
350
+ onLog: (level, message) => holder.spare?.owner.subscriber?.onLog?.(level, message),
351
+ onExit: (error) => {
352
+ const spare = holder.spare
353
+ if (!spare) return
354
+ const owner = spare.owner.subscriber
355
+ if (owner) {
356
+ owner.onExit?.(error)
357
+ return
358
+ }
359
+ if (state.spare !== spare) return
360
+ state.spare = undefined
361
+ this.retire(spare.client)
362
+ this.removeDir(spare.dir)
363
+ },
364
+ },
365
+ )
366
+ const spare: Spare = { client, dir: spareDir, link, owner: {} }
367
+ holder.spare = spare
368
+ state.spare = spare
369
+ void client.start().catch(() => {
370
+ if (state.spare !== spare) return
371
+ state.spare = undefined
372
+ this.retire(client)
373
+ this.removeDir(spare.dir)
374
+ })
375
+ } catch {
376
+ if (dir) this.removeDir(dir)
377
+ }
378
+ }
379
+
380
+ private knownClients() {
381
+ const clients = new Set<AcpClient>()
382
+ for (const entry of this.shared.values()) clients.add(entry.client)
383
+ for (const client of this.dedicatedClients) clients.add(client)
384
+ for (const state of this.dedicatedStates.values()) {
385
+ if (state.spare) clients.add(state.spare.client)
386
+ }
387
+ for (const client of this.retired) clients.add(client)
388
+ return clients
389
+ }
390
+
391
+ private createClient(launch: AgentLaunch, dispatch: Dispatch) {
392
+ if (!this.listening) {
393
+ process.on("exit", this.onProcessExit)
394
+ this.listening = true
395
+ }
396
+ return new AcpClient({
397
+ command: launch.command,
398
+ args: launch.args,
399
+ cwd: launch.cwd,
400
+ env: launch.env,
401
+ autoApprove: launch.autoApprove,
402
+ requestTimeoutMs: launch.requestTimeoutMs,
403
+ promptTimeoutMs: launch.promptTimeoutMs,
404
+ allowPathsOutsideCwd: launch.allowPathsOutsideCwd,
405
+ maxFileBytes: launch.maxFileBytes,
406
+ onLog: dispatch.onLog,
407
+ onExit: dispatch.onExit,
408
+ })
409
+ }
410
+
411
+ /** Stop a client and keep it killable from the exit hook for a while. */
412
+ private retire(client: AcpClient) {
413
+ const stopping = client.stop().catch(() => {})
414
+ this.retired.add(client)
415
+ const timer = setTimeout(() => {
416
+ this.retired.delete(client)
417
+ this.retireTimers.delete(timer)
418
+ }, RETIRED_TTL_MS)
419
+ timer.unref?.()
420
+ this.retireTimers.add(timer)
421
+ return stopping
422
+ }
423
+
424
+ private removeDir(dir: string) {
425
+ this.dirs.delete(dir)
426
+ rmSync(dir, { recursive: true, force: true })
427
+ }
428
+ }
429
+
430
+ const POOLS = Symbol.for("opencode-acp-provider.agent-pools")
431
+ /** Bump when AgentPool or AcpClient change incompatibly; copies only share a pool with the same ABI and version. */
432
+ const AGENT_POOL_ABI = 3
433
+
434
+ const { version } = createRequire(import.meta.url)("../package.json") as { version: string }
435
+
436
+ function pools() {
437
+ const scope = globalThis as unknown as Record<symbol, Map<string, AgentPool> | undefined>
438
+ return (scope[POOLS] ??= new Map())
439
+ }
440
+
441
+ export function sharedAgentPool(): AgentPool {
442
+ const key = `${AGENT_POOL_ABI}:${version}`
443
+ const existing = pools().get(key)
444
+ if (existing && !existing.stopped) return existing
445
+ const pool = new AgentPool({ lingerMs: 60_000, spares: true })
446
+ pools().set(key, pool)
447
+ return pool
448
+ }