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/src/setup.ts ADDED
@@ -0,0 +1,100 @@
1
+ import { spawn, type ChildProcess } from "node:child_process"
2
+ import { homedir } from "node:os"
3
+ import type { LogFn } from "./server-manager.ts"
4
+ import { errorMessage } from "./util.ts"
5
+
6
+ const DEFAULT_TIMEOUT_MS = 300_000
7
+ const FAILURE_TAIL_LINES = 20
8
+
9
+ /**
10
+ * One run per exact script string for the whole OpenCode server process. A
11
+ * setup command can have side effects (installing, logging in, writing config),
12
+ * so an identical command must not run again while it is in flight or after it
13
+ * finished; different commands are independent and start in parallel. The memo
14
+ * lives on `globalThis` because every location loads its own copy of this
15
+ * module: without it a new worktree would rerun every command. Only a server
16
+ * restart runs the commands again; an `opencode reload` in the same process
17
+ * reuses the finished runs.
18
+ */
19
+ const MEMO = Symbol.for("opencode-acp-provider.setup.runs")
20
+
21
+ type Runs = Map<string, Promise<void>>
22
+
23
+ function runs(): Runs {
24
+ const scope = globalThis as unknown as Record<symbol, Runs | undefined>
25
+ return (scope[MEMO] ??= new Map())
26
+ }
27
+
28
+ /**
29
+ * Run a server's setup command once per OpenCode server process. Never rejects:
30
+ * a failed or timed-out command resolves too, so the agent still starts and the
31
+ * command is never a hard dependency.
32
+ */
33
+ export function runSetup(script: string, log: LogFn, options: { timeoutMs?: number } = {}): Promise<void> {
34
+ const existing = runs().get(script)
35
+ if (existing) return existing
36
+ const run = execute(script, log, options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
37
+ runs().set(script, run)
38
+ return run
39
+ }
40
+
41
+ function execute(script: string, log: LogFn, timeoutMs: number): Promise<void> {
42
+ const startedAt = Date.now()
43
+ log("info", `ACP setup: running ${script}`)
44
+ return new Promise<void>((resolve) => {
45
+ let child: ChildProcess
46
+ let output = ""
47
+ let settled = false
48
+ let timedOut = false
49
+
50
+ const finish = (failure?: string) => {
51
+ if (settled) return
52
+ settled = true
53
+ clearTimeout(timer)
54
+ if (output.trim()) log("debug", `ACP setup output:\n${output.trimEnd()}`)
55
+ if (failure) log("warn", `ACP setup failed: ${failure}${outputTail(output)}`)
56
+ else log("info", `ACP setup finished in ${Date.now() - startedAt}ms: ${script}`)
57
+ resolve()
58
+ }
59
+
60
+ const timer = setTimeout(() => {
61
+ timedOut = true
62
+ child.kill("SIGTERM")
63
+ finish(`timed out after ${timeoutMs}ms`)
64
+ }, timeoutMs)
65
+ timer.unref?.()
66
+
67
+ try {
68
+ child = spawn("sh", ["-c", script], {
69
+ cwd: homedir(),
70
+ // stdin is ignored so a command that prompts cannot hang until the timeout.
71
+ stdio: ["ignore", "pipe", "pipe"],
72
+ env: process.env,
73
+ })
74
+ } catch (error) {
75
+ finish(errorMessage(error))
76
+ return
77
+ }
78
+
79
+ child.stdout?.on("data", (chunk: Buffer) => {
80
+ output += chunk.toString()
81
+ })
82
+ child.stderr?.on("data", (chunk: Buffer) => {
83
+ output += chunk.toString()
84
+ })
85
+ child.on("error", (error) => finish(error.message))
86
+ child.on("close", (code, signal) => {
87
+ if (timedOut) return
88
+ if (signal) finish(`killed by ${signal}`)
89
+ else if (code !== 0) finish(`exit code ${code}`)
90
+ else finish()
91
+ })
92
+ })
93
+ }
94
+
95
+ /** The last few lines of a failed command's combined output, for the warn log. */
96
+ function outputTail(output: string) {
97
+ const lines = output.trimEnd().split("\n").filter((line) => line.trim())
98
+ if (!lines.length) return ""
99
+ return `\n${lines.slice(-FAILURE_TAIL_LINES).join("\n")}`
100
+ }
package/src/shim.ts ADDED
@@ -0,0 +1,436 @@
1
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
2
+ import { randomUUID } from "node:crypto"
3
+ import type { AcpServerManager } from "./server-manager.ts"
4
+ import type { SessionUpdate } from "./acp-client.ts"
5
+ import { applyToolUpdate, type AcpToolState } from "./acp-tools.ts"
6
+ import { buildPrompts, historyLimits, isAuxiliaryRequest, type ChatMessage } from "./prompt.ts"
7
+ import { BodyTooLargeError, endFailedResponse, errorMessage, listenLocal, readBody } from "./util.ts"
8
+
9
+ export interface ShimOptions {
10
+ manager: AcpServerManager
11
+ /** Resolve an OpenAIChat model id to a registered ACP server id. */
12
+ resolveModel: (modelID: string) => { server: string; model: string } | undefined
13
+ log?: (level: "debug" | "info" | "warn" | "error", message: string) => void
14
+ /** Bearer token clients must present. When omitted the shim is unauthenticated. */
15
+ token?: string
16
+ /** Include OpenCode's system message in the ACP prompt. Defaults to false. */
17
+ includeSystem?: boolean
18
+ /** Turns of history replayed into a brand new ACP session. Defaults to 16. */
19
+ historyTurns?: number
20
+ /** Characters of history replayed into a brand new ACP session. Defaults to 8192. */
21
+ historyChars?: number
22
+ /** Largest chat-completions body accepted. Defaults to 32 MB. */
23
+ maxBodyBytes?: number
24
+ /** Precompute the debug strings. */
25
+ debugEnabled?: boolean
26
+ /** Show ACP tool calls in the answer stream. Defaults to "inline". */
27
+ toolCallDisplay?: "off" | "inline"
28
+ /**
29
+ * How long `close()` waits for requests that are still streaming before it
30
+ * drops their connections. Defaults to 30 minutes, matching one ACP turn.
31
+ */
32
+ drainTimeoutMs?: number
33
+ }
34
+
35
+ const DEFAULT_MAX_BODY_BYTES = 32 * 1024 * 1024
36
+ const DEFAULT_DRAIN_TIMEOUT_MS = 30 * 60_000
37
+
38
+ /** Answer with an OpenAI-style error body. */
39
+ function sendError(res: ServerResponse, status: number, message: string, type = "invalid_request_error") {
40
+ res.writeHead(status, { "content-type": "application/json" })
41
+ res.end(JSON.stringify({ error: { message, type } }))
42
+ }
43
+
44
+ function sessionKey(req: IncomingMessage, body: any): string | undefined {
45
+ // x-opencode-session-id is the session itself; x-opencode-session is the
46
+ // affinity/root session (parent or fork source), so it must come second.
47
+ for (const name of [
48
+ "x-opencode-session-id",
49
+ "x-opencode-session",
50
+ "x-session-id",
51
+ "x-session-affinity",
52
+ ]) {
53
+ const value = req.headers[name]
54
+ if (typeof value === "string" && value) return value
55
+ }
56
+ if (typeof body?.user === "string" && body.user) return body.user
57
+ return undefined
58
+ }
59
+
60
+ /**
61
+ * Reasoning effort selected by the OpenCode model variant. OpenAI-compatible
62
+ * providers send it as `reasoning_effort`; other provider shapes nest it.
63
+ */
64
+ function effortOf(body: any): string | undefined {
65
+ const value = body?.reasoning_effort ?? body?.reasoning?.effort ?? body?.providerOptions?.reasoningEffort ?? body?.effort
66
+ return typeof value === "string" && value.trim() ? value.trim() : undefined
67
+ }
68
+
69
+ function finishReason(stopReason: string) {
70
+ if (stopReason === "max_tokens" || stopReason === "max_turn_requests") return "length"
71
+ if (stopReason === "refusal") return "content_filter"
72
+ return "stop"
73
+ }
74
+
75
+ interface ToolCallState {
76
+ title: string
77
+ kind?: string
78
+ status: string
79
+ shown: boolean
80
+ }
81
+
82
+ /**
83
+ * ACP agents execute their own tools, so there is no OpenCode tool part to
84
+ * render. Show each finished tool call as a compact transcript line instead.
85
+ */
86
+ function toolCallLine(update: SessionUpdate, states: Map<string, ToolCallState>) {
87
+ const id = typeof update.toolCallId === "string" ? update.toolCallId : undefined
88
+ if (!id) return ""
89
+ const state = states.get(id) ?? { title: "tool", status: "pending", shown: false }
90
+ if (typeof update.title === "string" && update.title.trim()) state.title = update.title.trim()
91
+ if (typeof update.kind === "string" && update.kind) state.kind = update.kind
92
+ if (typeof update.status === "string" && update.status) state.status = update.status
93
+ states.set(id, state)
94
+ if (state.shown || (state.status !== "completed" && state.status !== "failed")) return ""
95
+ state.shown = true
96
+ const kind = state.kind === "execute" ? "shell" : state.kind ?? "tool"
97
+ const icon = state.status === "failed" ? "✗" : "✓"
98
+ const detail = toolDetail(update) || state.title
99
+ const label = detail.toLowerCase().startsWith(kind.toLowerCase()) ? detail : `${kind}: ${detail}`
100
+ return `\n\n> ${icon} ${label}\n\n`
101
+ }
102
+
103
+ function toolDetail(update: SessionUpdate) {
104
+ const raw = update.rawInput
105
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
106
+ for (const key of ["command", "path", "file_path", "query", "url", "pattern"]) {
107
+ const value = (raw as Record<string, unknown>)[key]
108
+ if (typeof value === "string" && value.trim()) return truncate(value.trim(), 120)
109
+ }
110
+ }
111
+ return ""
112
+ }
113
+
114
+ function truncate(text: string, max: number) {
115
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text
116
+ }
117
+
118
+ export async function createShim(options: ShimOptions) {
119
+ const { manager, log = () => {} } = options
120
+ const debug = options.debugEnabled === true
121
+ const limits = historyLimits(options)
122
+ const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES
123
+ const toolCallDisplay = options.toolCallDisplay !== "off"
124
+ const token = options.token
125
+ let loggedRequest = false
126
+ let loggedOneOff = false
127
+
128
+ const authorized = (req: IncomingMessage) => {
129
+ if (!token) return true
130
+ const header = req.headers.authorization
131
+ if (typeof header !== "string") return false
132
+ const separator = header.indexOf(" ")
133
+ return separator > 0 && header.slice(0, separator).toLowerCase() === "bearer" && header.slice(separator + 1).trim() === token
134
+ }
135
+
136
+ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
137
+ res.on("error", () => {})
138
+ const url = (req.url ?? "").split("?")[0]
139
+
140
+ if (!authorized(req)) {
141
+ res.setHeader("www-authenticate", "Bearer")
142
+ sendError(res, 401, "Unauthorized")
143
+ return
144
+ }
145
+
146
+ if (req.method === "GET" && (url === "/v1/models" || url === "/models")) {
147
+ const data = manager.list.flatMap((state) =>
148
+ state.models.map((model) => ({ id: model.id, object: "model", owned_by: state.config.id })),
149
+ )
150
+ res.writeHead(200, { "content-type": "application/json" })
151
+ res.end(JSON.stringify({ object: "list", data }))
152
+ return
153
+ }
154
+
155
+ if (req.method !== "POST" || !(url === "/v1/chat/completions" || url === "/chat/completions")) {
156
+ sendError(res, 404, `Not found: ${req.method} ${url}`)
157
+ return
158
+ }
159
+
160
+ let raw: string
161
+ try {
162
+ raw = await readBody(req, maxBodyBytes)
163
+ } catch (error) {
164
+ if (error instanceof BodyTooLargeError) {
165
+ sendError(res, 413, `Request body exceeds ${maxBodyBytes} bytes`)
166
+ req.destroy()
167
+ return
168
+ }
169
+ sendError(res, 400, "Could not read request body")
170
+ return
171
+ }
172
+
173
+ let body: any
174
+ try {
175
+ body = JSON.parse(raw)
176
+ } catch {
177
+ sendError(res, 400, "Invalid JSON body")
178
+ return
179
+ }
180
+
181
+ if (typeof body?.model !== "string" || !body.model) {
182
+ sendError(res, 400, "Missing model")
183
+ return
184
+ }
185
+ const modelID: string = body.model
186
+ const target = options.resolveModel(modelID)
187
+ if (!target) {
188
+ sendError(res, 404, `No ACP server registered for model "${modelID}"`)
189
+ return
190
+ }
191
+
192
+ const stream = body.stream === true
193
+ const messages: ChatMessage[] = Array.isArray(body.messages) ? body.messages : []
194
+ const effort = effortOf(body)
195
+ if (debug) {
196
+ if (!loggedRequest) {
197
+ loggedRequest = true
198
+ log("debug", `shim request keys: ${Object.keys(body).join(", ")}; headers: ${Object.keys(req.headers).join(", ")}`)
199
+ }
200
+ log("debug", `shim request: ${messages.length} msg(s), effort=${effort ?? "-"}`)
201
+ }
202
+ const id = `chatcmpl-${randomUUID()}`
203
+ const created = Math.floor(Date.now() / 1000)
204
+
205
+ // OpenCode's title/generate/compaction calls carry the same session id as
206
+ // chat. They need disposable ACP sessions, not another turn in its history.
207
+ const kind = req.headers["x-acp-request-kind"]
208
+ const auxiliary = isAuxiliaryRequest(kind)
209
+ const key = auxiliary ? undefined : sessionKey(req, body)
210
+ if (!key && !auxiliary && !loggedOneOff) {
211
+ loggedOneOff = true
212
+ log("warn", "no OpenCode session header on the shim request; ACP sessions will not be reused and MCP tools are unavailable")
213
+ }
214
+ // The AI SDK provider asks for structured tool events so OpenCode can
215
+ // render native tool cards; the OpenAI-compatible route keeps inline lines.
216
+ const structuredTools = req.headers["x-acp-tool-events"] === "1"
217
+ const prompt = buildPrompts(messages, limits, auxiliary || options.includeSystem === true)
218
+ if (!prompt.fresh.trim()) {
219
+ sendError(res, 400, "Empty prompt")
220
+ return
221
+ }
222
+ // The client may have disconnected while the body was being read.
223
+ if (res.destroyed) return
224
+
225
+ const controller = new AbortController()
226
+ res.on("close", () => {
227
+ if (!res.writableEnded) controller.abort()
228
+ })
229
+
230
+ const writeChunk = (delta: Record<string, unknown>, reason: string | null = null) => {
231
+ if (!stream || res.destroyed || res.writableEnded) return
232
+ res.write(
233
+ `data: ${JSON.stringify({
234
+ id,
235
+ object: "chat.completion.chunk",
236
+ created,
237
+ model: modelID,
238
+ choices: [{ index: 0, delta, finish_reason: reason }],
239
+ })}\n\n`,
240
+ )
241
+ }
242
+
243
+ if (stream) {
244
+ res.writeHead(200, {
245
+ "content-type": "text/event-stream",
246
+ "cache-control": "no-cache",
247
+ connection: "keep-alive",
248
+ })
249
+ writeChunk({ role: "assistant", content: "" })
250
+ }
251
+
252
+ // A silent agent turn can otherwise trip a client-side chunk timeout.
253
+ const heartbeat = stream
254
+ ? setInterval(() => {
255
+ if (!res.destroyed && !res.writableEnded) res.write(": keep-alive\n\n")
256
+ }, 15_000)
257
+ : undefined
258
+ heartbeat?.unref?.()
259
+
260
+ let emitted = ""
261
+ let reasoning = ""
262
+ let chunks = 0
263
+ let firstChunkAt: number | undefined
264
+ let firstThoughtAt: number | undefined
265
+ const startedAt = Math.round(performance.now())
266
+ const toolCalls = new Map<string, ToolCallState>()
267
+ const acpTools = new Map<string, AcpToolState>()
268
+ try {
269
+ const result = await manager.run({
270
+ server: target.server,
271
+ model: target.model,
272
+ effort,
273
+ prompt,
274
+ key,
275
+ sessionKey: key,
276
+ signal: controller.signal,
277
+ onUpdate: (update: SessionUpdate) => {
278
+ if (update.sessionUpdate === "agent_thought_chunk" && update.content?.type === "text") {
279
+ chunks += 1
280
+ if (!firstThoughtAt) {
281
+ firstThoughtAt = Math.round(performance.now())
282
+ if (debug) log("debug", `first ACP thought chunk after ${firstThoughtAt - startedAt}ms`)
283
+ }
284
+ const text = update.content.text ?? ""
285
+ reasoning += text
286
+ writeChunk({ reasoning_content: text })
287
+ } else if (update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text") {
288
+ chunks += 1
289
+ if (!firstChunkAt) {
290
+ firstChunkAt = Math.round(performance.now())
291
+ if (debug) log("debug", `first ACP text chunk after ${firstChunkAt - startedAt}ms`)
292
+ }
293
+ const text = update.content.text ?? ""
294
+ emitted += text
295
+ writeChunk({ content: text })
296
+ } else if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
297
+ if (structuredTools) {
298
+ const state = applyToolUpdate(update, acpTools)
299
+ if (state) {
300
+ writeChunk({
301
+ _acp_tool: {
302
+ id: state.id,
303
+ name: state.name,
304
+ kind: state.kind,
305
+ title: state.title,
306
+ status: state.status,
307
+ input: state.input,
308
+ output: state.done ? state.output : undefined,
309
+ isError: state.isError,
310
+ done: state.done,
311
+ },
312
+ })
313
+ }
314
+ } else if (toolCallDisplay) {
315
+ const line = toolCallLine(update, toolCalls)
316
+ if (line) {
317
+ emitted += line
318
+ writeChunk({ content: line })
319
+ }
320
+ }
321
+ }
322
+ },
323
+ })
324
+
325
+ if (!emitted && result.text) {
326
+ emitted = result.text
327
+ writeChunk({ content: result.text })
328
+ }
329
+ const elapsed = Math.round(performance.now()) - startedAt
330
+ if (debug || elapsed >= 5_000) {
331
+ log(
332
+ elapsed >= 5_000 ? "warn" : "debug",
333
+ `ACP turn finished for ${target.server}/${target.model} key=${key ?? "-"} kind=${kind ?? "primary"}: ${result.stopReason} in ${elapsed}ms (first text ${firstChunkAt ? firstChunkAt - startedAt : "-"}ms, first thought ${firstThoughtAt ? firstThoughtAt - startedAt : "-"}ms, ${chunks} chunks, ${reasoning.length} reasoning chars, ${emitted.length} text chars)`,
334
+ )
335
+ }
336
+
337
+ const reason = finishReason(result.stopReason)
338
+ if (stream) {
339
+ writeChunk({}, reason)
340
+ if (!res.destroyed && !res.writableEnded) {
341
+ res.write("data: [DONE]\n\n")
342
+ res.end()
343
+ }
344
+ } else {
345
+ if (res.destroyed) return
346
+ res.writeHead(200, { "content-type": "application/json" })
347
+ res.end(
348
+ JSON.stringify({
349
+ id,
350
+ object: "chat.completion",
351
+ created,
352
+ model: modelID,
353
+ choices: [
354
+ {
355
+ index: 0,
356
+ message: { role: "assistant", content: emitted, ...(reasoning ? { reasoning_content: reasoning } : {}) },
357
+ finish_reason: reason,
358
+ },
359
+ ],
360
+ }),
361
+ )
362
+ }
363
+ } catch (error) {
364
+ const message = errorMessage(error)
365
+ log("error", `ACP prompt failed for ${target.server}/${target.model}: ${message}`)
366
+ if (res.destroyed) return
367
+ if (!stream) {
368
+ sendError(res, 500, message, "acp_error")
369
+ return
370
+ }
371
+ if (!res.writableEnded) {
372
+ res.end(`data: ${JSON.stringify({ error: { message, type: "acp_error" } })}\n\n`)
373
+ }
374
+ } finally {
375
+ if (heartbeat) clearInterval(heartbeat)
376
+ }
377
+ }
378
+
379
+ const inflight = new Set<Promise<void>>()
380
+ const server = createServer((req, res) => {
381
+ const work = (async () => {
382
+ try {
383
+ await handleRequest(req, res)
384
+ } catch (error) {
385
+ log("error", `shim request failed: ${errorMessage(error)}`)
386
+ endFailedResponse(res)
387
+ }
388
+ })()
389
+ inflight.add(work)
390
+ void work.finally(() => inflight.delete(work))
391
+ })
392
+
393
+ // Bun keeps shim connections alive and reuses them across turns. Node's
394
+ // default 5s idle timeout closes a socket just as Bun picks it up again,
395
+ // which surfaces as an ECONNRESET in the middle of a turn. A local server
396
+ // does not need an idle timeout: `close()` drops the sockets it owns.
397
+ server.keepAliveTimeout = 0
398
+
399
+ const port = await listenLocal(server)
400
+ log("info", `ACP provider shim listening on http://127.0.0.1:${port}/v1`)
401
+
402
+ const drainTimeoutMs = options.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS
403
+
404
+ return {
405
+ url: `http://127.0.0.1:${port}/v1`,
406
+ /**
407
+ * A plugin reload disposes this instance while a turn may still be
408
+ * streaming. Destroying that connection is what the client reports as
409
+ * ECONNRESET, so stop accepting new requests, let the running turn finish,
410
+ * and only then drop the sockets.
411
+ */
412
+ async close() {
413
+ const drained = new Promise<void>((resolve) => {
414
+ server.close(() => resolve())
415
+ server.closeIdleConnections?.()
416
+ })
417
+ const deadline = Date.now() + Math.max(0, drainTimeoutMs)
418
+ while (inflight.size) {
419
+ const remaining = deadline - Date.now()
420
+ if (remaining <= 0) break
421
+ let timer: ReturnType<typeof setTimeout> | undefined
422
+ await Promise.race([
423
+ Promise.allSettled([...inflight]),
424
+ new Promise<void>((resolve) => {
425
+ timer = setTimeout(resolve, remaining)
426
+ timer.unref?.()
427
+ }),
428
+ ])
429
+ if (timer) clearTimeout(timer)
430
+ }
431
+ server.closeAllConnections?.()
432
+ await drained
433
+ },
434
+ }
435
+ }
436
+