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/LICENSE +21 -0
- package/README.md +380 -2
- package/package.json +41 -4
- package/src/acp-client.ts +1179 -0
- package/src/acp-tools.ts +311 -0
- package/src/agent-command.ts +20 -0
- package/src/agent-pool.ts +444 -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 +642 -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 +1001 -0
- package/src/prompt.ts +100 -0
- package/src/server-manager.ts +1137 -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/inventory.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import type { AcpModelInfo, AcpServerConfig } from "./server-manager.ts"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A server's last discovered model inventory. Setup registers it before the
|
|
6
|
+
* agent starts so a fresh location (a worktree, for example) has the models
|
|
7
|
+
* immediately instead of waiting out discovery.
|
|
8
|
+
*/
|
|
9
|
+
export interface AcpInventory {
|
|
10
|
+
models: AcpModelInfo[]
|
|
11
|
+
efforts: string[]
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Bump when the payload shape changes; an older entry is treated as a miss. */
|
|
15
|
+
const VERSION = 1
|
|
16
|
+
const MAX_MODELS = 1_000
|
|
17
|
+
|
|
18
|
+
interface Storage {
|
|
19
|
+
get(key: string): Promise<unknown>
|
|
20
|
+
set(key: string, value: unknown): Promise<void>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Two configs with the same command and environment advertise the same models,
|
|
25
|
+
* so the cache is shared across locations. The location is deliberately absent:
|
|
26
|
+
* a worktree resolves its agent exactly like its parent checkout.
|
|
27
|
+
*/
|
|
28
|
+
function cacheInput(config: AcpServerConfig) {
|
|
29
|
+
return {
|
|
30
|
+
command: Array.isArray(config.command) ? config.command : [config.command],
|
|
31
|
+
env: Object.entries(config.env ?? {}).sort(([a], [b]) => a.localeCompare(b)),
|
|
32
|
+
models: config.models ?? null,
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function inventoryKey(config: AcpServerConfig) {
|
|
37
|
+
const digest = createHash("sha256").update(JSON.stringify(cacheInput(config))).digest("hex")
|
|
38
|
+
return `acp-inventory/${digest}`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
42
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Normalize the effort levels an agent advertised, dropping the implicit default. */
|
|
46
|
+
export function effortLevels(values: readonly string[]) {
|
|
47
|
+
return [...new Set(values.filter((value) => typeof value === "string" && value !== "default" && value.trim()))]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Parse a cached payload. Anything unexpected is a miss: a corrupt entry must
|
|
52
|
+
* never prevent setup from registering the provider after discovery.
|
|
53
|
+
*/
|
|
54
|
+
export function parseInventory(value: unknown): AcpInventory | undefined {
|
|
55
|
+
if (!isRecord(value) || value.v !== VERSION) return undefined
|
|
56
|
+
if (!Array.isArray(value.models) || !value.models.length || value.models.length > MAX_MODELS) return undefined
|
|
57
|
+
|
|
58
|
+
const models: AcpModelInfo[] = []
|
|
59
|
+
for (const entry of value.models) {
|
|
60
|
+
if (!isRecord(entry)) return undefined
|
|
61
|
+
if (typeof entry.id !== "string" || !entry.id) return undefined
|
|
62
|
+
if (typeof entry.name !== "string" || !entry.name) return undefined
|
|
63
|
+
const model: AcpModelInfo = { id: entry.id, name: entry.name }
|
|
64
|
+
if (typeof entry.description === "string" && entry.description) model.description = entry.description
|
|
65
|
+
models.push(model)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const efforts = Array.isArray(value.efforts)
|
|
69
|
+
? effortLevels(value.efforts.filter((effort): effort is string => typeof effort === "string"))
|
|
70
|
+
: []
|
|
71
|
+
return { models, efforts }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function readInventory(storage: Storage | undefined, config: AcpServerConfig) {
|
|
75
|
+
if (!storage) return undefined
|
|
76
|
+
try {
|
|
77
|
+
return parseInventory(await storage.get(inventoryKey(config)))
|
|
78
|
+
} catch {
|
|
79
|
+
return undefined
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function writeInventory(storage: Storage | undefined, config: AcpServerConfig, inventory: AcpInventory) {
|
|
84
|
+
if (!storage || !inventory.models.length) return
|
|
85
|
+
await storage.set(inventoryKey(config), {
|
|
86
|
+
v: VERSION,
|
|
87
|
+
models: inventory.models,
|
|
88
|
+
efforts: inventory.efforts,
|
|
89
|
+
})
|
|
90
|
+
}
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
import { boundedMessages, historyLimits, isAuxiliaryRequest, type ChatMessage } from "./prompt.ts"
|
|
2
|
+
import type { LogFn } from "./server-manager.ts"
|
|
3
|
+
import { errorMessage, sleep } from "./util.ts"
|
|
4
|
+
|
|
5
|
+
export interface AcpLanguageModelOptions {
|
|
6
|
+
/** ACP server id, as registered with the manager. */
|
|
7
|
+
server: string
|
|
8
|
+
/** Model id advertised by that server. */
|
|
9
|
+
model: string
|
|
10
|
+
/** Base URL of the chat-completions shim, e.g. `http://127.0.0.1:1234/v1`. */
|
|
11
|
+
url: string
|
|
12
|
+
/** Bearer token required by the shim, when it enforces one. */
|
|
13
|
+
token?: string
|
|
14
|
+
log?: LogFn
|
|
15
|
+
includeSystem?: boolean
|
|
16
|
+
historyTurns?: number
|
|
17
|
+
historyChars?: number
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The AI SDK side of the bridge. OpenCode sees a normal language model; the
|
|
22
|
+
* model turns one ACP turn into AI SDK stream parts, including the agent's own
|
|
23
|
+
* tool calls flagged `providerExecuted` so OpenCode records them as native
|
|
24
|
+
* tool parts instead of running anything itself.
|
|
25
|
+
*/
|
|
26
|
+
export function createAcpLanguageModel(options: AcpLanguageModelOptions) {
|
|
27
|
+
const limits = historyLimits(options)
|
|
28
|
+
const model = {
|
|
29
|
+
specificationVersion: "v3" as const,
|
|
30
|
+
provider: "acp",
|
|
31
|
+
modelId: options.model,
|
|
32
|
+
supportedUrls: {},
|
|
33
|
+
|
|
34
|
+
async doStream(call: CallOptions) {
|
|
35
|
+
const sessionID = header(call.headers, "x-opencode-session-id")
|
|
36
|
+
const requestKind = header(call.headers, "x-acp-request-kind")
|
|
37
|
+
options.log?.(
|
|
38
|
+
"debug",
|
|
39
|
+
`acp language model ${options.server}/${options.model} session=${sessionID ?? "-"} kind=${requestKind ?? "primary"} messages=${call.prompt?.length ?? 0}`,
|
|
40
|
+
)
|
|
41
|
+
const response = await post(
|
|
42
|
+
`${options.url}/chat/completions`,
|
|
43
|
+
{
|
|
44
|
+
method: "POST",
|
|
45
|
+
headers: {
|
|
46
|
+
"content-type": "application/json",
|
|
47
|
+
// Ask the shim for structured tool events instead of inline markers.
|
|
48
|
+
"x-acp-tool-events": "1",
|
|
49
|
+
...(options.token ? { authorization: `Bearer ${options.token}` } : {}),
|
|
50
|
+
...(sessionID ? { "x-opencode-session-id": sessionID } : {}),
|
|
51
|
+
...(requestKind ? { "x-acp-request-kind": requestKind } : {}),
|
|
52
|
+
},
|
|
53
|
+
body: JSON.stringify({
|
|
54
|
+
model: `${options.server}::${options.model}`,
|
|
55
|
+
stream: true,
|
|
56
|
+
messages: boundedMessages(
|
|
57
|
+
call.prompt ?? [], limits, options.includeSystem === true || isAuxiliaryRequest(requestKind),
|
|
58
|
+
).map(({ message, text }) => ({ role: message.role, content: text })),
|
|
59
|
+
reasoning_effort: effortOf(call.providerOptions),
|
|
60
|
+
}),
|
|
61
|
+
signal: call.abortSignal ?? undefined,
|
|
62
|
+
},
|
|
63
|
+
options.log,
|
|
64
|
+
)
|
|
65
|
+
if (!response.ok || !response.body) {
|
|
66
|
+
const detail = await response.text().catch(() => "")
|
|
67
|
+
throw new Error(`ACP shim responded ${response.status}${detail ? `: ${detail.slice(0, 300)}` : ""}`)
|
|
68
|
+
}
|
|
69
|
+
return { stream: translate(response.body, options.log) }
|
|
70
|
+
},
|
|
71
|
+
|
|
72
|
+
async doGenerate(call: CallOptions) {
|
|
73
|
+
const { stream } = await this.doStream(call)
|
|
74
|
+
const content: any[] = []
|
|
75
|
+
let finishReason = "stop"
|
|
76
|
+
let usage: any = unknownUsage()
|
|
77
|
+
for await (const part of readAll(stream)) {
|
|
78
|
+
if (part.type === "text-delta") content.push({ type: "text", text: part.delta })
|
|
79
|
+
else if (part.type === "reasoning-delta") content.push({ type: "reasoning", text: part.delta })
|
|
80
|
+
else if (part.type === "tool-call")
|
|
81
|
+
content.push({
|
|
82
|
+
type: "tool-call",
|
|
83
|
+
toolCallId: part.toolCallId,
|
|
84
|
+
toolName: part.toolName,
|
|
85
|
+
input: part.input,
|
|
86
|
+
providerExecuted: true,
|
|
87
|
+
})
|
|
88
|
+
else if (part.type === "tool-result")
|
|
89
|
+
content.push({
|
|
90
|
+
type: "tool-result",
|
|
91
|
+
toolCallId: part.toolCallId,
|
|
92
|
+
toolName: part.toolName,
|
|
93
|
+
result: part.result,
|
|
94
|
+
})
|
|
95
|
+
else if (part.type === "finish") {
|
|
96
|
+
finishReason = part.finishReason?.unified ?? "stop"
|
|
97
|
+
usage = part.usage
|
|
98
|
+
} else if (part.type === "error") {
|
|
99
|
+
throw part.error instanceof Error ? part.error : new Error(String(part.error))
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
content,
|
|
104
|
+
finishReason: { unified: finishReason, raw: finishReason },
|
|
105
|
+
usage,
|
|
106
|
+
warnings: [],
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
}
|
|
110
|
+
return model
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
interface CallOptions {
|
|
114
|
+
prompt?: ChatMessage[]
|
|
115
|
+
headers?: Record<string, string>
|
|
116
|
+
providerOptions?: Record<string, unknown>
|
|
117
|
+
abortSignal?: AbortSignal
|
|
118
|
+
}
|
|
119
|
+
/** Transport failures worth one more attempt before the model call fails. */
|
|
120
|
+
const RETRYABLE_TRANSPORT = /ECONNRESET|ECONNREFUSED|EPIPE|socket hang up|other side closed|fetch failed/i
|
|
121
|
+
const RETRY_DELAYS_MS = [150, 600]
|
|
122
|
+
|
|
123
|
+
function failureText(error: unknown, depth = 0): string {
|
|
124
|
+
if (!error || depth > 4) return ""
|
|
125
|
+
if (typeof error === "string") return error
|
|
126
|
+
if (error instanceof Error) {
|
|
127
|
+
return `${error.name}: ${error.message} ${failureText((error as { cause?: unknown }).cause, depth + 1)}`
|
|
128
|
+
}
|
|
129
|
+
return String(error)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* POST to the shim, retrying a connection that died before the response
|
|
134
|
+
* started. A reset on a reused keep-alive socket is transient: the shim never
|
|
135
|
+
* saw the turn, so asking again cannot duplicate it. Once headers arrive the
|
|
136
|
+
* caller owns the stream, so a mid-stream reset is left to OpenCode's retry.
|
|
137
|
+
*/
|
|
138
|
+
async function post(url: string, init: RequestInit, log?: LogFn) {
|
|
139
|
+
for (let attempt = 0; ; attempt++) {
|
|
140
|
+
try {
|
|
141
|
+
return await fetch(url, init)
|
|
142
|
+
} catch (error) {
|
|
143
|
+
const detail = failureText(error)
|
|
144
|
+
const retryable = !init.signal?.aborted && RETRYABLE_TRANSPORT.test(detail) && attempt < RETRY_DELAYS_MS.length
|
|
145
|
+
if (!retryable) throw error
|
|
146
|
+
log?.("warn", `acp shim request failed (${detail.slice(0, 200)}); retrying`)
|
|
147
|
+
await sleep(RETRY_DELAYS_MS[attempt], init.signal ?? undefined)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function header(headers: Record<string, string> | undefined, name: string) {
|
|
153
|
+
if (!headers) return undefined
|
|
154
|
+
const value = headers[name] ?? headers[name.toLowerCase()]
|
|
155
|
+
return typeof value === "string" && value ? value : undefined
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The selected variant arrives as provider options nested under the provider's
|
|
160
|
+
* key. Find the effort anywhere in that tree so the ACP agent still receives
|
|
161
|
+
* the variant the user picked.
|
|
162
|
+
*/
|
|
163
|
+
function effortOf(providerOptions: unknown): string | undefined {
|
|
164
|
+
const seen = new Set<unknown>()
|
|
165
|
+
const walk = (value: unknown, depth: number): string | undefined => {
|
|
166
|
+
if (!value || typeof value !== "object" || depth > 4 || seen.has(value)) return undefined
|
|
167
|
+
seen.add(value)
|
|
168
|
+
const entry = value as Record<string, unknown>
|
|
169
|
+
for (const key of ["reasoningEffort", "reasoning_effort", "effort"]) {
|
|
170
|
+
const found = entry[key]
|
|
171
|
+
if (typeof found === "string" && found.trim()) return found.trim()
|
|
172
|
+
}
|
|
173
|
+
for (const nested of Object.values(entry)) {
|
|
174
|
+
const found = walk(nested, depth + 1)
|
|
175
|
+
if (found) return found
|
|
176
|
+
}
|
|
177
|
+
return undefined
|
|
178
|
+
}
|
|
179
|
+
return walk(providerOptions, 0)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Usage is never reported. OpenCode reads a step's tokens both as context size
|
|
184
|
+
* and as spend, and an ACP turn spans many model calls, so no number the agent
|
|
185
|
+
* gives is right for both. Unknown counts beat wrong ones.
|
|
186
|
+
*/
|
|
187
|
+
function unknownUsage() {
|
|
188
|
+
return {
|
|
189
|
+
inputTokens: { total: undefined, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
|
|
190
|
+
outputTokens: { total: undefined, text: undefined, reasoning: undefined },
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
interface ToolProgress {
|
|
195
|
+
name: string
|
|
196
|
+
started: boolean
|
|
197
|
+
called: boolean
|
|
198
|
+
settled: boolean
|
|
199
|
+
title?: string
|
|
200
|
+
output?: string
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Parse the shim's chat-completions SSE into AI SDK v3 stream parts. Text and
|
|
205
|
+
* reasoning fragments are closed around tool calls so the transcript keeps the
|
|
206
|
+
* agent's actual order (text, card, text).
|
|
207
|
+
*/
|
|
208
|
+
function translate(body: ReadableStream<Uint8Array>, log?: LogFn) {
|
|
209
|
+
let textID: string | undefined
|
|
210
|
+
let reasoningID: string | undefined
|
|
211
|
+
let textSeq = 0
|
|
212
|
+
let reasoningSeq = 0
|
|
213
|
+
let reason = "stop"
|
|
214
|
+
const usage = unknownUsage()
|
|
215
|
+
const tools = new Map<string, ToolProgress>()
|
|
216
|
+
const reader = body.getReader()
|
|
217
|
+
const decoder = new TextDecoder()
|
|
218
|
+
|
|
219
|
+
const pump = async (push: (part: any) => void) => {
|
|
220
|
+
push({ type: "stream-start", warnings: [] })
|
|
221
|
+
let buffer = ""
|
|
222
|
+
const closeText = () => {
|
|
223
|
+
if (textID === undefined) return
|
|
224
|
+
push({ type: "text-end", id: textID })
|
|
225
|
+
textID = undefined
|
|
226
|
+
}
|
|
227
|
+
const closeReasoning = () => {
|
|
228
|
+
if (reasoningID === undefined) return
|
|
229
|
+
push({ type: "reasoning-end", id: reasoningID })
|
|
230
|
+
reasoningID = undefined
|
|
231
|
+
}
|
|
232
|
+
const openText = () => {
|
|
233
|
+
if (textID !== undefined) return
|
|
234
|
+
closeReasoning()
|
|
235
|
+
textID = `text-${textSeq++}`
|
|
236
|
+
push({ type: "text-start", id: textID })
|
|
237
|
+
}
|
|
238
|
+
const openReasoning = () => {
|
|
239
|
+
if (reasoningID !== undefined) return
|
|
240
|
+
closeText()
|
|
241
|
+
reasoningID = `reasoning-${reasoningSeq++}`
|
|
242
|
+
push({ type: "reasoning-start", id: reasoningID })
|
|
243
|
+
}
|
|
244
|
+
const callTool = (id: string, current: { name: string; title?: string }, input: Record<string, unknown>) => {
|
|
245
|
+
// An agent that never sends raw input still gets a readable shell card
|
|
246
|
+
// from its own title instead of an empty command.
|
|
247
|
+
const value =
|
|
248
|
+
Object.keys(input).length === 0 && current.name === "shell" && current.title
|
|
249
|
+
? { command: current.title }
|
|
250
|
+
: input
|
|
251
|
+
push({
|
|
252
|
+
type: "tool-call",
|
|
253
|
+
toolCallId: id,
|
|
254
|
+
toolName: current.name,
|
|
255
|
+
input: JSON.stringify(value),
|
|
256
|
+
providerExecuted: true,
|
|
257
|
+
dynamic: true,
|
|
258
|
+
})
|
|
259
|
+
}
|
|
260
|
+
const settleTool = (id: string, current: { name: string; output?: string }, isError: boolean) => {
|
|
261
|
+
push({
|
|
262
|
+
type: "tool-result",
|
|
263
|
+
toolCallId: id,
|
|
264
|
+
toolName: current.name,
|
|
265
|
+
result: typeof current.output === "string" ? current.output : "",
|
|
266
|
+
isError,
|
|
267
|
+
dynamic: true,
|
|
268
|
+
})
|
|
269
|
+
}
|
|
270
|
+
const handleTool = (event: any) => {
|
|
271
|
+
if (!event || typeof event.id !== "string") return
|
|
272
|
+
const existing = tools.get(event.id)
|
|
273
|
+
const name = existing?.name ?? (typeof event.name === "string" && event.name ? event.name : "tool")
|
|
274
|
+
const current: ToolProgress = existing ?? { name, started: false, called: false, settled: false }
|
|
275
|
+
if (!existing) tools.set(event.id, current)
|
|
276
|
+
if (typeof event.title === "string" && event.title) current.title = event.title
|
|
277
|
+
if (typeof event.output === "string" && event.output) current.output = event.output
|
|
278
|
+
closeText()
|
|
279
|
+
closeReasoning()
|
|
280
|
+
if (!current.started) {
|
|
281
|
+
push({ type: "tool-input-start", id: event.id, toolName: name, providerExecuted: true })
|
|
282
|
+
current.started = true
|
|
283
|
+
}
|
|
284
|
+
const input = event.input && typeof event.input === "object" && !Array.isArray(event.input) ? event.input : {}
|
|
285
|
+
const done = event.done === true
|
|
286
|
+
const keys = Object.keys(input)
|
|
287
|
+
// Agents stream edit/write input in pieces. Wait for the actual change so
|
|
288
|
+
// the card is created with its diff instead of a path-only placeholder.
|
|
289
|
+
const partial =
|
|
290
|
+
(name === "edit" && (input.oldString === undefined || input.newString === undefined)) ||
|
|
291
|
+
(name === "write" && input.content === undefined)
|
|
292
|
+
if (!current.called && (done || (keys.length > 0 && !partial))) {
|
|
293
|
+
callTool(event.id, current, input)
|
|
294
|
+
current.called = true
|
|
295
|
+
}
|
|
296
|
+
if (done && !current.settled) {
|
|
297
|
+
settleTool(event.id, current, event.isError === true)
|
|
298
|
+
current.settled = true
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
const handleDelta = (delta: Record<string, any>) => {
|
|
302
|
+
if (typeof delta.content === "string" && delta.content) {
|
|
303
|
+
openText()
|
|
304
|
+
push({ type: "text-delta", id: textID, delta: delta.content })
|
|
305
|
+
}
|
|
306
|
+
if (typeof delta.reasoning_content === "string" && delta.reasoning_content) {
|
|
307
|
+
openReasoning()
|
|
308
|
+
push({ type: "reasoning-delta", id: reasoningID, delta: delta.reasoning_content })
|
|
309
|
+
}
|
|
310
|
+
if (delta._acp_tool) handleTool(delta._acp_tool)
|
|
311
|
+
}
|
|
312
|
+
let failed = false
|
|
313
|
+
let failure: unknown
|
|
314
|
+
try {
|
|
315
|
+
for (;;) {
|
|
316
|
+
const { done, value } = await reader.read()
|
|
317
|
+
if (done) break
|
|
318
|
+
buffer += decoder.decode(value, { stream: true })
|
|
319
|
+
let index = buffer.indexOf("\n")
|
|
320
|
+
while (index >= 0) {
|
|
321
|
+
const line = buffer.slice(0, index).replace(/\r$/, "")
|
|
322
|
+
buffer = buffer.slice(index + 1)
|
|
323
|
+
index = buffer.indexOf("\n")
|
|
324
|
+
if (!line.startsWith("data:")) continue
|
|
325
|
+
const data = line.slice(5).trim()
|
|
326
|
+
if (!data || data === "[DONE]") continue
|
|
327
|
+
let frame: any
|
|
328
|
+
try {
|
|
329
|
+
frame = JSON.parse(data)
|
|
330
|
+
} catch {
|
|
331
|
+
continue
|
|
332
|
+
}
|
|
333
|
+
if (frame?.error) {
|
|
334
|
+
throw new Error(typeof frame.error.message === "string" ? frame.error.message : "ACP shim stream failed")
|
|
335
|
+
}
|
|
336
|
+
const choice = frame?.choices?.[0]
|
|
337
|
+
if (choice?.delta) handleDelta(choice.delta)
|
|
338
|
+
if (typeof choice?.finish_reason === "string" && choice.finish_reason) reason = choice.finish_reason
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
} catch (error) {
|
|
342
|
+
failed = true
|
|
343
|
+
failure = error
|
|
344
|
+
log?.("warn", `acp language model stream failed: ${errorMessage(error)}`)
|
|
345
|
+
} finally {
|
|
346
|
+
closeText()
|
|
347
|
+
closeReasoning()
|
|
348
|
+
try {
|
|
349
|
+
reader.releaseLock()
|
|
350
|
+
} catch {
|
|
351
|
+
// the stream was already cancelled
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
// Settle every tool even when the turn was interrupted, so a cancelled or
|
|
355
|
+
// failed turn cannot leave a card stuck in the streaming state.
|
|
356
|
+
for (const [id, current] of tools) {
|
|
357
|
+
if (current.settled) continue
|
|
358
|
+
if (!current.called) {
|
|
359
|
+
callTool(id, current, {})
|
|
360
|
+
current.called = true
|
|
361
|
+
}
|
|
362
|
+
settleTool(id, current, failed)
|
|
363
|
+
current.settled = true
|
|
364
|
+
}
|
|
365
|
+
if (!failed) {
|
|
366
|
+
push({ type: "finish", finishReason: { unified: unifiedReason(reason), raw: reason }, usage })
|
|
367
|
+
} else {
|
|
368
|
+
push({ type: "error", error: failure })
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
let closed = false
|
|
373
|
+
return new ReadableStream<any>({
|
|
374
|
+
start(controller) {
|
|
375
|
+
const push = (part: any) => {
|
|
376
|
+
if (closed) return
|
|
377
|
+
try {
|
|
378
|
+
controller.enqueue(part)
|
|
379
|
+
} catch {
|
|
380
|
+
closed = true
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
const finish = () => {
|
|
384
|
+
if (closed) return
|
|
385
|
+
closed = true
|
|
386
|
+
try {
|
|
387
|
+
controller.close()
|
|
388
|
+
} catch {
|
|
389
|
+
// cancelled by the consumer
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
void pump(push).then(finish, (error) => {
|
|
393
|
+
if (closed) return
|
|
394
|
+
closed = true
|
|
395
|
+
try {
|
|
396
|
+
controller.error(error)
|
|
397
|
+
} catch {
|
|
398
|
+
// cancelled by the consumer
|
|
399
|
+
}
|
|
400
|
+
})
|
|
401
|
+
},
|
|
402
|
+
cancel(reason) {
|
|
403
|
+
closed = true
|
|
404
|
+
void reader.cancel(reason).catch(() => {})
|
|
405
|
+
},
|
|
406
|
+
})
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function unifiedReason(reason: string) {
|
|
410
|
+
if (reason === "length") return "length"
|
|
411
|
+
if (reason === "content_filter" || reason === "content-filter") return "content-filter"
|
|
412
|
+
if (reason === "tool_calls" || reason === "tool-calls") return "tool-calls"
|
|
413
|
+
return "stop"
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
async function* readAll(stream: ReadableStream<any>) {
|
|
417
|
+
const reader = stream.getReader()
|
|
418
|
+
try {
|
|
419
|
+
for (;;) {
|
|
420
|
+
const { done, value } = await reader.read()
|
|
421
|
+
if (done) return
|
|
422
|
+
yield value
|
|
423
|
+
}
|
|
424
|
+
} finally {
|
|
425
|
+
reader.releaseLock()
|
|
426
|
+
}
|
|
427
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Minimal stdio <-> HTTP bridge for the OpenCode MCP server.
|
|
3
|
+
// ACP agents that do not accept HTTP MCP servers launch this file.
|
|
4
|
+
|
|
5
|
+
const endpoint = process.env.OPENCODE_MCP_URL
|
|
6
|
+
const token = process.env.OPENCODE_MCP_TOKEN
|
|
7
|
+
const timeoutMs = Number(process.env.OPENCODE_MCP_TIMEOUT_MS ?? 10 * 60_000)
|
|
8
|
+
|
|
9
|
+
if (!endpoint || !token) {
|
|
10
|
+
process.stderr.write("mcp-bridge: OPENCODE_MCP_URL and OPENCODE_MCP_TOKEN are required\n")
|
|
11
|
+
process.exit(2)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
let sessionId = null
|
|
15
|
+
let protocolVersion = null
|
|
16
|
+
let buffer = ""
|
|
17
|
+
const aborters = new Map()
|
|
18
|
+
|
|
19
|
+
process.stdout.on("error", (error) => {
|
|
20
|
+
process.stderr.write(`mcp-bridge: stdout failed: ${error.message}\n`)
|
|
21
|
+
process.exit(1)
|
|
22
|
+
})
|
|
23
|
+
process.stderr.on("error", () => process.exit(1))
|
|
24
|
+
|
|
25
|
+
function write(message) {
|
|
26
|
+
process.stdout.write(`${JSON.stringify(message)}\n`)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function log(message) {
|
|
30
|
+
process.stderr.write(`mcp-bridge: ${message}\n`)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function signalWithTimeout(external) {
|
|
34
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return external
|
|
35
|
+
if (typeof AbortSignal.timeout !== "function") return external
|
|
36
|
+
const timeout = AbortSignal.timeout(timeoutMs)
|
|
37
|
+
if (typeof AbortSignal.any !== "function") return external ?? timeout
|
|
38
|
+
return external ? AbortSignal.any([external, timeout]) : timeout
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function post(message, signal) {
|
|
42
|
+
const headers = {
|
|
43
|
+
"content-type": "application/json",
|
|
44
|
+
accept: "application/json, text/event-stream",
|
|
45
|
+
authorization: `Bearer ${token}`,
|
|
46
|
+
}
|
|
47
|
+
if (sessionId) headers["mcp-session-id"] = sessionId
|
|
48
|
+
if (protocolVersion) headers["mcp-protocol-version"] = protocolVersion
|
|
49
|
+
|
|
50
|
+
const response = await fetch(endpoint, {
|
|
51
|
+
method: "POST",
|
|
52
|
+
headers,
|
|
53
|
+
body: JSON.stringify(message),
|
|
54
|
+
signal: signalWithTimeout(signal),
|
|
55
|
+
})
|
|
56
|
+
sessionId = response.headers.get("mcp-session-id") ?? sessionId
|
|
57
|
+
if (!response.ok) {
|
|
58
|
+
const text = await response.text().catch(() => "")
|
|
59
|
+
throw new Error(`MCP endpoint returned HTTP ${response.status}${text ? `: ${text.slice(0, 200)}` : ""}`)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const contentType = response.headers.get("content-type") ?? ""
|
|
63
|
+
const text = await response.text()
|
|
64
|
+
if (contentType.includes("text/event-stream")) {
|
|
65
|
+
const payloads = []
|
|
66
|
+
for (const line of text.split("\n")) {
|
|
67
|
+
if (!line.startsWith("data:")) continue
|
|
68
|
+
const data = line.slice(5).trim()
|
|
69
|
+
if (!data || data === "[DONE]") continue
|
|
70
|
+
try {
|
|
71
|
+
payloads.push(JSON.parse(data))
|
|
72
|
+
} catch {
|
|
73
|
+
// ignore non-JSON events
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return payloads
|
|
77
|
+
}
|
|
78
|
+
if (!text.trim()) return []
|
|
79
|
+
const parsed = JSON.parse(text)
|
|
80
|
+
return Array.isArray(parsed) ? parsed : [parsed]
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function handle(message) {
|
|
84
|
+
if (Array.isArray(message)) {
|
|
85
|
+
await Promise.all(message.map((entry) => handle(entry)))
|
|
86
|
+
return
|
|
87
|
+
}
|
|
88
|
+
if (!message || typeof message !== "object") return
|
|
89
|
+
if (!("id" in message) || message.id === null || message.id === undefined) {
|
|
90
|
+
if (message.method === "notifications/cancelled") {
|
|
91
|
+
const requestId = message.params?.requestId
|
|
92
|
+
aborters.get(requestId)?.abort()
|
|
93
|
+
aborters.delete(requestId)
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
await post(message)
|
|
97
|
+
} catch (error) {
|
|
98
|
+
log(error instanceof Error ? error.message : String(error))
|
|
99
|
+
}
|
|
100
|
+
return
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const controller = new AbortController()
|
|
104
|
+
aborters.set(message.id, controller)
|
|
105
|
+
try {
|
|
106
|
+
const payloads = await post(message, controller.signal)
|
|
107
|
+
const response = payloads.find((payload) => payload && payload.id === message.id) ?? payloads[0]
|
|
108
|
+
if (!response) {
|
|
109
|
+
write({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: "MCP server returned no response" } })
|
|
110
|
+
return
|
|
111
|
+
}
|
|
112
|
+
if (message.method === "initialize" && response.result && typeof response.result.protocolVersion === "string") {
|
|
113
|
+
protocolVersion = response.result.protocolVersion
|
|
114
|
+
}
|
|
115
|
+
write(response)
|
|
116
|
+
} catch (error) {
|
|
117
|
+
write({
|
|
118
|
+
jsonrpc: "2.0",
|
|
119
|
+
id: message.id,
|
|
120
|
+
error: { code: -32000, message: error instanceof Error ? error.message : String(error) },
|
|
121
|
+
})
|
|
122
|
+
} finally {
|
|
123
|
+
aborters.delete(message.id)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
process.stdin.setEncoding("utf8")
|
|
128
|
+
process.stdin.on("data", (chunk) => {
|
|
129
|
+
buffer += chunk
|
|
130
|
+
let index
|
|
131
|
+
while ((index = buffer.indexOf("\n")) >= 0) {
|
|
132
|
+
const line = buffer.slice(0, index).trim()
|
|
133
|
+
buffer = buffer.slice(index + 1)
|
|
134
|
+
if (!line) continue
|
|
135
|
+
let message
|
|
136
|
+
try {
|
|
137
|
+
message = JSON.parse(line)
|
|
138
|
+
} catch {
|
|
139
|
+
log(`ignoring invalid JSON: ${line.slice(0, 200)}`)
|
|
140
|
+
continue
|
|
141
|
+
}
|
|
142
|
+
void handle(message)
|
|
143
|
+
}
|
|
144
|
+
})
|
|
145
|
+
process.stdin.on("end", () => process.exit(0))
|
|
146
|
+
process.stdin.on("close", () => process.exit(0))
|
|
147
|
+
process.stdin.on("error", (error) => {
|
|
148
|
+
log(error.message)
|
|
149
|
+
process.exit(1)
|
|
150
|
+
})
|