opencode-claude-code-acpbridge 0.6.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/README.md +313 -0
- package/dist/acp/claude-config.d.ts +97 -0
- package/dist/acp/claude-config.d.ts.map +1 -0
- package/dist/acp/claude-config.js +60 -0
- package/dist/acp/claude-config.js.map +1 -0
- package/dist/acp/mcp-host.d.ts +45 -0
- package/dist/acp/mcp-host.d.ts.map +1 -0
- package/dist/acp/mcp-host.js +131 -0
- package/dist/acp/mcp-host.js.map +1 -0
- package/dist/acp/mcp-runtime.d.ts +2 -0
- package/dist/acp/mcp-runtime.d.ts.map +1 -0
- package/dist/acp/mcp-runtime.js +156 -0
- package/dist/acp/mcp-runtime.js.map +1 -0
- package/dist/bin/cli.d.ts +3 -0
- package/dist/bin/cli.d.ts.map +1 -0
- package/dist/bin/cli.js +48 -0
- package/dist/bin/cli.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -0
- package/dist/plugin/cache.d.ts +5 -0
- package/dist/plugin/cache.d.ts.map +1 -0
- package/dist/plugin/cache.js +45 -0
- package/dist/plugin/cache.js.map +1 -0
- package/dist/plugin/catalog.d.ts +30 -0
- package/dist/plugin/catalog.d.ts.map +1 -0
- package/dist/plugin/catalog.js +110 -0
- package/dist/plugin/catalog.js.map +1 -0
- package/dist/plugin/discover.d.ts +29 -0
- package/dist/plugin/discover.d.ts.map +1 -0
- package/dist/plugin/discover.js +82 -0
- package/dist/plugin/discover.js.map +1 -0
- package/dist/plugin/index.d.ts +14 -0
- package/dist/plugin/index.d.ts.map +1 -0
- package/dist/plugin/index.js +169 -0
- package/dist/plugin/index.js.map +1 -0
- package/dist/plugin/sessions.d.ts +30 -0
- package/dist/plugin/sessions.d.ts.map +1 -0
- package/dist/plugin/sessions.js +54 -0
- package/dist/plugin/sessions.js.map +1 -0
- package/dist/provider/env.d.ts +44 -0
- package/dist/provider/env.d.ts.map +1 -0
- package/dist/provider/env.js +79 -0
- package/dist/provider/env.js.map +1 -0
- package/dist/provider/factory.d.ts +70 -0
- package/dist/provider/factory.d.ts.map +1 -0
- package/dist/provider/factory.js +112 -0
- package/dist/provider/factory.js.map +1 -0
- package/dist/provider/model.d.ts +66 -0
- package/dist/provider/model.d.ts.map +1 -0
- package/dist/provider/model.js +640 -0
- package/dist/provider/model.js.map +1 -0
- package/docs/DEVELOPMENT.md +142 -0
- package/examples/01-minimal.jsonc +12 -0
- package/examples/02-permisos-por-agente.jsonc +29 -0
- package/examples/03-fidelidad-opencode.jsonc +20 -0
- package/examples/04-modelo-y-esfuerzo.jsonc +30 -0
- package/examples/05-agentes-personalizados.jsonc +19 -0
- package/examples/06-ecosistema-claude.jsonc +23 -0
- package/examples/07-provider-manual.jsonc +38 -0
- package/examples/README.md +20 -0
- package/package.json +53 -0
|
@@ -0,0 +1,640 @@
|
|
|
1
|
+
// LanguageModelV3 orchestrator: backs an OpenCode model with the Claude Code ACP
|
|
2
|
+
// agent while keeping OpenCode as the tool executor ("OpenCode orquesta").
|
|
3
|
+
//
|
|
4
|
+
// Session strategy (efficiency + prompt caching):
|
|
5
|
+
// - The AI SDK is stateless: OpenCode resends the FULL prompt every doStream.
|
|
6
|
+
// - We keep a PERSISTENT ACP session per conversation. On the first turn of a
|
|
7
|
+
// conversation we send the whole history; on later turns we send only the
|
|
8
|
+
// DELTA (the last user message) — the agent already holds its side (its
|
|
9
|
+
// answers + tool-results) in the session and reuses Claude's prompt cache.
|
|
10
|
+
// - We reset to a fresh session only when the conversation changes (different
|
|
11
|
+
// first user message) or the tool set changes — this isolates OpenCode's
|
|
12
|
+
// title/small-model call (tools=0) from the real call (tools=N).
|
|
13
|
+
//
|
|
14
|
+
// Tool flow: when the agent calls an MCP tool, the host fires onToolCall → we
|
|
15
|
+
// emit a `tool-call` with the REAL OpenCode tool name, finish `tool-calls`, and
|
|
16
|
+
// leave the MCP tools/call DEFERRED; the next doStream brings OpenCode's
|
|
17
|
+
// tool-result → we resolve it and the same agent turn continues.
|
|
18
|
+
import { spawn } from "node:child_process";
|
|
19
|
+
import { Writable, Readable } from "node:stream";
|
|
20
|
+
import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
|
|
21
|
+
import { McpHost } from "../acp/mcp-host.js";
|
|
22
|
+
import { buildClaudeCodeOptions, resolveConfigDir, } from "../acp/claude-config.js";
|
|
23
|
+
import { setLink, updateUsage } from "../plugin/sessions.js";
|
|
24
|
+
const DEBUG = !!process.env.ACP_DEBUG;
|
|
25
|
+
const dbg = (m) => { if (DEBUG)
|
|
26
|
+
process.stderr.write(`[acp-orchestrator] ${m}\n`); };
|
|
27
|
+
function emptyUsage() {
|
|
28
|
+
return {
|
|
29
|
+
inputTokens: { total: undefined, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
|
|
30
|
+
outputTokens: { total: undefined, text: undefined },
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** ACP turn `Usage` → `LanguageModelV3Usage` (so OpenCode shows the token consumption). */
|
|
34
|
+
function mapUsage(u) {
|
|
35
|
+
if (!u || typeof u !== "object")
|
|
36
|
+
return emptyUsage();
|
|
37
|
+
const noCache = u.inputTokens ?? undefined;
|
|
38
|
+
const cacheRead = u.cachedReadTokens ?? undefined;
|
|
39
|
+
const cacheWrite = u.cachedWriteTokens ?? undefined;
|
|
40
|
+
const inTotal = (noCache ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0);
|
|
41
|
+
return {
|
|
42
|
+
inputTokens: { total: inTotal || undefined, noCache, cacheRead, cacheWrite },
|
|
43
|
+
outputTokens: { total: u.outputTokens ?? undefined, text: u.outputTokens ?? undefined },
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** ACP usage is cumulative per session → subtract the previous snapshot to get this turn's. */
|
|
47
|
+
function subtractUsage(acc, prev) {
|
|
48
|
+
if (!acc || typeof acc !== "object")
|
|
49
|
+
return acc;
|
|
50
|
+
if (!prev)
|
|
51
|
+
return acc;
|
|
52
|
+
const d = (a, b) => Math.max(0, (a ?? 0) - (b ?? 0));
|
|
53
|
+
return {
|
|
54
|
+
inputTokens: d(acc.inputTokens, prev.inputTokens),
|
|
55
|
+
outputTokens: d(acc.outputTokens, prev.outputTokens),
|
|
56
|
+
cachedReadTokens: d(acc.cachedReadTokens, prev.cachedReadTokens),
|
|
57
|
+
cachedWriteTokens: d(acc.cachedWriteTokens, prev.cachedWriteTokens),
|
|
58
|
+
totalTokens: d(acc.totalTokens, prev.totalTokens),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function hashText(s) {
|
|
62
|
+
let h = 5381;
|
|
63
|
+
for (let i = 0; i < s.length; i++)
|
|
64
|
+
h = ((h << 5) + h) ^ s.charCodeAt(i);
|
|
65
|
+
return (h >>> 0).toString(36);
|
|
66
|
+
}
|
|
67
|
+
export class ACPOrchestratorModel {
|
|
68
|
+
config;
|
|
69
|
+
specificationVersion = "v3";
|
|
70
|
+
provider = "acp";
|
|
71
|
+
modelId;
|
|
72
|
+
supportedUrls = {};
|
|
73
|
+
agent = null;
|
|
74
|
+
connection = null;
|
|
75
|
+
connecting = null;
|
|
76
|
+
current = null;
|
|
77
|
+
idSeq = 0;
|
|
78
|
+
promptCaps = {};
|
|
79
|
+
constructor(config) {
|
|
80
|
+
this.config = config;
|
|
81
|
+
this.modelId = config.modelId ?? "claude-code";
|
|
82
|
+
}
|
|
83
|
+
// ---- LanguageModelV3 ------------------------------------------------------
|
|
84
|
+
async doStream(options) {
|
|
85
|
+
const continuation = this.detectContinuation(options.prompt);
|
|
86
|
+
const stream = new ReadableStream({
|
|
87
|
+
start: (controller) => void this.onStart(controller, options, continuation),
|
|
88
|
+
cancel: () => this.onCancel(),
|
|
89
|
+
});
|
|
90
|
+
return { stream, warnings: [] };
|
|
91
|
+
}
|
|
92
|
+
async doGenerate(options) {
|
|
93
|
+
const { stream } = await this.doStream(options);
|
|
94
|
+
const content = [];
|
|
95
|
+
let text = "";
|
|
96
|
+
let finishReason = { unified: "stop", raw: undefined };
|
|
97
|
+
let usage = emptyUsage();
|
|
98
|
+
const reader = stream.getReader();
|
|
99
|
+
for (;;) {
|
|
100
|
+
const { done, value } = await reader.read();
|
|
101
|
+
if (done)
|
|
102
|
+
break;
|
|
103
|
+
if (value.type === "text-delta")
|
|
104
|
+
text += value.delta;
|
|
105
|
+
else if (value.type === "tool-call")
|
|
106
|
+
content.push(value);
|
|
107
|
+
else if (value.type === "finish") {
|
|
108
|
+
finishReason = value.finishReason;
|
|
109
|
+
usage = value.usage;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (text)
|
|
113
|
+
content.unshift({ type: "text", text });
|
|
114
|
+
return { content, finishReason, usage, warnings: [] };
|
|
115
|
+
}
|
|
116
|
+
// ---- turn lifecycle -------------------------------------------------------
|
|
117
|
+
async onStart(controller, options, continuation) {
|
|
118
|
+
try {
|
|
119
|
+
controller.enqueue({ type: "stream-start", warnings: [] });
|
|
120
|
+
// (1) Continuation of a deferred tool-call — resume the same agent turn.
|
|
121
|
+
if (continuation && this.current) {
|
|
122
|
+
this.current.controller = controller;
|
|
123
|
+
this.current.textId = null;
|
|
124
|
+
this.current.reasoningId = null;
|
|
125
|
+
for (const { toolCallId, result } of continuation) {
|
|
126
|
+
this.current.pendingTools.delete(toolCallId);
|
|
127
|
+
this.current.host.resolveToolCall(toolCallId, result);
|
|
128
|
+
}
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
await this.ensureConnected();
|
|
132
|
+
const tools = this.convertTools(options.tools);
|
|
133
|
+
const ctrl = this.effectiveCtrl(options);
|
|
134
|
+
const convKey = hashText(this.firstUserText(options.prompt));
|
|
135
|
+
const toolsKey = tools.map((t) => t.name).sort().join(",");
|
|
136
|
+
// System prompt is part of the identity: OpenCode can switch agents within a
|
|
137
|
+
// session (same history, different system prompt). The agent can't change its
|
|
138
|
+
// system prompt mid-session, so a system change forces a fresh session that
|
|
139
|
+
// replays the full history under the new system prompt.
|
|
140
|
+
const systemKey = hashText(this.systemText(options.prompt));
|
|
141
|
+
// Params baked into newSession's _meta (thinking/systemPromptMode) can't change
|
|
142
|
+
// mid-session → a change forces a fresh session. mode/effort are applied at
|
|
143
|
+
// runtime via set_mode/set_config_option instead (no reset needed).
|
|
144
|
+
const cfgKey = hashText(JSON.stringify({ t: ctrl.thinking, s: ctrl.systemPromptMode ?? "preset" }));
|
|
145
|
+
// Session registry plumbing (chat.params → providerOptions.acp): `ocSession`
|
|
146
|
+
// is the OpenCode key; `resumeId`/`resumeLen` come from the persistent registry.
|
|
147
|
+
const po = options.providerOptions?.[this.provider] ?? {};
|
|
148
|
+
const ocSession = po.ocSession;
|
|
149
|
+
const histLen = options.prompt.length;
|
|
150
|
+
// (2) Same conversation + tools + system + creation-cfg → reuse session, send only the delta.
|
|
151
|
+
if (this.current &&
|
|
152
|
+
this.current.convKey === convKey &&
|
|
153
|
+
this.current.toolsKey === toolsKey &&
|
|
154
|
+
this.current.systemKey === systemKey &&
|
|
155
|
+
this.current.cfgKey === cfgKey) {
|
|
156
|
+
dbg(`reuse session ${this.current.sessionId} — delta only (cache-friendly)`);
|
|
157
|
+
this.current.controller = controller;
|
|
158
|
+
this.current.textId = null;
|
|
159
|
+
this.current.reasoningId = null;
|
|
160
|
+
if (ocSession)
|
|
161
|
+
this.current.ocSession = ocSession;
|
|
162
|
+
await this.applySessionConfig(this.current, ctrl); // runtime mode/effort change
|
|
163
|
+
if (ocSession)
|
|
164
|
+
setLink(ocSession, this.current.sessionId, histLen);
|
|
165
|
+
const blocks = this.lastUserBlocks(options.prompt);
|
|
166
|
+
this.connection
|
|
167
|
+
.prompt({ sessionId: this.current.sessionId, prompt: blocks })
|
|
168
|
+
.then((resp) => this.onPromptDone(resp))
|
|
169
|
+
.catch((err) => this.onPromptError(err));
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
// (3) Need a session: new conversation / tools / system / cfg changed, OR a
|
|
173
|
+
// resumable session from a new process. Set up the MCP host once.
|
|
174
|
+
const reason = !this.current ? "new conversation"
|
|
175
|
+
: this.current.convKey !== convKey ? "new conversation"
|
|
176
|
+
: this.current.toolsKey !== toolsKey ? "tools changed"
|
|
177
|
+
: this.current.systemKey !== systemKey ? "system prompt changed"
|
|
178
|
+
: "config changed";
|
|
179
|
+
this.endTurn();
|
|
180
|
+
const host = new McpHost("opencode");
|
|
181
|
+
host.onToolCall((c) => this.onToolCall(c));
|
|
182
|
+
await host.start();
|
|
183
|
+
host.setTools(tools);
|
|
184
|
+
const serverConfig = host.getServerConfig();
|
|
185
|
+
// Try to RESUME a registered Claude Code session (new process, no live state,
|
|
186
|
+
// history grew rather than diverged) → no history replay (saves tokens). Else
|
|
187
|
+
// create a fresh session and replay the full history.
|
|
188
|
+
const resumeId = po.resumeId;
|
|
189
|
+
let sessionId;
|
|
190
|
+
let replayFull = true;
|
|
191
|
+
if (!this.current && resumeId && histLen > (po.resumeLen ?? 0)) {
|
|
192
|
+
try {
|
|
193
|
+
await this.connection.unstable_resumeSession({
|
|
194
|
+
sessionId: resumeId,
|
|
195
|
+
cwd: this.config.cwd ?? process.cwd(),
|
|
196
|
+
mcpServers: [serverConfig],
|
|
197
|
+
// Re-apply the clean-brain options on resume too. Without this the agent
|
|
198
|
+
// falls back to its defaults (--tools default, --setting-sources=user,
|
|
199
|
+
// project,local, no --strict-mcp-config) and the resumed session regains
|
|
200
|
+
// native tools + the claude.ai connectors. getOrCreateSession forwards
|
|
201
|
+
// this _meta to createSession when the session isn't live in-process.
|
|
202
|
+
_meta: { claudeCode: { options: buildClaudeCodeOptions(ctrl) } },
|
|
203
|
+
});
|
|
204
|
+
sessionId = resumeId;
|
|
205
|
+
replayFull = false;
|
|
206
|
+
dbg(`resume ${resumeId} (oc=${ocSession ?? "?"}) — no history replay`);
|
|
207
|
+
}
|
|
208
|
+
catch (e) {
|
|
209
|
+
dbg(`resume ${resumeId} failed (${e instanceof Error ? e.message : String(e)}) — fresh session`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (!sessionId) {
|
|
213
|
+
// OpenCode's system prompt → _meta.systemPrompt (preset/append/replace).
|
|
214
|
+
const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
|
|
215
|
+
const sysMeta = this.buildSystemPromptMeta(options.prompt, ctrl.systemPromptMode ?? "preset");
|
|
216
|
+
if (sysMeta !== undefined)
|
|
217
|
+
meta.systemPrompt = sysMeta;
|
|
218
|
+
const session = await this.connection.newSession({
|
|
219
|
+
cwd: this.config.cwd ?? process.cwd(),
|
|
220
|
+
mcpServers: [serverConfig],
|
|
221
|
+
_meta: meta,
|
|
222
|
+
});
|
|
223
|
+
sessionId = session.sessionId;
|
|
224
|
+
dbg(`new session ${sessionId} (${reason}) model=${session.models?.currentModelId ?? "?"} (requested: ${ctrl.model ?? "default"}, mode: ${ctrl.mode ?? "default"}, effort: ${ctrl.effort ?? "default"}) — tools(${tools.length})`);
|
|
225
|
+
}
|
|
226
|
+
if (!sessionId)
|
|
227
|
+
throw new Error("failed to create or resume an ACP session");
|
|
228
|
+
const t = {
|
|
229
|
+
host,
|
|
230
|
+
sessionId,
|
|
231
|
+
convKey,
|
|
232
|
+
toolsKey,
|
|
233
|
+
systemKey,
|
|
234
|
+
cfgKey,
|
|
235
|
+
ocSession,
|
|
236
|
+
// Resume path: seed the cumulative usage snapshot from the persisted
|
|
237
|
+
// registry so the first post-resume `subtractUsage` produces a real
|
|
238
|
+
// turn delta instead of the full cumulative.
|
|
239
|
+
lastUsage: replayFull ? undefined : po.resumeLastUsage,
|
|
240
|
+
controller,
|
|
241
|
+
pendingTools: new Set(),
|
|
242
|
+
textId: null,
|
|
243
|
+
reasoningId: null,
|
|
244
|
+
};
|
|
245
|
+
this.current = t;
|
|
246
|
+
await this.applySessionConfig(t, ctrl); // mode/effort at runtime
|
|
247
|
+
if (ocSession)
|
|
248
|
+
setLink(ocSession, sessionId, histLen);
|
|
249
|
+
this.connection
|
|
250
|
+
.prompt({ sessionId, prompt: replayFull ? this.convertMessages(options.prompt) : this.lastUserBlocks(options.prompt) })
|
|
251
|
+
.then((resp) => this.onPromptDone(resp))
|
|
252
|
+
.catch((err) => this.onPromptError(err));
|
|
253
|
+
}
|
|
254
|
+
catch (err) {
|
|
255
|
+
dbg(`onStart error: ${err instanceof Error ? err.message : String(err)}`);
|
|
256
|
+
controller.enqueue({ type: "error", error: err });
|
|
257
|
+
try {
|
|
258
|
+
controller.close();
|
|
259
|
+
}
|
|
260
|
+
catch { /* ignore */ }
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
onPromptDone(resp) {
|
|
264
|
+
const t = this.current;
|
|
265
|
+
if (!t || !t.controller)
|
|
266
|
+
return; // cut for a pending tool-call
|
|
267
|
+
this.closeBlocks(t);
|
|
268
|
+
const turn = subtractUsage(resp?.usage, t.lastUsage); // ACP usage is cumulative per session
|
|
269
|
+
if (resp?.usage) {
|
|
270
|
+
t.lastUsage = resp.usage;
|
|
271
|
+
if (t.ocSession)
|
|
272
|
+
updateUsage(t.ocSession, resp.usage); // survive process restarts
|
|
273
|
+
}
|
|
274
|
+
if (DEBUG && turn)
|
|
275
|
+
dbg(`usage(turn): in=${turn.inputTokens} out=${turn.outputTokens} cacheR=${turn.cachedReadTokens} cacheW=${turn.cachedWriteTokens}`);
|
|
276
|
+
t.controller.enqueue({
|
|
277
|
+
type: "finish",
|
|
278
|
+
usage: mapUsage(turn),
|
|
279
|
+
finishReason: { unified: resp?.stopReason === "max_tokens" ? "length" : "stop", raw: resp?.stopReason },
|
|
280
|
+
});
|
|
281
|
+
try {
|
|
282
|
+
t.controller.close();
|
|
283
|
+
}
|
|
284
|
+
catch { /* ignore */ }
|
|
285
|
+
t.controller = null; // keep the session for the next turn (delta)
|
|
286
|
+
}
|
|
287
|
+
onPromptError(err) {
|
|
288
|
+
const t = this.current;
|
|
289
|
+
if (!t || !t.controller)
|
|
290
|
+
return;
|
|
291
|
+
dbg(`prompt error: ${err instanceof Error ? err.message : String(err)}`);
|
|
292
|
+
t.controller.enqueue({ type: "error", error: err });
|
|
293
|
+
try {
|
|
294
|
+
t.controller.close();
|
|
295
|
+
}
|
|
296
|
+
catch { /* ignore */ }
|
|
297
|
+
t.controller = null;
|
|
298
|
+
}
|
|
299
|
+
/** Fired by the MCP host when the agent calls an OpenCode tool. */
|
|
300
|
+
onToolCall(call) {
|
|
301
|
+
const t = this.current;
|
|
302
|
+
if (!t || !t.controller)
|
|
303
|
+
return;
|
|
304
|
+
dbg(`agent → tool-call ${call.name} (${call.toolCallId}) → emit to OpenCode`);
|
|
305
|
+
this.closeBlocks(t);
|
|
306
|
+
t.pendingTools.add(call.toolCallId);
|
|
307
|
+
const inputJson = JSON.stringify(call.args ?? {});
|
|
308
|
+
t.controller.enqueue({ type: "tool-input-start", id: call.toolCallId, toolName: call.name });
|
|
309
|
+
t.controller.enqueue({ type: "tool-input-delta", id: call.toolCallId, delta: inputJson });
|
|
310
|
+
t.controller.enqueue({ type: "tool-input-end", id: call.toolCallId });
|
|
311
|
+
t.controller.enqueue({ type: "tool-call", toolCallId: call.toolCallId, toolName: call.name, input: inputJson });
|
|
312
|
+
t.controller.enqueue({ type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
|
|
313
|
+
try {
|
|
314
|
+
t.controller.close();
|
|
315
|
+
}
|
|
316
|
+
catch { /* ignore */ }
|
|
317
|
+
t.controller = null; // DO NOT resolve yet — wait for the continuation doStream
|
|
318
|
+
}
|
|
319
|
+
/** Fired by the ACP client on session/update. */
|
|
320
|
+
onSessionUpdate(update) {
|
|
321
|
+
const t = this.current;
|
|
322
|
+
if (!t || !t.controller)
|
|
323
|
+
return;
|
|
324
|
+
switch (update?.sessionUpdate) {
|
|
325
|
+
case "agent_message_chunk":
|
|
326
|
+
if (update.content?.type === "text") {
|
|
327
|
+
if (!t.textId) {
|
|
328
|
+
t.textId = `t${++this.idSeq}`;
|
|
329
|
+
t.controller.enqueue({ type: "text-start", id: t.textId });
|
|
330
|
+
}
|
|
331
|
+
t.controller.enqueue({ type: "text-delta", id: t.textId, delta: update.content.text });
|
|
332
|
+
}
|
|
333
|
+
break;
|
|
334
|
+
case "agent_thought_chunk":
|
|
335
|
+
if (update.content?.type === "text") {
|
|
336
|
+
if (!t.reasoningId) {
|
|
337
|
+
t.reasoningId = `r${++this.idSeq}`;
|
|
338
|
+
t.controller.enqueue({ type: "reasoning-start", id: t.reasoningId });
|
|
339
|
+
}
|
|
340
|
+
t.controller.enqueue({ type: "reasoning-delta", id: t.reasoningId, delta: update.content.text });
|
|
341
|
+
}
|
|
342
|
+
break;
|
|
343
|
+
default:
|
|
344
|
+
break; // tool_call/tool_call_update are informational; MCP host drives emission
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
closeBlocks(t) {
|
|
348
|
+
if (t.textId && t.controller) {
|
|
349
|
+
t.controller.enqueue({ type: "text-end", id: t.textId });
|
|
350
|
+
t.textId = null;
|
|
351
|
+
}
|
|
352
|
+
if (t.reasoningId && t.controller) {
|
|
353
|
+
t.controller.enqueue({ type: "reasoning-end", id: t.reasoningId });
|
|
354
|
+
t.reasoningId = null;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
endTurn() {
|
|
358
|
+
const t = this.current;
|
|
359
|
+
if (!t)
|
|
360
|
+
return;
|
|
361
|
+
try {
|
|
362
|
+
if (this.connection && t.sessionId)
|
|
363
|
+
this.connection.cancel?.({ sessionId: t.sessionId });
|
|
364
|
+
}
|
|
365
|
+
catch { /* ignore */ }
|
|
366
|
+
t.host.stop();
|
|
367
|
+
this.current = null;
|
|
368
|
+
}
|
|
369
|
+
/** Provider config overlaid with per-call `providerOptions.acp` (per-agent mode/effort/…). */
|
|
370
|
+
effectiveCtrl(options) {
|
|
371
|
+
const ctrl = { ...(this.config.claudeCode ?? {}) };
|
|
372
|
+
const po = options.providerOptions?.[this.provider];
|
|
373
|
+
if (po && typeof po === "object") {
|
|
374
|
+
if (po.mode)
|
|
375
|
+
ctrl.mode = po.mode;
|
|
376
|
+
if (po.effort)
|
|
377
|
+
ctrl.effort = po.effort;
|
|
378
|
+
if (po.thinking)
|
|
379
|
+
ctrl.thinking = po.thinking;
|
|
380
|
+
if (po.systemPromptMode)
|
|
381
|
+
ctrl.systemPromptMode = po.systemPromptMode;
|
|
382
|
+
}
|
|
383
|
+
// OpenCode's modelId maps to Claude's model unless claudeCode.model overrides it.
|
|
384
|
+
if (!ctrl.model && this.modelId && this.modelId !== "claude-code")
|
|
385
|
+
ctrl.model = this.modelId;
|
|
386
|
+
return ctrl;
|
|
387
|
+
}
|
|
388
|
+
/** Apply runtime config (mode/effort) to a live ACP session via set_mode/set_config_option. */
|
|
389
|
+
async applySessionConfig(t, ctrl) {
|
|
390
|
+
if (ctrl.mode && ctrl.mode !== t.appliedMode) {
|
|
391
|
+
try {
|
|
392
|
+
await this.connection.setSessionMode({ sessionId: t.sessionId, modeId: ctrl.mode });
|
|
393
|
+
t.appliedMode = ctrl.mode;
|
|
394
|
+
dbg(`mode → ${ctrl.mode}`);
|
|
395
|
+
}
|
|
396
|
+
catch (e) {
|
|
397
|
+
dbg(`setSessionMode(${ctrl.mode}) failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (ctrl.effort && ctrl.effort !== t.appliedEffort) {
|
|
401
|
+
try {
|
|
402
|
+
await this.connection.setSessionConfigOption({ sessionId: t.sessionId, configId: "effort", value: ctrl.effort });
|
|
403
|
+
t.appliedEffort = ctrl.effort;
|
|
404
|
+
dbg(`effort → ${ctrl.effort}`);
|
|
405
|
+
}
|
|
406
|
+
catch (e) {
|
|
407
|
+
dbg(`setSessionConfigOption(effort=${ctrl.effort}) failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
// ---- connection -----------------------------------------------------------
|
|
412
|
+
ensureConnected() {
|
|
413
|
+
if (this.connection)
|
|
414
|
+
return Promise.resolve();
|
|
415
|
+
if (this.connecting)
|
|
416
|
+
return this.connecting;
|
|
417
|
+
this.connecting = this.connect();
|
|
418
|
+
return this.connecting;
|
|
419
|
+
}
|
|
420
|
+
async connect() {
|
|
421
|
+
const ctrl = this.config.claudeCode ?? {};
|
|
422
|
+
const env = { ...process.env, ...(this.config.env ?? {}) };
|
|
423
|
+
if (this.config.claudeExecutable)
|
|
424
|
+
env.CLAUDE_CODE_EXECUTABLE = this.config.claudeExecutable;
|
|
425
|
+
const configDir = resolveConfigDir(ctrl);
|
|
426
|
+
if (configDir)
|
|
427
|
+
env.CLAUDE_CONFIG_DIR = configDir;
|
|
428
|
+
if (this.config.streamCloseTimeoutMs)
|
|
429
|
+
env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT = String(this.config.streamCloseTimeoutMs);
|
|
430
|
+
// Model selection: the agent resolves the effective model from ANTHROPIC_MODEL
|
|
431
|
+
// (getAvailableModels overrides options.model otherwise). claudeCode.model wins,
|
|
432
|
+
// else the OpenCode modelId (unless the neutral "claude-code").
|
|
433
|
+
const model = ctrl.model ?? (this.modelId !== "claude-code" ? this.modelId : undefined);
|
|
434
|
+
if (model)
|
|
435
|
+
env.ANTHROPIC_MODEL = model;
|
|
436
|
+
this.agent = spawn(this.config.command, this.config.args ?? [], {
|
|
437
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
438
|
+
cwd: this.config.cwd ?? process.cwd(),
|
|
439
|
+
env,
|
|
440
|
+
});
|
|
441
|
+
// If the agent dies (e.g. after an API error) a pending write to its stdin
|
|
442
|
+
// raises EPIPE; swallow pipe errors so they don't crash the OpenCode process.
|
|
443
|
+
this.agent.on("error", () => { });
|
|
444
|
+
this.agent.stdin?.on("error", () => { });
|
|
445
|
+
this.agent.stdout?.on("error", () => { });
|
|
446
|
+
// The agent's stderr carries its own diagnostics — e.g. claude-agent-acp's
|
|
447
|
+
// benign `No onPostToolUseHook found` (expected here: OpenCode, not the agent,
|
|
448
|
+
// executes the tools, so the agent never sees the tool_response that would fire
|
|
449
|
+
// its PostToolUse hook). With stdio "inherit" these print RAW over OpenCode's
|
|
450
|
+
// TUI; pipe them and forward to our stderr ONLY under ACP_DEBUG so the TUI stays
|
|
451
|
+
// clean in normal use.
|
|
452
|
+
this.agent.stderr?.on("error", () => { });
|
|
453
|
+
this.agent.stderr?.on("data", (chunk) => { if (DEBUG)
|
|
454
|
+
process.stderr.write(chunk); });
|
|
455
|
+
const stream = ndJsonStream(Writable.toWeb(this.agent.stdin), Readable.toWeb(this.agent.stdout));
|
|
456
|
+
const self = this;
|
|
457
|
+
this.connection = new ClientSideConnection(() => ({
|
|
458
|
+
async sessionUpdate(params) { self.onSessionUpdate(params.update); },
|
|
459
|
+
async requestPermission(params) {
|
|
460
|
+
const opt = params.options?.find((o) => o.optionId === "allow" || o.kind === "allow_once") ?? params.options?.[0];
|
|
461
|
+
return { outcome: { outcome: "selected", optionId: opt?.optionId ?? "allow" } };
|
|
462
|
+
},
|
|
463
|
+
async writeTextFile() { return {}; },
|
|
464
|
+
async readTextFile() { return { content: "" }; },
|
|
465
|
+
}), stream);
|
|
466
|
+
const initResult = await this.connection.initialize({
|
|
467
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
468
|
+
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
|
469
|
+
});
|
|
470
|
+
this.promptCaps = (initResult?.agentCapabilities?.promptCapabilities ?? {});
|
|
471
|
+
dbg(`connected to agent — promptCapabilities: ${JSON.stringify(this.promptCaps)}`);
|
|
472
|
+
}
|
|
473
|
+
onCancel() {
|
|
474
|
+
this.endTurn();
|
|
475
|
+
}
|
|
476
|
+
cleanup() {
|
|
477
|
+
this.endTurn();
|
|
478
|
+
try {
|
|
479
|
+
this.agent?.kill();
|
|
480
|
+
}
|
|
481
|
+
catch { /* ignore */ }
|
|
482
|
+
this.agent = null;
|
|
483
|
+
this.connection = null;
|
|
484
|
+
this.connecting = null;
|
|
485
|
+
}
|
|
486
|
+
// ---- conversions ----------------------------------------------------------
|
|
487
|
+
convertTools(tools) {
|
|
488
|
+
if (!tools)
|
|
489
|
+
return [];
|
|
490
|
+
const out = [];
|
|
491
|
+
for (const t of tools) {
|
|
492
|
+
if (t.type === "function") {
|
|
493
|
+
out.push({
|
|
494
|
+
name: t.name,
|
|
495
|
+
description: t.description,
|
|
496
|
+
inputSchema: t.inputSchema ?? { type: "object", properties: {} },
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return out;
|
|
501
|
+
}
|
|
502
|
+
/** Text of the first user message — stable identifier for the conversation. */
|
|
503
|
+
firstUserText(prompt) {
|
|
504
|
+
for (const m of prompt) {
|
|
505
|
+
if (m.role !== "user")
|
|
506
|
+
continue;
|
|
507
|
+
if (typeof m.content === "string")
|
|
508
|
+
return m.content;
|
|
509
|
+
return m.content.filter((p) => p.type === "text").map((p) => p.text).join("");
|
|
510
|
+
}
|
|
511
|
+
return "";
|
|
512
|
+
}
|
|
513
|
+
messageToBlocks(msg, withPrefix) {
|
|
514
|
+
const prefixes = { system: "System: ", assistant: "Assistant: ", tool: "", user: "" };
|
|
515
|
+
const prefix = withPrefix ? (prefixes[msg.role] ?? "") : "";
|
|
516
|
+
if (typeof msg.content === "string")
|
|
517
|
+
return [{ type: "text", text: `${prefix}${msg.content}` }];
|
|
518
|
+
const blocks = [];
|
|
519
|
+
let first = true;
|
|
520
|
+
for (const part of msg.content) {
|
|
521
|
+
const px = first ? prefix : "";
|
|
522
|
+
if (part.type === "text") {
|
|
523
|
+
blocks.push({ type: "text", text: px + part.text });
|
|
524
|
+
first = false;
|
|
525
|
+
}
|
|
526
|
+
else if (part.type === "tool-call") {
|
|
527
|
+
blocks.push({ type: "text", text: `${px}[Called tool ${part.toolName}(${JSON.stringify(part.input)})]` });
|
|
528
|
+
first = false;
|
|
529
|
+
}
|
|
530
|
+
else if (part.type === "tool-result") {
|
|
531
|
+
blocks.push({ type: "text", text: `${px}[Tool ${part.toolName} result: ${this.outputToText(part.output)}]` });
|
|
532
|
+
first = false;
|
|
533
|
+
}
|
|
534
|
+
else if (part.type === "file") {
|
|
535
|
+
const fb = this.fileToBlock(part);
|
|
536
|
+
blocks.push(fb ?? { type: "text", text: `${px}[Attachment ${part.mediaType ?? "file"} not supported by the agent]` });
|
|
537
|
+
first = false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
return blocks;
|
|
541
|
+
}
|
|
542
|
+
/** Map an AI SDK file part to an ACP ContentBlock, honoring the agent's promptCapabilities. */
|
|
543
|
+
fileToBlock(part) {
|
|
544
|
+
const mt = part.mediaType || "application/octet-stream";
|
|
545
|
+
const data = this.toBase64(part.data);
|
|
546
|
+
if (!data)
|
|
547
|
+
return null; // URL or non-embeddable data
|
|
548
|
+
if (mt.startsWith("image/"))
|
|
549
|
+
return this.promptCaps.image ? { type: "image", data, mimeType: mt } : null;
|
|
550
|
+
if (mt.startsWith("audio/"))
|
|
551
|
+
return this.promptCaps.audio ? { type: "audio", data, mimeType: mt } : null;
|
|
552
|
+
if (mt.startsWith("video/"))
|
|
553
|
+
return null; // not representable in ACP / not understood by Claude
|
|
554
|
+
// PDFs and other documents → embedded resource (blob) when the agent accepts embedded context.
|
|
555
|
+
if (this.promptCaps.embeddedContext) {
|
|
556
|
+
const ext = mt.split("/")[1] || "bin";
|
|
557
|
+
return { type: "resource", resource: { uri: part.filename || `attachment.${ext}`, mimeType: mt, blob: data } };
|
|
558
|
+
}
|
|
559
|
+
return null;
|
|
560
|
+
}
|
|
561
|
+
toBase64(data) {
|
|
562
|
+
if (data instanceof Uint8Array)
|
|
563
|
+
return Buffer.from(data).toString("base64");
|
|
564
|
+
if (typeof data === "string")
|
|
565
|
+
return data.includes(",") ? data.split(",")[1] : data; // data URL or raw base64
|
|
566
|
+
return null; // URL or other — not embeddable
|
|
567
|
+
}
|
|
568
|
+
/** Full prompt flattened to ACP ContentBlocks (first turn of a conversation). */
|
|
569
|
+
convertMessages(prompt) {
|
|
570
|
+
const blocks = [];
|
|
571
|
+
for (const msg of prompt) {
|
|
572
|
+
if (msg.role === "system")
|
|
573
|
+
continue; // forwarded via _meta.systemPrompt
|
|
574
|
+
blocks.push(...this.messageToBlocks(msg, true));
|
|
575
|
+
}
|
|
576
|
+
return blocks.length ? blocks : [{ type: "text", text: "" }];
|
|
577
|
+
}
|
|
578
|
+
/** OpenCode's system text → `_meta.systemPrompt` per mode. */
|
|
579
|
+
buildSystemPromptMeta(prompt, mode) {
|
|
580
|
+
if (mode === "preset")
|
|
581
|
+
return undefined;
|
|
582
|
+
const text = this.systemText(prompt);
|
|
583
|
+
if (!text)
|
|
584
|
+
return undefined;
|
|
585
|
+
return mode === "replace" ? text : { append: text };
|
|
586
|
+
}
|
|
587
|
+
systemText(prompt) {
|
|
588
|
+
const parts = [];
|
|
589
|
+
for (const m of prompt) {
|
|
590
|
+
if (m.role !== "system")
|
|
591
|
+
continue;
|
|
592
|
+
parts.push(typeof m.content === "string"
|
|
593
|
+
? m.content
|
|
594
|
+
: m.content.filter((p) => p.type === "text").map((p) => p.text).join(""));
|
|
595
|
+
}
|
|
596
|
+
return parts.join("\n").trim();
|
|
597
|
+
}
|
|
598
|
+
/** Only the last user message (delta for a persistent session). */
|
|
599
|
+
lastUserBlocks(prompt) {
|
|
600
|
+
for (let i = prompt.length - 1; i >= 0; i--) {
|
|
601
|
+
if (prompt[i].role === "user") {
|
|
602
|
+
const b = this.messageToBlocks(prompt[i], false);
|
|
603
|
+
if (b.length)
|
|
604
|
+
return b;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return [{ type: "text", text: "" }];
|
|
608
|
+
}
|
|
609
|
+
detectContinuation(prompt) {
|
|
610
|
+
if (!this.current || this.current.pendingTools.size === 0)
|
|
611
|
+
return null;
|
|
612
|
+
const results = [];
|
|
613
|
+
for (const msg of prompt) {
|
|
614
|
+
if (msg.role !== "tool" && msg.role !== "assistant")
|
|
615
|
+
continue;
|
|
616
|
+
for (const part of msg.content) {
|
|
617
|
+
if (part?.type === "tool-result" && this.current.pendingTools.has(part.toolCallId)) {
|
|
618
|
+
results.push({ toolCallId: part.toolCallId, result: this.toMcpResult(part.output) });
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return results.length ? results : null;
|
|
623
|
+
}
|
|
624
|
+
outputToText(output) {
|
|
625
|
+
if (!output)
|
|
626
|
+
return "";
|
|
627
|
+
if (output.type === "text" || output.type === "error-text")
|
|
628
|
+
return String(output.value ?? "");
|
|
629
|
+
if (output.type === "json" || output.type === "error-json")
|
|
630
|
+
return JSON.stringify(output.value);
|
|
631
|
+
if (output.type === "content")
|
|
632
|
+
return output.value.map((c) => (c.type === "text" ? c.text : "")).join("");
|
|
633
|
+
return typeof output === "string" ? output : JSON.stringify(output);
|
|
634
|
+
}
|
|
635
|
+
toMcpResult(output) {
|
|
636
|
+
const isErr = output?.type === "error-text" || output?.type === "error-json";
|
|
637
|
+
return { content: [{ type: "text", text: this.outputToText(output) }], ...(isErr ? { isError: true } : {}) };
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
//# sourceMappingURL=model.js.map
|