opencode-acp-provider 0.0.0-stage → 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/src/index.ts ADDED
@@ -0,0 +1,642 @@
1
+ import { Model, Plugin, Provider } from "@opencode/plugin"
2
+ import { createHash, randomUUID } from "node:crypto"
3
+ import { readFile } from "node:fs/promises"
4
+ import { homedir } from "node:os"
5
+ import { join } from "node:path"
6
+ import {
7
+ AcpServerManager,
8
+ type AcpCompactResult,
9
+ type AcpServerConfig,
10
+ type AcpServerState,
11
+ type AcpSessionStore,
12
+ } from "./server-manager.ts"
13
+ import { sharedAgentPool } from "./agent-pool.ts"
14
+ import { createShim } from "./shim.ts"
15
+ import { boundedMessages, historyLimits, recentConversation } from "./prompt.ts"
16
+ import { createAcpLanguageModel } from "./language-model.ts"
17
+ import { createMcpServer } from "./mcp-server.ts"
18
+ import { createOpenCodeMcpSource } from "./mcp-config.ts"
19
+ import { createSteering, type LocalService } from "./steering.ts"
20
+ import { createSkillMirror } from "./skills.ts"
21
+ import { createCommandBridge } from "./commands.ts"
22
+ import { effortLevels, readInventory, writeInventory, type AcpInventory } from "./inventory.ts"
23
+ import { debugLog } from "./debug.ts"
24
+ import { agentName, errorMessage } from "./util.ts"
25
+
26
+ type LogLevel = "debug" | "info" | "warn" | "error"
27
+
28
+ /** What a compaction did, in the agent's own words where it gave any. */
29
+ function compactionOutcome(agent: string, result: AcpCompactResult) {
30
+ if (result.status === "no-session") return `${agent} has no open session for this conversation, so nothing was compacted.`
31
+ if (result.status === "unsupported")
32
+ return `${agent} can't compact on request. It compacts its own context when it fills up, so nothing was compacted.`
33
+ const sizes = result.tokens
34
+ ? ` from ${result.tokens.before.toLocaleString("en-US")} to ${result.tokens.after.toLocaleString("en-US")} tokens`
35
+ : ""
36
+ const said = result.text ? `\n\n${agent}: ${result.text}` : ""
37
+ return `${agent} ran its own /compact${sizes}.${said}`
38
+ }
39
+
40
+ interface AcpPluginOptions {
41
+ servers?: AcpServerConfig[]
42
+ includeSystem?: boolean
43
+ logLevel?: LogLevel
44
+ /** Turns of history replayed into a brand new ACP session. Defaults to 16. */
45
+ historyTurns?: number
46
+ /** Characters of history replayed into a brand new ACP session. Defaults to 8192. */
47
+ historyChars?: number
48
+ /** Most reused ACP sessions kept alive per plugin instance. Defaults to 32. */
49
+ maxSessions?: number
50
+ /** Idle time before a reusable ACP session is closed. Defaults to 30 minutes. */
51
+ sessionIdleMs?: number
52
+ /** Let ACP agents read and write outside the session directory. Defaults to false. */
53
+ allowPathsOutsideCwd?: boolean
54
+ /** Largest file the ACP client will read on the agent's behalf. Defaults to 16 MB. */
55
+ maxFileBytes?: number
56
+ /** Largest chat-completions body accepted by the shim. Defaults to 32 MB. */
57
+ maxBodyBytes?: number
58
+ /** Output limit advertised for ACP models. Defaults to 32000. */
59
+ outputLimit?: number
60
+ /** How long to wait for one agent to initialize. Defaults to 20 seconds. */
61
+ initTimeoutMs?: number
62
+ /** Timeout for ACP handshake and control calls such as `session/new`. Defaults to 15 seconds. */
63
+ requestTimeoutMs?: number
64
+ /** How long one ACP turn may run. Defaults to 30 minutes. */
65
+ promptTimeoutMs?: number
66
+ /** Show ACP tool calls as inline transcript lines when the server cannot render native tool cards. Defaults to "inline"; "off" hides them. */
67
+ toolCallDisplay?: "off" | "inline"
68
+ /** Expose OpenCode tools to ACP agents through an MCP bridge. Defaults to true. */
69
+ mcp?: boolean
70
+ /** Expose the agents' own slash commands as namespaced OpenCode commands. Defaults to true. */
71
+ commands?: boolean
72
+ /** Make OpenCode's skills available to ACP agents through their own discovery. `false` disables it; an array is an allowlist of skill IDs. Defaults to true. */
73
+ skills?: boolean | string[]
74
+ /** MCP transport handed to ACP agents. Defaults to "stdio". */
75
+ mcpTransport?: "stdio" | "http"
76
+ /** Runtime that can execute a JavaScript file for the stdio bridge, e.g. "node". */
77
+ mcpRuntime?: string
78
+ }
79
+
80
+ const RETRY_DELAYS = [2_000, 5_000, 15_000, 30_000, 60_000]
81
+
82
+ function providerIDFor(id: string) {
83
+ return `acp-${id.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "server"}`
84
+ }
85
+
86
+ /** Storage key for one pooled ACP session; the manager's key is an opaque tuple. */
87
+ function storedSessionKey(poolKey: string) {
88
+ return `acp-session/${createHash("sha256").update(poolKey).digest("hex")}`
89
+ }
90
+
91
+
92
+ /**
93
+ * A `serve --service` server records its address and password next to its
94
+ * state, with the owning pid. Match that pid so the MCP question tool can use
95
+ * the HTTP API of the server that is hosting this plugin. Default CLI servers
96
+ * do not write the file, and the builtin question tool is used instead.
97
+ */
98
+ async function readLocalService(): Promise<LocalService | undefined> {
99
+ const candidates = new Set<string>()
100
+ const home = homedir()
101
+ if (process.env.OPENCODE_STATE_HOME) candidates.add(process.env.OPENCODE_STATE_HOME)
102
+ if (process.env.XDG_STATE_HOME) candidates.add(join(process.env.XDG_STATE_HOME, "opencode"))
103
+ candidates.add(join(home, ".local", "state", "opencode"))
104
+ candidates.add(join(home, "Library", "Application Support", "opencode"))
105
+ if (process.env.APPDATA) candidates.add(join(process.env.APPDATA, "opencode"))
106
+ if (process.env.LOCALAPPDATA) candidates.add(join(process.env.LOCALAPPDATA, "opencode"))
107
+
108
+ for (const directory of candidates) {
109
+ try {
110
+ const raw = await readFile(join(directory, "service.json"), "utf8")
111
+ const data = JSON.parse(raw) as { pid?: number; url?: unknown; password?: unknown }
112
+ if (data.pid !== process.pid) continue
113
+ if (typeof data.url !== "string" || typeof data.password !== "string") continue
114
+ return { url: data.url, password: data.password }
115
+ } catch {
116
+ // no matching service file here
117
+ }
118
+ }
119
+ return undefined
120
+ }
121
+
122
+ export default Plugin.define({
123
+ id: "acp-provider",
124
+ async setup(ctx) {
125
+ const options = (ctx.options ?? {}) as AcpPluginOptions
126
+ const servers = Array.isArray(options.servers) ? options.servers : []
127
+ if (!servers.length) return
128
+
129
+ const levels: LogLevel[] = ["debug", "info", "warn", "error"]
130
+ const minLevel =
131
+ options.logLevel && levels.includes(options.logLevel) ? levels.indexOf(options.logLevel) : 1
132
+ const debugEnabled = levels.indexOf("debug") >= minLevel
133
+ const log = (level: LogLevel, message: string) => {
134
+ if (levels.indexOf(level) < minLevel) return
135
+ debugLog(level, message)
136
+ const write = level === "error" ? console.error : console.log
137
+ write(`[acp] ${level}: ${message}`)
138
+ }
139
+ debugLog("info", "setup started")
140
+ const setupStartedAt = Date.now()
141
+
142
+ // Servers with the AI SDK hook can show the agent's own tools as native
143
+ // cards; older servers fall back to the chat-completions route and the
144
+ // inline transcript markers.
145
+ const nativeToolParts = typeof ctx.aisdk?.hook === "function"
146
+
147
+ let skills: Awaited<ReturnType<typeof createSkillMirror>> | undefined
148
+ const skillFilter = Array.isArray(options.skills) ? options.skills : undefined
149
+ const skillsEnabled = options.skills !== false && skillFilter?.length !== 0
150
+ if (skillsEnabled && servers.some((server) => server.skills !== false)) {
151
+ try {
152
+ // Kept even when empty: OpenCode discovers skills in the background,
153
+ // and the mirror picks them up on `skill.updated`.
154
+ skills = await createSkillMirror(ctx, { include: skillFilter, log })
155
+ } catch (error) {
156
+ log("warn", `OpenCode skills mirror disabled: ${errorMessage(error)}`)
157
+ }
158
+ }
159
+
160
+ let mcp: Awaited<ReturnType<typeof createMcpServer>> | undefined
161
+ if (options.mcp !== false) {
162
+ try {
163
+ mcp = await createMcpServer({
164
+ ctx,
165
+ log,
166
+ localService: () => readLocalService(),
167
+ transport: options.mcpTransport === "http" ? "http" : "stdio",
168
+ runtime: options.mcpRuntime,
169
+ })
170
+ } catch (error) {
171
+ log("warn", `OpenCode MCP bridge disabled: ${errorMessage(error)}`)
172
+ }
173
+ }
174
+
175
+ // Forward the MCP servers OpenCode is configured with so a server is set up
176
+ // once and reaches every ACP agent, alongside this plugin's own bridge.
177
+ let openCodeMcp: Awaited<ReturnType<typeof createOpenCodeMcpSource>> | undefined
178
+ try {
179
+ openCodeMcp = await createOpenCodeMcpSource(ctx, log)
180
+ } catch (error) {
181
+ log("warn", `OpenCode MCP servers disabled: ${errorMessage(error)}`)
182
+ }
183
+
184
+ // A plugin reload or a crashed agent starts a new process with no in-memory
185
+ // sessions. Persist which ACP session belongs to each OpenCode session so
186
+ // the next process can resume it instead of losing the conversation.
187
+ const sessionStore: AcpSessionStore | undefined = ctx.storage
188
+ ? {
189
+ async get(key) {
190
+ const value = await ctx.storage.get(storedSessionKey(key))
191
+ return typeof value === "string" && value ? value : undefined
192
+ },
193
+ async set(key, sessionId) {
194
+ await ctx.storage.set(storedSessionKey(key), sessionId)
195
+ },
196
+ async delete(key) {
197
+ await ctx.storage.remove(storedSessionKey(key))
198
+ },
199
+ }
200
+ : undefined
201
+
202
+ // Assigned once the agents are up and their skills are known, but the
203
+ // manager reports command updates from the first `session/new` onward.
204
+ let commandBridge: Awaited<ReturnType<typeof createCommandBridge>> | undefined
205
+
206
+ const manager = new AcpServerManager({
207
+ servers,
208
+ defaultCwd: ctx.location.directory,
209
+ log,
210
+ sessions: sessionStore,
211
+ agents: sharedAgentPool(),
212
+ onCommands: (server) => void commandBridge?.sync(server),
213
+ mcp:
214
+ mcp || openCodeMcp
215
+ ? {
216
+ servers: async (sessionKey, agent) => {
217
+ const lease = mcp?.issue(sessionKey)
218
+ try {
219
+ const configured = (await openCodeMcp?.servers(agent)) ?? []
220
+ // Let the plugin's own bridge win a name collision with a
221
+ // configured server, since that is the one agents rely on.
222
+ const taken = new Set(lease?.servers.map((server) => server.name) ?? [])
223
+ return {
224
+ servers: [...(lease?.servers ?? []), ...configured.filter((server) => !taken.has(server.name))],
225
+ release: () => lease?.release(),
226
+ }
227
+ } catch (error) {
228
+ lease?.release()
229
+ throw error
230
+ }
231
+ },
232
+ }
233
+ : undefined,
234
+ additionalDirectories: skills ? [skills.root] : undefined,
235
+ cmdSkillDir: skills?.agentsDir,
236
+ cmdOrchestration: mcp !== undefined,
237
+ initTimeoutMs: options.initTimeoutMs,
238
+ requestTimeoutMs: options.requestTimeoutMs,
239
+ maxSessions: options.maxSessions,
240
+ sessionIdleMs: options.sessionIdleMs,
241
+ allowPathsOutsideCwd: options.allowPathsOutsideCwd === true,
242
+ maxFileBytes: options.maxFileBytes,
243
+ promptTimeoutMs: options.promptTimeoutMs,
244
+ // Only consulted when a server sets `autoApprove: false`.
245
+ requestPermission: async (input) => {
246
+ const sessionID = input.sessionKey as Parameters<typeof ctx.permission.assert>[0]["sessionID"]
247
+ await ctx.permission.assert({
248
+ sessionID,
249
+ action: "acp_tool",
250
+ resources: [input.title],
251
+ metadata: {
252
+ server: input.server,
253
+ ...(input.kind ? { kind: input.kind } : {}),
254
+ ...(input.detail ? { detail: input.detail } : {}),
255
+ },
256
+ })
257
+ return true
258
+ },
259
+ })
260
+
261
+ const outputLimit = options.outputLimit ?? 32_000
262
+ const shimToken = randomUUID()
263
+
264
+ let disposed = false
265
+ const retryTimers = new Set<ReturnType<typeof setTimeout>>()
266
+ const registrations: Awaited<ReturnType<typeof ctx.provider.transform>>[] = []
267
+ const registered = new Set<string>()
268
+ const providerIDs = new Map<string, string>()
269
+ /** The inventory a registered provider currently exposes, keyed by server id. */
270
+ const inventories = new Map<string, AcpInventory>()
271
+
272
+ const providerIDForServer = (serverID: string) => {
273
+ const existing = providerIDs.get(serverID)
274
+ if (existing) return existing
275
+ const base = providerIDFor(serverID)
276
+ const used = new Set(providerIDs.values())
277
+ let id = base
278
+ let suffix = 2
279
+ while (used.has(id)) id = `${base}-${suffix++}`
280
+ providerIDs.set(serverID, id)
281
+ return id
282
+ }
283
+
284
+ const providerModels = (state: AcpServerState, providerID: ReturnType<typeof Provider.ID.make>, inventory: AcpInventory) => {
285
+ const variants = effortLevels(inventory.efforts).map((effort) => ({
286
+ id: Model.VariantID.make(effort),
287
+ settings: { reasoningEffort: effort },
288
+ }))
289
+ return inventory.models.map((model) => ({
290
+ ...Model.Info.default(providerID, Model.ID.make(model.id)),
291
+ modelID: Model.ID.make(`${state.config.id}::${model.id}`),
292
+ // Codex advertises names such as "6.1 Sol"; keep the GPT branding in
293
+ // OpenCode's picker without changing the wire model id.
294
+ name: /^gpt-/i.test(model.id) && /^[0-9]/.test(model.name) ? `GPT-${model.name}` : model.name,
295
+ status: "active" as const,
296
+ enabled: true,
297
+ capabilities: {
298
+ tools: false,
299
+ input: ["text"],
300
+ output: ["text"],
301
+ temperature: false,
302
+ },
303
+ variants,
304
+ // The agent keeps the conversation in its reused ACP session and
305
+ // compacts it itself. A known window would let OpenCode auto-compact,
306
+ // which only spends a turn on a summary the agent never reads. OpenCode
307
+ // treats 0 as an unknown window and never auto-compacts it.
308
+ limit: { context: 0, output: outputLimit },
309
+ // Pricing is reported by the ACP agent, not known here. An empty cost
310
+ // list means "unknown" and avoids OpenCode's zero-cost "Free" badge.
311
+ cost: [],
312
+ })) as Model.Info[]
313
+ }
314
+
315
+ const registerProvider = async (state: AcpServerState) => {
316
+ if (disposed) return false
317
+ if (registered.has(state.config.id)) return true
318
+ if (!inventories.get(state.config.id)?.models.length) return false
319
+ const providerID = Provider.ID.make(providerIDForServer(state.config.id))
320
+ const registration = await ctx.provider.transform((editor) => {
321
+ // Transforms replay on every rebuild, so read the current inventory
322
+ // rather than capturing the one known when this registration was made.
323
+ const inventory = inventories.get(state.config.id)
324
+ if (!inventory?.models.length) return
325
+ editor.add({
326
+ info: {
327
+ ...Provider.Info.empty(providerID),
328
+ name: state.config.name ?? `${state.config.id} (ACP)`,
329
+ activation: "enabled",
330
+ // The AI SDK route lets the plugin supply the language model, so
331
+ // ACP tool calls can surface as native OpenCode tool parts.
332
+ package: nativeToolParts ? "aisdk:acp" : "@opencode/ai/providers/openai-compatible",
333
+ compatibility: { reasoningField: "reasoning_content" },
334
+ settings: { baseURL: shim.url, apiKey: shimToken },
335
+ },
336
+ models: providerModels(state, providerID, inventory),
337
+ })
338
+ })
339
+ // The plugin can unload while OpenCode is registering this provider.
340
+ if (disposed) {
341
+ await registration.dispose().catch(() => {})
342
+ return false
343
+ }
344
+ registrations.push(registration)
345
+ registered.add(state.config.id)
346
+ return true
347
+ }
348
+
349
+ const sameInventory = (left: AcpInventory | undefined, right: AcpInventory) => {
350
+ if (!left) return false
351
+ if (left.models.length !== right.models.length || left.efforts.length !== right.efforts.length) return false
352
+ const modelsMatch = left.models.every((model, index) => {
353
+ const other = right.models[index]
354
+ return other !== undefined && model.id === other.id && model.name === other.name && model.description === other.description
355
+ })
356
+ return modelsMatch && left.efforts.every((effort, index) => effort === right.efforts[index])
357
+ }
358
+
359
+ /** Register or refresh a server's models from what discovery reported. */
360
+ const publishInventory = async (state: AcpServerState) => {
361
+ const id = state.config.id
362
+ if (!state.models.length) return false
363
+ const next: AcpInventory = { models: state.models, efforts: effortLevels(state.efforts) }
364
+ const previous = inventories.get(id)
365
+ inventories.set(id, next)
366
+ if (!registered.has(id)) return registerProvider(state)
367
+ if (sameInventory(previous, next)) return true
368
+ try {
369
+ await ctx.provider.reload()
370
+ } catch (error) {
371
+ log(
372
+ "warn",
373
+ `could not refresh models for ACP server "${id}": ${errorMessage(error)}`,
374
+ )
375
+ }
376
+ return true
377
+ }
378
+
379
+ const persistInventory = async (state: AcpServerState) => {
380
+ const inventory = inventories.get(state.config.id)
381
+ if (!inventory) return
382
+ try {
383
+ await writeInventory(ctx.storage, state.config, inventory)
384
+ } catch (error) {
385
+ log(
386
+ "debug",
387
+ `could not cache models for ACP server "${state.config.id}": ${errorMessage(error)}`,
388
+ )
389
+ }
390
+ }
391
+
392
+ const scheduleRetry = (state: AcpServerState, attempt: number) => {
393
+ if (attempt >= RETRY_DELAYS.length || disposed || state.retryable === false) return
394
+ const timer = setTimeout(() => {
395
+ retryTimers.delete(timer)
396
+ void (async () => {
397
+ if (disposed) return
398
+ try {
399
+ await manager.refresh(state)
400
+ if (disposed) return
401
+ if (state.models.length) {
402
+ await publishInventory(state)
403
+ await persistInventory(state)
404
+ log("info", `ACP server "${state.config.id}" refreshed after retry`)
405
+ return
406
+ }
407
+ scheduleRetry(state, attempt + 1)
408
+ } catch (error) {
409
+ if (disposed) return
410
+ log(
411
+ "warn",
412
+ `ACP server "${state.config.id}" retry failed: ${errorMessage(error)}`,
413
+ )
414
+ scheduleRetry(state, attempt + 1)
415
+ }
416
+ })()
417
+ }, RETRY_DELAYS[attempt])
418
+ timer.unref?.()
419
+ retryTimers.add(timer)
420
+ }
421
+
422
+ const resolveModel = (modelID: string) => {
423
+ const separator = modelID.indexOf("::")
424
+ if (separator < 0) return undefined
425
+ const server = modelID.slice(0, separator)
426
+ const model = modelID.slice(separator + 2)
427
+ if (!manager.get(server)) return undefined
428
+ return { server, model }
429
+ }
430
+
431
+ let shim: Awaited<ReturnType<typeof createShim>>
432
+ try {
433
+ shim = await createShim({
434
+ manager,
435
+ resolveModel,
436
+ token: shimToken,
437
+ includeSystem: options.includeSystem === true,
438
+ toolCallDisplay: options.toolCallDisplay,
439
+ historyTurns: options.historyTurns,
440
+ historyChars: options.historyChars,
441
+ maxBodyBytes: options.maxBodyBytes,
442
+ debugEnabled,
443
+ log,
444
+ // A turn can run for as long as an ACP prompt is allowed to.
445
+ drainTimeoutMs: options.promptTimeoutMs,
446
+ })
447
+ } catch (error) {
448
+ await manager.stop().catch(() => {})
449
+ await mcp?.close().catch(() => {})
450
+ await skills?.close().catch(() => {})
451
+ await openCodeMcp?.close().catch(() => {})
452
+ throw error
453
+ }
454
+
455
+ const cleanup = async () => {
456
+ disposed = true
457
+ for (const timer of retryTimers) clearTimeout(timer)
458
+ retryTimers.clear()
459
+ for (const registration of registrations) await registration.dispose().catch(() => {})
460
+ // A turn may still be streaming. Tearing down its connection here is what
461
+ // OpenCode reports as ECONNRESET, so let the shim drain first. Do not
462
+ // await it: a reload must stay responsive, and a shutdown does not need
463
+ // to wait for the old turn either.
464
+ void (async () => {
465
+ await commandBridge?.close().catch(() => {})
466
+ await shim.close().catch(() => {})
467
+ await manager.stop().catch(() => {})
468
+ await skills?.close().catch(() => {})
469
+ await mcp?.close().catch(() => {})
470
+ await openCodeMcp?.close().catch(() => {})
471
+ })()
472
+ }
473
+
474
+ try {
475
+ // Reserve provider ids in configuration order so a server that succeeds
476
+ // late cannot steal the id of one that already registered.
477
+ for (const state of manager.list) providerIDForServer(state.config.id)
478
+ // Every provider id is reserved above, so this reverse map is complete.
479
+ const serverForProvider = new Map([...providerIDs].map(([server, providerID]) => [providerID, server]))
480
+
481
+ // A server whose models were discovered before, in another location or an
482
+ // earlier process, is registered now, so this location resolves them
483
+ // without waiting for its agent. Discovery still runs and refreshes the
484
+ // list when it lands.
485
+ await Promise.all(
486
+ manager.list.map(async (state) => {
487
+ const inventory = await readInventory(ctx.storage, state.config)
488
+ if (inventory) inventories.set(state.config.id, inventory)
489
+ }),
490
+ )
491
+ for (const state of manager.list) {
492
+ if (await registerProvider(state)) {
493
+ log("debug", `ACP server "${state.config.id}" registered from cached models`)
494
+ }
495
+ }
496
+
497
+ // Expose the agents' own slash commands. Created before the agents start
498
+ // so the first `available_commands_update` from each setup session is
499
+ // recorded instead of dropped, and so the `skill.updated` event that
500
+ // fires while they initialize is already being watched.
501
+ if (options.commands !== false) {
502
+ try {
503
+ commandBridge = await createCommandBridge({
504
+ ctx,
505
+ manager,
506
+ serverForProvider: (providerID) => serverForProvider.get(providerID),
507
+ log,
508
+ })
509
+ } catch (error) {
510
+ commandBridge = undefined
511
+ log("warn", `ACP commands disabled: ${errorMessage(error)}`)
512
+ }
513
+ }
514
+
515
+ // Supply the ACP language model to OpenCode's AI SDK layer. Tool calls the
516
+ // agent runs itself come back as provider-executed parts, so the session
517
+ // shows the real shell/read/edit card without routing the tool.
518
+
519
+ // Auxiliary calls share the OpenCode session id, but must not write to
520
+ // the ACP agent's conversation. Carry the typed request kind to the shim
521
+ // through both the AI SDK and OpenAI-compatible provider routes.
522
+ registrations.push(
523
+ await ctx.session.hook("model.request", (event) => {
524
+ if (!serverForProvider.has(event.model.providerID)) return
525
+ event.headers["x-acp-request-kind"] = event.kind
526
+ }),
527
+ )
528
+ const limits = historyLimits(options)
529
+ if (nativeToolParts) {
530
+ registrations.push(
531
+ await ctx.aisdk.hook("sdk", (evt) => {
532
+ if (evt.package !== "acp") return
533
+ if (!serverForProvider.has(evt.model.providerID as string)) return
534
+ const target = resolveModel(String(evt.model.modelID ?? ""))
535
+ if (!target) return
536
+ evt.sdk = {
537
+ languageModel: () =>
538
+ createAcpLanguageModel({
539
+ server: target.server,
540
+ model: target.model,
541
+ url: shim.url,
542
+ token: shimToken,
543
+ log,
544
+ includeSystem: options.includeSystem,
545
+ historyTurns: options.historyTurns,
546
+ historyChars: options.historyChars,
547
+ }),
548
+ }
549
+ }),
550
+ )
551
+ } else {
552
+ // The native HTTP provider serializes these messages itself. Trim
553
+ // its model request before that happens, without changing the transcript.
554
+ for (const kind of ["context", "generate", "title"] as const) {
555
+ registrations.push(await ctx.session.hook(kind, (event) => {
556
+ if (!serverForProvider.has(event.model.providerID)) return
557
+ const includeSystem = kind !== "context" || options.includeSystem === true
558
+ if (!includeSystem) event.system = []
559
+ const messages: typeof event.messages = []
560
+ for (const { message, text } of boundedMessages(event.messages, limits, includeSystem)) {
561
+ if (message.role !== "tool") messages.push({ ...message, content: [{ type: "text", text }] })
562
+ }
563
+ event.messages = messages
564
+ }))
565
+ }
566
+ }
567
+
568
+ // The agent holds the conversation in its reused ACP session, so an
569
+ // OpenCode summary turn would cost a full prompt and never be read.
570
+ // Compaction goes to the agent's own /compact instead, and the summary
571
+ // keeps the recent conversation for a new ACP session to replay.
572
+ registrations.push(
573
+ await ctx.session.hook("compaction", async (evt) => {
574
+ const server = serverForProvider.get(evt.model.providerID)
575
+
576
+ const state = server ? manager.get(server) : undefined
577
+ if (!server || !state) return
578
+ const agent = agentName(state.config)
579
+ let outcome: string
580
+ try {
581
+ const result = await manager.compact({ server, key: evt.sessionID })
582
+ outcome = compactionOutcome(agent, result)
583
+ } catch (error) {
584
+ const message = errorMessage(error)
585
+ log("warn", `ACP /compact failed for ${server}: ${message}`)
586
+ outcome = `${agent} could not compact its context: ${message}`
587
+ }
588
+ const recent = recentConversation(evt.messages, limits)
589
+ evt.result = { summary: recent ? `${outcome}\n\nRecent conversation:\n\n${recent}` : outcome }
590
+ }),
591
+ )
592
+
593
+ // An ACP turn is one OpenCode step. Interrupt it on a steer and let the
594
+ // host deliver the complete message at the next step boundary.
595
+ const steer = createSteering({
596
+ manager,
597
+ localService: () => readLocalService(),
598
+ directory: ctx.location.directory,
599
+ log,
600
+ })
601
+ registrations.push(await ctx.session.hook("prompt", steer))
602
+
603
+ // Hooks must be in place before models become selectable. Discovery then
604
+ // runs in parallel without holding up OpenCode or neighboring providers.
605
+ // A cached provider keeps its registration when an attempt fails; the
606
+ // retry below refreshes it once the agent answers.
607
+ void manager.initialize(async (state) => {
608
+ try {
609
+ if (state.models.length) {
610
+ await publishInventory(state)
611
+ await persistInventory(state)
612
+ return
613
+ }
614
+ if (disposed) return
615
+ if (registered.has(state.config.id)) {
616
+ log(
617
+ "warn",
618
+ `ACP server "${state.config.id}" could not refresh its models: ${state.error ?? "no models available"}; keeping the cached list`,
619
+ )
620
+ } else if (state.retryable === false) {
621
+ log("error", `ACP server "${state.config.id}" cannot be registered: ${state.error ?? "no models available"}`)
622
+ return
623
+ } else {
624
+ log("warn", `deferring provider for ACP server "${state.config.id}": no models available yet`)
625
+ }
626
+ } catch (error) {
627
+ if (disposed) return
628
+ log("warn", `could not register ACP server "${state.config.id}": ${errorMessage(error)}`)
629
+ }
630
+ scheduleRetry(state, 0)
631
+ }).then(() => {
632
+ if (!disposed) log("info", `registered ${registered.size} ACP provider(s) in ${Date.now() - setupStartedAt}ms`)
633
+ }).catch((error) => {
634
+ if (!disposed) log("error", `ACP discovery failed: ${errorMessage(error)}`)
635
+ })
636
+ return cleanup
637
+ } catch (error) {
638
+ await cleanup()
639
+ throw error
640
+ }
641
+ },
642
+ })