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