opencode-claude-code-acpbridge 0.10.1 → 0.11.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 +61 -0
- package/README.md +80 -46
- package/dist/acp/claude-config.d.ts +3 -2
- package/dist/acp/claude-config.d.ts.map +1 -1
- package/dist/acp/claude-config.js +5 -1
- package/dist/acp/claude-config.js.map +1 -1
- package/dist/plugin/compat.d.ts +1 -1
- package/dist/plugin/compat.d.ts.map +1 -1
- package/dist/plugin/compat.js +1 -1
- package/dist/plugin/compat.js.map +1 -1
- package/dist/plugin/discover.d.ts.map +1 -1
- package/dist/plugin/discover.js +9 -6
- package/dist/plugin/discover.js.map +1 -1
- package/dist/plugin/index.d.ts +8 -0
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/index.js +115 -27
- package/dist/plugin/index.js.map +1 -1
- package/dist/plugin/pairing.d.ts +66 -0
- package/dist/plugin/pairing.d.ts.map +1 -0
- package/dist/plugin/pairing.js +110 -0
- package/dist/plugin/pairing.js.map +1 -0
- package/dist/provider/factory.d.ts.map +1 -1
- package/dist/provider/factory.js +10 -1
- package/dist/provider/factory.js.map +1 -1
- package/dist/provider/model.d.ts +28 -0
- package/dist/provider/model.d.ts.map +1 -1
- package/dist/provider/model.js +215 -20
- package/dist/provider/model.js.map +1 -1
- package/docs/DEVELOPMENT.md +36 -13
- package/examples/01-minimal.jsonc +7 -5
- package/examples/02-per-agent-permissions.jsonc +2 -2
- package/examples/04-model-and-effort.jsonc +5 -4
- package/examples/05-custom-agents.jsonc +1 -1
- package/examples/08-permission-bridge.jsonc +2 -2
- package/examples/README.md +3 -3
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/provider/model.ts"],"names":[],"mappings":"AAgCA,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,EACV,eAAe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ACrE,OAAO,CAAC,aAAa;IA2BrB;;+EAE2E;IAC3E,OAAO,CAAC,aAAa;IAerB,sFAAsF;IACtF,OAAO,CAAC,cAAc;IAOtB,mEAAmE;IACnE,OAAO,CAAC,cAAc;IAUtB;;kFAE8E;IAC9E,OAAO,CAAC,kBAAkB;IA0C1B;mFAC+E;IAC/E,OAAO,CAAC,aAAa;IAKrB;;;;;;;wFAOoF;IACpF,OAAO,CAAC,eAAe;IAQvB,iEAAiE;IACjE,OAAO,CAAC,eAAe;IAIvB;yEACqE;IACrE,OAAO,CAAC,WAAW;IAgBnB,OAAO,CAAC,YAAY;IAQpB;;0DAEsD;IACtD,OAAO,CAAC,WAAW;CAiBpB;AAED;;;8DAG8D;AAC9D,qBAAa,YAAa,YAAW,eAAe;IAKtC,OAAO,CAAC,QAAQ,CAAC,IAAI;IAAwB,QAAQ,CAAC,OAAO,EAAE,MAAM;IAJjF,QAAQ,CAAC,oBAAoB,EAAG,IAAI,CAAU;IAC9C,QAAQ,CAAC,QAAQ,SAAS;IAC1B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAM;gBAEzB,IAAI,EAAE,oBAAoB,EAAW,OAAO,EAAE,MAAM;IAEjF,QAAQ,CAAC,OAAO,EAAE,0BAA0B;gBAl7DvB,cAAc,CAAC,yBAAyB,CAAC;kBAAY,KAAK,EAAE;;IAs7D3E,UAAU,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,6BAA6B,CAAC;CAI9F"}
|
package/dist/provider/model.js
CHANGED
|
@@ -83,6 +83,9 @@ const COMPACT_WAIT_MS = 180_000;
|
|
|
83
83
|
const CHECKPOINT_NOTE = "<context_update>\n(The conversation continued in OpenCode with another model and was then compacted. " +
|
|
84
84
|
"OpenCode's checkpoint follows: it summarizes everything, including what happened after your last turn. " +
|
|
85
85
|
"Keep what you remember; use it to catch up on what you did not see.)\n</context_update>";
|
|
86
|
+
/** Session updates only a turn that actually runs produces (not the command/config
|
|
87
|
+
* notices an agent sends on its own). */
|
|
88
|
+
const TURN_UPDATES = new Set(["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "usage_update", "plan"]);
|
|
86
89
|
/** How long a turn being replaced may take to wind down after a cancel. */
|
|
87
90
|
const SETTLE_MS = 5000;
|
|
88
91
|
/** The `# Code Mode` section of OpenCode's system prompt (up to the next top-level
|
|
@@ -191,7 +194,7 @@ export function limitError(err) {
|
|
|
191
194
|
// QuotaExceeded and fails at once, so the user can switch models right away.
|
|
192
195
|
// (APICallError.isInstance matches by a global symbol, so the host's AI SDK copy accepts it.)
|
|
193
196
|
return new APICallError({
|
|
194
|
-
message: `Claude Code: usage limit reached${when ? ` (resets: ${when})` : ""}. Switch to another
|
|
197
|
+
message: `Claude Code: usage limit reached${when ? ` (resets: ${when})` : ""}. Switch to another agent in OpenCode (not claude-*) to continue with its model; the Claude Code session is kept for when you come back.`,
|
|
195
198
|
url: "acp://claude-code",
|
|
196
199
|
requestBodyValues: {},
|
|
197
200
|
statusCode: 402,
|
|
@@ -200,6 +203,25 @@ export function limitError(err) {
|
|
|
200
203
|
cause: err,
|
|
201
204
|
});
|
|
202
205
|
}
|
|
206
|
+
/** A request from an agent other than the Claude Code ones: the plugin pairs this
|
|
207
|
+
* provider's models with its `claude-*` agents (see plugin/pairing.ts) and flags the
|
|
208
|
+
* call with `pairedAgent: false`. A 400 with `x-should-retry: false`, so OpenCode
|
|
209
|
+
* fails the turn at once with the message instead of retrying it. */
|
|
210
|
+
export function pairingError(agent, modelId) {
|
|
211
|
+
return new APICallError({
|
|
212
|
+
message: `Claude Code: the model ${modelId} is reserved for the Claude Code agents (claude-*), and agent "${String(agent ?? "?")}" cannot use it. Switch to a claude-* agent, or pick another model for this agent.`,
|
|
213
|
+
url: "acp://claude-code",
|
|
214
|
+
requestBodyValues: {},
|
|
215
|
+
statusCode: 400,
|
|
216
|
+
responseHeaders: { "x-should-retry": "false" },
|
|
217
|
+
isRetryable: false,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
/** Current value of the session's `effort` config option, as new/resume report it. */
|
|
221
|
+
function effortOption(res) {
|
|
222
|
+
const opt = (res?.configOptions ?? []).find((o) => o?.id === "effort");
|
|
223
|
+
return typeof opt?.currentValue === "string" ? opt.currentValue : undefined;
|
|
224
|
+
}
|
|
203
225
|
/** Total text size of a prompt (diagnostics). */
|
|
204
226
|
function blocksChars(blocks) {
|
|
205
227
|
let n = 0;
|
|
@@ -231,6 +253,8 @@ export class ACPOrchestratorModel {
|
|
|
231
253
|
promptCaps = {};
|
|
232
254
|
/** The agent merges a prompt sent mid-turn into the running turn (claude-agent-acp). */
|
|
233
255
|
promptQueueing = false;
|
|
256
|
+
/** The agent has no session/set_model: models go through the `model` config option. */
|
|
257
|
+
modelByConfig = false;
|
|
234
258
|
constructor(config) {
|
|
235
259
|
this.config = config;
|
|
236
260
|
this.modelId = config.modelId ?? "claude-code";
|
|
@@ -242,8 +266,10 @@ export class ACPOrchestratorModel {
|
|
|
242
266
|
modelId) {
|
|
243
267
|
if (modelId)
|
|
244
268
|
this.callModel.set(options, modelId);
|
|
269
|
+
const po = this.providerOptions(options);
|
|
270
|
+
if (po.pairedAgent === false)
|
|
271
|
+
throw pairingError(po.ocAgent, this.callModel.get(options) ?? this.modelId);
|
|
245
272
|
if (recording()) {
|
|
246
|
-
const po = this.providerOptions(options);
|
|
247
273
|
record(this.convId(options), {
|
|
248
274
|
kind: "call",
|
|
249
275
|
modelId: this.callModel.get(options) ?? this.modelId,
|
|
@@ -327,8 +353,12 @@ export class ACPOrchestratorModel {
|
|
|
327
353
|
});
|
|
328
354
|
if (extraBlocks.length && !piggyback)
|
|
329
355
|
this.sendPrompt(t, extraBlocks);
|
|
356
|
+
// The prompt already failed (usage limit hit while OpenCode ran the step): nothing
|
|
357
|
+
// will continue this turn — fail it now instead of leaving OpenCode waiting.
|
|
358
|
+
if (t.doneErr)
|
|
359
|
+
this.failFromDone(t);
|
|
330
360
|
// Calls that arrived while OpenCode ran the previous step go out now as the next one.
|
|
331
|
-
if (t.queuedItems.length) {
|
|
361
|
+
else if (t.queuedItems.length) {
|
|
332
362
|
t.stepItems.push(...t.queuedItems);
|
|
333
363
|
t.queuedItems = [];
|
|
334
364
|
this.closeStep(t);
|
|
@@ -431,6 +461,8 @@ export class ACPOrchestratorModel {
|
|
|
431
461
|
// (2) Reuse the live session whenever we can — this is what keeps the cache warm.
|
|
432
462
|
if (t) {
|
|
433
463
|
let drop = null;
|
|
464
|
+
if (t.compacting)
|
|
465
|
+
await Promise.race([t.compacting, new Promise((r) => setTimeout(r, COMPACT_WAIT_MS))]);
|
|
434
466
|
if (t.systemKey !== systemKey)
|
|
435
467
|
drop = "system prompt changed";
|
|
436
468
|
else if (t.cfgKey !== cfgKey) {
|
|
@@ -442,6 +474,11 @@ export class ACPOrchestratorModel {
|
|
|
442
474
|
drop = "creation config changed";
|
|
443
475
|
}
|
|
444
476
|
}
|
|
477
|
+
// The previous prompt failed agent-side: talk to a new agent process, not to the one
|
|
478
|
+
// still holding that turn's leftovers (see `resync`).
|
|
479
|
+
if (!drop && t.resync && !(await this.reopenInPlace(t, ctrl, tools, systemMode, options.prompt, cfgKey, "recovering after an agent error"))) {
|
|
480
|
+
drop = "agent session out of sync";
|
|
481
|
+
}
|
|
445
482
|
if (!drop) {
|
|
446
483
|
// A changed tool set is applied to the LIVE session (MCP list_changed)
|
|
447
484
|
// rather than forcing a new one.
|
|
@@ -451,8 +488,6 @@ export class ACPOrchestratorModel {
|
|
|
451
488
|
t.toolsKey = toolsKey;
|
|
452
489
|
dbg(`tools changed (${tools.length}) — refreshed in place, session kept`);
|
|
453
490
|
}
|
|
454
|
-
if (t.compacting)
|
|
455
|
-
await Promise.race([t.compacting, new Promise((r) => setTimeout(r, COMPACT_WAIT_MS))]);
|
|
456
491
|
let cls = this.classify(t, hist, keys, ctrl, options);
|
|
457
492
|
// v2: OpenCode's checkpoint replaced the history. Keep the session: either it
|
|
458
493
|
// compacted itself in step (adopt — only what follows the checkpoint is new), or
|
|
@@ -495,6 +530,8 @@ export class ACPOrchestratorModel {
|
|
|
495
530
|
}
|
|
496
531
|
live.pending = [];
|
|
497
532
|
live.doneResp = null;
|
|
533
|
+
live.doneErr = null;
|
|
534
|
+
live.reopen = this.reopener(live, ctrl, tools, systemMode, options.prompt, cfgKey);
|
|
498
535
|
live.controller = controller;
|
|
499
536
|
live.lastActive = Date.now();
|
|
500
537
|
live.isChild = isChildCall(options);
|
|
@@ -556,6 +593,7 @@ export class ACPOrchestratorModel {
|
|
|
556
593
|
const resumePrefixes = Array.isArray(po.resumeIdPrefixes) ? po.resumeIdPrefixes.map(String) : [];
|
|
557
594
|
let sessionId;
|
|
558
595
|
let replayFull = true;
|
|
596
|
+
let defaultEffort;
|
|
559
597
|
// A registry entry for a DIFFERENT conversation (first message changed: compaction,
|
|
560
598
|
// or a reused id) must not be resumed — the agent would carry the wrong context.
|
|
561
599
|
const sameConv = !po.resumeConvKey || po.resumeConvKey === convKey;
|
|
@@ -563,7 +601,7 @@ export class ACPOrchestratorModel {
|
|
|
563
601
|
dbg(`resumeConvKey mismatch (registry=${po.resumeConvKey} current=${convKey}) — not resuming`);
|
|
564
602
|
if (resumeId && sameConv && resumeLen > 0 && hist.length > resumeLen) {
|
|
565
603
|
try {
|
|
566
|
-
await this.connection.unstable_resumeSession({
|
|
604
|
+
const resumed = await this.connection.unstable_resumeSession({
|
|
567
605
|
sessionId: resumeId,
|
|
568
606
|
cwd: this.config.cwd ?? process.cwd(),
|
|
569
607
|
mcpServers: [serverConfig],
|
|
@@ -575,6 +613,7 @@ export class ACPOrchestratorModel {
|
|
|
575
613
|
});
|
|
576
614
|
sessionId = resumeId;
|
|
577
615
|
replayFull = false;
|
|
616
|
+
defaultEffort = effortOption(resumed);
|
|
578
617
|
dbg(`resume ${resumeId} (oc=${ocSession ?? "?"}) — no history replay`);
|
|
579
618
|
}
|
|
580
619
|
catch (e) {
|
|
@@ -593,6 +632,7 @@ export class ACPOrchestratorModel {
|
|
|
593
632
|
_meta: meta,
|
|
594
633
|
});
|
|
595
634
|
sessionId = session.sessionId;
|
|
635
|
+
defaultEffort = effortOption(session);
|
|
596
636
|
dbg(`model=${session.models?.currentModelId ?? "?"} (requested: ${ctrl.model ?? "default"}, mode: ${ctrl.mode ?? "default"}, effort: ${ctrl.effort ?? "default"}) — tools(${tools.length})`);
|
|
597
637
|
}
|
|
598
638
|
if (!sessionId)
|
|
@@ -613,6 +653,7 @@ export class ACPOrchestratorModel {
|
|
|
613
653
|
ocAgent: po.ocAgent ? String(po.ocAgent) : undefined,
|
|
614
654
|
hasQuestion: typeof po.hasQuestion === "boolean" ? po.hasQuestion : undefined,
|
|
615
655
|
isChild: isChildCall(options),
|
|
656
|
+
defaultEffort,
|
|
616
657
|
// Resume path: carry the persisted snapshot over so the registry keeps a
|
|
617
658
|
// value even if the resumed session never completes another turn.
|
|
618
659
|
lastUsage: replayFull ? undefined : po.resumeLastUsage,
|
|
@@ -634,6 +675,10 @@ export class ACPOrchestratorModel {
|
|
|
634
675
|
gen: 0,
|
|
635
676
|
inflight: null,
|
|
636
677
|
doneResp: null,
|
|
678
|
+
doneErr: null,
|
|
679
|
+
resync: false,
|
|
680
|
+
genEvents: 0,
|
|
681
|
+
reopen: null,
|
|
637
682
|
aborted: false,
|
|
638
683
|
stepItems: [],
|
|
639
684
|
stepTimer: null,
|
|
@@ -647,6 +692,7 @@ export class ACPOrchestratorModel {
|
|
|
647
692
|
lastActive: Date.now(),
|
|
648
693
|
};
|
|
649
694
|
ref.t = t;
|
|
695
|
+
t.reopen = this.reopener(t, ctrl, tools, systemMode, options.prompt, cfgKey);
|
|
650
696
|
host.onToolCall((c) => this.onToolCall(t, c));
|
|
651
697
|
host.onToolCancelled((id) => this.onToolCancelled(t, id));
|
|
652
698
|
this.sessions.set(key, t);
|
|
@@ -707,6 +753,7 @@ export class ACPOrchestratorModel {
|
|
|
707
753
|
t.appliedMode = undefined; // re-applied on the fork by applySessionConfig
|
|
708
754
|
t.appliedEffort = undefined;
|
|
709
755
|
t.appliedModel = undefined;
|
|
756
|
+
t.resync = false; // a fork is a new agent process: nothing of the old one is queued
|
|
710
757
|
host.onToolCall((c) => this.onToolCall(t, c));
|
|
711
758
|
host.onToolCancelled((id) => this.onToolCancelled(t, id));
|
|
712
759
|
this.byAcpSession.set(t.sessionId, t);
|
|
@@ -721,6 +768,69 @@ export class ACPOrchestratorModel {
|
|
|
721
768
|
return false;
|
|
722
769
|
}
|
|
723
770
|
}
|
|
771
|
+
/** `reopenInPlace` bound to the latest turn's profile, with its mode/model/effort
|
|
772
|
+
* re-applied — for a recovery that happens outside `startFresh`. */
|
|
773
|
+
reopener(t, ctrl, tools, systemMode, prompt, cfgKey) {
|
|
774
|
+
return async (why) => {
|
|
775
|
+
if (!(await this.reopenInPlace(t, ctrl, tools, systemMode, prompt, cfgKey, why)))
|
|
776
|
+
return false;
|
|
777
|
+
await this.applySessionConfig(t, ctrl);
|
|
778
|
+
return true;
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
/** Re-open `t`'s agent session in a NEW agent process under the same id: close it and
|
|
782
|
+
* resume it from its transcript. Whatever the old process still had queued is gone, and
|
|
783
|
+
* unlike a fork no transcript copy is written (a retry loop would write one per try).
|
|
784
|
+
* Falls back to a fork when the resume fails. */
|
|
785
|
+
async reopenInPlace(t, ctrl, tools, systemMode, prompt, cfgKey, why) {
|
|
786
|
+
if (t.inflight || t.pendingTools.size || t.pendingPermissions.size) {
|
|
787
|
+
this.abortTurn(t, why);
|
|
788
|
+
await this.settle(t);
|
|
789
|
+
}
|
|
790
|
+
const idPrefix = `acp_${randomBytes(5).toString("hex")}_`;
|
|
791
|
+
const host = new McpHost("opencode", idPrefix);
|
|
792
|
+
try {
|
|
793
|
+
await host.start();
|
|
794
|
+
host.setTools(tools);
|
|
795
|
+
// Awaited: resuming an id the agent still holds would hand back the same process.
|
|
796
|
+
let timer;
|
|
797
|
+
await Promise.race([
|
|
798
|
+
Promise.resolve(this.connection.extMethod?.("session/close", { sessionId: t.sessionId })).catch(() => { }),
|
|
799
|
+
new Promise((r) => { timer = setTimeout(r, SETTLE_MS); }),
|
|
800
|
+
]);
|
|
801
|
+
clearTimeout(timer);
|
|
802
|
+
const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
|
|
803
|
+
const sysMeta = this.buildSystemPromptMeta(prompt, systemMode);
|
|
804
|
+
if (sysMeta !== undefined)
|
|
805
|
+
meta.systemPrompt = sysMeta;
|
|
806
|
+
const res = await this.connection.unstable_resumeSession({
|
|
807
|
+
sessionId: t.sessionId,
|
|
808
|
+
cwd: this.config.cwd ?? process.cwd(),
|
|
809
|
+
mcpServers: [host.getServerConfig()],
|
|
810
|
+
_meta: meta,
|
|
811
|
+
});
|
|
812
|
+
const oldHost = t.host;
|
|
813
|
+
t.host = host;
|
|
814
|
+
t.idPrefix = idPrefix;
|
|
815
|
+
t.ownPrefixes = [idPrefix, ...t.ownPrefixes].slice(0, 8);
|
|
816
|
+
t.cfgKey = cfgKey;
|
|
817
|
+
t.appliedMode = undefined; // re-applied on the new process by applySessionConfig
|
|
818
|
+
t.appliedEffort = undefined;
|
|
819
|
+
t.appliedModel = undefined;
|
|
820
|
+
t.defaultEffort = effortOption(res) ?? t.defaultEffort;
|
|
821
|
+
t.resync = false;
|
|
822
|
+
host.onToolCall((c) => this.onToolCall(t, c));
|
|
823
|
+
host.onToolCancelled((id) => this.onToolCancelled(t, id));
|
|
824
|
+
oldHost.stop();
|
|
825
|
+
note(`session ${t.sessionId} re-opened in a new agent process (${why}, context kept)`);
|
|
826
|
+
return true;
|
|
827
|
+
}
|
|
828
|
+
catch (e) {
|
|
829
|
+
host.stop();
|
|
830
|
+
dbg(`re-open of ${t.sessionId} failed (${e instanceof Error ? e.message : String(e)}) — forking instead`);
|
|
831
|
+
return this.forkInPlace(t, ctrl, tools, systemMode, prompt, cfgKey, undefined, why);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
724
834
|
/** Remember where this turn starts (index of its first user message) and Claude's
|
|
725
835
|
* last transcript entry before it. */
|
|
726
836
|
recordCheckpoint(t, hist, from) {
|
|
@@ -797,7 +907,10 @@ export class ACPOrchestratorModel {
|
|
|
797
907
|
const done = this.connection
|
|
798
908
|
.prompt({ sessionId: t.sessionId, prompt: [{ type: "text", text: "/compact" }] })
|
|
799
909
|
.then(() => { if (gen === t.gen)
|
|
800
|
-
t.adoptCheckpoint = true; }, (e) =>
|
|
910
|
+
t.adoptCheckpoint = true; }, (e) => {
|
|
911
|
+
note(`native /compact of ${t.sessionId} failed (${errorText(e)}) — the session is re-opened on the next turn`);
|
|
912
|
+
t.resync = true;
|
|
913
|
+
})
|
|
801
914
|
.finally(() => {
|
|
802
915
|
t.hidden = false;
|
|
803
916
|
if (t.compacting === done)
|
|
@@ -912,17 +1025,25 @@ export class ACPOrchestratorModel {
|
|
|
912
1025
|
/** Send a prompt as the session's newest generation. Completions of older ones — a
|
|
913
1026
|
* cancelled turn, or the original prompt the agent resolves early when it merges a
|
|
914
1027
|
* queued one — are ignored instead of closing the stream of the current turn. */
|
|
915
|
-
sendPrompt(t, blocks) {
|
|
1028
|
+
sendPrompt(t, blocks, retry = true) {
|
|
1029
|
+
// An empty prompt (nothing new to say) may legitimately run nothing.
|
|
1030
|
+
if (!blocks.some((b) => b?.type !== "text" || b.text))
|
|
1031
|
+
retry = false;
|
|
916
1032
|
const gen = ++t.gen;
|
|
917
1033
|
t.aborted = false;
|
|
918
1034
|
t.doneResp = null;
|
|
1035
|
+
t.doneErr = null;
|
|
1036
|
+
t.genEvents = 0;
|
|
919
1037
|
const settled = this.connection
|
|
920
1038
|
.prompt({ sessionId: t.sessionId, prompt: blocks })
|
|
921
1039
|
.then((resp) => {
|
|
922
|
-
if (gen
|
|
923
|
-
this.onPromptDone(t, resp);
|
|
924
|
-
else
|
|
1040
|
+
if (gen !== t.gen) {
|
|
925
1041
|
dbg(`stale prompt completion ignored (gen ${gen} < ${t.gen}, ${resp?.stopReason})`);
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
if (retry && this.isStale(t, resp))
|
|
1045
|
+
return this.recoverStale(t, blocks);
|
|
1046
|
+
this.onPromptDone(t, resp);
|
|
926
1047
|
}, (err) => {
|
|
927
1048
|
if (gen === t.gen)
|
|
928
1049
|
this.onPromptError(t, err);
|
|
@@ -933,6 +1054,40 @@ export class ACPOrchestratorModel {
|
|
|
933
1054
|
t.inflight = null; });
|
|
934
1055
|
t.inflight = settled;
|
|
935
1056
|
}
|
|
1057
|
+
/** The agent ended the prompt on a turn-over left queued by an EARLIER turn (see
|
|
1058
|
+
* `resync`): `end_turn` with nothing streamed and a usage of exactly zero — a turn that
|
|
1059
|
+
* ran always bills a request. An agent that reports no usage is never flagged. */
|
|
1060
|
+
isStale(t, resp) {
|
|
1061
|
+
const u = resp?.usage;
|
|
1062
|
+
if (resp?.stopReason !== "end_turn" || t.genEvents > 0 || !u || typeof u !== "object")
|
|
1063
|
+
return false;
|
|
1064
|
+
return !(u.inputTokens || u.outputTokens || u.cachedReadTokens || u.cachedWriteTokens);
|
|
1065
|
+
}
|
|
1066
|
+
/** The prompt "finished" without running and its real turn now runs unread. Stop it,
|
|
1067
|
+
* re-open the session and send the prompt again on the SAME stream, so OpenCode only
|
|
1068
|
+
* sees a slower answer instead of an empty one. Once per prompt. */
|
|
1069
|
+
async recoverStale(t, blocks) {
|
|
1070
|
+
note(`session ${t.sessionId}: the agent ended a turn it never ran (leftover of an earlier turn) — re-opening the session`);
|
|
1071
|
+
// Stop the unread run (agent-side cancel, its calls released) but keep the stream.
|
|
1072
|
+
const controller = t.controller;
|
|
1073
|
+
this.abortTurn(t, "turn the agent never ran");
|
|
1074
|
+
t.aborted = false;
|
|
1075
|
+
// reopenInPlace checks for a busy turn synchronously, before its first await: hide
|
|
1076
|
+
// this one from that check only. Kept in flight otherwise, so a user turn arriving
|
|
1077
|
+
// meanwhile waits for the recovery (and cancels it) instead of racing it.
|
|
1078
|
+
const inflight = t.inflight;
|
|
1079
|
+
t.inflight = null;
|
|
1080
|
+
const reopening = t.reopen?.("recovering a turn the agent never ran");
|
|
1081
|
+
t.inflight = inflight;
|
|
1082
|
+
const ok = (await reopening) ?? false;
|
|
1083
|
+
if (this.sessions.get(t.key) !== t || t.aborted)
|
|
1084
|
+
return; // ended, or the user cancelled meanwhile
|
|
1085
|
+
t.controller = controller;
|
|
1086
|
+
if (ok)
|
|
1087
|
+
this.sendPrompt(t, blocks, false);
|
|
1088
|
+
else
|
|
1089
|
+
this.onPromptError(t, new Error("Claude Code: the agent session went out of sync and could not be re-opened. Send the message again."));
|
|
1090
|
+
}
|
|
936
1091
|
/** Wait (bounded) for the running prompt to settle — e.g. after a cancel. */
|
|
937
1092
|
async settle(t, ms = SETTLE_MS) {
|
|
938
1093
|
const p = t.inflight;
|
|
@@ -961,6 +1116,7 @@ export class ACPOrchestratorModel {
|
|
|
961
1116
|
t.textAcc.clear();
|
|
962
1117
|
t.pending = [];
|
|
963
1118
|
t.doneResp = null;
|
|
1119
|
+
t.doneErr = null;
|
|
964
1120
|
if (t.stepTimer) {
|
|
965
1121
|
clearTimeout(t.stepTimer);
|
|
966
1122
|
t.stepTimer = null;
|
|
@@ -1037,9 +1193,17 @@ export class ACPOrchestratorModel {
|
|
|
1037
1193
|
note(`session ${t.sessionId} lost agent-side — the next turn resumes it`);
|
|
1038
1194
|
queueMicrotask(() => this.endTurn(t));
|
|
1039
1195
|
}
|
|
1040
|
-
|
|
1041
|
-
|
|
1196
|
+
else {
|
|
1197
|
+
t.resync = true;
|
|
1198
|
+
}
|
|
1042
1199
|
dbg(`prompt error: ${errorText(err)}`);
|
|
1200
|
+
// Failed while OpenCode runs a step (the stream is closed between a tool-call and its
|
|
1201
|
+
// continuation): kept for the continuation, which would otherwise wait forever.
|
|
1202
|
+
if (!t.controller) {
|
|
1203
|
+
if (!t.aborted)
|
|
1204
|
+
t.doneErr = err;
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1043
1207
|
try {
|
|
1044
1208
|
t.controller.enqueue({ type: "error", error: limitError(err) ?? err });
|
|
1045
1209
|
t.controller.close();
|
|
@@ -1047,6 +1211,13 @@ export class ACPOrchestratorModel {
|
|
|
1047
1211
|
catch { /* ignore */ }
|
|
1048
1212
|
t.controller = null;
|
|
1049
1213
|
}
|
|
1214
|
+
/** The prompt failed while no stream was attached: fail the current one with it. */
|
|
1215
|
+
failFromDone(t) {
|
|
1216
|
+
const err = t.doneErr;
|
|
1217
|
+
t.doneErr = null;
|
|
1218
|
+
this.flushPending(t);
|
|
1219
|
+
this.onPromptError(t, err);
|
|
1220
|
+
}
|
|
1050
1221
|
/** Fired by the MCP host when the agent calls an OpenCode tool. The call is NOT
|
|
1051
1222
|
* resolved here: it waits for OpenCode to run the tool and send the continuation. */
|
|
1052
1223
|
onToolCall(t, call) {
|
|
@@ -1327,6 +1498,8 @@ export class ACPOrchestratorModel {
|
|
|
1327
1498
|
if (!t)
|
|
1328
1499
|
return;
|
|
1329
1500
|
const update = params?.update;
|
|
1501
|
+
if (TURN_UPDATES.has(update?.sessionUpdate))
|
|
1502
|
+
t.genEvents++;
|
|
1330
1503
|
// Mode switch (e.g. ExitPlanMode approved: plan → default). Track it even without a
|
|
1331
1504
|
// live controller so the bridge stays in sync and won't re-force the agent's
|
|
1332
1505
|
// configured mode on the next turn (which would undo the plan-exit).
|
|
@@ -1530,16 +1703,32 @@ export class ACPOrchestratorModel {
|
|
|
1530
1703
|
ctrl.model = modelId;
|
|
1531
1704
|
return ctrl;
|
|
1532
1705
|
}
|
|
1706
|
+
/** session/set_model, or — claude-agent-acp ≥ 0.99 dropped it ("Method not found") —
|
|
1707
|
+
* the `model` config option, which takes the same ids. Learned once per connection. */
|
|
1708
|
+
async setModel(sessionId, modelId) {
|
|
1709
|
+
if (!this.modelByConfig) {
|
|
1710
|
+
try {
|
|
1711
|
+
await this.connection.unstable_setSessionModel({ sessionId, modelId });
|
|
1712
|
+
return;
|
|
1713
|
+
}
|
|
1714
|
+
catch (e) {
|
|
1715
|
+
if (e?.code !== -32601)
|
|
1716
|
+
throw e;
|
|
1717
|
+
this.modelByConfig = true;
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
await this.connection.setSessionConfigOption({ sessionId, configId: "model", value: modelId });
|
|
1721
|
+
}
|
|
1533
1722
|
/** Apply runtime config (mode/effort) to a live ACP session via set_mode/set_config_option. */
|
|
1534
1723
|
async applySessionConfig(t, ctrl) {
|
|
1535
1724
|
if (ctrl.model && ctrl.model !== t.appliedModel) {
|
|
1536
1725
|
try {
|
|
1537
|
-
await this.
|
|
1726
|
+
await this.setModel(t.sessionId, ctrl.model);
|
|
1538
1727
|
t.appliedModel = ctrl.model;
|
|
1539
1728
|
dbg(`model → ${ctrl.model}`);
|
|
1540
1729
|
}
|
|
1541
1730
|
catch (e) {
|
|
1542
|
-
note(`warning: could not apply model ${ctrl.model} (${
|
|
1731
|
+
note(`warning: could not apply model ${ctrl.model} (${errorText(e)})`);
|
|
1543
1732
|
}
|
|
1544
1733
|
}
|
|
1545
1734
|
// A CHANGED request (the user reselected the plan agent) overrides a mode the agent
|
|
@@ -1566,16 +1755,19 @@ export class ACPOrchestratorModel {
|
|
|
1566
1755
|
dbg(`setSessionMode(${ctrl.mode}) failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
1567
1756
|
}
|
|
1568
1757
|
}
|
|
1569
|
-
|
|
1758
|
+
// Every effort variant shares this session, so the model WITHOUT a variant means the
|
|
1759
|
+
// session's own effort again, not whatever variant was picked last.
|
|
1760
|
+
const effort = ctrl.effort ?? (t.appliedEffort !== undefined ? t.defaultEffort : undefined);
|
|
1761
|
+
if (effort && effort !== t.appliedEffort) {
|
|
1570
1762
|
try {
|
|
1571
|
-
await this.connection.setSessionConfigOption({ sessionId: t.sessionId, configId: "effort", value:
|
|
1572
|
-
t.appliedEffort =
|
|
1573
|
-
dbg(`effort → ${
|
|
1763
|
+
await this.connection.setSessionConfigOption({ sessionId: t.sessionId, configId: "effort", value: effort });
|
|
1764
|
+
t.appliedEffort = effort;
|
|
1765
|
+
dbg(`effort → ${effort}`);
|
|
1574
1766
|
}
|
|
1575
1767
|
catch (e) {
|
|
1576
1768
|
// Not a debug detail: a rejected effort means the user picked `:max` and is
|
|
1577
1769
|
// silently getting something else — including no visible reasoning.
|
|
1578
|
-
note(`warning: could not apply effort=${
|
|
1770
|
+
note(`warning: could not apply effort=${effort} (${e instanceof Error ? e.message : String(e)})`);
|
|
1579
1771
|
}
|
|
1580
1772
|
}
|
|
1581
1773
|
}
|
|
@@ -1622,6 +1814,9 @@ export class ACPOrchestratorModel {
|
|
|
1622
1814
|
},
|
|
1623
1815
|
async writeTextFile() { return {}; },
|
|
1624
1816
|
async readTextFile() { return { content: "" }; },
|
|
1817
|
+
// Agent notices (claude-agent-acp ≥ 0.99 sends `_auth/status_update`): not ours,
|
|
1818
|
+
// but unhandled they print an SDK error over OpenCode's output.
|
|
1819
|
+
async extNotification() { },
|
|
1625
1820
|
}), stream);
|
|
1626
1821
|
const initResult = await this.connection.initialize({
|
|
1627
1822
|
protocolVersion: PROTOCOL_VERSION,
|