opencode-claude-code-acpbridge 0.9.0 → 0.10.1
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/CHANGELOG.md +314 -191
- package/LICENSE +21 -0
- package/README.md +596 -279
- package/dist/acp/claude-config.d.ts +52 -0
- package/dist/acp/claude-config.d.ts.map +1 -1
- package/dist/acp/claude-config.js +6 -2
- package/dist/acp/claude-config.js.map +1 -1
- package/dist/acp/mcp-host.d.ts +10 -0
- package/dist/acp/mcp-host.d.ts.map +1 -1
- package/dist/acp/mcp-host.js +17 -4
- package/dist/acp/mcp-host.js.map +1 -1
- package/dist/acp/mcp-runtime.js +21 -4
- package/dist/acp/mcp-runtime.js.map +1 -1
- package/dist/log.d.ts +11 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +50 -0
- package/dist/log.js.map +1 -0
- package/dist/plugin/compat.d.ts +14 -0
- package/dist/plugin/compat.d.ts.map +1 -0
- package/dist/plugin/compat.js +45 -0
- package/dist/plugin/compat.js.map +1 -0
- package/dist/plugin/index.d.ts +3 -0
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/index.js +80 -14
- package/dist/plugin/index.js.map +1 -1
- package/dist/plugin/sessions.d.ts +11 -8
- package/dist/plugin/sessions.d.ts.map +1 -1
- package/dist/plugin/sessions.js +37 -4
- package/dist/plugin/sessions.js.map +1 -1
- package/dist/provider/factory.d.ts.map +1 -1
- package/dist/provider/factory.js +5 -3
- package/dist/provider/factory.js.map +1 -1
- package/dist/provider/history.d.ts +44 -0
- package/dist/provider/history.d.ts.map +1 -0
- package/dist/provider/history.js +145 -0
- package/dist/provider/history.js.map +1 -0
- package/dist/provider/model.d.ts +160 -23
- package/dist/provider/model.d.ts.map +1 -1
- package/dist/provider/model.js +1373 -480
- package/dist/provider/model.js.map +1 -1
- package/dist/provider/recorder.d.ts +5 -0
- package/dist/provider/recorder.d.ts.map +1 -0
- package/dist/provider/recorder.js +63 -0
- package/dist/provider/recorder.js.map +1 -0
- package/docs/DEVELOPMENT.md +413 -127
- package/examples/01-minimal.jsonc +12 -9
- package/examples/02-per-agent-permissions.jsonc +39 -0
- package/examples/03-opencode-fidelity.jsonc +21 -0
- package/examples/04-model-and-effort.jsonc +35 -0
- package/examples/05-custom-agents.jsonc +32 -0
- package/examples/06-claude-ecosystem.jsonc +28 -0
- package/examples/07-manual-provider.jsonc +55 -0
- package/examples/08-permission-bridge.jsonc +42 -0
- package/examples/README.md +35 -17
- package/package.json +35 -29
- package/examples/02-permisos-por-agente.jsonc +0 -34
- package/examples/03-fidelidad-opencode.jsonc +0 -21
- package/examples/04-modelo-y-esfuerzo.jsonc +0 -36
- package/examples/05-agentes-personalizados.jsonc +0 -29
- package/examples/06-ecosistema-claude.jsonc +0 -24
- package/examples/07-provider-manual.jsonc +0 -42
- package/examples/08-puente-permisos.jsonc +0 -50
package/dist/provider/model.js
CHANGED
|
@@ -8,38 +8,105 @@
|
|
|
8
8
|
// tool-results it received over MCP) and reuses Claude's prompt cache, which
|
|
9
9
|
// lives and dies with the session — so NOT recreating the session is exactly
|
|
10
10
|
// the same thing as preserving the cache.
|
|
11
|
-
// -
|
|
12
|
-
//
|
|
13
|
-
//
|
|
11
|
+
// - What it has seen: a fingerprint of the history already sent (history.ts,
|
|
12
|
+
// `historyMode`), plus its own output — answers it emitted and ids it minted —
|
|
13
|
+
// which OpenCode stores and sends back next turn and is never forwarded again.
|
|
14
|
+
// - Turns of ANOTHER model in between are caught up, labelled as such. A different
|
|
15
|
+
// agent or tool set keeps the session; another creation profile forks it; another
|
|
16
|
+
// acp model is a set_model. Only a genuine divergence (revert, compaction) starts
|
|
17
|
+
// over — and even those can fork back (`smartRevert`) or be adopted (`v2`).
|
|
14
18
|
//
|
|
15
19
|
// Tool flow: when the agent calls an MCP tool, the host fires onToolCall → we
|
|
16
20
|
// emit a `tool-call` with the REAL OpenCode tool name, finish `tool-calls`, and
|
|
17
21
|
// leave the MCP tools/call DEFERRED; the next doStream brings OpenCode's
|
|
18
|
-
// tool-result → we resolve it and the same agent turn continues.
|
|
19
|
-
// arriving while
|
|
22
|
+
// tool-result → we resolve it and the same agent turn continues. Calls issued
|
|
23
|
+
// together share a step; calls arriving while the stream is closed are queued.
|
|
24
|
+
// Text/thinking arriving meanwhile is BUFFERED, never dropped. Whatever the user
|
|
25
|
+
// wrote in between (steer) is delivered into the running turn; an interrupt stops it.
|
|
20
26
|
import { spawn } from "node:child_process";
|
|
21
27
|
import { Writable, Readable } from "node:stream";
|
|
22
28
|
import { randomBytes } from "node:crypto";
|
|
29
|
+
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
|
30
|
+
import { homedir } from "node:os";
|
|
31
|
+
import { join } from "node:path";
|
|
23
32
|
import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
|
|
33
|
+
import { APICallError } from "@ai-sdk/provider";
|
|
24
34
|
import { McpHost } from "../acp/mcp-host.js";
|
|
25
35
|
import { buildClaudeCodeOptions, resolveConfigDir, } from "../acp/claude-config.js";
|
|
26
36
|
import { setLink, updateUsage } from "../plugin/sessions.js";
|
|
27
37
|
import { addAlwaysRule, evaluate as evaluateBridge } from "../plugin/bridge-rules.js";
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
38
|
+
import { DEBUG, logger } from "../log.js";
|
|
39
|
+
import { record, recording, sanitizePrompt } from "./recorder.js";
|
|
40
|
+
import { anchorsOf, classifyAnchors, classifyHistory, firstUserText, hashText, historyOf, isTransient, msgKey, stripInjected, systemText, } from "./history.js";
|
|
41
|
+
const log = logger("acp-orchestrator");
|
|
42
|
+
const dbg = log.dbg;
|
|
31
43
|
/** Always-on notices (session lifecycle) — the user needs these without ACP_DEBUG. */
|
|
32
|
-
const note =
|
|
33
|
-
/** Max live conversations
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
44
|
+
const note = log.note;
|
|
45
|
+
/** Max live conversations (LRU, `maxLiveSessions`); older idle ones are closed. Each one
|
|
46
|
+
* is a Claude Code process (~250-400 MB) plus its MCP runtime. */
|
|
47
|
+
const MAX_LIVE_SESSIONS = 6;
|
|
48
|
+
/** Idle time before a resumable session is closed (`idleSessionTtlMs`). Coming back
|
|
49
|
+
* costs a process start: Anthropic keeps the prompt cache ~1 h on subscriptions. */
|
|
50
|
+
const IDLE_TTL_MS = 15 * 60_000;
|
|
51
|
+
/** Same for subagent sessions (`childSessionTtlMs`): rarely continued. */
|
|
52
|
+
const CHILD_TTL_MS = 2 * 60_000;
|
|
53
|
+
/** A turn still waiting on OpenCode after this long was abandoned. */
|
|
54
|
+
const ABANDONED_TTL_MS = 2 * 60 * 60_000;
|
|
55
|
+
/** Cap on a foreign tool-result replayed as text during catch-up (`catchupResultChars`).
|
|
56
|
+
* Big enough that switching back from another model doesn't lose what it read. */
|
|
57
|
+
const CATCHUP_RESULT_CHARS = 8000;
|
|
58
|
+
/** Ceiling for a full-history replay into a new session (~100k tokens): beyond it the
|
|
59
|
+
* oldest turns are dropped — a 656k-char replay was seen in the wild. */
|
|
60
|
+
const REPLAY_BUDGET_CHARS = 400_000;
|
|
37
61
|
/** Tope del buffer `pending` (chunks emitidos sin controller vivo): sin cap un turno
|
|
38
62
|
* largo con el stream cerrado lo haría crecer sin límite (OOM). */
|
|
39
63
|
const MAX_PENDING_PARTS = 1000;
|
|
40
64
|
/** System-prompt blocks worth forwarding to the agent as FACTUAL context (never as
|
|
41
65
|
* a system prompt — that would make Anthropic bill the session as extra usage). */
|
|
42
66
|
const CONTEXT_TAGS = ["env", "available_references"];
|
|
67
|
+
/** Bound on the hashes of emitted text kept per session (`ownTexts`). */
|
|
68
|
+
const MAX_OWN_TEXTS = 500;
|
|
69
|
+
/** How long a read-only tool-call waits for parallel siblings before its step closes. */
|
|
70
|
+
const TOOL_BATCH_MS = 40;
|
|
71
|
+
/** OpenCode V2 tools that are safe to run in parallel: announced to the agent with MCP
|
|
72
|
+
* `readOnlyHint`, so Claude Code issues them concurrently and they share one step. */
|
|
73
|
+
const PARALLEL_TOOLS = ["read", "glob", "grep", "webfetch", "websearch", "skill", "subagent"];
|
|
74
|
+
/** Native tools whose completion is not worth a line (the bridge shows them already). */
|
|
75
|
+
const NATIVE_SILENT = new Set(["ExitPlanMode", "EnterPlanMode", "TodoWrite"]);
|
|
76
|
+
/** Native tools whose RESULT matters to whoever continues the conversation. */
|
|
77
|
+
const NATIVE_WITH_RESULT = new Set(["Task", "Agent", "WebSearch", "WebFetch", "Skill"]);
|
|
78
|
+
/** Cap on a native tool result written into the answer (`nativeActivityChars`). */
|
|
79
|
+
const NATIVE_RESULT_CHARS = 2000;
|
|
80
|
+
/** How long the next turn waits for a native /compact still running. */
|
|
81
|
+
const COMPACT_WAIT_MS = 180_000;
|
|
82
|
+
/** Lead-in when another model's compaction summary is caught up into this session. */
|
|
83
|
+
const CHECKPOINT_NOTE = "<context_update>\n(The conversation continued in OpenCode with another model and was then compacted. " +
|
|
84
|
+
"OpenCode's checkpoint follows: it summarizes everything, including what happened after your last turn. " +
|
|
85
|
+
"Keep what you remember; use it to catch up on what you did not see.)\n</context_update>";
|
|
86
|
+
/** How long a turn being replaced may take to wind down after a cancel. */
|
|
87
|
+
const SETTLE_MS = 5000;
|
|
88
|
+
/** The `# Code Mode` section of OpenCode's system prompt (up to the next top-level
|
|
89
|
+
* heading or tag block), or "" when Code Mode is off. */
|
|
90
|
+
function codeModeSection(system) {
|
|
91
|
+
const start = system.search(/^# Code Mode\s*$/m);
|
|
92
|
+
if (start < 0)
|
|
93
|
+
return "";
|
|
94
|
+
const rest = system.slice(start);
|
|
95
|
+
const end = rest.slice(1).search(/^(# (?!#)|<[a-z_-]+>)/m);
|
|
96
|
+
return (end < 0 ? rest : rest.slice(0, end + 1)).trim();
|
|
97
|
+
}
|
|
98
|
+
/** OpenCode's record of a tool the user interrupted (or that never got a result):
|
|
99
|
+
* V2 sends it as a TEXT output holding `{"error":{"type":"aborted",…}}`. */
|
|
100
|
+
function isInterrupted(output) {
|
|
101
|
+
const v = output?.value;
|
|
102
|
+
const text = typeof v === "string" ? v : v != null ? JSON.stringify(v) : "";
|
|
103
|
+
if (/"type"\s*:\s*"aborted"/.test(text))
|
|
104
|
+
return true;
|
|
105
|
+
return /^(Tool execution interrupted|Tool result missing)/.test(text.trim());
|
|
106
|
+
}
|
|
107
|
+
function ownTextKey(text) {
|
|
108
|
+
return hashText(stripInjected(text).trim());
|
|
109
|
+
}
|
|
43
110
|
/** Dialog labels — also the strings the verdict parser looks for (see `questionVerdict`). */
|
|
44
111
|
const ALLOW_ONCE = "Allow once";
|
|
45
112
|
const ALWAYS_ALLOW = "Always allow";
|
|
@@ -63,26 +130,82 @@ function mapUsage(u) {
|
|
|
63
130
|
outputTokens: { total: u.outputTokens ?? undefined, text: u.outputTokens ?? undefined },
|
|
64
131
|
};
|
|
65
132
|
}
|
|
66
|
-
/**
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
133
|
+
/** Usage accounting (claude-agent-acp 0.31): `PromptResponse.usage` is the SUM over
|
|
134
|
+
* every API request of the turn — neither per request nor per session — so it is
|
|
135
|
+
* only used for ratios; the context size comes from `usage_update.used` (see
|
|
136
|
+
* `usageNow`). Subtracting snapshots (≤0.8) or reporting the sum as-is (0.9 working
|
|
137
|
+
* tree) both misled OpenCode's auto-compaction. */
|
|
138
|
+
async function collectGenerate(stream) {
|
|
139
|
+
const content = [];
|
|
140
|
+
let text = "";
|
|
141
|
+
let finishReason = { unified: "stop", raw: undefined };
|
|
142
|
+
let usage = emptyUsage();
|
|
143
|
+
const reader = stream.getReader();
|
|
144
|
+
for (;;) {
|
|
145
|
+
const { done, value } = await reader.read();
|
|
146
|
+
if (done)
|
|
147
|
+
break;
|
|
148
|
+
if (value.type === "text-delta")
|
|
149
|
+
text += value.delta;
|
|
150
|
+
else if (value.type === "tool-call")
|
|
151
|
+
content.push(value);
|
|
152
|
+
else if (value.type === "finish") {
|
|
153
|
+
finishReason = value.finishReason;
|
|
154
|
+
usage = value.usage;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (text)
|
|
158
|
+
content.unshift({ type: "text", text });
|
|
159
|
+
return { content, finishReason, usage, warnings: [] };
|
|
160
|
+
}
|
|
161
|
+
/** The call comes from an OpenCode subagent session (V2 sends the parent's id). */
|
|
162
|
+
function isChildCall(options) {
|
|
163
|
+
const h = options.headers ?? {};
|
|
164
|
+
return !!(h["x-parent-session-id"] ?? h["X-Parent-Session-Id"]);
|
|
165
|
+
}
|
|
166
|
+
/** Identity of what a session is CREATED with (`_meta.claudeCode.options` + system
|
|
167
|
+
* prompt mode). Model, effort and mode are applied live, so they don't count. */
|
|
168
|
+
function profileKey(ctrl, systemMode) {
|
|
169
|
+
const { model: _m, effort: _e, ...creation } = buildClaudeCodeOptions(ctrl);
|
|
170
|
+
return hashText(JSON.stringify({ o: creation, s: systemMode }));
|
|
171
|
+
}
|
|
172
|
+
/** Message + structured data of an ACP error (`RequestError.data.errorKind`, details). */
|
|
173
|
+
function errorText(err) {
|
|
174
|
+
if (!err || typeof err !== "object")
|
|
175
|
+
return String(err ?? "");
|
|
176
|
+
const e = err;
|
|
177
|
+
return [e.message, e.data !== undefined ? JSON.stringify(e.data) : ""].filter(Boolean).join(" ");
|
|
80
178
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
179
|
+
/** Claude's usage/rate limit, rewritten so the user knows to switch models — and in
|
|
180
|
+
* words OpenCode's retry classifier doesn't match ("try again", "overloaded"…), so it
|
|
181
|
+
* isn't retried in a loop against an exhausted subscription. */
|
|
182
|
+
export function limitError(err) {
|
|
183
|
+
const raw = errorText(err);
|
|
184
|
+
if (!/usage limit|rate[ _-]?limit|billing_error|hit your limit|limit reached|out of (?:extra )?usage|quota exceeded|\b429\b/i.test(raw))
|
|
185
|
+
return undefined;
|
|
186
|
+
const epoch = raw.match(/\|(\d{10})\b/)?.[1];
|
|
187
|
+
const resets = raw.match(/resets? (?:at )?([^.,;\n"]+)/i)?.[1]?.trim();
|
|
188
|
+
const when = epoch ? new Date(Number(epoch) * 1000).toLocaleString() : resets;
|
|
189
|
+
// An APICallError with HTTP 402 and `x-should-retry: false`: OpenCode >= 2.1 retries any
|
|
190
|
+
// error it cannot classify (about 10 attempts over ~84 s); this one it classifies as
|
|
191
|
+
// QuotaExceeded and fails at once, so the user can switch models right away.
|
|
192
|
+
// (APICallError.isInstance matches by a global symbol, so the host's AI SDK copy accepts it.)
|
|
193
|
+
return new APICallError({
|
|
194
|
+
message: `Claude Code: usage limit reached${when ? ` (resets: ${when})` : ""}. Switch to another model in OpenCode to continue; the Claude Code session is kept for when you come back.`,
|
|
195
|
+
url: "acp://claude-code",
|
|
196
|
+
requestBodyValues: {},
|
|
197
|
+
statusCode: 402,
|
|
198
|
+
responseHeaders: { "x-should-retry": "false" },
|
|
199
|
+
isRetryable: false,
|
|
200
|
+
cause: err,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
/** Total text size of a prompt (diagnostics). */
|
|
204
|
+
function blocksChars(blocks) {
|
|
205
|
+
let n = 0;
|
|
206
|
+
for (const b of blocks)
|
|
207
|
+
n += typeof b?.text === "string" ? b.text.length : 0;
|
|
208
|
+
return n;
|
|
86
209
|
}
|
|
87
210
|
export class ACPOrchestratorModel {
|
|
88
211
|
config;
|
|
@@ -91,6 +214,7 @@ export class ACPOrchestratorModel {
|
|
|
91
214
|
modelId;
|
|
92
215
|
supportedUrls = {};
|
|
93
216
|
agent = null;
|
|
217
|
+
closeTransport = null;
|
|
94
218
|
connection = null;
|
|
95
219
|
connecting = null;
|
|
96
220
|
/** Live conversations, keyed by OpenCode sessionID (or the conversation hash).
|
|
@@ -99,14 +223,38 @@ export class ACPOrchestratorModel {
|
|
|
99
223
|
sessions = new Map();
|
|
100
224
|
/** Same states indexed by ACP sessionId, to route agent-initiated callbacks. */
|
|
101
225
|
byAcpSession = new Map();
|
|
226
|
+
/** Per-conversation lock for session lookup/creation (see `startFresh`). */
|
|
227
|
+
locks = new Map();
|
|
228
|
+
/** Per-call model override (see `doStream`). */
|
|
229
|
+
callModel = new WeakMap();
|
|
102
230
|
idSeq = 0;
|
|
103
231
|
promptCaps = {};
|
|
232
|
+
/** The agent merges a prompt sent mid-turn into the running turn (claude-agent-acp). */
|
|
233
|
+
promptQueueing = false;
|
|
104
234
|
constructor(config) {
|
|
105
235
|
this.config = config;
|
|
106
236
|
this.modelId = config.modelId ?? "claude-code";
|
|
107
237
|
}
|
|
108
238
|
// ---- LanguageModelV3 ------------------------------------------------------
|
|
109
|
-
async doStream(options
|
|
239
|
+
async doStream(options,
|
|
240
|
+
/** Model for THIS call when one orchestrator (one agent process) serves several
|
|
241
|
+
* OpenCode models — see `ACPModelView`. */
|
|
242
|
+
modelId) {
|
|
243
|
+
if (modelId)
|
|
244
|
+
this.callModel.set(options, modelId);
|
|
245
|
+
if (recording()) {
|
|
246
|
+
const po = this.providerOptions(options);
|
|
247
|
+
record(this.convId(options), {
|
|
248
|
+
kind: "call",
|
|
249
|
+
modelId: this.callModel.get(options) ?? this.modelId,
|
|
250
|
+
ocAgent: po.ocAgent,
|
|
251
|
+
poKeys: Object.keys(po),
|
|
252
|
+
headers: Object.fromEntries(Object.entries(options.headers ?? {}).filter(([k]) => /^x-/i.test(k))),
|
|
253
|
+
tools: (options.tools ?? []).map((x) => x.name),
|
|
254
|
+
toolChoice: options.toolChoice,
|
|
255
|
+
prompt: sanitizePrompt(options.prompt),
|
|
256
|
+
});
|
|
257
|
+
}
|
|
110
258
|
const continuation = this.detectContinuation(options.prompt, options);
|
|
111
259
|
const ref = { t: continuation?.t ?? null };
|
|
112
260
|
const stream = new ReadableStream({
|
|
@@ -117,27 +265,7 @@ export class ACPOrchestratorModel {
|
|
|
117
265
|
}
|
|
118
266
|
async doGenerate(options) {
|
|
119
267
|
const { stream } = await this.doStream(options);
|
|
120
|
-
|
|
121
|
-
let text = "";
|
|
122
|
-
let finishReason = { unified: "stop", raw: undefined };
|
|
123
|
-
let usage = emptyUsage();
|
|
124
|
-
const reader = stream.getReader();
|
|
125
|
-
for (;;) {
|
|
126
|
-
const { done, value } = await reader.read();
|
|
127
|
-
if (done)
|
|
128
|
-
break;
|
|
129
|
-
if (value.type === "text-delta")
|
|
130
|
-
text += value.delta;
|
|
131
|
-
else if (value.type === "tool-call")
|
|
132
|
-
content.push(value);
|
|
133
|
-
else if (value.type === "finish") {
|
|
134
|
-
finishReason = value.finishReason;
|
|
135
|
-
usage = value.usage;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
if (text)
|
|
139
|
-
content.unshift({ type: "text", text });
|
|
140
|
-
return { content, finishReason, usage, warnings: [] };
|
|
268
|
+
return collectGenerate(stream);
|
|
141
269
|
}
|
|
142
270
|
// ---- turn lifecycle -------------------------------------------------------
|
|
143
271
|
async onStart(controller, options, continuation, ref) {
|
|
@@ -145,231 +273,74 @@ export class ACPOrchestratorModel {
|
|
|
145
273
|
controller.enqueue({ type: "stream-start", warnings: [] });
|
|
146
274
|
// (1) Continuation of a deferred tool-call OR a bridged permission — resume
|
|
147
275
|
// the same agent turn.
|
|
276
|
+
if (continuation?.aborted && continuation.extras.length) {
|
|
277
|
+
// The user interrupted the turn while a tool ran and then wrote again: OpenCode
|
|
278
|
+
// records the tool as `aborted` and appends the new message. Resolving the tool
|
|
279
|
+
// would continue the OLD turn and swallow that message — stop the turn instead,
|
|
280
|
+
// then handle the prompt as a fresh turn whose tail is the new message.
|
|
281
|
+
const t = continuation.t;
|
|
282
|
+
this.decide(options, { decision: "interrupted", session: t.sessionId, results: continuation.results.map((r) => r.toolCallId), extras: continuation.extras.length });
|
|
283
|
+
this.abortTurn(t, "tool interrupted by the user");
|
|
284
|
+
await this.settle(t);
|
|
285
|
+
this.markKnown(t, historyOf(options.prompt).slice(0, continuation.lastResultAt + 1));
|
|
286
|
+
continuation = null;
|
|
287
|
+
}
|
|
148
288
|
if (continuation) {
|
|
149
289
|
const t = continuation.t;
|
|
150
290
|
ref.t = t;
|
|
151
|
-
this.clearCancelWatchdog(t); // the turn DID continue — disarm the abort timer
|
|
152
291
|
t.controller = controller;
|
|
153
292
|
t.lastActive = Date.now();
|
|
154
|
-
// Everything in this prompt is
|
|
155
|
-
//
|
|
156
|
-
// the next turn from replaying
|
|
157
|
-
|
|
293
|
+
// Everything in this prompt is known to the agent once this branch is done: its
|
|
294
|
+
// own tool-calls, the results it receives right now and the extras delivered
|
|
295
|
+
// below. Recording them is what stops the next turn from replaying them.
|
|
296
|
+
this.markKnown(t, historyOf(options.prompt));
|
|
158
297
|
// Text/thinking that arrived while the stream was closed goes out FIRST, in
|
|
159
298
|
// order, so nothing the agent said before calling the tool is lost.
|
|
160
299
|
this.flushPending(t);
|
|
161
|
-
|
|
300
|
+
this.decide(options, {
|
|
301
|
+
decision: "continuation", session: t.sessionId,
|
|
302
|
+
results: continuation.results.map((r) => r.toolCallId), extras: continuation.extras.length,
|
|
303
|
+
});
|
|
304
|
+
// Steered message / update: queued into the RUNNING turn, exactly like typing
|
|
305
|
+
// while Claude Code works (claude-agent-acp `promptQueueing`). The original
|
|
306
|
+
// prompt then resolves early; the generation guard keeps it off this stream.
|
|
307
|
+
// Without queueing it rides on the last tool result instead.
|
|
308
|
+
// Keep the registry in step mid-turn too: a restart now resumes right here
|
|
309
|
+
// instead of replaying every tool round-trip since the user's message.
|
|
310
|
+
if (t.ocSession)
|
|
311
|
+
setLink(t.ocSession, t.sessionId, t.sentKeys.length, t.convKey, t.ownPrefixes);
|
|
312
|
+
const extraBlocks = continuation.extras.length ? this.midTurnBlocks(t, continuation.extras) : [];
|
|
313
|
+
const results = continuation.results;
|
|
314
|
+
const lastTool = results.map((r) => !t.pendingPermissions.has(r.toolCallId)).lastIndexOf(true);
|
|
315
|
+
const piggyback = extraBlocks.length > 0 && !this.promptQueueing && lastTool >= 0;
|
|
316
|
+
results.forEach(({ toolCallId, result, output }, i) => {
|
|
162
317
|
const permResolve = t.pendingPermissions.get(toolCallId);
|
|
163
318
|
if (permResolve) {
|
|
164
319
|
// Permission bridge: the user's `question` answer came back as the
|
|
165
320
|
// tool-result → resolve the deferred requestPermission.
|
|
166
321
|
t.pendingPermissions.delete(toolCallId);
|
|
167
|
-
permResolve(
|
|
168
|
-
}
|
|
169
|
-
else {
|
|
170
|
-
t.pendingTools.delete(toolCallId);
|
|
171
|
-
t.host.resolveToolCall(toolCallId, result);
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
return;
|
|
175
|
-
}
|
|
176
|
-
await this.ensureConnected();
|
|
177
|
-
const tools = this.convertTools(options.tools);
|
|
178
|
-
const ctrl = this.effectiveCtrl(options);
|
|
179
|
-
const po = this.providerOptions(options);
|
|
180
|
-
const ocSession = po.ocSession;
|
|
181
|
-
const convKey = hashText(this.firstUserText(options.prompt));
|
|
182
|
-
const toolsKey = tools.map((x) => x.name).sort().join(",");
|
|
183
|
-
// The system prompt is part of the session identity ONLY when it actually
|
|
184
|
-
// travels. Under the default `preset` mode OpenCode's system is never sent
|
|
185
|
-
// (see buildSystemPromptMeta), so hashing it would tear the session down —
|
|
186
|
-
// and replay the whole history — every time OpenCode swaps agents or its
|
|
187
|
-
// dynamic blocks (date, AGENTS.md, skills) shift. The factual part of that
|
|
188
|
-
// system is forwarded separately as user context (see contextBlocks).
|
|
189
|
-
const systemMode = ctrl.systemPromptMode ?? "preset";
|
|
190
|
-
const systemKey = systemMode === "preset" ? "preset" : hashText(this.systemText(options.prompt));
|
|
191
|
-
// Params baked into newSession's _meta (thinking/systemPromptMode) can't change
|
|
192
|
-
// mid-session → a change forces a fresh session. mode/effort are applied at
|
|
193
|
-
// runtime via set_mode/set_config_option instead (no reset needed).
|
|
194
|
-
const cfgKey = hashText(JSON.stringify({ t: ctrl.thinking, s: systemMode }));
|
|
195
|
-
const hist = this.history(options.prompt);
|
|
196
|
-
const keys = hist.map((m) => this.msgKey(m));
|
|
197
|
-
// OpenCode's title/summary call arrives on the same model and session but with
|
|
198
|
-
// NO tools. Give it a throwaway session instead of letting it evict the real
|
|
199
|
-
// conversation. Only when the live conversation DOES have tools — a genuinely
|
|
200
|
-
// tool-less conversation (programmatic use) must keep reusing its own session.
|
|
201
|
-
const baseKey = ocSession ?? convKey;
|
|
202
|
-
const live = this.sessions.get(baseKey);
|
|
203
|
-
const key = tools.length === 0 && live && live.toolsKey !== "" ? `${baseKey}:notools` : baseKey;
|
|
204
|
-
let t = this.sessions.get(key);
|
|
205
|
-
if (t && t.convKey !== convKey) {
|
|
206
|
-
this.endTurn(t);
|
|
207
|
-
t = undefined;
|
|
208
|
-
} // key reused for another conversation
|
|
209
|
-
// (2) Reuse the live session whenever we can — this is what keeps the cache warm.
|
|
210
|
-
if (t) {
|
|
211
|
-
let drop = null;
|
|
212
|
-
if (t.systemKey !== systemKey)
|
|
213
|
-
drop = "system prompt changed";
|
|
214
|
-
else if (t.cfgKey !== cfgKey)
|
|
215
|
-
drop = "creation config changed";
|
|
216
|
-
if (!drop) {
|
|
217
|
-
// A changed tool set is applied to the LIVE session (MCP list_changed)
|
|
218
|
-
// rather than forcing a new one.
|
|
219
|
-
if (t.toolsKey !== toolsKey) {
|
|
220
|
-
t.host.setTools(tools);
|
|
221
|
-
t.host.notifyToolsChanged();
|
|
222
|
-
t.toolsKey = toolsKey;
|
|
223
|
-
dbg(`tools changed (${tools.length}) — refreshed in place, session kept`);
|
|
224
|
-
}
|
|
225
|
-
const cls = this.classifyHistory(t, keys);
|
|
226
|
-
if (cls.kind !== "append") {
|
|
227
|
-
drop = cls.kind === "revert" ? "history reverted" : "history diverged (compaction/rollback)";
|
|
228
|
-
}
|
|
229
|
-
else {
|
|
230
|
-
const live = t;
|
|
231
|
-
ref.t = live;
|
|
232
|
-
dbg(`reuse session ${live.sessionId} — ${keys.length - cls.fromIndex} new msg(s) (cache-friendly)`);
|
|
233
|
-
// A fresh user turn: drop any deferred state left by a prior turn that was
|
|
234
|
-
// abandoned (continuation never arrived) so it can't hang or leak.
|
|
235
|
-
this.clearCancelWatchdog(live);
|
|
236
|
-
this.drainPermissions(live);
|
|
237
|
-
live.pendingTools.clear();
|
|
238
|
-
live.controller = controller;
|
|
239
|
-
live.lastActive = Date.now();
|
|
240
|
-
if (ocSession)
|
|
241
|
-
live.ocSession = ocSession;
|
|
242
|
-
if (po.ocAgent)
|
|
243
|
-
live.ocAgent = String(po.ocAgent);
|
|
244
|
-
this.flushPending(live);
|
|
245
|
-
await this.applySessionConfig(live, ctrl);
|
|
246
|
-
const tail = hist.slice(cls.fromIndex);
|
|
247
|
-
const blocks = [
|
|
248
|
-
...this.contextBlocks(live, options.prompt, ctrl),
|
|
249
|
-
...(tail.length ? this.blocksFor(tail, live) : this.lastUserBlocks(options.prompt)),
|
|
250
|
-
];
|
|
251
|
-
live.sentKeys = keys;
|
|
252
|
-
if (ocSession)
|
|
253
|
-
setLink(ocSession, live.sessionId, hist.length, convKey);
|
|
254
|
-
this.connection
|
|
255
|
-
.prompt({ sessionId: live.sessionId, prompt: blocks })
|
|
256
|
-
.then((resp) => this.onPromptDone(live, resp))
|
|
257
|
-
.catch((err) => this.onPromptError(live, err));
|
|
322
|
+
permResolve(output);
|
|
258
323
|
return;
|
|
259
324
|
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
this.endTurn(t);
|
|
263
|
-
t = undefined;
|
|
264
|
-
}
|
|
265
|
-
// (3) Need a session: new conversation, or the history diverged, or a
|
|
266
|
-
// resumable session from a new process. Set up the MCP host once.
|
|
267
|
-
// Unique per-host prefix so minted toolCallIds NEVER collide with ids from a
|
|
268
|
-
// previous session still present in OpenCode's replayed history (a fresh host is
|
|
269
|
-
// created on every session reset). A random nonce is robust across resets, process
|
|
270
|
-
// restarts and resume — unlike a per-host counter, which restarts at 0.
|
|
271
|
-
const idPrefix = `acp_${randomBytes(5).toString("hex")}_`;
|
|
272
|
-
const host = new McpHost("opencode", idPrefix);
|
|
273
|
-
await host.start();
|
|
274
|
-
host.setTools(tools);
|
|
275
|
-
const serverConfig = host.getServerConfig();
|
|
276
|
-
// Try to RESUME a registered Claude Code session (new process, no live state,
|
|
277
|
-
// history grew rather than diverged) → no history replay (saves tokens). Else
|
|
278
|
-
// create a fresh session and replay the full history.
|
|
279
|
-
const resumeId = po.resumeId;
|
|
280
|
-
const resumeLen = typeof po.resumeLen === "number" ? po.resumeLen : 0;
|
|
281
|
-
let sessionId;
|
|
282
|
-
let replayFull = true;
|
|
283
|
-
if (DEBUG && po.resumeConvKey && po.resumeConvKey !== convKey) {
|
|
284
|
-
dbg(`resumeConvKey mismatch (registry=${po.resumeConvKey} current=${convKey}) — resuming anyway`);
|
|
285
|
-
}
|
|
286
|
-
if (resumeId && resumeLen > 0 && hist.length > resumeLen) {
|
|
287
|
-
try {
|
|
288
|
-
await this.connection.unstable_resumeSession({
|
|
289
|
-
sessionId: resumeId,
|
|
290
|
-
cwd: this.config.cwd ?? process.cwd(),
|
|
291
|
-
mcpServers: [serverConfig],
|
|
292
|
-
// Re-apply the clean-brain options on resume too. Without this the agent
|
|
293
|
-
// falls back to its defaults (--tools default, --setting-sources=user,
|
|
294
|
-
// project,local, no --strict-mcp-config) and the resumed session regains
|
|
295
|
-
// native tools + the claude.ai connectors.
|
|
296
|
-
_meta: { claudeCode: { options: buildClaudeCodeOptions(ctrl) } },
|
|
297
|
-
});
|
|
298
|
-
sessionId = resumeId;
|
|
299
|
-
replayFull = false;
|
|
300
|
-
dbg(`resume ${resumeId} (oc=${ocSession ?? "?"}) — no history replay`);
|
|
301
|
-
}
|
|
302
|
-
catch (e) {
|
|
303
|
-
dbg(`resume ${resumeId} failed (${e instanceof Error ? e.message : String(e)}) — fresh session`);
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
if (!sessionId) {
|
|
307
|
-
// OpenCode's system prompt → _meta.systemPrompt (preset/append/replace).
|
|
308
|
-
const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
|
|
309
|
-
const sysMeta = this.buildSystemPromptMeta(options.prompt, systemMode);
|
|
310
|
-
if (sysMeta !== undefined)
|
|
311
|
-
meta.systemPrompt = sysMeta;
|
|
312
|
-
const session = await this.connection.newSession({
|
|
313
|
-
cwd: this.config.cwd ?? process.cwd(),
|
|
314
|
-
mcpServers: [serverConfig],
|
|
315
|
-
_meta: meta,
|
|
325
|
+
t.pendingTools.delete(toolCallId);
|
|
326
|
+
t.host.resolveToolCall(toolCallId, piggyback && i === lastTool ? this.appendToResult(result, extraBlocks) : result);
|
|
316
327
|
});
|
|
317
|
-
|
|
318
|
-
|
|
328
|
+
if (extraBlocks.length && !piggyback)
|
|
329
|
+
this.sendPrompt(t, extraBlocks);
|
|
330
|
+
// Calls that arrived while OpenCode ran the previous step go out now as the next one.
|
|
331
|
+
if (t.queuedItems.length) {
|
|
332
|
+
t.stepItems.push(...t.queuedItems);
|
|
333
|
+
t.queuedItems = [];
|
|
334
|
+
this.closeStep(t);
|
|
335
|
+
}
|
|
336
|
+
else if (t.doneResp && !(extraBlocks.length && !piggyback))
|
|
337
|
+
this.finishFromDone(t);
|
|
338
|
+
return;
|
|
319
339
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
//
|
|
323
|
-
|
|
324
|
-
note(`session ${sessionId}${replayFull ? "" : " (resumed)"} — retomable con: claude --resume ${sessionId}`);
|
|
325
|
-
t = {
|
|
326
|
-
key,
|
|
327
|
-
host,
|
|
328
|
-
idPrefix,
|
|
329
|
-
sessionId,
|
|
330
|
-
convKey,
|
|
331
|
-
toolsKey,
|
|
332
|
-
systemKey,
|
|
333
|
-
cfgKey,
|
|
334
|
-
ocSession,
|
|
335
|
-
ocAgent: po.ocAgent ? String(po.ocAgent) : undefined,
|
|
336
|
-
// Resume path: seed the cumulative usage snapshot from the persisted
|
|
337
|
-
// registry so the first post-resume `subtractUsage` produces a real
|
|
338
|
-
// turn delta instead of the full cumulative.
|
|
339
|
-
lastUsage: replayFull ? undefined : po.resumeLastUsage,
|
|
340
|
-
// Full replay covers the whole history; a bare resume only covers up to what
|
|
341
|
-
// the registry last recorded — the rest still needs sending below.
|
|
342
|
-
sentKeys: replayFull ? [] : keys.slice(0, resumeLen),
|
|
343
|
-
controller,
|
|
344
|
-
pending: [],
|
|
345
|
-
pendingTools: new Set(),
|
|
346
|
-
pendingPermissions: new Map(),
|
|
347
|
-
textId: null,
|
|
348
|
-
reasoningId: null,
|
|
349
|
-
cancelWatchdogs: new Set(),
|
|
350
|
-
lastActive: Date.now(),
|
|
351
|
-
};
|
|
352
|
-
ref.t = t;
|
|
353
|
-
host.onToolCall((c) => this.onToolCall(t, c));
|
|
354
|
-
this.sessions.set(key, t);
|
|
355
|
-
this.byAcpSession.set(sessionId, t);
|
|
356
|
-
this.evictIdleSessions();
|
|
357
|
-
await this.applySessionConfig(t, ctrl);
|
|
358
|
-
if (ocSession)
|
|
359
|
-
setLink(ocSession, sessionId, hist.length, convKey);
|
|
360
|
-
const tail = replayFull ? hist : hist.slice(resumeLen);
|
|
361
|
-
if (DEBUG && !replayFull)
|
|
362
|
-
dbg(`resume — catch-up ${tail.length} msg(s)`);
|
|
363
|
-
const promptBlocks = [
|
|
364
|
-
...this.contextBlocks(t, options.prompt, ctrl),
|
|
365
|
-
...(tail.length ? this.blocksFor(tail, t) : [{ type: "text", text: "" }]),
|
|
366
|
-
];
|
|
367
|
-
t.sentKeys = keys;
|
|
368
|
-
const started = t;
|
|
369
|
-
this.connection
|
|
370
|
-
.prompt({ sessionId, prompt: promptBlocks })
|
|
371
|
-
.then((resp) => this.onPromptDone(started, resp))
|
|
372
|
-
.catch((err) => this.onPromptError(started, err));
|
|
340
|
+
// Serialized per conversation: two calls racing for the same key (title + first
|
|
341
|
+
// turn in programmatic use, a retry) must not both create a session — the loser
|
|
342
|
+
// would be orphaned with its Claude Code process.
|
|
343
|
+
await this.withLock(this.convId(options), () => this.startFresh(controller, options, ref));
|
|
373
344
|
}
|
|
374
345
|
catch (err) {
|
|
375
346
|
dbg(`onStart error: ${err instanceof Error ? err.message : String(err)}`);
|
|
@@ -388,6 +359,9 @@ export class ACPOrchestratorModel {
|
|
|
388
359
|
* (independent) ACP stdio channel meanwhile — dropping them truncated answers and
|
|
389
360
|
* hid the reasoning block entirely. */
|
|
390
361
|
emit(t, part) {
|
|
362
|
+
if (t.hidden)
|
|
363
|
+
return; // native /compact chatter ("Compacting…") is not part of the answer
|
|
364
|
+
this.trackOwnText(t, part);
|
|
391
365
|
if (t.controller) {
|
|
392
366
|
try {
|
|
393
367
|
t.controller.enqueue(part);
|
|
@@ -400,9 +374,606 @@ export class ACPOrchestratorModel {
|
|
|
400
374
|
// límite — se descartan los chunks más antiguos.
|
|
401
375
|
if (t.pending.length > MAX_PENDING_PARTS) {
|
|
402
376
|
t.pending.splice(0, t.pending.length - MAX_PENDING_PARTS);
|
|
403
|
-
dbg(`pending
|
|
377
|
+
dbg(`pending overflow (>${MAX_PENDING_PARTS}) — dropped the oldest parts`);
|
|
404
378
|
}
|
|
405
379
|
}
|
|
380
|
+
/** A turn that is not a continuation: reuse the live session (append), or create /
|
|
381
|
+
* resume one. Runs under the conversation lock. */
|
|
382
|
+
async startFresh(controller, options, ref) {
|
|
383
|
+
await this.ensureConnected();
|
|
384
|
+
const tools = this.convertTools(options.tools);
|
|
385
|
+
const ctrl = this.effectiveCtrl(options);
|
|
386
|
+
const po = this.providerOptions(options);
|
|
387
|
+
const ocSession = po.ocSession;
|
|
388
|
+
const convKey = hashText(firstUserText(options.prompt));
|
|
389
|
+
const toolsKey = tools.map((x) => x.name).sort().join(",");
|
|
390
|
+
// The system prompt is part of the session identity ONLY when it actually
|
|
391
|
+
// travels. Under the default `preset` mode OpenCode's system is never sent
|
|
392
|
+
// (see buildSystemPromptMeta), so hashing it would tear the session down —
|
|
393
|
+
// and replay the whole history — every time OpenCode swaps agents or its
|
|
394
|
+
// dynamic blocks (date, AGENTS.md, skills) shift. The factual part of that
|
|
395
|
+
// system is forwarded separately as user context (see contextBlocks).
|
|
396
|
+
const systemMode = ctrl.systemPromptMode ?? "preset";
|
|
397
|
+
const systemKey = systemMode === "preset" ? "preset" : hashText(systemText(options.prompt));
|
|
398
|
+
// Params baked into newSession's _meta (thinking/systemPromptMode) can't change
|
|
399
|
+
// mid-session → a change forces a fresh session. mode/effort are applied at
|
|
400
|
+
// runtime via set_mode/set_config_option instead (no reset needed).
|
|
401
|
+
const cfgKey = profileKey(ctrl, systemMode);
|
|
402
|
+
const hist = historyOf(options.prompt);
|
|
403
|
+
const keys = hist.map((m) => msgKey(m));
|
|
404
|
+
// OpenCode's title/summary call arrives on the same model and session but with
|
|
405
|
+
// NO tools. Give it a throwaway session instead of letting it evict the real
|
|
406
|
+
// conversation. Only when the live conversation DOES have tools — a genuinely
|
|
407
|
+
// tool-less conversation (programmatic use) must keep reusing its own session.
|
|
408
|
+
const baseKey = ocSession ?? convKey;
|
|
409
|
+
const live = this.sessions.get(baseKey);
|
|
410
|
+
const key = tools.length === 0 && live && live.toolsKey !== "" ? `${baseKey}:notools` : baseKey;
|
|
411
|
+
const mode = this.historyMode(ctrl);
|
|
412
|
+
// OpenCode compacted (this session, or another model before switching back): the
|
|
413
|
+
// history now starts at its `<conversation-checkpoint>`.
|
|
414
|
+
const checkpoint = firstUserText(options.prompt).startsWith("<conversation-checkpoint>");
|
|
415
|
+
// An OpenCode compaction request: the live session holds the whole conversation
|
|
416
|
+
// with a warm cache — summarizing there costs a normal turn, not a cold replay of
|
|
417
|
+
// everything into a throwaway session.
|
|
418
|
+
if (po.requestKind === "compaction" && live && (await this.serveCompaction(live, controller, options, ref, mode)))
|
|
419
|
+
return;
|
|
420
|
+
let t = this.sessions.get(key);
|
|
421
|
+
if (t && t.convKey !== convKey) {
|
|
422
|
+
if (checkpoint && mode !== "legacy") {
|
|
423
|
+
this.decide(options, { decision: mode === "v2" ? "checkpoint-keep" : "shadow-checkpoint", session: t.sessionId, adopt: t.adoptCheckpoint });
|
|
424
|
+
}
|
|
425
|
+
// key reused for another conversation (or compacted, outside v2)
|
|
426
|
+
if (!(checkpoint && mode === "v2")) {
|
|
427
|
+
this.endTurn(t);
|
|
428
|
+
t = undefined;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
// (2) Reuse the live session whenever we can — this is what keeps the cache warm.
|
|
432
|
+
if (t) {
|
|
433
|
+
let drop = null;
|
|
434
|
+
if (t.systemKey !== systemKey)
|
|
435
|
+
drop = "system prompt changed";
|
|
436
|
+
else if (t.cfgKey !== cfgKey) {
|
|
437
|
+
// Another agent profile (native tools, allowed tools, setting sources…): those are
|
|
438
|
+
// fixed at creation. Fork the live session with the new profile — same context,
|
|
439
|
+
// no replay — instead of starting over; only a failed fork falls back to that.
|
|
440
|
+
const cls = this.classify(t, hist, keys, ctrl);
|
|
441
|
+
if (cls.kind !== "append" || !(await this.forkInPlace(t, ctrl, tools, systemMode, options.prompt, cfgKey))) {
|
|
442
|
+
drop = "creation config changed";
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (!drop) {
|
|
446
|
+
// A changed tool set is applied to the LIVE session (MCP list_changed)
|
|
447
|
+
// rather than forcing a new one.
|
|
448
|
+
if (t.toolsKey !== toolsKey) {
|
|
449
|
+
t.host.setTools(tools);
|
|
450
|
+
t.host.notifyToolsChanged();
|
|
451
|
+
t.toolsKey = toolsKey;
|
|
452
|
+
dbg(`tools changed (${tools.length}) — refreshed in place, session kept`);
|
|
453
|
+
}
|
|
454
|
+
if (t.compacting)
|
|
455
|
+
await Promise.race([t.compacting, new Promise((r) => setTimeout(r, COMPACT_WAIT_MS))]);
|
|
456
|
+
let cls = this.classify(t, hist, keys, ctrl, options);
|
|
457
|
+
// v2: OpenCode's checkpoint replaced the history. Keep the session: either it
|
|
458
|
+
// compacted itself in step (adopt — only what follows the checkpoint is new), or
|
|
459
|
+
// another model ran meanwhile (its summary is what the agent hasn't seen).
|
|
460
|
+
let lead = [];
|
|
461
|
+
if (cls.kind !== "append" && checkpoint && mode === "v2" && t.convKey !== convKey) {
|
|
462
|
+
const adopt = t.adoptCheckpoint && hist.length > 1;
|
|
463
|
+
cls = { kind: "append", fromIndex: adopt ? 1 : 0 };
|
|
464
|
+
if (!adopt)
|
|
465
|
+
lead = [{ type: "text", text: CHECKPOINT_NOTE }];
|
|
466
|
+
t.convKey = convKey;
|
|
467
|
+
t.adoptCheckpoint = false;
|
|
468
|
+
}
|
|
469
|
+
// smartRevert: the user rewound to a message that opened a turn of this session →
|
|
470
|
+
// fork the session at Claude's state right before it. Nothing is replayed and the
|
|
471
|
+
// shared prefix stays cached; anything unexpected falls back to a new session.
|
|
472
|
+
if (cls.kind !== "append" && ctrl.smartRevert !== false) {
|
|
473
|
+
const at = classifyHistory(t.sentKeys, keys).fromIndex;
|
|
474
|
+
const cp = t.checkpoints.find((c) => c.at === at);
|
|
475
|
+
if (cp && (await this.forkInPlace(t, ctrl, tools, systemMode, options.prompt, cfgKey, { resumeSessionAt: cp.uuid }, "revert"))) {
|
|
476
|
+
this.markKnown(t, hist.slice(0, at));
|
|
477
|
+
t.checkpoints = t.checkpoints.filter((c) => c.at < at);
|
|
478
|
+
this.decide(options, { decision: "smart-revert", session: t.sessionId, at, uuid: cp.uuid });
|
|
479
|
+
cls = { kind: "append", fromIndex: at };
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (cls.kind !== "append") {
|
|
483
|
+
drop = cls.kind === "revert" ? "history reverted" : "history diverged (compaction/rollback)";
|
|
484
|
+
}
|
|
485
|
+
else {
|
|
486
|
+
const live = t;
|
|
487
|
+
ref.t = live;
|
|
488
|
+
dbg(`reuse session ${live.sessionId} — ${keys.length - cls.fromIndex} new msg(s) (cache-friendly)`);
|
|
489
|
+
// A fresh user turn: a prior turn that is still running or was abandoned
|
|
490
|
+
// (continuation never arrived) is stopped first, so it can neither hang the
|
|
491
|
+
// agent nor leak its leftovers into this answer.
|
|
492
|
+
if (live.inflight || live.pendingTools.size || live.pendingPermissions.size) {
|
|
493
|
+
this.abortTurn(live, "superseded by a new user turn");
|
|
494
|
+
await this.settle(live);
|
|
495
|
+
}
|
|
496
|
+
live.pending = [];
|
|
497
|
+
live.doneResp = null;
|
|
498
|
+
live.controller = controller;
|
|
499
|
+
live.lastActive = Date.now();
|
|
500
|
+
live.isChild = isChildCall(options);
|
|
501
|
+
if (ocSession)
|
|
502
|
+
live.ocSession = ocSession;
|
|
503
|
+
if (po.ocAgent)
|
|
504
|
+
live.ocAgent = String(po.ocAgent);
|
|
505
|
+
live.hasQuestion = typeof po.hasQuestion === "boolean" ? po.hasQuestion : undefined;
|
|
506
|
+
await this.applySessionConfig(live, ctrl);
|
|
507
|
+
// The tail opens with the agent's OWN previous answer (V2 stores it after we
|
|
508
|
+
// sent the prompt): it already has it, so it isn't sent back.
|
|
509
|
+
const rawTail = hist.slice(cls.fromIndex);
|
|
510
|
+
const tail = this.dropOwnLead(live, rawTail);
|
|
511
|
+
const blocks = [
|
|
512
|
+
...this.contextBlocks(live, options.prompt, ctrl),
|
|
513
|
+
...lead,
|
|
514
|
+
...(tail.length ? this.blocksFor(tail, live) : rawTail.length ? [] : this.lastUserBlocks(options.prompt)),
|
|
515
|
+
];
|
|
516
|
+
this.decide(options, {
|
|
517
|
+
decision: "reuse", session: live.sessionId, from: cls.fromIndex, sent: live.sentKeys.length,
|
|
518
|
+
keys: keys.length, tail: tail.length, ownSkipped: rawTail.length - tail.length, chars: blocksChars(blocks),
|
|
519
|
+
});
|
|
520
|
+
if (ctrl.smartRevert !== false)
|
|
521
|
+
this.recordCheckpoint(live, hist, cls.fromIndex);
|
|
522
|
+
this.markKnown(live, hist);
|
|
523
|
+
if (ocSession)
|
|
524
|
+
setLink(ocSession, live.sessionId, hist.length, convKey, live.ownPrefixes);
|
|
525
|
+
this.sendPrompt(live, blocks.length ? blocks : [{ type: "text", text: "" }]);
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
dbg(`dropping session ${t.sessionId} — ${drop}`);
|
|
530
|
+
{
|
|
531
|
+
const at = this.classify(t, hist, keys, ctrl).fromIndex;
|
|
532
|
+
this.decide(options, {
|
|
533
|
+
decision: "drop", session: t.sessionId, reason: drop, at, sent: t.sentKeys.length, keys: keys.length,
|
|
534
|
+
sentKey: t.sentKeys[at], inKey: keys[at],
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
this.endTurn(t);
|
|
538
|
+
t = undefined;
|
|
539
|
+
}
|
|
540
|
+
// (3) Need a session: new conversation, or the history diverged, or a
|
|
541
|
+
// resumable session from a new process. Set up the MCP host once.
|
|
542
|
+
// Unique per-host prefix so minted toolCallIds NEVER collide with ids from a
|
|
543
|
+
// previous session still present in OpenCode's replayed history (a fresh host is
|
|
544
|
+
// created on every session reset). A random nonce is robust across resets, process
|
|
545
|
+
// restarts and resume — unlike a per-host counter, which restarts at 0.
|
|
546
|
+
const idPrefix = `acp_${randomBytes(5).toString("hex")}_`;
|
|
547
|
+
const host = new McpHost("opencode", idPrefix);
|
|
548
|
+
await host.start();
|
|
549
|
+
host.setTools(tools);
|
|
550
|
+
const serverConfig = host.getServerConfig();
|
|
551
|
+
// Try to RESUME a registered Claude Code session (new process, no live state,
|
|
552
|
+
// history grew rather than diverged) → no history replay (saves tokens). Else
|
|
553
|
+
// create a fresh session and replay the full history.
|
|
554
|
+
const resumeId = po.resumeId;
|
|
555
|
+
const resumeLen = typeof po.resumeLen === "number" ? po.resumeLen : 0;
|
|
556
|
+
const resumePrefixes = Array.isArray(po.resumeIdPrefixes) ? po.resumeIdPrefixes.map(String) : [];
|
|
557
|
+
let sessionId;
|
|
558
|
+
let replayFull = true;
|
|
559
|
+
// A registry entry for a DIFFERENT conversation (first message changed: compaction,
|
|
560
|
+
// or a reused id) must not be resumed — the agent would carry the wrong context.
|
|
561
|
+
const sameConv = !po.resumeConvKey || po.resumeConvKey === convKey;
|
|
562
|
+
if (!sameConv)
|
|
563
|
+
dbg(`resumeConvKey mismatch (registry=${po.resumeConvKey} current=${convKey}) — not resuming`);
|
|
564
|
+
if (resumeId && sameConv && resumeLen > 0 && hist.length > resumeLen) {
|
|
565
|
+
try {
|
|
566
|
+
await this.connection.unstable_resumeSession({
|
|
567
|
+
sessionId: resumeId,
|
|
568
|
+
cwd: this.config.cwd ?? process.cwd(),
|
|
569
|
+
mcpServers: [serverConfig],
|
|
570
|
+
// Re-apply the clean-brain options on resume too. Without this the agent
|
|
571
|
+
// falls back to its defaults (--tools default, --setting-sources=user,
|
|
572
|
+
// project,local, no --strict-mcp-config) and the resumed session regains
|
|
573
|
+
// native tools + the claude.ai connectors.
|
|
574
|
+
_meta: { claudeCode: { options: buildClaudeCodeOptions(ctrl) } },
|
|
575
|
+
});
|
|
576
|
+
sessionId = resumeId;
|
|
577
|
+
replayFull = false;
|
|
578
|
+
dbg(`resume ${resumeId} (oc=${ocSession ?? "?"}) — no history replay`);
|
|
579
|
+
}
|
|
580
|
+
catch (e) {
|
|
581
|
+
dbg(`resume ${resumeId} failed (${e instanceof Error ? e.message : String(e)}) — fresh session`);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
if (!sessionId) {
|
|
585
|
+
// OpenCode's system prompt → _meta.systemPrompt (preset/append/replace).
|
|
586
|
+
const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
|
|
587
|
+
const sysMeta = this.buildSystemPromptMeta(options.prompt, systemMode);
|
|
588
|
+
if (sysMeta !== undefined)
|
|
589
|
+
meta.systemPrompt = sysMeta;
|
|
590
|
+
const session = await this.connection.newSession({
|
|
591
|
+
cwd: this.config.cwd ?? process.cwd(),
|
|
592
|
+
mcpServers: [serverConfig],
|
|
593
|
+
_meta: meta,
|
|
594
|
+
});
|
|
595
|
+
sessionId = session.sessionId;
|
|
596
|
+
dbg(`model=${session.models?.currentModelId ?? "?"} (requested: ${ctrl.model ?? "default"}, mode: ${ctrl.mode ?? "default"}, effort: ${ctrl.effort ?? "default"}) — tools(${tools.length})`);
|
|
597
|
+
}
|
|
598
|
+
if (!sessionId)
|
|
599
|
+
throw new Error("failed to create or resume an ACP session");
|
|
600
|
+
// The ACP sessionId IS the Claude Code session id: surfacing it lets the user
|
|
601
|
+
// pick the conversation back up natively.
|
|
602
|
+
note(`session ${sessionId}${replayFull ? "" : " (resumed)"} — resumable with: claude --resume ${sessionId}`);
|
|
603
|
+
t = {
|
|
604
|
+
key,
|
|
605
|
+
host,
|
|
606
|
+
idPrefix,
|
|
607
|
+
sessionId,
|
|
608
|
+
convKey,
|
|
609
|
+
toolsKey,
|
|
610
|
+
systemKey,
|
|
611
|
+
cfgKey,
|
|
612
|
+
ocSession,
|
|
613
|
+
ocAgent: po.ocAgent ? String(po.ocAgent) : undefined,
|
|
614
|
+
hasQuestion: typeof po.hasQuestion === "boolean" ? po.hasQuestion : undefined,
|
|
615
|
+
isChild: isChildCall(options),
|
|
616
|
+
// Resume path: carry the persisted snapshot over so the registry keeps a
|
|
617
|
+
// value even if the resumed session never completes another turn.
|
|
618
|
+
lastUsage: replayFull ? undefined : po.resumeLastUsage,
|
|
619
|
+
// Full replay covers the whole history; a bare resume only covers up to what
|
|
620
|
+
// the registry last recorded — the rest still needs sending below.
|
|
621
|
+
sentKeys: replayFull ? [] : keys.slice(0, resumeLen),
|
|
622
|
+
sentAnchors: replayFull ? [] : anchorsOf(hist.slice(0, resumeLen)).map((a) => a.key),
|
|
623
|
+
sentTransient: new Set(),
|
|
624
|
+
controller,
|
|
625
|
+
pending: [],
|
|
626
|
+
pendingTools: new Set(),
|
|
627
|
+
pendingPermissions: new Map(),
|
|
628
|
+
textId: null,
|
|
629
|
+
reasoningId: null,
|
|
630
|
+
ownPrefixes: [idPrefix, ...(replayFull ? [] : resumePrefixes)],
|
|
631
|
+
ownTexts: new Set(),
|
|
632
|
+
textAcc: new Map(),
|
|
633
|
+
stepText: "",
|
|
634
|
+
gen: 0,
|
|
635
|
+
inflight: null,
|
|
636
|
+
doneResp: null,
|
|
637
|
+
aborted: false,
|
|
638
|
+
stepItems: [],
|
|
639
|
+
stepTimer: null,
|
|
640
|
+
queuedItems: [],
|
|
641
|
+
nativeCalls: new Map(),
|
|
642
|
+
checkpoints: [],
|
|
643
|
+
compacting: null,
|
|
644
|
+
hidden: false,
|
|
645
|
+
adoptCheckpoint: false,
|
|
646
|
+
afterTurn: null,
|
|
647
|
+
lastActive: Date.now(),
|
|
648
|
+
};
|
|
649
|
+
ref.t = t;
|
|
650
|
+
host.onToolCall((c) => this.onToolCall(t, c));
|
|
651
|
+
host.onToolCancelled((id) => this.onToolCancelled(t, id));
|
|
652
|
+
this.sessions.set(key, t);
|
|
653
|
+
this.byAcpSession.set(sessionId, t);
|
|
654
|
+
this.evictIdleSessions();
|
|
655
|
+
this.startSweeper();
|
|
656
|
+
await this.applySessionConfig(t, ctrl);
|
|
657
|
+
if (ocSession)
|
|
658
|
+
setLink(ocSession, sessionId, hist.length, convKey, t.ownPrefixes);
|
|
659
|
+
// Resume: the registry may lag behind (process died mid-turn), and the agent's own
|
|
660
|
+
// last answer follows the recorded point — the resumed session already has it.
|
|
661
|
+
const tail = replayFull ? hist : this.dropOwnLead(t, hist.slice(resumeLen));
|
|
662
|
+
if (DEBUG && !replayFull)
|
|
663
|
+
dbg(`resume — catch-up ${tail.length} msg(s)`);
|
|
664
|
+
const promptBlocks = [
|
|
665
|
+
...this.contextBlocks(t, options.prompt, ctrl),
|
|
666
|
+
...(tail.length ? this.blocksFor(tail, t, replayFull ? "replay" : "tail") : [{ type: "text", text: "" }]),
|
|
667
|
+
];
|
|
668
|
+
this.decide(options, {
|
|
669
|
+
decision: replayFull ? "new" : "resume", session: sessionId, keys: keys.length,
|
|
670
|
+
tail: tail.length, chars: blocksChars(promptBlocks),
|
|
671
|
+
});
|
|
672
|
+
this.markKnown(t, hist);
|
|
673
|
+
this.sendPrompt(t, promptBlocks);
|
|
674
|
+
}
|
|
675
|
+
/** Swap `t` onto a fork of its ACP session created with the current profile. The
|
|
676
|
+
* fork carries the whole transcript, so what `t` knows (sentKeys, own output) still
|
|
677
|
+
* holds; it gets its own MCP host. The old session is closed. */
|
|
678
|
+
async forkInPlace(t, ctrl, tools, systemMode, prompt, cfgKey, extra, why = "agent profile changed") {
|
|
679
|
+
if (t.inflight || t.pendingTools.size || t.pendingPermissions.size) {
|
|
680
|
+
this.abortTurn(t, why);
|
|
681
|
+
await this.settle(t);
|
|
682
|
+
}
|
|
683
|
+
const idPrefix = `acp_${randomBytes(5).toString("hex")}_`;
|
|
684
|
+
const host = new McpHost("opencode", idPrefix);
|
|
685
|
+
try {
|
|
686
|
+
await host.start();
|
|
687
|
+
host.setTools(tools);
|
|
688
|
+
const meta = { claudeCode: { options: { ...buildClaudeCodeOptions(ctrl), ...(extra ?? {}) } } };
|
|
689
|
+
const sysMeta = this.buildSystemPromptMeta(prompt, systemMode);
|
|
690
|
+
if (sysMeta !== undefined)
|
|
691
|
+
meta.systemPrompt = sysMeta;
|
|
692
|
+
const res = await this.connection.unstable_forkSession({
|
|
693
|
+
sessionId: t.sessionId,
|
|
694
|
+
cwd: this.config.cwd ?? process.cwd(),
|
|
695
|
+
mcpServers: [host.getServerConfig()],
|
|
696
|
+
_meta: meta,
|
|
697
|
+
});
|
|
698
|
+
if (!res?.sessionId)
|
|
699
|
+
throw new Error("fork returned no sessionId");
|
|
700
|
+
const old = { id: t.sessionId, host: t.host };
|
|
701
|
+
this.byAcpSession.delete(old.id);
|
|
702
|
+
t.sessionId = res.sessionId;
|
|
703
|
+
t.host = host;
|
|
704
|
+
t.idPrefix = idPrefix;
|
|
705
|
+
t.ownPrefixes = [idPrefix, ...t.ownPrefixes].slice(0, 8);
|
|
706
|
+
t.cfgKey = cfgKey;
|
|
707
|
+
t.appliedMode = undefined; // re-applied on the fork by applySessionConfig
|
|
708
|
+
t.appliedEffort = undefined;
|
|
709
|
+
t.appliedModel = undefined;
|
|
710
|
+
host.onToolCall((c) => this.onToolCall(t, c));
|
|
711
|
+
host.onToolCancelled((id) => this.onToolCancelled(t, id));
|
|
712
|
+
this.byAcpSession.set(t.sessionId, t);
|
|
713
|
+
old.host.stop();
|
|
714
|
+
this.closeAcpSession(old.id);
|
|
715
|
+
note(`session ${old.id} → fork ${t.sessionId} (${why}, context kept) — resumable with: claude --resume ${t.sessionId}`);
|
|
716
|
+
return true;
|
|
717
|
+
}
|
|
718
|
+
catch (e) {
|
|
719
|
+
host.stop();
|
|
720
|
+
dbg(`fork of ${t.sessionId} failed (${e instanceof Error ? e.message : String(e)}) — new session instead`);
|
|
721
|
+
return false;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
/** Remember where this turn starts (index of its first user message) and Claude's
|
|
725
|
+
* last transcript entry before it. */
|
|
726
|
+
recordCheckpoint(t, hist, from) {
|
|
727
|
+
let at = from;
|
|
728
|
+
while (at < hist.length && hist[at].role !== "user")
|
|
729
|
+
at++;
|
|
730
|
+
if (at >= hist.length || t.checkpoints.some((c) => c.at === at))
|
|
731
|
+
return;
|
|
732
|
+
const uuid = this.lastAssistantUuid(t);
|
|
733
|
+
if (uuid)
|
|
734
|
+
t.checkpoints.push({ at, uuid });
|
|
735
|
+
}
|
|
736
|
+
/** uuid of the last main-thread assistant entry in the session's transcript
|
|
737
|
+
* (`<configDir>/projects/<cwd as slug>/<sessionId>.jsonl`), read from its tail. */
|
|
738
|
+
lastAssistantUuid(t) {
|
|
739
|
+
try {
|
|
740
|
+
const dir = resolveConfigDir(this.config.claudeCode ?? {}) ?? join(homedir(), ".claude");
|
|
741
|
+
const slug = (this.config.cwd ?? process.cwd()).replace(/[^a-zA-Z0-9]/g, "-");
|
|
742
|
+
const file = join(dir, "projects", slug, `${t.sessionId}.jsonl`);
|
|
743
|
+
const fd = openSync(file, "r");
|
|
744
|
+
try {
|
|
745
|
+
const size = fstatSync(fd).size;
|
|
746
|
+
const len = Math.min(size, 256 * 1024);
|
|
747
|
+
const buf = Buffer.alloc(len);
|
|
748
|
+
readSync(fd, buf, 0, len, size - len);
|
|
749
|
+
const lines = buf.toString("utf8").split("\n");
|
|
750
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
751
|
+
try {
|
|
752
|
+
const e = JSON.parse(lines[i]);
|
|
753
|
+
if (e?.type === "assistant" && typeof e.uuid === "string" && !e.isSidechain)
|
|
754
|
+
return e.uuid;
|
|
755
|
+
}
|
|
756
|
+
catch { /* partial first line */ }
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
finally {
|
|
760
|
+
closeSync(fd);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
catch { /* no transcript (other configDir, agent not writing one) */ }
|
|
764
|
+
return undefined;
|
|
765
|
+
}
|
|
766
|
+
/** Free the agent-side session (its Claude Code process and MCP servers). The client
|
|
767
|
+
* SDK has no method for it; the agent implements `session/close`. */
|
|
768
|
+
closeAcpSession(sessionId) {
|
|
769
|
+
try {
|
|
770
|
+
Promise.resolve(this.connection?.extMethod?.("session/close", { sessionId })).catch(() => { });
|
|
771
|
+
}
|
|
772
|
+
catch { /* ignore */ }
|
|
773
|
+
}
|
|
774
|
+
/** Answer OpenCode's compaction request inside the live session (it already holds
|
|
775
|
+
* the conversation and its cache): only the summary instruction is sent. In v2 the
|
|
776
|
+
* session then compacts itself natively, so the checkpoint can be adopted next turn.
|
|
777
|
+
* Returns false when the session is busy (V2 can compact mid tool loop). */
|
|
778
|
+
async serveCompaction(t, controller, options, ref, mode) {
|
|
779
|
+
if (t.compacting)
|
|
780
|
+
await Promise.race([t.compacting, new Promise((r) => setTimeout(r, COMPACT_WAIT_MS))]);
|
|
781
|
+
if (t.inflight || t.pendingTools.size || t.pendingPermissions.size || t.queuedItems.length)
|
|
782
|
+
return false;
|
|
783
|
+
ref.t = t;
|
|
784
|
+
t.controller = controller;
|
|
785
|
+
t.pending = [];
|
|
786
|
+
t.doneResp = null;
|
|
787
|
+
t.lastActive = Date.now();
|
|
788
|
+
this.decide(options, { decision: "compaction-live", session: t.sessionId, mode });
|
|
789
|
+
t.afterTurn = mode === "v2" ? () => this.nativeCompact(t) : null;
|
|
790
|
+
this.sendPrompt(t, this.lastUserBlocks(options.prompt));
|
|
791
|
+
return true;
|
|
792
|
+
}
|
|
793
|
+
/** Native `/compact` of the live session, output hidden. */
|
|
794
|
+
nativeCompact(t) {
|
|
795
|
+
t.hidden = true;
|
|
796
|
+
const gen = ++t.gen;
|
|
797
|
+
const done = this.connection
|
|
798
|
+
.prompt({ sessionId: t.sessionId, prompt: [{ type: "text", text: "/compact" }] })
|
|
799
|
+
.then(() => { if (gen === t.gen)
|
|
800
|
+
t.adoptCheckpoint = true; }, (e) => dbg(`native /compact failed: ${errorText(e)}`))
|
|
801
|
+
.finally(() => {
|
|
802
|
+
t.hidden = false;
|
|
803
|
+
if (t.compacting === done)
|
|
804
|
+
t.compacting = null;
|
|
805
|
+
});
|
|
806
|
+
t.compacting = done;
|
|
807
|
+
}
|
|
808
|
+
async withLock(key, fn) {
|
|
809
|
+
const prev = this.locks.get(key) ?? Promise.resolve();
|
|
810
|
+
let release;
|
|
811
|
+
const mine = new Promise((r) => { release = r; });
|
|
812
|
+
const chained = prev.then(() => mine);
|
|
813
|
+
this.locks.set(key, chained);
|
|
814
|
+
await prev;
|
|
815
|
+
try {
|
|
816
|
+
return await fn();
|
|
817
|
+
}
|
|
818
|
+
finally {
|
|
819
|
+
release();
|
|
820
|
+
if (this.locks.get(key) === chained)
|
|
821
|
+
this.locks.delete(key);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
/** Remember the text of every block we emit: OpenCode stores each block as one part of
|
|
825
|
+
* the assistant message it sends back next turn, which is how `dropOwnLead` knows the
|
|
826
|
+
* agent already has it. */
|
|
827
|
+
trackOwnText(t, part) {
|
|
828
|
+
switch (part.type) {
|
|
829
|
+
case "text-delta":
|
|
830
|
+
case "reasoning-delta":
|
|
831
|
+
t.textAcc.set(part.id, (t.textAcc.get(part.id) ?? "") + part.delta);
|
|
832
|
+
if (part.type === "text-delta")
|
|
833
|
+
t.stepText += part.delta;
|
|
834
|
+
break;
|
|
835
|
+
case "finish":
|
|
836
|
+
if (t.stepText.trim())
|
|
837
|
+
t.ownTexts.add(ownTextKey(t.stepText));
|
|
838
|
+
t.stepText = "";
|
|
839
|
+
break;
|
|
840
|
+
case "text-end":
|
|
841
|
+
case "reasoning-end": {
|
|
842
|
+
const text = t.textAcc.get(part.id);
|
|
843
|
+
t.textAcc.delete(part.id);
|
|
844
|
+
if (text)
|
|
845
|
+
t.ownTexts.add(ownTextKey(text));
|
|
846
|
+
if (t.ownTexts.size > MAX_OWN_TEXTS)
|
|
847
|
+
t.ownTexts.delete(t.ownTexts.values().next().value);
|
|
848
|
+
break;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
isOwnId(t, id) {
|
|
853
|
+
const s = String(id ?? "");
|
|
854
|
+
return t.ownPrefixes.some((p) => s.startsWith(p));
|
|
855
|
+
}
|
|
856
|
+
/** Strip the agent's own output from the head of a tail: the assistant/tool messages
|
|
857
|
+
* before the next user message, as long as they carry only our ids and (when this
|
|
858
|
+
* process emitted them) only text we emitted. A message that fails the check — another
|
|
859
|
+
* model's turn — stops the skip, so it still reaches the agent. After a restart there
|
|
860
|
+
* is no emitted text to compare, and the position alone decides. */
|
|
861
|
+
dropOwnLead(t, tail) {
|
|
862
|
+
let i = 0;
|
|
863
|
+
for (; i < tail.length; i++) {
|
|
864
|
+
const m = tail[i];
|
|
865
|
+
if (m.role === "user" || m.role === "system" || !Array.isArray(m.content))
|
|
866
|
+
break;
|
|
867
|
+
const joined = m.content.filter((p) => p?.type === "text").map((p) => String(p.text ?? "")).join("");
|
|
868
|
+
const wholeOwn = !!joined.trim() && t.ownTexts.has(ownTextKey(joined));
|
|
869
|
+
const own = m.content.every((p) => {
|
|
870
|
+
if (p?.type === "tool-call" || p?.type === "tool-result")
|
|
871
|
+
return this.isOwnId(t, p.toolCallId);
|
|
872
|
+
if (p?.type === "text" || p?.type === "reasoning") {
|
|
873
|
+
const text = String(p.text ?? "");
|
|
874
|
+
return !text.trim() || t.ownTexts.size === 0 || t.ownTexts.has(ownTextKey(text)) || (p.type === "text" && wholeOwn);
|
|
875
|
+
}
|
|
876
|
+
return true;
|
|
877
|
+
});
|
|
878
|
+
if (!own)
|
|
879
|
+
break;
|
|
880
|
+
}
|
|
881
|
+
return tail.slice(i);
|
|
882
|
+
}
|
|
883
|
+
/** Everything in `hist` is now known to the agent (both fingerprints). */
|
|
884
|
+
markKnown(t, hist) {
|
|
885
|
+
t.sentKeys = hist.map((m) => msgKey(m));
|
|
886
|
+
t.sentAnchors = anchorsOf(hist).map((a) => a.key);
|
|
887
|
+
}
|
|
888
|
+
historyMode(ctrl) {
|
|
889
|
+
return ctrl.historyMode ?? process.env.ACP_HISTORY_MODE ?? "shadow";
|
|
890
|
+
}
|
|
891
|
+
/** Legacy per-message keys or anchors, per `historyMode`. In `shadow` (the default
|
|
892
|
+
* while the anchor fingerprint proves itself on real sessions) both are computed, the
|
|
893
|
+
* legacy one decides, and every disagreement is logged for review. */
|
|
894
|
+
classify(t, hist, keys, ctrl, options) {
|
|
895
|
+
const mode = this.historyMode(ctrl);
|
|
896
|
+
const legacy = classifyHistory(t.sentKeys, keys);
|
|
897
|
+
if (mode === "legacy")
|
|
898
|
+
return legacy;
|
|
899
|
+
const anchors = classifyAnchors(t.sentAnchors, anchorsOf(hist));
|
|
900
|
+
// Cut points are comparable only for appends (for a divergence each scheme reports a
|
|
901
|
+
// different landmark), so only a different kind — or a different cut — is evidence.
|
|
902
|
+
const differs = legacy.kind !== anchors.kind || (legacy.kind === "append" && legacy.fromIndex !== anchors.fromIndex);
|
|
903
|
+
if (options && differs) {
|
|
904
|
+
this.decide(options, {
|
|
905
|
+
decision: "shadow-diff", mode, session: t.sessionId,
|
|
906
|
+
legacy: `${legacy.kind}@${legacy.fromIndex}`, anchors: `${anchors.kind}@${anchors.fromIndex}`,
|
|
907
|
+
legacyKey: [t.sentKeys[legacy.fromIndex], keys[legacy.fromIndex]],
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
return mode === "v2" ? anchors : legacy;
|
|
911
|
+
}
|
|
912
|
+
/** Send a prompt as the session's newest generation. Completions of older ones — a
|
|
913
|
+
* cancelled turn, or the original prompt the agent resolves early when it merges a
|
|
914
|
+
* queued one — are ignored instead of closing the stream of the current turn. */
|
|
915
|
+
sendPrompt(t, blocks) {
|
|
916
|
+
const gen = ++t.gen;
|
|
917
|
+
t.aborted = false;
|
|
918
|
+
t.doneResp = null;
|
|
919
|
+
const settled = this.connection
|
|
920
|
+
.prompt({ sessionId: t.sessionId, prompt: blocks })
|
|
921
|
+
.then((resp) => {
|
|
922
|
+
if (gen === t.gen)
|
|
923
|
+
this.onPromptDone(t, resp);
|
|
924
|
+
else
|
|
925
|
+
dbg(`stale prompt completion ignored (gen ${gen} < ${t.gen}, ${resp?.stopReason})`);
|
|
926
|
+
}, (err) => {
|
|
927
|
+
if (gen === t.gen)
|
|
928
|
+
this.onPromptError(t, err);
|
|
929
|
+
else
|
|
930
|
+
dbg(`stale prompt error ignored (gen ${gen} < ${t.gen})`);
|
|
931
|
+
})
|
|
932
|
+
.then(() => { if (t.inflight === settled)
|
|
933
|
+
t.inflight = null; });
|
|
934
|
+
t.inflight = settled;
|
|
935
|
+
}
|
|
936
|
+
/** Wait (bounded) for the running prompt to settle — e.g. after a cancel. */
|
|
937
|
+
async settle(t, ms = SETTLE_MS) {
|
|
938
|
+
const p = t.inflight;
|
|
939
|
+
if (!p)
|
|
940
|
+
return;
|
|
941
|
+
let timer;
|
|
942
|
+
await Promise.race([p, new Promise((r) => { timer = setTimeout(r, ms); })]);
|
|
943
|
+
clearTimeout(timer);
|
|
944
|
+
}
|
|
945
|
+
/** Stop the current turn for good: cancel it agent-side, unblock everything it waits
|
|
946
|
+
* on (deferred tool calls, bridged permissions) and drop what it still produces. */
|
|
947
|
+
abortTurn(t, why) {
|
|
948
|
+
dbg(`abort turn of ${t.sessionId} (${why})`);
|
|
949
|
+
t.aborted = true;
|
|
950
|
+
try {
|
|
951
|
+
this.connection?.cancel?.({ sessionId: t.sessionId });
|
|
952
|
+
}
|
|
953
|
+
catch { /* ignore */ }
|
|
954
|
+
for (const id of t.pendingTools)
|
|
955
|
+
t.host.rejectToolCall(id, "Tool execution interrupted by the user");
|
|
956
|
+
t.pendingTools.clear();
|
|
957
|
+
this.drainPermissions(t);
|
|
958
|
+
t.controller = null;
|
|
959
|
+
t.textId = null;
|
|
960
|
+
t.reasoningId = null;
|
|
961
|
+
t.textAcc.clear();
|
|
962
|
+
t.pending = [];
|
|
963
|
+
t.doneResp = null;
|
|
964
|
+
if (t.stepTimer) {
|
|
965
|
+
clearTimeout(t.stepTimer);
|
|
966
|
+
t.stepTimer = null;
|
|
967
|
+
}
|
|
968
|
+
t.stepItems = [];
|
|
969
|
+
t.queuedItems = [];
|
|
970
|
+
}
|
|
971
|
+
/** The prompt completed while no stream was attached: close the current one with it. */
|
|
972
|
+
finishFromDone(t) {
|
|
973
|
+
const resp = t.doneResp;
|
|
974
|
+
t.doneResp = null;
|
|
975
|
+
this.onPromptDone(t, resp);
|
|
976
|
+
}
|
|
406
977
|
flushPending(t) {
|
|
407
978
|
if (!t.controller || t.pending.length === 0)
|
|
408
979
|
return;
|
|
@@ -417,46 +988,73 @@ export class ACPOrchestratorModel {
|
|
|
417
988
|
}
|
|
418
989
|
}
|
|
419
990
|
onPromptDone(t, resp) {
|
|
420
|
-
if (!t.controller)
|
|
421
|
-
|
|
991
|
+
if (!t.controller) {
|
|
992
|
+
// Finished while detached. After an abort that's just the cancellation landing;
|
|
993
|
+
// otherwise keep it, so the next stream of this turn can still be finished.
|
|
994
|
+
if (!t.aborted && resp?.stopReason !== "cancelled")
|
|
995
|
+
t.doneResp = resp;
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
if (t.stepItems.length) {
|
|
999
|
+
this.closeStep(t);
|
|
1000
|
+
t.doneResp = resp;
|
|
1001
|
+
return;
|
|
1002
|
+
}
|
|
422
1003
|
this.closeBlocks(t);
|
|
423
1004
|
this.flushPending(t);
|
|
424
|
-
const turn =
|
|
425
|
-
if (
|
|
426
|
-
t.lastUsage =
|
|
1005
|
+
const turn = resp?.usage; // sum over the turn's requests (see usageNow)
|
|
1006
|
+
if (turn) {
|
|
1007
|
+
t.lastUsage = turn;
|
|
427
1008
|
if (t.ocSession)
|
|
428
|
-
updateUsage(t.ocSession,
|
|
1009
|
+
updateUsage(t.ocSession, turn); // survive process restarts
|
|
429
1010
|
}
|
|
430
1011
|
if (DEBUG && turn)
|
|
431
1012
|
dbg(`usage(turn): in=${turn.inputTokens} out=${turn.outputTokens} cacheR=${turn.cachedReadTokens} cacheW=${turn.cachedWriteTokens}`);
|
|
1013
|
+
const finish = {
|
|
1014
|
+
type: "finish",
|
|
1015
|
+
usage: this.usageNow(t, turn),
|
|
1016
|
+
finishReason: { unified: resp?.stopReason === "max_tokens" ? "length" : "stop", raw: resp?.stopReason },
|
|
1017
|
+
};
|
|
1018
|
+
this.trackOwnText(t, finish);
|
|
432
1019
|
try {
|
|
433
|
-
t.controller.enqueue(
|
|
434
|
-
type: "finish",
|
|
435
|
-
usage: mapUsage(turn),
|
|
436
|
-
finishReason: { unified: resp?.stopReason === "max_tokens" ? "length" : "stop", raw: resp?.stopReason },
|
|
437
|
-
});
|
|
1020
|
+
t.controller.enqueue(finish);
|
|
438
1021
|
t.controller.close();
|
|
439
1022
|
}
|
|
440
1023
|
catch { /* ignore */ }
|
|
441
1024
|
t.controller = null; // keep the session for the next turn (delta)
|
|
1025
|
+
t.lastActive = Date.now();
|
|
1026
|
+
const after = t.afterTurn;
|
|
1027
|
+
t.afterTurn = null;
|
|
1028
|
+
after?.();
|
|
1029
|
+
// A tool-less side call (title/summary in programmatic use) never continues.
|
|
1030
|
+
if (t.key.endsWith(":notools"))
|
|
1031
|
+
queueMicrotask(() => this.endTurn(t));
|
|
442
1032
|
}
|
|
443
1033
|
onPromptError(t, err) {
|
|
1034
|
+
// The agent dropped the session (its Claude Code process died): talking to it again
|
|
1035
|
+
// would fail every turn. Forget it here; the next turn resumes the transcript.
|
|
1036
|
+
if (/process exited unexpectedly|session not found/i.test(errorText(err))) {
|
|
1037
|
+
note(`session ${t.sessionId} lost agent-side — the next turn resumes it`);
|
|
1038
|
+
queueMicrotask(() => this.endTurn(t));
|
|
1039
|
+
}
|
|
444
1040
|
if (!t.controller)
|
|
445
1041
|
return;
|
|
446
|
-
dbg(`prompt error: ${
|
|
1042
|
+
dbg(`prompt error: ${errorText(err)}`);
|
|
447
1043
|
try {
|
|
448
|
-
t.controller.enqueue({ type: "error", error: err });
|
|
1044
|
+
t.controller.enqueue({ type: "error", error: limitError(err) ?? err });
|
|
449
1045
|
t.controller.close();
|
|
450
1046
|
}
|
|
451
1047
|
catch { /* ignore */ }
|
|
452
1048
|
t.controller = null;
|
|
453
1049
|
}
|
|
454
|
-
/** Fired by the MCP host when the agent calls an OpenCode tool.
|
|
1050
|
+
/** Fired by the MCP host when the agent calls an OpenCode tool. The call is NOT
|
|
1051
|
+
* resolved here: it waits for OpenCode to run the tool and send the continuation. */
|
|
455
1052
|
onToolCall(t, call) {
|
|
456
|
-
if (
|
|
1053
|
+
if (t.aborted) {
|
|
1054
|
+
t.host.rejectToolCall(call.toolCallId, "Turn aborted");
|
|
457
1055
|
return;
|
|
1056
|
+
}
|
|
458
1057
|
dbg(`agent → tool-call ${call.name} (${call.toolCallId}) → emit to OpenCode`);
|
|
459
|
-
this.closeBlocks(t);
|
|
460
1058
|
t.pendingTools.add(call.toolCallId);
|
|
461
1059
|
// `call.args` puede traer refs circulares/BigInt → JSON.stringify lanzaría y
|
|
462
1060
|
// tumbaría el turno: degradar a marcador en vez de crashear.
|
|
@@ -468,11 +1066,95 @@ export class ACPOrchestratorModel {
|
|
|
468
1066
|
dbg(`tool-call ${call.name}: args no serializables (${e instanceof Error ? e.message : String(e)}) — input="<serialization error>"`);
|
|
469
1067
|
inputJson = '"<serialization error>"';
|
|
470
1068
|
}
|
|
471
|
-
this.
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
1069
|
+
this.addStepItem(t, { id: call.toolCallId, toolName: call.name, input: inputJson, parallel: this.parallelTools().includes(call.name) });
|
|
1070
|
+
}
|
|
1071
|
+
/** The agent cancelled a call: if OpenCode hasn't been given it yet, it never will be.
|
|
1072
|
+
* (An already emitted one stays pending so its continuation is still recognised.) */
|
|
1073
|
+
onToolCancelled(t, toolCallId) {
|
|
1074
|
+
const queued = (items) => items.filter((it) => it.id !== toolCallId);
|
|
1075
|
+
const before = t.queuedItems.length + t.stepItems.length;
|
|
1076
|
+
t.queuedItems = queued(t.queuedItems);
|
|
1077
|
+
t.stepItems = queued(t.stepItems);
|
|
1078
|
+
if (t.queuedItems.length + t.stepItems.length < before)
|
|
1079
|
+
t.pendingTools.delete(toolCallId);
|
|
1080
|
+
dbg(`agent cancelled tool-call ${toolCallId}`);
|
|
1081
|
+
}
|
|
1082
|
+
parallelTools() {
|
|
1083
|
+
return this.config.claudeCode?.parallelTools ?? PARALLEL_TOOLS;
|
|
1084
|
+
}
|
|
1085
|
+
/** Collect a call into the current step. Serial tools close the step at once; a
|
|
1086
|
+
* read-only one waits TOOL_BATCH_MS for the siblings Claude Code issues in parallel,
|
|
1087
|
+
* so OpenCode gets them in ONE step and runs them in parallel too. With no stream
|
|
1088
|
+
* attached the call is queued for the next continuation — never dropped. */
|
|
1089
|
+
addStepItem(t, item) {
|
|
1090
|
+
if (!t.controller) {
|
|
1091
|
+
t.queuedItems.push(item);
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
t.stepItems.push(item);
|
|
1095
|
+
if (!item.parallel) {
|
|
1096
|
+
this.closeStep(t);
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
1099
|
+
if (!t.stepTimer) {
|
|
1100
|
+
t.stepTimer = setTimeout(() => this.closeStep(t), this.config.claudeCode?.toolBatchMs ?? TOOL_BATCH_MS);
|
|
1101
|
+
t.stepTimer.unref?.();
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
/** Usage for a `finish`: the CURRENT context size (OpenCode reads input + cache +
|
|
1105
|
+
* output of the last step as the prompt size when deciding to compact), split into
|
|
1106
|
+
* cache read/write/no-cache with the ratios of the turn's totals. The turn totals
|
|
1107
|
+
* themselves are a sum over all its requests — reporting them inflated the context
|
|
1108
|
+
* N-fold and triggered compactions early. */
|
|
1109
|
+
usageNow(t, turn) {
|
|
1110
|
+
const used = t.contextUsed;
|
|
1111
|
+
if (used === undefined)
|
|
1112
|
+
return turn ? mapUsage(turn) : emptyUsage(); // agent without usage_update
|
|
1113
|
+
if (used === 0) {
|
|
1114
|
+
// just compacted: tiny but non-zero, so OpenCode keeps this step as its anchor
|
|
1115
|
+
return { inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 }, outputTokens: { total: 0, text: 0 } };
|
|
1116
|
+
}
|
|
1117
|
+
const ratios = turn ?? t.lastUsage ?? {};
|
|
1118
|
+
const out = Math.min(turn?.outputTokens ?? 0, used);
|
|
1119
|
+
const input = used - out;
|
|
1120
|
+
const nc = ratios.inputTokens ?? 0, cr = ratios.cachedReadTokens ?? 0, cw = ratios.cachedWriteTokens ?? 0;
|
|
1121
|
+
const all = nc + cr + cw;
|
|
1122
|
+
const cacheRead = all ? Math.round((input * cr) / all) : 0;
|
|
1123
|
+
const cacheWrite = all ? Math.round((input * cw) / all) : 0;
|
|
1124
|
+
return {
|
|
1125
|
+
inputTokens: { total: input, noCache: Math.max(0, input - cacheRead - cacheWrite), cacheRead, cacheWrite },
|
|
1126
|
+
outputTokens: { total: out, text: out },
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
/** Emit the collected calls and end the stream with ONE `tool-calls` finish (OpenCode
|
|
1130
|
+
* rejects a second finish in a step). */
|
|
1131
|
+
closeStep(t) {
|
|
1132
|
+
if (t.stepTimer) {
|
|
1133
|
+
clearTimeout(t.stepTimer);
|
|
1134
|
+
t.stepTimer = null;
|
|
1135
|
+
}
|
|
1136
|
+
const items = t.stepItems;
|
|
1137
|
+
t.stepItems = [];
|
|
1138
|
+
if (!items.length)
|
|
1139
|
+
return;
|
|
1140
|
+
if (!t.controller) {
|
|
1141
|
+
t.queuedItems.push(...items);
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1144
|
+
this.closeBlocks(t);
|
|
1145
|
+
for (const it of items) {
|
|
1146
|
+
if (it.preface) {
|
|
1147
|
+
const id = `plan${++this.idSeq}`;
|
|
1148
|
+
this.emit(t, { type: "text-start", id });
|
|
1149
|
+
this.emit(t, { type: "text-delta", id, delta: it.preface });
|
|
1150
|
+
this.emit(t, { type: "text-end", id });
|
|
1151
|
+
}
|
|
1152
|
+
this.emit(t, { type: "tool-input-start", id: it.id, toolName: it.toolName });
|
|
1153
|
+
this.emit(t, { type: "tool-input-delta", id: it.id, delta: it.input });
|
|
1154
|
+
this.emit(t, { type: "tool-input-end", id: it.id });
|
|
1155
|
+
this.emit(t, { type: "tool-call", toolCallId: it.id, toolName: it.toolName, input: it.input });
|
|
1156
|
+
}
|
|
1157
|
+
this.emit(t, { type: "finish", usage: this.usageNow(t), finishReason: { unified: "tool-calls", raw: "tool_use" } });
|
|
476
1158
|
try {
|
|
477
1159
|
t.controller?.close();
|
|
478
1160
|
}
|
|
@@ -530,8 +1212,9 @@ export class ACPOrchestratorModel {
|
|
|
530
1212
|
* the `question` tool-result (resolved in onStart's continuation branch). */
|
|
531
1213
|
onRequestPermission(params) {
|
|
532
1214
|
const t = this.byAcpSession.get(String(params?.sessionId ?? ""));
|
|
533
|
-
// Sin turno vivo (crash/reinicio) — denegar es más seguro que aprobar
|
|
534
|
-
|
|
1215
|
+
// Sin turno vivo (crash/reinicio, turno abortado) — denegar es más seguro que aprobar
|
|
1216
|
+
// a ciegas. Con el stream cerrado por un paso de tools, la pregunta se encola.
|
|
1217
|
+
if (!t || t.aborted)
|
|
535
1218
|
return Promise.resolve(this.permOutcome(params, false));
|
|
536
1219
|
const toolCall = params?.toolCall;
|
|
537
1220
|
const native = this.permToolName(toolCall);
|
|
@@ -545,11 +1228,22 @@ export class ACPOrchestratorModel {
|
|
|
545
1228
|
return Promise.resolve(this.permOutcome(params, true));
|
|
546
1229
|
if (rules === "deny")
|
|
547
1230
|
return Promise.resolve(this.permOutcome(params, false));
|
|
1231
|
+
// An agent without `question` (OpenCode's `general` subagent denies it) can't show
|
|
1232
|
+
// the dialog: the call would just fail. Deny now, with nothing left hanging.
|
|
1233
|
+
if (t.hasQuestion === false) {
|
|
1234
|
+
dbg(`requestPermission(${native}) → denied: agent ${agent} has no question tool`);
|
|
1235
|
+
return Promise.resolve(this.permOutcome(params, false));
|
|
1236
|
+
}
|
|
548
1237
|
// (2) "ask": raise a `question` dialog and wait for its tool-result.
|
|
549
|
-
|
|
1238
|
+
// Own prefix: unique across processes (a bare counter restarts at 0 and collided
|
|
1239
|
+
// with old `perm_N` answers still in the history) and recognised as own traffic.
|
|
1240
|
+
const callId = `${t.idPrefix}perm_${++this.idSeq}`;
|
|
550
1241
|
dbg(`requestPermission(${native}) → bridge as question (${callId})`);
|
|
1242
|
+
if (toolCall?.kind === "switch_mode")
|
|
1243
|
+
return this.askPlanApproval(t, callId, params);
|
|
551
1244
|
return new Promise((resolve) => {
|
|
552
|
-
t.pendingPermissions.set(callId, (
|
|
1245
|
+
t.pendingPermissions.set(callId, (output) => {
|
|
1246
|
+
const verdict = this.questionVerdict(output);
|
|
553
1247
|
if (verdict.approved && verdict.always && target.always)
|
|
554
1248
|
addAlwaysRule(agent, native, target.always);
|
|
555
1249
|
resolve(this.permOutcome(params, verdict.approved));
|
|
@@ -557,6 +1251,40 @@ export class ACPOrchestratorModel {
|
|
|
557
1251
|
this.emitPermissionCall(t, callId, toolCall, native, target);
|
|
558
1252
|
});
|
|
559
1253
|
}
|
|
1254
|
+
/** ExitPlanMode: offer the agent's OWN choices (auto / accept edits / approve each
|
|
1255
|
+
* edit / keep planning) instead of a generic allow/deny that always meant "approve
|
|
1256
|
+
* each edit". A typed answer means "keep planning, and here's why": the plan is
|
|
1257
|
+
* rejected and the text reaches the agent as a message, so it revises the plan. */
|
|
1258
|
+
askPlanApproval(t, callId, params) {
|
|
1259
|
+
const options = (params?.options ?? []).filter((o) => o?.optionId && o?.name);
|
|
1260
|
+
const reject = options.find((o) => o.kind === "reject_once" || o.kind === "reject_always");
|
|
1261
|
+
const input = JSON.stringify({
|
|
1262
|
+
questions: [{
|
|
1263
|
+
question: "Approve the plan above?",
|
|
1264
|
+
header: "Plan",
|
|
1265
|
+
options: options.map((o) => ({
|
|
1266
|
+
label: String(o.name),
|
|
1267
|
+
description: o.optionId === "plan" ? "Reject and keep refining the plan (or type what to change)" : `Approve; session mode → ${o.optionId}`,
|
|
1268
|
+
})),
|
|
1269
|
+
}],
|
|
1270
|
+
});
|
|
1271
|
+
return new Promise((resolve) => {
|
|
1272
|
+
t.pendingPermissions.set(callId, (output) => {
|
|
1273
|
+
const picked = this.isErrorOutput(output) ? undefined : this.answerLabel(output);
|
|
1274
|
+
const norm = this.normalizeAnswer(picked ?? "");
|
|
1275
|
+
const match = norm ? options.find((o) => this.normalizeAnswer(String(o.name)) === norm) : undefined;
|
|
1276
|
+
if (match) {
|
|
1277
|
+
resolve({ outcome: { outcome: "selected", optionId: match.optionId } });
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
resolve(reject ? { outcome: { outcome: "selected", optionId: reject.optionId } } : { outcome: { outcome: "cancelled" } });
|
|
1281
|
+
const feedback = String(picked ?? "").trim();
|
|
1282
|
+
if (feedback && !t.aborted)
|
|
1283
|
+
this.sendPrompt(t, [{ type: "text", text: `Feedback on the proposed plan — keep planning and revise it:\n${feedback}` }]);
|
|
1284
|
+
});
|
|
1285
|
+
this.addStepItem(t, { id: callId, toolName: "question", input, preface: this.planText(params?.toolCall) || undefined });
|
|
1286
|
+
});
|
|
1287
|
+
}
|
|
560
1288
|
/** Action target of a native request (command / skill / path), plus the glob an
|
|
561
1289
|
* "Always allow" would persist. Shell commands collapse to their first token
|
|
562
1290
|
* (`git status` → `git *`); a request with no real target persists nothing, so
|
|
@@ -576,21 +1304,6 @@ export class ACPOrchestratorModel {
|
|
|
576
1304
|
* Always allow / Deny — and the answer arrives as the tool-result on the next
|
|
577
1305
|
* doStream. The agent itself only ever sees the ACP permission outcome. */
|
|
578
1306
|
emitPermissionCall(t, callId, toolCall, native, target) {
|
|
579
|
-
if (!t.controller)
|
|
580
|
-
return;
|
|
581
|
-
this.closeBlocks(t);
|
|
582
|
-
// ExitPlanMode (switch_mode): render the PLAN as visible assistant text before the
|
|
583
|
-
// approval prompt — otherwise it's only buried in the permission metadata and the
|
|
584
|
-
// user would approve blind. Presenting the plan for approval IS the point of the tool.
|
|
585
|
-
if (toolCall?.kind === "switch_mode") {
|
|
586
|
-
const plan = this.planText(toolCall);
|
|
587
|
-
if (plan) {
|
|
588
|
-
const id = `plan${++this.idSeq}`;
|
|
589
|
-
this.emit(t, { type: "text-start", id });
|
|
590
|
-
this.emit(t, { type: "text-delta", id, delta: plan });
|
|
591
|
-
this.emit(t, { type: "text-end", id });
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
1307
|
const input = JSON.stringify({
|
|
595
1308
|
questions: [
|
|
596
1309
|
{
|
|
@@ -606,16 +1319,7 @@ export class ACPOrchestratorModel {
|
|
|
606
1319
|
},
|
|
607
1320
|
],
|
|
608
1321
|
});
|
|
609
|
-
this.
|
|
610
|
-
this.emit(t, { type: "tool-input-delta", id: callId, delta: input });
|
|
611
|
-
this.emit(t, { type: "tool-input-end", id: callId });
|
|
612
|
-
this.emit(t, { type: "tool-call", toolCallId: callId, toolName: "question", input });
|
|
613
|
-
this.emit(t, { type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
|
|
614
|
-
try {
|
|
615
|
-
t.controller?.close();
|
|
616
|
-
}
|
|
617
|
-
catch { /* ignore */ }
|
|
618
|
-
t.controller = null;
|
|
1322
|
+
this.addStepItem(t, { id: callId, toolName: "question", input });
|
|
619
1323
|
}
|
|
620
1324
|
/** Fired by the ACP client on session/update. */
|
|
621
1325
|
onSessionUpdate(params) {
|
|
@@ -637,12 +1341,16 @@ export class ACPOrchestratorModel {
|
|
|
637
1341
|
// same tool profile, so this is informational, not a call to action.
|
|
638
1342
|
const id = `mode${++this.idSeq}`;
|
|
639
1343
|
this.emit(t, { type: "text-start", id });
|
|
640
|
-
this.emit(t, { type: "text-delta", id, delta: `\
|
|
1344
|
+
this.emit(t, { type: "text-delta", id, delta: `\n_Session mode: ${from} → ${t.appliedMode}_\n` });
|
|
641
1345
|
this.emit(t, { type: "text-end", id });
|
|
642
1346
|
}
|
|
643
1347
|
return;
|
|
644
1348
|
}
|
|
645
1349
|
switch (update?.sessionUpdate) {
|
|
1350
|
+
case "usage_update":
|
|
1351
|
+
if (typeof update.used === "number")
|
|
1352
|
+
t.contextUsed = update.used;
|
|
1353
|
+
break;
|
|
646
1354
|
case "agent_message_chunk":
|
|
647
1355
|
if (update.content?.type === "text") {
|
|
648
1356
|
if (!t.textId) {
|
|
@@ -661,10 +1369,63 @@ export class ACPOrchestratorModel {
|
|
|
661
1369
|
this.emit(t, { type: "reasoning-delta", id: t.reasoningId, delta: update.content.text });
|
|
662
1370
|
}
|
|
663
1371
|
break;
|
|
1372
|
+
case "tool_call":
|
|
1373
|
+
case "tool_call_update":
|
|
1374
|
+
this.onNativeTool(t, update);
|
|
1375
|
+
break;
|
|
664
1376
|
default:
|
|
665
|
-
break;
|
|
1377
|
+
break;
|
|
666
1378
|
}
|
|
667
1379
|
}
|
|
1380
|
+
/** Native Claude Code tools run INSIDE the agent: OpenCode never sees them, so after a
|
|
1381
|
+
* switch to another model what Claude read, searched or delegated was simply gone.
|
|
1382
|
+
* Each one that completes is written into the answer as a short text block — plain
|
|
1383
|
+
* text, the only form every model accepts (tools marked provider-executed would be
|
|
1384
|
+
* replayed to other providers as calls they don't know). OpenCode's own tools
|
|
1385
|
+
* (mcp__opencode__*) are skipped: they're already in the history. */
|
|
1386
|
+
onNativeTool(t, u) {
|
|
1387
|
+
const mode = this.config.claudeCode?.nativeActivity ?? "text";
|
|
1388
|
+
if (mode === "off" || !u?.toolCallId)
|
|
1389
|
+
return;
|
|
1390
|
+
const meta = u._meta?.claudeCode ?? {};
|
|
1391
|
+
const prev = t.nativeCalls.get(u.toolCallId) ?? {};
|
|
1392
|
+
const call = {
|
|
1393
|
+
toolName: meta.toolName ?? prev.toolName,
|
|
1394
|
+
title: (typeof u.title === "string" && u.title) || prev.title,
|
|
1395
|
+
parent: meta.parentToolUseId ?? prev.parent,
|
|
1396
|
+
};
|
|
1397
|
+
t.nativeCalls.set(u.toolCallId, call);
|
|
1398
|
+
if (u.status !== "completed" && u.status !== "failed")
|
|
1399
|
+
return;
|
|
1400
|
+
t.nativeCalls.delete(u.toolCallId);
|
|
1401
|
+
const name = String(call.toolName ?? "");
|
|
1402
|
+
if (!name || name.startsWith("mcp__") || NATIVE_SILENT.has(name))
|
|
1403
|
+
return;
|
|
1404
|
+
const result = NATIVE_WITH_RESULT.has(name) ? this.nativeResultText(u) : "";
|
|
1405
|
+
const cap = this.config.claudeCode?.nativeActivityChars ?? NATIVE_RESULT_CHARS;
|
|
1406
|
+
const body = result.length > cap ? `${result.slice(0, cap)}…[truncated, ${result.length} chars]` : result;
|
|
1407
|
+
const head = `${call.parent ? " ↳ " : ""}⚙ ${name}${call.title && call.title !== name ? `: ${call.title}` : ""}${u.status === "failed" ? " — failed" : ""}`;
|
|
1408
|
+
const id = `n${++this.idSeq}`;
|
|
1409
|
+
this.closeBlocks(t);
|
|
1410
|
+
this.emit(t, { type: "text-start", id });
|
|
1411
|
+
this.emit(t, { type: "text-delta", id, delta: `\n${head}\n${body ? `\n\`\`\`text\n${body}\n\`\`\`\n` : ""}` });
|
|
1412
|
+
this.emit(t, { type: "text-end", id });
|
|
1413
|
+
}
|
|
1414
|
+
nativeResultText(u) {
|
|
1415
|
+
const content = Array.isArray(u.content) ? u.content : [];
|
|
1416
|
+
const text = content
|
|
1417
|
+
.map((c) => (c?.type === "content" && c.content?.type === "text" ? c.content.text : typeof c?.text === "string" ? c.text : ""))
|
|
1418
|
+
.filter(Boolean)
|
|
1419
|
+
.join("\n");
|
|
1420
|
+
if (text)
|
|
1421
|
+
return text.trim();
|
|
1422
|
+
const raw = u.rawOutput;
|
|
1423
|
+
if (typeof raw === "string")
|
|
1424
|
+
return raw.trim();
|
|
1425
|
+
if (Array.isArray(raw))
|
|
1426
|
+
return raw.map((x) => (typeof x?.text === "string" ? x.text : "")).join("\n").trim();
|
|
1427
|
+
return "";
|
|
1428
|
+
}
|
|
668
1429
|
closeBlocks(t) {
|
|
669
1430
|
if (t.textId) {
|
|
670
1431
|
this.emit(t, { type: "text-end", id: t.textId });
|
|
@@ -676,7 +1437,6 @@ export class ACPOrchestratorModel {
|
|
|
676
1437
|
}
|
|
677
1438
|
}
|
|
678
1439
|
endTurn(t) {
|
|
679
|
-
this.clearCancelWatchdog(t);
|
|
680
1440
|
// Settle any deferred permission requests (deny/cancel) so the agent never
|
|
681
1441
|
// stays blocked awaiting a verdict that will no longer arrive.
|
|
682
1442
|
this.drainPermissions(t);
|
|
@@ -686,6 +1446,9 @@ export class ACPOrchestratorModel {
|
|
|
686
1446
|
}
|
|
687
1447
|
catch { /* ignore */ }
|
|
688
1448
|
t.host.stop();
|
|
1449
|
+
// Without this the agent keeps the session — and its `claude` process — forever.
|
|
1450
|
+
if (this.connection && t.sessionId)
|
|
1451
|
+
this.closeAcpSession(t.sessionId);
|
|
689
1452
|
if (this.sessions.get(t.key) === t)
|
|
690
1453
|
this.sessions.delete(t.key);
|
|
691
1454
|
this.byAcpSession.delete(t.sessionId);
|
|
@@ -693,12 +1456,13 @@ export class ACPOrchestratorModel {
|
|
|
693
1456
|
/** Keep at most MAX_LIVE_SESSIONS conversations alive; tear down the oldest idle ones
|
|
694
1457
|
* (never one with work in flight) so hosts and agent sessions don't pile up. */
|
|
695
1458
|
evictIdleSessions() {
|
|
696
|
-
|
|
1459
|
+
const max = this.config.claudeCode?.maxLiveSessions ?? MAX_LIVE_SESSIONS;
|
|
1460
|
+
if (this.sessions.size <= max)
|
|
697
1461
|
return;
|
|
698
1462
|
const idle = [...this.sessions.values()]
|
|
699
1463
|
.filter((s) => !s.controller && s.pendingTools.size === 0 && s.pendingPermissions.size === 0)
|
|
700
1464
|
.sort((a, b) => a.lastActive - b.lastActive);
|
|
701
|
-
while (this.sessions.size >
|
|
1465
|
+
while (this.sessions.size > max && idle.length) {
|
|
702
1466
|
const victim = idle.shift();
|
|
703
1467
|
dbg(`evicting idle session ${victim.sessionId} (LRU)`);
|
|
704
1468
|
this.endTurn(victim);
|
|
@@ -708,10 +1472,10 @@ export class ACPOrchestratorModel {
|
|
|
708
1472
|
drainPermissions(t) {
|
|
709
1473
|
if (t.pendingPermissions.size === 0)
|
|
710
1474
|
return;
|
|
711
|
-
const
|
|
1475
|
+
const abandoned = { type: "error-text", value: "Permission request abandoned" };
|
|
712
1476
|
for (const resolve of [...t.pendingPermissions.values()]) {
|
|
713
1477
|
try {
|
|
714
|
-
resolve(
|
|
1478
|
+
resolve(abandoned);
|
|
715
1479
|
}
|
|
716
1480
|
catch { /* ignore */ }
|
|
717
1481
|
}
|
|
@@ -728,7 +1492,8 @@ export class ACPOrchestratorModel {
|
|
|
728
1492
|
if (own && typeof own === "object")
|
|
729
1493
|
return own;
|
|
730
1494
|
const SHAPE_KEYS = new Set([
|
|
731
|
-
"ocSession", "ocAgent", "resumeId", "resumeLen", "resumeConvKey", "resumeLastUsage",
|
|
1495
|
+
"ocSession", "ocAgent", "resumeId", "resumeLen", "resumeConvKey", "resumeLastUsage", "resumeIdPrefixes",
|
|
1496
|
+
"requestKind", "hasQuestion",
|
|
732
1497
|
"mode", "effort", "thinking", "systemPromptMode", "forwardEnvContext",
|
|
733
1498
|
"tools", "allowedTools", "disallowedTools", "settingSources", "strictMcpConfig",
|
|
734
1499
|
"nativeTools", "resourceSearch", "nativeSubagents", "nativeSkills", "projectMemory", "skillShell",
|
|
@@ -760,18 +1525,34 @@ export class ACPOrchestratorModel {
|
|
|
760
1525
|
ctrl[k] = po[k];
|
|
761
1526
|
}
|
|
762
1527
|
// OpenCode's modelId maps to Claude's model unless claudeCode.model overrides it.
|
|
763
|
-
|
|
764
|
-
|
|
1528
|
+
const modelId = this.callModel.get(options) ?? this.modelId;
|
|
1529
|
+
if (!ctrl.model && modelId && modelId !== "claude-code")
|
|
1530
|
+
ctrl.model = modelId;
|
|
765
1531
|
return ctrl;
|
|
766
1532
|
}
|
|
767
1533
|
/** Apply runtime config (mode/effort) to a live ACP session via set_mode/set_config_option. */
|
|
768
1534
|
async applySessionConfig(t, ctrl) {
|
|
1535
|
+
if (ctrl.model && ctrl.model !== t.appliedModel) {
|
|
1536
|
+
try {
|
|
1537
|
+
await this.connection.unstable_setSessionModel({ sessionId: t.sessionId, modelId: ctrl.model });
|
|
1538
|
+
t.appliedModel = ctrl.model;
|
|
1539
|
+
dbg(`model → ${ctrl.model}`);
|
|
1540
|
+
}
|
|
1541
|
+
catch (e) {
|
|
1542
|
+
note(`warning: could not apply model ${ctrl.model} (${e instanceof Error ? e.message : String(e)})`);
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
769
1545
|
// A CHANGED request (the user reselected the plan agent) overrides a mode the agent
|
|
770
1546
|
// set for itself. Without this reset an ExitPlanMode would permanently pin the
|
|
771
1547
|
// session out of plan mode, and going back to the plan agent would do nothing.
|
|
772
1548
|
if (ctrl.mode !== t.requestedMode) {
|
|
773
1549
|
t.requestedMode = ctrl.mode;
|
|
774
|
-
|
|
1550
|
+
// Leaving the plan agent for a non-plan one after the plan was approved keeps the
|
|
1551
|
+
// mode the user picked in that approval (acceptEdits, auto…) instead of downgrading
|
|
1552
|
+
// it to the new agent's default. Only (re)entering plan resets it.
|
|
1553
|
+
const keepApproved = t.modeChangedByAgent && ctrl.mode !== "plan" && t.appliedMode !== "plan";
|
|
1554
|
+
if (!keepApproved)
|
|
1555
|
+
t.modeChangedByAgent = false;
|
|
775
1556
|
}
|
|
776
1557
|
// Don't re-force the configured mode once the agent switched it itself (ExitPlanMode):
|
|
777
1558
|
// the user approved leaving plan mode, so the next turn must not snap back to plan.
|
|
@@ -794,7 +1575,7 @@ export class ACPOrchestratorModel {
|
|
|
794
1575
|
catch (e) {
|
|
795
1576
|
// Not a debug detail: a rejected effort means the user picked `:max` and is
|
|
796
1577
|
// silently getting something else — including no visible reasoning.
|
|
797
|
-
note(`
|
|
1578
|
+
note(`warning: could not apply effort=${ctrl.effort} (${e instanceof Error ? e.message : String(e)})`);
|
|
798
1579
|
}
|
|
799
1580
|
}
|
|
800
1581
|
}
|
|
@@ -819,12 +1600,43 @@ export class ACPOrchestratorModel {
|
|
|
819
1600
|
env.CLAUDE_CONFIG_DIR = configDir;
|
|
820
1601
|
if (this.config.streamCloseTimeoutMs)
|
|
821
1602
|
env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT = String(this.config.streamCloseTimeoutMs);
|
|
1603
|
+
// Claude compacts its own session before OpenCode's threshold (context − 32k), so
|
|
1604
|
+
// OpenCode's compaction — which forces a new session elsewhere — rarely triggers.
|
|
1605
|
+
const pct = ctrl.autoCompactPct ?? 75;
|
|
1606
|
+
if (pct && !env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE)
|
|
1607
|
+
env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE = String(pct);
|
|
822
1608
|
// Model selection: the agent resolves the effective model from ANTHROPIC_MODEL
|
|
823
1609
|
// (getAvailableModels overrides options.model otherwise). claudeCode.model wins,
|
|
824
1610
|
// else the OpenCode modelId (unless the neutral "claude-code").
|
|
825
1611
|
const model = ctrl.model ?? (this.modelId !== "claude-code" ? this.modelId : undefined);
|
|
826
1612
|
if (model)
|
|
827
1613
|
env.ANTHROPIC_MODEL = model;
|
|
1614
|
+
const stream = this.config.transport ? this.openTransport() : this.spawnAgent(env);
|
|
1615
|
+
const self = this;
|
|
1616
|
+
this.connection = new ClientSideConnection(() => ({
|
|
1617
|
+
// Keep the whole params object: `sessionId` is what routes the update to the
|
|
1618
|
+
// right conversation now that several can be live at once.
|
|
1619
|
+
async sessionUpdate(params) { self.onSessionUpdate(params); },
|
|
1620
|
+
async requestPermission(params) {
|
|
1621
|
+
return self.onRequestPermission(params);
|
|
1622
|
+
},
|
|
1623
|
+
async writeTextFile() { return {}; },
|
|
1624
|
+
async readTextFile() { return { content: "" }; },
|
|
1625
|
+
}), stream);
|
|
1626
|
+
const initResult = await this.connection.initialize({
|
|
1627
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
1628
|
+
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
|
1629
|
+
});
|
|
1630
|
+
this.promptCaps = (initResult?.agentCapabilities?.promptCapabilities ?? {});
|
|
1631
|
+
this.promptQueueing = !!initResult?.agentCapabilities?._meta?.claudeCode?.promptQueueing;
|
|
1632
|
+
dbg(`connected to agent — promptCapabilities: ${JSON.stringify(this.promptCaps)}`);
|
|
1633
|
+
}
|
|
1634
|
+
openTransport() {
|
|
1635
|
+
const t = this.config.transport();
|
|
1636
|
+
this.closeTransport = t.close ?? null;
|
|
1637
|
+
return ndJsonStream(t.input, t.output);
|
|
1638
|
+
}
|
|
1639
|
+
spawnAgent(env) {
|
|
828
1640
|
this.agent = spawn(this.config.command, this.config.args ?? [], {
|
|
829
1641
|
stdio: ["pipe", "pipe", "pipe"],
|
|
830
1642
|
cwd: this.config.cwd ?? process.cwd(),
|
|
@@ -844,69 +1656,59 @@ export class ACPOrchestratorModel {
|
|
|
844
1656
|
this.agent.stderr?.on("error", () => { });
|
|
845
1657
|
this.agent.stderr?.on("data", (chunk) => { if (DEBUG)
|
|
846
1658
|
process.stderr.write(chunk); });
|
|
847
|
-
|
|
848
|
-
const self = this;
|
|
849
|
-
this.connection = new ClientSideConnection(() => ({
|
|
850
|
-
// Keep the whole params object: `sessionId` is what routes the update to the
|
|
851
|
-
// right conversation now that several can be live at once.
|
|
852
|
-
async sessionUpdate(params) { self.onSessionUpdate(params); },
|
|
853
|
-
async requestPermission(params) {
|
|
854
|
-
return self.onRequestPermission(params);
|
|
855
|
-
},
|
|
856
|
-
async writeTextFile() { return {}; },
|
|
857
|
-
async readTextFile() { return { content: "" }; },
|
|
858
|
-
}), stream);
|
|
859
|
-
const initResult = await this.connection.initialize({
|
|
860
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
861
|
-
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
|
862
|
-
});
|
|
863
|
-
this.promptCaps = (initResult?.agentCapabilities?.promptCapabilities ?? {});
|
|
864
|
-
dbg(`connected to agent — promptCapabilities: ${JSON.stringify(this.promptCaps)}`);
|
|
1659
|
+
return ndJsonStream(Writable.toWeb(this.agent.stdin), Readable.toWeb(this.agent.stdout));
|
|
865
1660
|
}
|
|
1661
|
+
/** V2 reads every stream to its end; a cancel only comes from an error or the user
|
|
1662
|
+
* aborting (V1 also cancelled to PAUSE for a permission prompt — not anymore). So a
|
|
1663
|
+
* cancel ends the turn: the agent stops, deferred calls are released, leftovers are
|
|
1664
|
+
* dropped. The session itself — and its prompt cache — stays for the next message. */
|
|
866
1665
|
onCancel(ref) {
|
|
867
1666
|
const t = ref.t;
|
|
868
1667
|
if (!t)
|
|
869
1668
|
return;
|
|
870
|
-
|
|
871
|
-
// PAUSING (e.g. to show a permission prompt), not a real abort — tearing the
|
|
872
|
-
// host down here kills the pending tools/call with "host closed". Keep the
|
|
873
|
-
// session/host alive; the continuation doStream resolves them. A WATCHDOG
|
|
874
|
-
// guarantees teardown if the continuation never arrives (session truly aborted,
|
|
875
|
-
// prompt dropped) so the agent can't hang forever.
|
|
876
|
-
if (t.pendingTools.size > 0 || t.pendingPermissions.size > 0) {
|
|
877
|
-
dbg("onCancel ignored — deferred tool-call/permission in flight (likely a permission pause)");
|
|
878
|
-
this.armCancelWatchdog(t);
|
|
879
|
-
return;
|
|
880
|
-
}
|
|
881
|
-
// A plain cancel ends the TURN, not the conversation: keep the session (and its
|
|
882
|
-
// prompt cache) so the next message continues where this one stopped.
|
|
883
|
-
try {
|
|
884
|
-
this.connection?.cancel?.({ sessionId: t.sessionId });
|
|
885
|
-
}
|
|
886
|
-
catch { /* ignore */ }
|
|
887
|
-
t.controller = null;
|
|
888
|
-
this.closeBlocks(t);
|
|
1669
|
+
this.abortTurn(t, "stream cancelled");
|
|
889
1670
|
}
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
const
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
}, this.config.streamCloseTimeoutMs ?? 600_000);
|
|
899
|
-
timer.unref?.();
|
|
900
|
-
t.cancelWatchdogs.add(timer);
|
|
1671
|
+
sweeper = null;
|
|
1672
|
+
startSweeper() {
|
|
1673
|
+
if (this.sweeper)
|
|
1674
|
+
return;
|
|
1675
|
+
const c = this.config.claudeCode ?? {};
|
|
1676
|
+
const shortest = Math.min(c.idleSessionTtlMs ?? IDLE_TTL_MS, c.childSessionTtlMs ?? CHILD_TTL_MS);
|
|
1677
|
+
this.sweeper = setInterval(() => this.sweepIdle(), Math.max(20, Math.min(30_000, shortest / 2)));
|
|
1678
|
+
this.sweeper.unref?.();
|
|
901
1679
|
}
|
|
902
|
-
/**
|
|
903
|
-
*
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
1680
|
+
/** Close sessions nobody is using. Only resumable ones (an OpenCode session id, so
|
|
1681
|
+
* the registry can bring them back without a replay); a turn left waiting on
|
|
1682
|
+
* OpenCode for hours is treated as abandoned. */
|
|
1683
|
+
sweepIdle() {
|
|
1684
|
+
const c = this.config.claudeCode ?? {};
|
|
1685
|
+
const now = Date.now();
|
|
1686
|
+
for (const t of [...this.sessions.values()]) {
|
|
1687
|
+
if (!t.ocSession)
|
|
1688
|
+
continue;
|
|
1689
|
+
const idle = now - t.lastActive;
|
|
1690
|
+
const waiting = t.pendingTools.size > 0 || t.pendingPermissions.size > 0 || t.queuedItems.length > 0;
|
|
1691
|
+
if (waiting) {
|
|
1692
|
+
if (idle > ABANDONED_TTL_MS) {
|
|
1693
|
+
this.abortTurn(t, "abandoned");
|
|
1694
|
+
this.endTurn(t);
|
|
1695
|
+
}
|
|
1696
|
+
continue;
|
|
1697
|
+
}
|
|
1698
|
+
if (t.controller || t.inflight)
|
|
1699
|
+
continue;
|
|
1700
|
+
const ttl = t.isChild ? c.childSessionTtlMs ?? CHILD_TTL_MS : c.idleSessionTtlMs ?? IDLE_TTL_MS;
|
|
1701
|
+
if (idle > ttl) {
|
|
1702
|
+
dbg(`closing idle session ${t.sessionId} (${Math.round(idle / 1000)}s)`);
|
|
1703
|
+
this.endTurn(t);
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
908
1706
|
}
|
|
909
1707
|
cleanup() {
|
|
1708
|
+
if (this.sweeper) {
|
|
1709
|
+
clearInterval(this.sweeper);
|
|
1710
|
+
this.sweeper = null;
|
|
1711
|
+
}
|
|
910
1712
|
for (const t of [...this.sessions.values()])
|
|
911
1713
|
this.endTurn(t);
|
|
912
1714
|
this.sessions.clear();
|
|
@@ -915,10 +1717,28 @@ export class ACPOrchestratorModel {
|
|
|
915
1717
|
this.agent?.kill();
|
|
916
1718
|
}
|
|
917
1719
|
catch { /* ignore */ }
|
|
1720
|
+
try {
|
|
1721
|
+
this.closeTransport?.();
|
|
1722
|
+
}
|
|
1723
|
+
catch { /* ignore */ }
|
|
918
1724
|
this.agent = null;
|
|
1725
|
+
this.closeTransport = null;
|
|
919
1726
|
this.connection = null;
|
|
920
1727
|
this.connecting = null;
|
|
921
1728
|
}
|
|
1729
|
+
// ---- diagnostics ----------------------------------------------------------
|
|
1730
|
+
/** Conversation id for logs/recordings: OpenCode's sessionID, else the first-message hash. */
|
|
1731
|
+
convId(options) {
|
|
1732
|
+
const po = this.providerOptions(options);
|
|
1733
|
+
return typeof po.ocSession === "string" ? po.ocSession : `conv_${hashText(firstUserText(options.prompt))}`;
|
|
1734
|
+
}
|
|
1735
|
+
/** One line per turn decision (file log + recording): the evidence needed to tell a
|
|
1736
|
+
* genuine divergence from a false one after the fact. */
|
|
1737
|
+
decide(options, d) {
|
|
1738
|
+
const conv = this.convId(options);
|
|
1739
|
+
log.trace(`${conv} ${JSON.stringify(d)}`);
|
|
1740
|
+
record(conv, { kind: "decision", ...d });
|
|
1741
|
+
}
|
|
922
1742
|
// ---- conversions ----------------------------------------------------------
|
|
923
1743
|
convertTools(tools) {
|
|
924
1744
|
if (!tools)
|
|
@@ -926,10 +1746,12 @@ export class ACPOrchestratorModel {
|
|
|
926
1746
|
const out = [];
|
|
927
1747
|
for (const t of tools) {
|
|
928
1748
|
if (t.type === "function") {
|
|
1749
|
+
const name = t.name;
|
|
929
1750
|
out.push({
|
|
930
|
-
name
|
|
931
|
-
description: this.toolDescription(
|
|
1751
|
+
name,
|
|
1752
|
+
description: this.toolDescription(name, t.description),
|
|
932
1753
|
inputSchema: t.inputSchema ?? { type: "object", properties: {} },
|
|
1754
|
+
...(this.parallelTools().includes(name) ? { annotations: { readOnlyHint: true } } : {}),
|
|
933
1755
|
});
|
|
934
1756
|
}
|
|
935
1757
|
}
|
|
@@ -942,113 +1764,129 @@ export class ACPOrchestratorModel {
|
|
|
942
1764
|
* agent silently assumes instead of asking. A tool description is NOT a system
|
|
943
1765
|
* prompt, so this doesn't affect how Anthropic bills the session. */
|
|
944
1766
|
toolDescription(name, description) {
|
|
1767
|
+
if (name === "subagent") {
|
|
1768
|
+
return `${description ?? ""}\n\nPrefer this tool for delegating substantial work: the child session is visible in OpenCode and any model can continue it, so its result stays part of the shared conversation. Use your native Task tool for your own specialised agents or quick self-contained lookups.`.trim();
|
|
1769
|
+
}
|
|
945
1770
|
if (name === "question") {
|
|
946
1771
|
return `${description ?? ""}\n\nIMPORTANT: this is the ONLY way to ask the user something — the native AskUserQuestion tool is unavailable here. Use it whenever the request is ambiguous or a decision is the user's to make, instead of assuming.`.trim();
|
|
947
1772
|
}
|
|
948
1773
|
return description;
|
|
949
1774
|
}
|
|
950
|
-
/**
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
1775
|
+
/** Messages the agent hasn't seen, as prompt blocks.
|
|
1776
|
+
* - `tail` (live or resumed session): the user's messages verbatim; every run of
|
|
1777
|
+
* assistant/tool messages between them was produced by ANOTHER model or agent in
|
|
1778
|
+
* OpenCode (the agent's own output is dropped beforehand), and is labelled so —
|
|
1779
|
+
* as a bare "Assistant:" the agent took those actions for its own.
|
|
1780
|
+
* - `replay` (brand-new session): everything before the current request becomes a
|
|
1781
|
+
* bounded `<conversation_history>`; the request itself follows on its own. */
|
|
1782
|
+
blocksFor(msgs, t, mode = "tail") {
|
|
1783
|
+
if (mode === "replay")
|
|
1784
|
+
return this.replayBlocks(msgs, t);
|
|
1785
|
+
const blocks = [];
|
|
1786
|
+
for (let i = 0; i < msgs.length;) {
|
|
1787
|
+
if (msgs[i].role === "user") {
|
|
1788
|
+
const m = msgs[i++];
|
|
1789
|
+
if (isTransient(m) && t) {
|
|
1790
|
+
const k = msgKey(m);
|
|
1791
|
+
if (t.sentTransient.has(k))
|
|
1792
|
+
continue;
|
|
1793
|
+
t.sentTransient.add(k);
|
|
1794
|
+
}
|
|
1795
|
+
blocks.push(...this.messageToBlocks(m, false, t));
|
|
954
1796
|
continue;
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
history(prompt) {
|
|
965
|
-
return prompt.filter((m) => m.role !== "system");
|
|
966
|
-
}
|
|
967
|
-
/** Cheap, stable per-message identity. Deliberately keyed on tool-call IDs rather
|
|
968
|
-
* than payloads: it must survive re-serialization but change if the turn changes. */
|
|
969
|
-
msgKey(msg) {
|
|
970
|
-
let body = "";
|
|
971
|
-
if (typeof msg.content === "string")
|
|
972
|
-
body = msg.content;
|
|
973
|
-
else if (Array.isArray(msg.content)) {
|
|
974
|
-
for (const p of msg.content) {
|
|
975
|
-
if (p?.type === "text")
|
|
976
|
-
body += `t:${p.text}`;
|
|
977
|
-
else if (p?.type === "tool-call")
|
|
978
|
-
body += `c:${p.toolCallId}`;
|
|
979
|
-
else if (p?.type === "tool-result")
|
|
980
|
-
body += `r:${p.toolCallId}`;
|
|
981
|
-
else if (p?.type === "file")
|
|
982
|
-
body += `f:${p.filename ?? p.mediaType ?? ""}`;
|
|
983
|
-
else
|
|
984
|
-
body += `?${p?.type}`;
|
|
1797
|
+
}
|
|
1798
|
+
const run = [];
|
|
1799
|
+
while (i < msgs.length && msgs[i].role !== "user")
|
|
1800
|
+
run.push(msgs[i++]);
|
|
1801
|
+
const inner = run.flatMap((m) => this.renderMessage(m, t));
|
|
1802
|
+
if (inner.length) {
|
|
1803
|
+
blocks.push({ type: "text", text: "<other_model_turn>\n(Another model or agent answered this part in OpenCode — you did not write it or run these tools.)" });
|
|
1804
|
+
blocks.push(...inner);
|
|
1805
|
+
blocks.push({ type: "text", text: "</other_model_turn>" });
|
|
985
1806
|
}
|
|
986
1807
|
}
|
|
987
|
-
return `${msg.role}:${hashText(body)}`;
|
|
988
|
-
}
|
|
989
|
-
/** How the incoming history relates to what the agent already knows.
|
|
990
|
-
* - append → normal turn (or another agent ran turns meanwhile): send the tail.
|
|
991
|
-
* - revert → the user rewound: the agent can't unremember, so it needs a new session.
|
|
992
|
-
* - diverged → compaction/rollback replaced the middle: same, a new session. */
|
|
993
|
-
classifyHistory(t, keys) {
|
|
994
|
-
const sent = t.sentKeys;
|
|
995
|
-
let i = 0;
|
|
996
|
-
while (i < sent.length && i < keys.length && sent[i] === keys[i])
|
|
997
|
-
i++;
|
|
998
|
-
if (i === sent.length)
|
|
999
|
-
return { kind: "append", fromIndex: i };
|
|
1000
|
-
// Prefijo estricto = revert SOLO si incoming es más corto; si son iguales no hay
|
|
1001
|
-
// mensajes nuevos → append desde el final (evita falsos revert).
|
|
1002
|
-
if (i === keys.length)
|
|
1003
|
-
return keys.length < sent.length
|
|
1004
|
-
? { kind: "revert", fromIndex: i }
|
|
1005
|
-
: { kind: "append", fromIndex: keys.length };
|
|
1006
|
-
return { kind: "diverged", fromIndex: i };
|
|
1007
|
-
}
|
|
1008
|
-
blocksFor(msgs, t) {
|
|
1009
|
-
const blocks = [];
|
|
1010
|
-
for (const msg of msgs)
|
|
1011
|
-
blocks.push(...this.messageToBlocks(msg, true, t));
|
|
1012
1808
|
return blocks;
|
|
1013
1809
|
}
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1810
|
+
replayBlocks(msgs, t) {
|
|
1811
|
+
let cut = msgs.length;
|
|
1812
|
+
while (cut > 0 && msgs[cut - 1].role === "user")
|
|
1813
|
+
cut--;
|
|
1814
|
+
const current = msgs.slice(cut).flatMap((m) => this.messageToBlocks(m, false, t));
|
|
1815
|
+
let rendered = msgs.slice(0, cut).map((m) => this.renderMessage(m, t)).filter((b) => b.length);
|
|
1816
|
+
if (!rendered.length)
|
|
1817
|
+
return current;
|
|
1818
|
+
// Budget: keep the opening message (usually the task) and the most recent ones.
|
|
1819
|
+
let omitted = 0;
|
|
1820
|
+
while (rendered.length > 2 && rendered.reduce((n, b) => n + blocksChars(b), 0) > REPLAY_BUDGET_CHARS) {
|
|
1821
|
+
rendered.splice(1, 1);
|
|
1822
|
+
omitted++;
|
|
1823
|
+
}
|
|
1824
|
+
return [
|
|
1825
|
+
{ type: "text", text: "<conversation_history>\n(Earlier turns of this conversation, replayed because the session was restarted. Context only: do not repeat or re-run anything from it.)" },
|
|
1826
|
+
...rendered[0],
|
|
1827
|
+
...(omitted ? [{ type: "text", text: `<omitted messages="${omitted}" reason="replay budget"/>` }] : []),
|
|
1828
|
+
...rendered.slice(1).flat(),
|
|
1829
|
+
{ type: "text", text: "</conversation_history>" },
|
|
1830
|
+
...(current.length ? current : [{ type: "text", text: "(Continue the conversation above.)" }]),
|
|
1831
|
+
];
|
|
1832
|
+
}
|
|
1833
|
+
/** One message as tagged blocks (for history and other models' turns). Reasoning and
|
|
1834
|
+
* the agent's own tool traffic are left out: neither is something to re-read. */
|
|
1835
|
+
renderMessage(msg, t) {
|
|
1836
|
+
const role = msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : null;
|
|
1837
|
+
if (typeof msg.content === "string") {
|
|
1838
|
+
const text = stripInjected(msg.content).trim();
|
|
1839
|
+
return text && role ? [{ type: "text", text: `<${role}>\n${text}\n</${role}>` }] : [];
|
|
1840
|
+
}
|
|
1019
1841
|
const blocks = [];
|
|
1020
|
-
let first = true;
|
|
1021
1842
|
for (const part of msg.content) {
|
|
1022
|
-
const px = first ? prefix : "";
|
|
1023
1843
|
// OUR OWN tool traffic: the agent already holds these in its session (they came
|
|
1024
1844
|
// back over MCP). Replaying them as text duplicated whole file/shell outputs on
|
|
1025
1845
|
// every turn and blew the prompt cache — by far the biggest token sink.
|
|
1026
|
-
if ((part.type === "tool-call" || part.type === "tool-result") && t &&
|
|
1846
|
+
if ((part.type === "tool-call" || part.type === "tool-result") && t && this.isOwnId(t, part.toolCallId))
|
|
1027
1847
|
continue;
|
|
1028
1848
|
if (part.type === "text") {
|
|
1029
|
-
|
|
1030
|
-
|
|
1849
|
+
const text = stripInjected(String(part.text ?? "")).trim();
|
|
1850
|
+
if (text && role)
|
|
1851
|
+
blocks.push({ type: "text", text: `<${role}>\n${text}\n</${role}>` });
|
|
1031
1852
|
}
|
|
1032
1853
|
else if (part.type === "tool-call") {
|
|
1033
|
-
|
|
1034
|
-
|
|
1854
|
+
const input = typeof part.input === "string" ? part.input : JSON.stringify(part.input ?? {});
|
|
1855
|
+
blocks.push({ type: "text", text: `<tool_call name="${part.toolName}">${input}</tool_call>` });
|
|
1035
1856
|
}
|
|
1036
1857
|
else if (part.type === "tool-result") {
|
|
1037
|
-
blocks.push({ type: "text", text:
|
|
1038
|
-
first = false;
|
|
1858
|
+
blocks.push({ type: "text", text: `<tool_result name="${part.toolName}">${this.truncate(stripInjected(this.outputToText(part.output)))}</tool_result>` });
|
|
1039
1859
|
}
|
|
1040
1860
|
else if (part.type === "file") {
|
|
1041
|
-
|
|
1042
|
-
blocks.push(fb ?? { type: "text", text: `${px}[Attachment ${part.mediaType ?? "file"} not supported by the agent]` });
|
|
1043
|
-
first = false;
|
|
1861
|
+
blocks.push(this.fileToBlock(part) ?? { type: "text", text: `[Attachment ${part.mediaType ?? "file"} not supported by the agent]` });
|
|
1044
1862
|
}
|
|
1045
1863
|
}
|
|
1046
1864
|
return blocks;
|
|
1047
1865
|
}
|
|
1866
|
+
/** A user message verbatim (text + attachments), minus tags other plugins inject. */
|
|
1867
|
+
messageToBlocks(msg, _withPrefix, t) {
|
|
1868
|
+
if (typeof msg.content === "string")
|
|
1869
|
+
return [{ type: "text", text: stripInjected(msg.content) }];
|
|
1870
|
+
const blocks = [];
|
|
1871
|
+
for (const part of msg.content) {
|
|
1872
|
+
if ((part.type === "tool-call" || part.type === "tool-result") && t && this.isOwnId(t, part.toolCallId))
|
|
1873
|
+
continue;
|
|
1874
|
+
if (part.type === "text")
|
|
1875
|
+
blocks.push({ type: "text", text: stripInjected(String(part.text ?? "")) });
|
|
1876
|
+
else if (part.type === "tool-call")
|
|
1877
|
+
blocks.push({ type: "text", text: `<tool_call name="${part.toolName}">${JSON.stringify(part.input)}</tool_call>` });
|
|
1878
|
+
else if (part.type === "tool-result")
|
|
1879
|
+
blocks.push({ type: "text", text: `<tool_result name="${part.toolName}">${this.truncate(this.outputToText(part.output))}</tool_result>` });
|
|
1880
|
+
else if (part.type === "file")
|
|
1881
|
+
blocks.push(this.fileToBlock(part) ?? { type: "text", text: `[Attachment ${part.mediaType ?? "file"} not supported by the agent]` });
|
|
1882
|
+
}
|
|
1883
|
+
return blocks;
|
|
1884
|
+
}
|
|
1048
1885
|
/** A foreign tool-result is replayed only so the agent can follow the thread —
|
|
1049
1886
|
* the full payload isn't worth the tokens. */
|
|
1050
1887
|
truncate(s) {
|
|
1051
|
-
|
|
1888
|
+
const cap = this.config.claudeCode?.catchupResultChars ?? CATCHUP_RESULT_CHARS;
|
|
1889
|
+
return s.length <= cap ? s : `${s.slice(0, cap)}…[truncated, ${s.length} chars]`;
|
|
1052
1890
|
}
|
|
1053
1891
|
/** Map an AI SDK file part to an ACP ContentBlock, honoring the agent's promptCapabilities. */
|
|
1054
1892
|
fileToBlock(part) {
|
|
@@ -1080,22 +1918,11 @@ export class ACPOrchestratorModel {
|
|
|
1080
1918
|
buildSystemPromptMeta(prompt, mode) {
|
|
1081
1919
|
if (mode === "preset")
|
|
1082
1920
|
return undefined;
|
|
1083
|
-
const text =
|
|
1921
|
+
const text = systemText(prompt);
|
|
1084
1922
|
if (!text)
|
|
1085
1923
|
return undefined;
|
|
1086
1924
|
return mode === "replace" ? text : { append: text };
|
|
1087
1925
|
}
|
|
1088
|
-
systemText(prompt) {
|
|
1089
|
-
const parts = [];
|
|
1090
|
-
for (const m of prompt) {
|
|
1091
|
-
if (m.role !== "system")
|
|
1092
|
-
continue;
|
|
1093
|
-
parts.push(typeof m.content === "string"
|
|
1094
|
-
? m.content
|
|
1095
|
-
: m.content.filter((p) => p.type === "text").map((p) => p.text).join(""));
|
|
1096
|
-
}
|
|
1097
|
-
return parts.join("\n").trim();
|
|
1098
|
-
}
|
|
1099
1926
|
/** The FACTUAL part of OpenCode's system prompt: where we are, what the workspace is,
|
|
1100
1927
|
* what references exist. Under `preset` the system prompt itself never reaches the
|
|
1101
1928
|
* agent (forwarding it would get the session billed as extra usage), but this
|
|
@@ -1104,7 +1931,7 @@ export class ACPOrchestratorModel {
|
|
|
1104
1931
|
* AGENTS.md (the agent loads it itself via projectMemory), MCP/skill catalogues —
|
|
1105
1932
|
* is deliberately left out. */
|
|
1106
1933
|
extractContextBlock(prompt) {
|
|
1107
|
-
const sys =
|
|
1934
|
+
const sys = systemText(prompt);
|
|
1108
1935
|
if (!sys)
|
|
1109
1936
|
return "";
|
|
1110
1937
|
const out = [];
|
|
@@ -1129,9 +1956,14 @@ export class ACPOrchestratorModel {
|
|
|
1129
1956
|
// The time is included only here: OpenCode's <env> is day-granular, and a
|
|
1130
1957
|
// per-turn clock update would be pure noise.
|
|
1131
1958
|
const now = new Date();
|
|
1959
|
+
// V2's Code Mode catalog lives in the system prompt (which `preset` never sends):
|
|
1960
|
+
// without it the agent sees an `execute` tool but not what it can call through it.
|
|
1961
|
+
// Sent once; V2 announces later changes itself as a `<system-update>` message.
|
|
1962
|
+
const catalog = codeModeSection(systemText(prompt));
|
|
1132
1963
|
return [{
|
|
1133
1964
|
type: "text",
|
|
1134
|
-
text: `<opencode_context>\n${block}\n Session started: ${now.toLocaleString()} (${Intl.DateTimeFormat().resolvedOptions().timeZone})\n</opencode_context
|
|
1965
|
+
text: `<opencode_context>\n${block}\n Session started: ${now.toLocaleString()} (${Intl.DateTimeFormat().resolvedOptions().timeZone})\n</opencode_context>`
|
|
1966
|
+
+ (catalog ? `\n<code_mode_catalog>\n${catalog}\n</code_mode_catalog>` : ""),
|
|
1135
1967
|
}];
|
|
1136
1968
|
}
|
|
1137
1969
|
const prev = new Set(t.lastContextBlock.split("\n").map((l) => l.trim()).filter(Boolean));
|
|
@@ -1142,6 +1974,32 @@ export class ACPOrchestratorModel {
|
|
|
1142
1974
|
dbg(`context delta (${changed.length} line(s))`);
|
|
1143
1975
|
return [{ type: "text", text: `<opencode_context_update>\n${changed.join("\n")}\n</opencode_context_update>` }];
|
|
1144
1976
|
}
|
|
1977
|
+
/** What OpenCode appended after the results of a continuation, as prompt blocks:
|
|
1978
|
+
* user text verbatim (a steered message, a subagent result, a `<system-update>`), and
|
|
1979
|
+
* any assistant prefill (V2's max-steps notice) as an explicit notice. */
|
|
1980
|
+
midTurnBlocks(t, extras) {
|
|
1981
|
+
const blocks = [];
|
|
1982
|
+
for (const m of extras) {
|
|
1983
|
+
if (m.role === "user")
|
|
1984
|
+
blocks.push(...this.messageToBlocks(m, false, t));
|
|
1985
|
+
else if (m.role === "assistant") {
|
|
1986
|
+
const text = (Array.isArray(m.content) ? m.content : [{ type: "text", text: String(m.content ?? "") }])
|
|
1987
|
+
.filter((p) => p?.type === "text" && String(p.text ?? "").trim())
|
|
1988
|
+
.map((p) => p.text)
|
|
1989
|
+
.join("\n");
|
|
1990
|
+
if (text)
|
|
1991
|
+
blocks.push({ type: "text", text: `<opencode_notice>\n${text}\n</opencode_notice>` });
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
return blocks;
|
|
1995
|
+
}
|
|
1996
|
+
/** Fallback when the agent can't queue a prompt: the extras ride on a tool result. */
|
|
1997
|
+
appendToResult(result, blocks) {
|
|
1998
|
+
const text = blocks.filter((b) => b.type === "text").map((b) => b.text).join("\n");
|
|
1999
|
+
const note = { type: "text", text: `<user_message_during_turn>\n${text}\n</user_message_during_turn>` };
|
|
2000
|
+
const content = Array.isArray(result?.content) ? result.content : [];
|
|
2001
|
+
return { ...(result ?? {}), content: [...content, note] };
|
|
2002
|
+
}
|
|
1145
2003
|
/** Only the last user message (delta for a persistent session). */
|
|
1146
2004
|
lastUserBlocks(prompt) {
|
|
1147
2005
|
for (let i = prompt.length - 1; i >= 0; i--) {
|
|
@@ -1160,29 +2018,42 @@ export class ACPOrchestratorModel {
|
|
|
1160
2018
|
let candidates;
|
|
1161
2019
|
if (options) {
|
|
1162
2020
|
const po = this.providerOptions(options);
|
|
1163
|
-
const baseKey = typeof po.ocSession === "string" ? po.ocSession : hashText(
|
|
2021
|
+
const baseKey = typeof po.ocSession === "string" ? po.ocSession : hashText(firstUserText(prompt));
|
|
1164
2022
|
candidates = [this.sessions.get(baseKey), this.sessions.get(`${baseKey}:notools`)];
|
|
1165
2023
|
}
|
|
1166
2024
|
else {
|
|
1167
2025
|
candidates = [...this.sessions.values()];
|
|
1168
2026
|
}
|
|
2027
|
+
const hist = historyOf(prompt);
|
|
1169
2028
|
for (const t of candidates) {
|
|
1170
2029
|
if (!t)
|
|
1171
2030
|
continue;
|
|
1172
2031
|
if (t.pendingTools.size === 0 && t.pendingPermissions.size === 0)
|
|
1173
2032
|
continue;
|
|
1174
|
-
|
|
1175
|
-
|
|
2033
|
+
// Last occurrence wins: ids are unique per session now, but a history can still
|
|
2034
|
+
// hold an older answer with the same id (pre-0.10 bare `perm_N`).
|
|
2035
|
+
const found = new Map();
|
|
2036
|
+
let lastResultAt = -1;
|
|
2037
|
+
hist.forEach((msg, idx) => {
|
|
1176
2038
|
if (msg.role !== "tool" && msg.role !== "assistant")
|
|
1177
|
-
|
|
2039
|
+
return;
|
|
1178
2040
|
for (const part of msg.content) {
|
|
1179
2041
|
if (part?.type === "tool-result" && (t.pendingTools.has(part.toolCallId) || t.pendingPermissions.has(part.toolCallId))) {
|
|
1180
|
-
|
|
2042
|
+
found.set(part.toolCallId, { toolCallId: part.toolCallId, result: this.toMcpResult(part.output), output: part.output });
|
|
2043
|
+
lastResultAt = idx;
|
|
1181
2044
|
}
|
|
1182
2045
|
}
|
|
1183
|
-
}
|
|
1184
|
-
if (
|
|
1185
|
-
|
|
2046
|
+
});
|
|
2047
|
+
if (!found.size)
|
|
2048
|
+
continue;
|
|
2049
|
+
const results = [...found.values()];
|
|
2050
|
+
return {
|
|
2051
|
+
t,
|
|
2052
|
+
results,
|
|
2053
|
+
lastResultAt,
|
|
2054
|
+
extras: hist.slice(lastResultAt + 1),
|
|
2055
|
+
aborted: results.some((r) => isInterrupted(r.output)),
|
|
2056
|
+
};
|
|
1186
2057
|
}
|
|
1187
2058
|
return null;
|
|
1188
2059
|
}
|
|
@@ -1268,4 +2139,26 @@ export class ACPOrchestratorModel {
|
|
|
1268
2139
|
return { content: [{ type: "text", text: this.outputToText(output) }], ...(isErr ? { isError: true } : {}) };
|
|
1269
2140
|
}
|
|
1270
2141
|
}
|
|
2142
|
+
/** One OpenCode model served by a shared orchestrator. Every model of the provider
|
|
2143
|
+
* talks to the SAME agent process and session map: switching opus ↔ sonnet mid-
|
|
2144
|
+
* conversation is a `session/set_model` on the live session, not a second process
|
|
2145
|
+
* resuming a session that is still open in the first one. */
|
|
2146
|
+
export class ACPModelView {
|
|
2147
|
+
core;
|
|
2148
|
+
modelId;
|
|
2149
|
+
specificationVersion = "v3";
|
|
2150
|
+
provider = "acp";
|
|
2151
|
+
supportedUrls = {};
|
|
2152
|
+
constructor(core, modelId) {
|
|
2153
|
+
this.core = core;
|
|
2154
|
+
this.modelId = modelId;
|
|
2155
|
+
}
|
|
2156
|
+
doStream(options) {
|
|
2157
|
+
return this.core.doStream(options, this.modelId);
|
|
2158
|
+
}
|
|
2159
|
+
async doGenerate(options) {
|
|
2160
|
+
const { stream } = await this.doStream(options);
|
|
2161
|
+
return collectGenerate(stream);
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
1271
2164
|
//# sourceMappingURL=model.js.map
|