opencode-claude-code-acpbridge 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +69 -39
  3. package/dist/acp/claude-config.d.ts.map +1 -1
  4. package/dist/acp/claude-config.js +17 -5
  5. package/dist/acp/claude-config.js.map +1 -1
  6. package/dist/acp/mcp-runtime.js +93 -9
  7. package/dist/acp/mcp-runtime.js.map +1 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +3 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/plugin/bridge-rules.d.ts +22 -0
  12. package/dist/plugin/bridge-rules.d.ts.map +1 -0
  13. package/dist/plugin/bridge-rules.js +104 -0
  14. package/dist/plugin/bridge-rules.js.map +1 -0
  15. package/dist/plugin/catalog.d.ts +7 -0
  16. package/dist/plugin/catalog.d.ts.map +1 -1
  17. package/dist/plugin/catalog.js +38 -0
  18. package/dist/plugin/catalog.js.map +1 -1
  19. package/dist/plugin/index.d.ts +3 -13
  20. package/dist/plugin/index.d.ts.map +1 -1
  21. package/dist/plugin/index.js +242 -238
  22. package/dist/plugin/index.js.map +1 -1
  23. package/dist/plugin/sessions.d.ts.map +1 -1
  24. package/dist/plugin/sessions.js +12 -5
  25. package/dist/plugin/sessions.js.map +1 -1
  26. package/dist/provider/model.d.ts +36 -11
  27. package/dist/provider/model.d.ts.map +1 -1
  28. package/dist/provider/model.js +188 -49
  29. package/dist/provider/model.js.map +1 -1
  30. package/docs/DEVELOPMENT.md +42 -22
  31. package/examples/01-minimal.jsonc +9 -6
  32. package/examples/02-permisos-por-agente.jsonc +22 -17
  33. package/examples/03-fidelidad-opencode.jsonc +8 -7
  34. package/examples/04-modelo-y-esfuerzo.jsonc +29 -23
  35. package/examples/05-agentes-personalizados.jsonc +24 -14
  36. package/examples/06-ecosistema-claude.jsonc +12 -11
  37. package/examples/07-provider-manual.jsonc +12 -8
  38. package/examples/08-puente-permisos.jsonc +43 -25
  39. package/examples/README.md +10 -9
  40. package/package.json +4 -4
@@ -3,7 +3,7 @@
3
3
  // synced: when OpenCode resumes a session (new process), the provider can call
4
4
  // `resumeSession(acpSessionId)` instead of replaying the whole history → saves
5
5
  // tokens. The OpenCode id is only a KEY here; the agent id is what gets resumed.
6
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
6
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync } from "node:fs";
7
7
  import { homedir } from "node:os";
8
8
  import { join } from "node:path";
9
9
  const DIR = join(homedir(), ".acp-model-provider");
@@ -16,6 +16,14 @@ function readAll() {
16
16
  return {};
17
17
  }
18
18
  }
19
+ /** Escritura atómica (tmp + rename en el mismo filesystem): el fichero nunca
20
+ * queda truncado a medias aunque varios procesos OpenCode escriban a la vez. */
21
+ function atomicWriteJson(data) {
22
+ mkdirSync(DIR, { recursive: true });
23
+ const tmp = `${FILE}.${process.pid}.${Date.now()}.tmp`;
24
+ writeFileSync(tmp, JSON.stringify(data));
25
+ renameSync(tmp, FILE);
26
+ }
19
27
  /** Lookup the agent session linked to an OpenCode sessionID (undefined if none). */
20
28
  export function getLink(ocSession) {
21
29
  return readAll()[ocSession];
@@ -35,7 +43,7 @@ export function setLink(ocSession, acpSessionId, sentHistoryLen, convKey) {
35
43
  ...(prev?.lastUsage ? { lastUsage: prev.lastUsage } : {}),
36
44
  ...(convKey ? { convKey } : {}),
37
45
  };
38
- writeFileSync(FILE, JSON.stringify(all));
46
+ atomicWriteJson(all);
39
47
  }
40
48
  catch {
41
49
  /* best-effort: a missing registry just means resume won't kick in */
@@ -51,8 +59,7 @@ export function clearLink(ocSession) {
51
59
  if (!all[ocSession])
52
60
  return false;
53
61
  delete all[ocSession];
54
- mkdirSync(DIR, { recursive: true });
55
- writeFileSync(FILE, JSON.stringify(all));
62
+ atomicWriteJson(all);
56
63
  return true;
57
64
  }
58
65
  catch {
@@ -69,7 +76,7 @@ export function updateUsage(ocSession, lastUsage) {
69
76
  if (!entry)
70
77
  return;
71
78
  all[ocSession] = { ...entry, lastUsage, ts: Date.now() };
72
- writeFileSync(FILE, JSON.stringify(all));
79
+ atomicWriteJson(all);
73
80
  }
74
81
  catch {
75
82
  /* best-effort, same policy as setLink */
@@ -1 +1 @@
1
- {"version":3,"file":"sessions.js","sourceRoot":"","sources":["../../src/plugin/sessions.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,iFAAiF;AACjF,+EAA+E;AAC/E,+EAA+E;AAC/E,iFAAiF;AACjF,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,EAAE,EAAE,qBAAqB,CAAC,CAAC;AACnD,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;AA+BxC,SAAS,OAAO;IACd,IAAI,CAAC;QACH,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAE,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAiC,CAAC,CAAC,CAAC,EAAE,CAAC;IACzG,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,OAAO,CAAC,SAAiB;IACvC,OAAO,OAAO,EAAE,CAAC,SAAS,CAAC,CAAC;AAC9B,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,OAAO,CAAC,SAAiB,EAAE,YAAoB,EAAE,cAAsB,EAAE,OAAgB;IACvG,IAAI,CAAC;QACH,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC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AC,GAAG,CAAC,SAAS,CAAC;YAAE,OAAO,KAAK,CAAC;QAClC,OAAO,GAAG,CAAC,SAAS,CAAC,CAAC;QACtB,eAAe,CAAC,GAAG,CAAC,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;8EAC8E;AAC9E,MAAM,UAAU,WAAW,CAAC,SAAiB,EAAE,SAA2B;IACxE,IAAI,CAAC;QACH,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACpC,MAAM,GAAG,GAAG,OAAO,EAAE,CAAC;QACtB,MAAM,KAAK,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;QAC7B,IAAI,CAAC,KAAK;YAAE,OAAO;QACnB,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;QACzD,eAAe,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC;IAAC,MAAM,CAAC;QACP,yCAAyC;IAC3C,CAAC;AACH,CAAC"}
@@ -54,13 +54,19 @@ export declare class ACPOrchestratorModel implements LanguageModelV3 {
54
54
  /** Extract the markdown plan from an ExitPlanMode (`switch_mode`) tool call: it rides
55
55
  * in `rawInput.plan`, with the tool-call text content as a fallback. */
56
56
  private planText;
57
- /** ACP requestPermission → OpenCode `ask`, via the claude_permission meta-tool.
58
- * Deferred: returns a Promise the agent awaits until OpenCode's verdict comes
59
- * back as the meta-tool's result (resolved in onStart's continuation branch). */
57
+ /** ACP requestPermission → the agent's own rules first, then the `question` dialog.
58
+ * Deferred: returns a Promise the agent awaits until the verdict comes back as
59
+ * the `question` tool-result (resolved in onStart's continuation branch). */
60
60
  private onRequestPermission;
61
- /** Emit a claude_permission tool-call to OpenCode (same deferred pattern as a
62
- * real tool-call): OpenCode applies its `ask` permission and returns the
63
- * verdict as the tool-result on the next doStream. */
61
+ /** Action target of a native request (command / skill / path), plus the glob an
62
+ * "Always allow" would persist. Shell commands collapse to their first token
63
+ * (`git status` → `git *`); a request with no real target persists nothing, so
64
+ * the dialog never offers a broad rule that would auto-approve everything. */
65
+ private bridgeTarget;
66
+ /** Emit a `question` tool-call to OpenCode (same deferred pattern as a real
67
+ * tool-call): the native tool's request becomes a dialog — Allow once /
68
+ * Always allow / Deny — and the answer arrives as the tool-result on the next
69
+ * doStream. The agent itself only ever sees the ACP permission outcome. */
64
70
  private emitPermissionCall;
65
71
  /** Fired by the ACP client on session/update. */
66
72
  private onSessionUpdate;
@@ -71,6 +77,12 @@ export declare class ACPOrchestratorModel implements LanguageModelV3 {
71
77
  private evictIdleSessions;
72
78
  /** Resolve every outstanding bridged permission as denied so the agent unblocks. */
73
79
  private drainPermissions;
80
+ /** Per-call provider options: V2 nests them under `providerOptionKey(package,
81
+ * providerID)` = the providerID. El fallback al primer objeto del mapa sería
82
+ * voraz (podría tomar opciones de OTRO provider): solo se acepta si la key
83
+ * contiene nuestro provider id (`acp`) o el objeto trae forma conocida
84
+ * (ocSession/ocAgent/resumeId/…/mode/effort/native*); si no, como ausente. */
85
+ private providerOptions;
74
86
  /** Provider config overlaid with per-call `providerOptions.acp` (per-agent mode/effort/…). */
75
87
  private effectiveCtrl;
76
88
  /** Apply runtime config (mode/effort) to a live ACP session via set_mode/set_config_option. */
@@ -81,6 +93,8 @@ export declare class ACPOrchestratorModel implements LanguageModelV3 {
81
93
  /** If a cancel was ignored (deferred work in flight) but no continuation comes,
82
94
  * force teardown so the agent doesn't stay blocked. Cleared by a continuation. */
83
95
  private armCancelWatchdog;
96
+ /** Barre TODOS los watchdogs del turno (cada `onCancel` ignorado arma uno);
97
+ * llamado desde endTurn/cleanup y al continuar el turno. */
84
98
  private clearCancelWatchdog;
85
99
  cleanup(): void;
86
100
  private convertTools;
@@ -131,15 +145,26 @@ export declare class ACPOrchestratorModel implements LanguageModelV3 {
131
145
  /** Only the last user message (delta for a persistent session). */
132
146
  private lastUserBlocks;
133
147
  /** Find the live conversation whose deferred tool-calls/permissions this prompt
134
- * answers. Scoped per session, so two concurrent chats can't cross-resolve. */
148
+ * answers. Acotado a la conversación actual (`ocSession`/convKey de ESTA llamada):
149
+ * iterar todas las sesiones cruzaba continuaciones de chats concurrentes. */
135
150
  private detectContinuation;
136
151
  /** A tool-result is an error/denial when its output type is error-* (OpenCode
137
152
  * RejectedError) — used by the permission bridge to map approve vs reject. */
138
153
  private isErrorOutput;
139
- /** Approve a bridged permission ONLY on an explicit positive verdict (the
140
- * claude_permission meta-tool returns "approved: …"). Errors, denials, and any
141
- * ambiguous output fail CLOSED so an unclear verdict never runs the native tool. */
142
- private isApprovedOutput;
154
+ /** Approve a bridged permission ONLY on an explicit positive answer to the
155
+ * `question` dialog. Errors, dismissals, and any ambiguous output (including
156
+ * a typed-in answer) fail CLOSED so an unclear verdict never runs the tool.
157
+ * Verificado: OpenCode V2 no expone identificador estable (sin schema de la tool
158
+ * `question` en node_modules/@opencode-ai ni en /opt/OpenCode/resources; el shape
159
+ * documentado es etiqueta en `{ answers: [["…"]] }` o texto renderizado) → match
160
+ * por etiqueta normalizada (minúsculas, trim, "_" y espacios colapsados) con
161
+ * fallback deny ante cualquier cosa no reconocida. Flujo de 3 opciones intacto. */
162
+ private questionVerdict;
163
+ /** Normaliza una etiqueta de respuesta para el match robusto. */
164
+ private normalizeAnswer;
165
+ /** The chosen label: typed output (`{ answers: [["Always allow"]] }`) first,
166
+ * then the rendered text fallback (`"question"="Always allow"`). */
167
+ private answerLabel;
143
168
  private outputToText;
144
169
  /** OpenCode tool output → MCP CallToolResult. Structured content (images from a
145
170
  * `read`, mixed blocks) is mapped through rather than flattened to a string, so
@@ -1 +1 @@
1
- {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/provider/model.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EACV,eAAe,EACf,0BAA0B,EAC1B,yBAAyB,E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IAC9F,OAAO,CAAC,aAAa;IAkBrB,+FAA+F;YACjF,kBAAkB;IAgChC,OAAO,CAAC,eAAe;YAYT,OAAO;IAyDrB,OAAO,CAAC,QAAQ;IAqBhB;uFACmF;IACnF,OAAO,CAAC,iBAAiB;IAWzB;iEAC6D;IAC7D,OAAO,CAAC,mBAAmB;IAK3B,OAAO;IAYP,OAAO,CAAC,YAAY;IAepB;;;;;0EAKsE;IACtE,OAAO,CAAC,eAAe;IAOvB,+EAA+E;IAC/E,OAAO,CAAC,aAAa;IASrB;;sEAEkE;IAClE,OAAO,CAAC,OAAO;IAIf;0FACsF;IACtF,OAAO,CAAC,MAAM;IAed;;;sFAGkF;IAClF,OAAO,CAAC,eAAe;IAavB,OAAO,CAAC,SAAS;IAMjB,OAAO,CAAC,eAAe;IAwBvB;mDAC+C;IAC/C,OAAO,CAAC,QAAQ;IAIhB,+FAA+F;IAC/F,OAAO,CAAC,WAAW;IAenB,OAAO,CAAC,QAAQ;IAMhB,8DAA8D;IAC9D,OAAO,CAAC,qBAAqB;IAO7B,OAAO,CAAC,UAAU;IAalB;;;;;;oCAMgC;IAChC,OAAO,CAAC,mBAAmB;IAW3B;;yEAEqE;IACrE,OAAO,CAAC,aAAa;IAsBrB,mEAAmE;IACnE,OAAO,CAAC,cAAc;IAUtB;;kFAE8E;IAC9E,OAAO,CAAC,kBAAkB;IA6B1B;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"}
@@ -24,6 +24,7 @@ import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION } from "@agentclie
24
24
  import { McpHost } from "../acp/mcp-host.js";
25
25
  import { buildClaudeCodeOptions, resolveConfigDir, } from "../acp/claude-config.js";
26
26
  import { setLink, updateUsage } from "../plugin/sessions.js";
27
+ import { addAlwaysRule, evaluate as evaluateBridge } from "../plugin/bridge-rules.js";
27
28
  const DEBUG = !!process.env.ACP_DEBUG;
28
29
  const dbg = (m) => { if (DEBUG)
29
30
  process.stderr.write(`[acp-orchestrator] ${m}\n`); };
@@ -33,9 +34,16 @@ const note = (m) => process.stderr.write(`[acp] ${m}\n`);
33
34
  const MAX_LIVE_SESSIONS = 8;
34
35
  /** Cap on a foreign tool-result replayed as text during catch-up. */
35
36
  const CATCHUP_RESULT_CHARS = 2000;
37
+ /** Tope del buffer `pending` (chunks emitidos sin controller vivo): sin cap un turno
38
+ * largo con el stream cerrado lo haría crecer sin límite (OOM). */
39
+ const MAX_PENDING_PARTS = 1000;
36
40
  /** System-prompt blocks worth forwarding to the agent as FACTUAL context (never as
37
41
  * a system prompt — that would make Anthropic bill the session as extra usage). */
38
42
  const CONTEXT_TAGS = ["env", "available_references"];
43
+ /** Dialog labels — also the strings the verdict parser looks for (see `questionVerdict`). */
44
+ const ALLOW_ONCE = "Allow once";
45
+ const ALWAYS_ALLOW = "Always allow";
46
+ const DENY = "Deny";
39
47
  function emptyUsage() {
40
48
  return {
41
49
  inputTokens: { total: undefined, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
@@ -99,7 +107,7 @@ export class ACPOrchestratorModel {
99
107
  }
100
108
  // ---- LanguageModelV3 ------------------------------------------------------
101
109
  async doStream(options) {
102
- const continuation = this.detectContinuation(options.prompt);
110
+ const continuation = this.detectContinuation(options.prompt, options);
103
111
  const ref = { t: continuation?.t ?? null };
104
112
  const stream = new ReadableStream({
105
113
  start: (controller) => void this.onStart(controller, options, continuation, ref),
@@ -153,10 +161,10 @@ export class ACPOrchestratorModel {
153
161
  for (const { toolCallId, result, output } of continuation.results) {
154
162
  const permResolve = t.pendingPermissions.get(toolCallId);
155
163
  if (permResolve) {
156
- // Permission bridge: OpenCode's `ask` verdict came back as the
157
- // claude_permission tool-result → resolve the deferred requestPermission.
164
+ // Permission bridge: the user's `question` answer came back as the
165
+ // tool-result → resolve the deferred requestPermission.
158
166
  t.pendingPermissions.delete(toolCallId);
159
- permResolve(this.isApprovedOutput(output));
167
+ permResolve(this.questionVerdict(output));
160
168
  }
161
169
  else {
162
170
  t.pendingTools.delete(toolCallId);
@@ -168,7 +176,7 @@ export class ACPOrchestratorModel {
168
176
  await this.ensureConnected();
169
177
  const tools = this.convertTools(options.tools);
170
178
  const ctrl = this.effectiveCtrl(options);
171
- const po = options.providerOptions?.[this.provider] ?? {};
179
+ const po = this.providerOptions(options);
172
180
  const ocSession = po.ocSession;
173
181
  const convKey = hashText(this.firstUserText(options.prompt));
174
182
  const toolsKey = tools.map((x) => x.name).sort().join(",");
@@ -338,7 +346,7 @@ export class ACPOrchestratorModel {
338
346
  pendingPermissions: new Map(),
339
347
  textId: null,
340
348
  reasoningId: null,
341
- cancelWatchdog: null,
349
+ cancelWatchdogs: new Set(),
342
350
  lastActive: Date.now(),
343
351
  };
344
352
  ref.t = t;
@@ -388,6 +396,12 @@ export class ACPOrchestratorModel {
388
396
  catch { /* closed underneath us */ }
389
397
  }
390
398
  t.pending.push(part);
399
+ // Cap anti-OOM: con el controller cerrado mucho rato `pending` crecería sin
400
+ // límite — se descartan los chunks más antiguos.
401
+ if (t.pending.length > MAX_PENDING_PARTS) {
402
+ t.pending.splice(0, t.pending.length - MAX_PENDING_PARTS);
403
+ dbg(`pending desbordado (>${MAX_PENDING_PARTS}) — descartados los más antiguos`);
404
+ }
391
405
  }
392
406
  flushPending(t) {
393
407
  if (!t.controller || t.pending.length === 0)
@@ -444,7 +458,16 @@ export class ACPOrchestratorModel {
444
458
  dbg(`agent → tool-call ${call.name} (${call.toolCallId}) → emit to OpenCode`);
445
459
  this.closeBlocks(t);
446
460
  t.pendingTools.add(call.toolCallId);
447
- const inputJson = JSON.stringify(call.args ?? {});
461
+ // `call.args` puede traer refs circulares/BigInt → JSON.stringify lanzaría y
462
+ // tumbaría el turno: degradar a marcador en vez de crashear.
463
+ let inputJson;
464
+ try {
465
+ inputJson = JSON.stringify(call.args ?? {});
466
+ }
467
+ catch (e) {
468
+ dbg(`tool-call ${call.name}: args no serializables (${e instanceof Error ? e.message : String(e)}) — input="<serialization error>"`);
469
+ inputJson = '"<serialization error>"';
470
+ }
448
471
  this.emit(t, { type: "tool-input-start", id: call.toolCallId, toolName: call.name });
449
472
  this.emit(t, { type: "tool-input-delta", id: call.toolCallId, delta: inputJson });
450
473
  this.emit(t, { type: "tool-input-end", id: call.toolCallId });
@@ -502,25 +525,57 @@ export class ACPOrchestratorModel {
502
525
  .filter(Boolean)
503
526
  .join("\n");
504
527
  }
505
- /** ACP requestPermission → OpenCode `ask`, via the claude_permission meta-tool.
506
- * Deferred: returns a Promise the agent awaits until OpenCode's verdict comes
507
- * back as the meta-tool's result (resolved in onStart's continuation branch). */
528
+ /** ACP requestPermission → the agent's own rules first, then the `question` dialog.
529
+ * Deferred: returns a Promise the agent awaits until the verdict comes back as
530
+ * the `question` tool-result (resolved in onStart's continuation branch). */
508
531
  onRequestPermission(params) {
509
532
  const t = this.byAcpSession.get(String(params?.sessionId ?? ""));
510
- // No live turn/controller → approve so the agent never hangs.
533
+ // Sin turno vivo (crash/reinicio) — denegar es más seguro que aprobar a ciegas.
511
534
  if (!t || !t.controller)
535
+ return Promise.resolve(this.permOutcome(params, false));
536
+ const toolCall = params?.toolCall;
537
+ const native = this.permToolName(toolCall);
538
+ const target = this.bridgeTarget(toolCall);
539
+ const agent = t.ocAgent ?? "default";
540
+ // (1) allow/deny rules answer outright — no dialog, same as a native tool
541
+ // OpenCode would resolve itself.
542
+ const rules = evaluateBridge(agent, native, target.pattern);
543
+ dbg(`requestPermission(${native} → ${target.pattern}) agent=${agent} rules=${rules}`);
544
+ if (rules === "allow")
512
545
  return Promise.resolve(this.permOutcome(params, true));
546
+ if (rules === "deny")
547
+ return Promise.resolve(this.permOutcome(params, false));
548
+ // (2) "ask": raise a `question` dialog and wait for its tool-result.
513
549
  const callId = `perm_${++this.idSeq}`;
514
- dbg(`requestPermission(${this.permToolName(params?.toolCall)}) → bridge as claude_permission (${callId})`);
550
+ dbg(`requestPermission(${native}) → bridge as question (${callId})`);
515
551
  return new Promise((resolve) => {
516
- t.pendingPermissions.set(callId, (approved) => resolve(this.permOutcome(params, approved)));
517
- this.emitPermissionCall(t, callId, params?.toolCall);
552
+ t.pendingPermissions.set(callId, (verdict) => {
553
+ if (verdict.approved && verdict.always && target.always)
554
+ addAlwaysRule(agent, native, target.always);
555
+ resolve(this.permOutcome(params, verdict.approved));
556
+ });
557
+ this.emitPermissionCall(t, callId, toolCall, native, target);
518
558
  });
519
559
  }
520
- /** Emit a claude_permission tool-call to OpenCode (same deferred pattern as a
521
- * real tool-call): OpenCode applies its `ask` permission and returns the
522
- * verdict as the tool-result on the next doStream. */
523
- emitPermissionCall(t, callId, toolCall) {
560
+ /** Action target of a native request (command / skill / path), plus the glob an
561
+ * "Always allow" would persist. Shell commands collapse to their first token
562
+ * (`git status` → `git *`); a request with no real target persists nothing, so
563
+ * the dialog never offers a broad rule that would auto-approve everything. */
564
+ bridgeTarget(toolCall) {
565
+ const raw = toolCall?.rawInput;
566
+ const inp = raw && typeof raw === "object" ? raw : {};
567
+ const text = String((inp.command ?? inp.skill ?? inp.name ?? inp.notebook_path ?? inp.file_path ?? inp.path) ||
568
+ (typeof raw === "string" ? raw : "") ||
569
+ toolCall?.title ||
570
+ "").trim();
571
+ const always = toolCall?.kind === "execute" && text.includes(" ") ? `${text.split(/\s+/)[0]} *` : text || undefined;
572
+ return { pattern: text || "*", always };
573
+ }
574
+ /** Emit a `question` tool-call to OpenCode (same deferred pattern as a real
575
+ * tool-call): the native tool's request becomes a dialog — Allow once /
576
+ * Always allow / Deny — and the answer arrives as the tool-result on the next
577
+ * doStream. The agent itself only ever sees the ACP permission outcome. */
578
+ emitPermissionCall(t, callId, toolCall, native, target) {
524
579
  if (!t.controller)
525
580
  return;
526
581
  this.closeBlocks(t);
@@ -537,15 +592,24 @@ export class ACPOrchestratorModel {
537
592
  }
538
593
  }
539
594
  const input = JSON.stringify({
540
- tool: this.permToolName(toolCall),
541
- kind: toolCall?.kind,
542
- title: toolCall?.title,
543
- input: toolCall?.rawInput,
595
+ questions: [
596
+ {
597
+ question: `${native}: ${toolCall?.title ?? target.pattern}`,
598
+ header: "Permission",
599
+ options: [
600
+ { label: ALLOW_ONCE, description: "Approve this action for this call only" },
601
+ ...(target.always
602
+ ? [{ label: ALWAYS_ALLOW, description: `Approve and stop asking for ${target.always}` }]
603
+ : []),
604
+ { label: DENY, description: "Block this action" },
605
+ ],
606
+ },
607
+ ],
544
608
  });
545
- this.emit(t, { type: "tool-input-start", id: callId, toolName: "claude_permission" });
609
+ this.emit(t, { type: "tool-input-start", id: callId, toolName: "question" });
546
610
  this.emit(t, { type: "tool-input-delta", id: callId, delta: input });
547
611
  this.emit(t, { type: "tool-input-end", id: callId });
548
- this.emit(t, { type: "tool-call", toolCallId: callId, toolName: "claude_permission", input });
612
+ this.emit(t, { type: "tool-call", toolCallId: callId, toolName: "question", input });
549
613
  this.emit(t, { type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
550
614
  try {
551
615
  t.controller?.close();
@@ -644,18 +708,45 @@ export class ACPOrchestratorModel {
644
708
  drainPermissions(t) {
645
709
  if (t.pendingPermissions.size === 0)
646
710
  return;
711
+ const denied = { approved: false, always: false };
647
712
  for (const resolve of [...t.pendingPermissions.values()]) {
648
713
  try {
649
- resolve(false);
714
+ resolve(denied);
650
715
  }
651
716
  catch { /* ignore */ }
652
717
  }
653
718
  t.pendingPermissions.clear();
654
719
  }
720
+ /** Per-call provider options: V2 nests them under `providerOptionKey(package,
721
+ * providerID)` = the providerID. El fallback al primer objeto del mapa sería
722
+ * voraz (podría tomar opciones de OTRO provider): solo se acepta si la key
723
+ * contiene nuestro provider id (`acp`) o el objeto trae forma conocida
724
+ * (ocSession/ocAgent/resumeId/…/mode/effort/native*); si no, como ausente. */
725
+ providerOptions(options) {
726
+ const all = (options.providerOptions ?? {});
727
+ const own = all[this.provider];
728
+ if (own && typeof own === "object")
729
+ return own;
730
+ const SHAPE_KEYS = new Set([
731
+ "ocSession", "ocAgent", "resumeId", "resumeLen", "resumeConvKey", "resumeLastUsage",
732
+ "mode", "effort", "thinking", "systemPromptMode", "forwardEnvContext",
733
+ "tools", "allowedTools", "disallowedTools", "settingSources", "strictMcpConfig",
734
+ "nativeTools", "resourceSearch", "nativeSubagents", "nativeSkills", "projectMemory", "skillShell",
735
+ ]);
736
+ for (const [key, value] of Object.entries(all)) {
737
+ if (!value || typeof value !== "object" || Array.isArray(value))
738
+ continue;
739
+ if (String(key).toLowerCase().includes(this.provider))
740
+ return value;
741
+ if (Object.keys(value).some((k) => SHAPE_KEYS.has(k) || k.startsWith("native")))
742
+ return value;
743
+ }
744
+ return {};
745
+ }
655
746
  /** Provider config overlaid with per-call `providerOptions.acp` (per-agent mode/effort/…). */
656
747
  effectiveCtrl(options) {
657
748
  const ctrl = { ...(this.config.claudeCode ?? {}) };
658
- const po = options.providerOptions?.[this.provider];
749
+ const po = this.providerOptions(options);
659
750
  if (po && typeof po === "object") {
660
751
  // Per-agent overrides from `agent.<name>.options` (→ providerOptions.acp):
661
752
  // mode/effort/reasoning plus the native-feature toggles.
@@ -713,7 +804,9 @@ export class ACPOrchestratorModel {
713
804
  return Promise.resolve();
714
805
  if (this.connecting)
715
806
  return this.connecting;
716
- this.connecting = this.connect();
807
+ // Si `connect()` lanza, `connecting` debe resetearse: si no, todos los
808
+ // `ensureConnected()` futuros reutilizarían la promesa rechazada y colgarían.
809
+ this.connecting = this.connect().then(() => undefined, (err) => { this.connecting = null; throw err; });
717
810
  return this.connecting;
718
811
  }
719
812
  async connect() {
@@ -798,18 +891,20 @@ export class ACPOrchestratorModel {
798
891
  * force teardown so the agent doesn't stay blocked. Cleared by a continuation. */
799
892
  armCancelWatchdog(t) {
800
893
  this.clearCancelWatchdog(t);
801
- t.cancelWatchdog = setTimeout(() => {
802
- t.cancelWatchdog = null;
894
+ const timer = setTimeout(() => {
895
+ t.cancelWatchdogs.delete(timer);
803
896
  dbg("cancel watchdog fired — no continuation arrived; tearing down");
804
897
  this.endTurn(t);
805
898
  }, this.config.streamCloseTimeoutMs ?? 600_000);
806
- t.cancelWatchdog.unref?.();
899
+ timer.unref?.();
900
+ t.cancelWatchdogs.add(timer);
807
901
  }
902
+ /** Barre TODOS los watchdogs del turno (cada `onCancel` ignorado arma uno);
903
+ * llamado desde endTurn/cleanup y al continuar el turno. */
808
904
  clearCancelWatchdog(t) {
809
- if (t.cancelWatchdog) {
810
- clearTimeout(t.cancelWatchdog);
811
- t.cancelWatchdog = null;
812
- }
905
+ for (const timer of t.cancelWatchdogs)
906
+ clearTimeout(timer);
907
+ t.cancelWatchdogs.clear();
813
908
  }
814
909
  cleanup() {
815
910
  for (const t of [...this.sessions.values()])
@@ -830,11 +925,6 @@ export class ACPOrchestratorModel {
830
925
  return [];
831
926
  const out = [];
832
927
  for (const t of tools) {
833
- // Skip the permission-bridge meta-tool: the provider emits `claude_permission`
834
- // itself and OpenCode runs it via the plugin, so the AGENT must NOT see it
835
- // (otherwise it surfaces as mcp__opencode__claude_permission and confuses it).
836
- if (t.name === "claude_permission")
837
- continue;
838
928
  if (t.type === "function") {
839
929
  out.push({
840
930
  name: t.name,
@@ -907,8 +997,12 @@ export class ACPOrchestratorModel {
907
997
  i++;
908
998
  if (i === sent.length)
909
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).
910
1002
  if (i === keys.length)
911
- return { kind: "revert", fromIndex: i };
1003
+ return keys.length < sent.length
1004
+ ? { kind: "revert", fromIndex: i }
1005
+ : { kind: "append", fromIndex: keys.length };
912
1006
  return { kind: "diverged", fromIndex: i };
913
1007
  }
914
1008
  blocksFor(msgs, t) {
@@ -1060,9 +1154,21 @@ export class ACPOrchestratorModel {
1060
1154
  return [{ type: "text", text: "" }];
1061
1155
  }
1062
1156
  /** Find the live conversation whose deferred tool-calls/permissions this prompt
1063
- * answers. Scoped per session, so two concurrent chats can't cross-resolve. */
1064
- detectContinuation(prompt) {
1065
- for (const t of this.sessions.values()) {
1157
+ * answers. Acotado a la conversación actual (`ocSession`/convKey de ESTA llamada):
1158
+ * iterar todas las sesiones cruzaba continuaciones de chats concurrentes. */
1159
+ detectContinuation(prompt, options) {
1160
+ let candidates;
1161
+ if (options) {
1162
+ const po = this.providerOptions(options);
1163
+ const baseKey = typeof po.ocSession === "string" ? po.ocSession : hashText(this.firstUserText(prompt));
1164
+ candidates = [this.sessions.get(baseKey), this.sessions.get(`${baseKey}:notools`)];
1165
+ }
1166
+ else {
1167
+ candidates = [...this.sessions.values()];
1168
+ }
1169
+ for (const t of candidates) {
1170
+ if (!t)
1171
+ continue;
1066
1172
  if (t.pendingTools.size === 0 && t.pendingPermissions.size === 0)
1067
1173
  continue;
1068
1174
  const results = [];
@@ -1086,13 +1192,46 @@ export class ACPOrchestratorModel {
1086
1192
  const ty = output?.type;
1087
1193
  return ty === "error-text" || ty === "error-json" || ty === "error";
1088
1194
  }
1089
- /** Approve a bridged permission ONLY on an explicit positive verdict (the
1090
- * claude_permission meta-tool returns "approved: …"). Errors, denials, and any
1091
- * ambiguous output fail CLOSED so an unclear verdict never runs the native tool. */
1092
- isApprovedOutput(output) {
1195
+ /** Approve a bridged permission ONLY on an explicit positive answer to the
1196
+ * `question` dialog. Errors, dismissals, and any ambiguous output (including
1197
+ * a typed-in answer) fail CLOSED so an unclear verdict never runs the tool.
1198
+ * Verificado: OpenCode V2 no expone identificador estable (sin schema de la tool
1199
+ * `question` en node_modules/@opencode-ai ni en /opt/OpenCode/resources; el shape
1200
+ * documentado es etiqueta en `{ answers: [["…"]] }` o texto renderizado) → match
1201
+ * por etiqueta normalizada (minúsculas, trim, "_" y espacios colapsados) con
1202
+ * fallback deny ante cualquier cosa no reconocida. Flujo de 3 opciones intacto. */
1203
+ questionVerdict(output) {
1093
1204
  if (this.isErrorOutput(output))
1094
- return false;
1095
- return this.outputToText(output).toLowerCase().includes("approved");
1205
+ return { approved: false, always: false };
1206
+ const answer = this.normalizeAnswer(this.answerLabel(output));
1207
+ if (answer.includes("always allow"))
1208
+ return { approved: true, always: true };
1209
+ if (answer.includes("allow once"))
1210
+ return { approved: true, always: false };
1211
+ return { approved: false, always: false };
1212
+ }
1213
+ /** Normaliza una etiqueta de respuesta para el match robusto. */
1214
+ normalizeAnswer(s) {
1215
+ return String(s ?? "").trim().toLowerCase().replace(/[_-]+/g, " ").replace(/\s+/g, " ");
1216
+ }
1217
+ /** The chosen label: typed output (`{ answers: [["Always allow"]] }`) first,
1218
+ * then the rendered text fallback (`"question"="Always allow"`). */
1219
+ answerLabel(output) {
1220
+ const answers = output?.value?.answers;
1221
+ if (Array.isArray(answers)) {
1222
+ const first = answers[0];
1223
+ const cand = Array.isArray(first) ? first[0] : first;
1224
+ if (typeof cand === "string")
1225
+ return cand;
1226
+ // Por si OpenCode V2 tipa la respuesta algún día (objeto con optionId/id
1227
+ // estable): preferir el identificador antes que el texto renderizado.
1228
+ if (cand && typeof cand === "object") {
1229
+ const stable = cand.label ?? cand.value ?? cand.text ?? cand.optionId ?? cand.id;
1230
+ if (typeof stable === "string")
1231
+ return stable;
1232
+ }
1233
+ }
1234
+ return this.outputToText(output);
1096
1235
  }
1097
1236
  outputToText(output) {
1098
1237
  if (!output)