backeer-codex 0.11.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/opencode.mjs CHANGED
@@ -12950,6 +12950,9 @@ var require_dist = __commonJS({
12950
12950
  }
12951
12951
  });
12952
12952
 
12953
+ // src/version.mjs
12954
+ var VERSION = "0.13.0";
12955
+
12953
12956
  // src/opencode.mjs
12954
12957
  import path2 from "node:path";
12955
12958
  import { createInterface } from "node:readline/promises";
@@ -12959,6 +12962,28 @@ import { readFile, mkdir, writeFile, rename, rm } from "node:fs/promises";
12959
12962
  import { dirname, isAbsolute as isAbsolute2 } from "node:path";
12960
12963
  import { randomUUID } from "node:crypto";
12961
12964
 
12965
+ // ../opencode-plugin/src/updates.js
12966
+ var PLUGIN_VERSION = "0.16.0";
12967
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
12968
+
12969
+ // ../opencode-plugin/src/live-compatibility.js
12970
+ var LIVE_PROTOCOL = { name: "backeer-live", major: 1, revision: 2 };
12971
+ function compatibility(bridge, adapterVersion) {
12972
+ const capabilities = bridge?.capabilities ?? {};
12973
+ const protocol = bridge?.liveProtocol;
12974
+ const supported = !protocol || protocol.name === LIVE_PROTOCOL.name && protocol.major === LIVE_PROTOCOL.major;
12975
+ const features = Object.fromEntries(["sessionTree", "treeFanIn", "activity", "deliveryTracking", "durableCommands", "diagnostics", "childQuestions"].map((name) => [name, supported && capabilities[name] === true]));
12976
+ return {
12977
+ supported,
12978
+ protocol: protocol ?? { name: "legacy", major: 1 },
12979
+ client: { embeddedBridgeVersion: PLUGIN_VERSION, ...adapterVersion ? { adapterVersion } : {} },
12980
+ remote: { loadedVersion: bridge?.bridgeVersion ?? "unknown", installation: "not_verified_by_metadata" },
12981
+ features,
12982
+ unavailable: Object.entries(features).filter(([, available]) => !available).map(([name]) => name),
12983
+ ...supported ? {} : { code: "bridge_protocol_unsupported" }
12984
+ };
12985
+ }
12986
+
12962
12987
  // ../opencode-plugin/src/live-timeouts.js
12963
12988
  var LIVE_REQUEST_TIMEOUT_MS = 45e3;
12964
12989
 
@@ -13016,6 +13041,11 @@ var details = Object.freeze({
13016
13041
  session_unavailable: ["The current verified OpenCode owner cannot find this exact session.", "Check its project, worktree and owning process. This response does not prove deletion; never create or substitute a session automatically.", false],
13017
13042
  session_project_mismatch: ["The exact session is outside this connection's verified project/worktree scope.", "Discover its actual project connection or verify the already authorized worktree. Keep the exact session ID; do not substitute another session.", false],
13018
13043
  session_archived: ["The native API reports that the selected session is archived.", "Confirm the intended session state with the user. Do not create or choose a replacement automatically.", false],
13044
+ command_delivery_uncertain: ["Previous delivery is unresolved.", "Inspect its exact request receipt and native session. Do not automatically replay or change the request ID.", false],
13045
+ command_journal_unavailable: ["The protected command journal is unavailable.", "Check its storage and permissions; never delete reservations to force another delivery.", false],
13046
+ instruction_not_found: ["No receipt is available for that exact request ID.", "Check the same session and request; absence is not proof of non-delivery.", false],
13047
+ native_session_api_circuit_open: ["The native owner is recovering after repeated read failures.", "Keep this binding and wait for the next health probe. Never repeat an instruction automatically.", true],
13048
+ bridge_protocol_unsupported: ["The remote bridge protocol is incompatible.", "Load compatible plugin versions before reconnecting the same session. No fallback was selected.", false],
13019
13049
  native_session_api_timeout: ["The native OpenCode session read timed out.", "Keep the same binding and retry the read after load settles. Do not resend instructions or infer deletion.", true],
13020
13050
  native_session_api_unavailable: ["The owning native OpenCode API is temporarily unavailable.", "Keep the same binding, project and session. Check the native API connection and retry after recovery; this is not evidence of deletion.", true],
13021
13051
  bridge_unavailable: ["The remote bridge endpoint is unavailable.", "Check the existing bridge and its version without restarting the active session.", true],
@@ -13055,6 +13085,11 @@ function safeConnectionMessage(error62) {
13055
13085
 
13056
13086
  // ../opencode-plugin/src/live-errors.js
13057
13087
  var liveErrorMessages = Object.freeze({
13088
+ command_delivery_uncertain: "A previous delivery is unresolved. Inspect the exact request receipt and native session; do not resubmit it or create another request ID automatically.",
13089
+ command_journal_unavailable: "The protected command journal is unavailable. Delivery may be unresolved; keep the same request ID, inspect storage/permissions and never delete reservations or automatically replay work.",
13090
+ instruction_not_found: "This native owner has no receipt for that exact request ID. Do not infer that the command was never delivered.",
13091
+ native_session_api_circuit_open: "The native owner is cooling down after repeated read failures. Keep this session and retry after recovery; do not repeat commands.",
13092
+ bridge_protocol_unsupported: "The remote bridge uses an unsupported protocol. Update compatible plugins before reconnecting; no fallback was selected.",
13058
13093
  native_session_api_timeout: "The native OpenCode session read timed out. Keep the same session; do not resend work or treat it as deleted.",
13059
13094
  native_session_api_unavailable: "The owning native OpenCode API could not be reached or verified. This does not mean the session was deleted. Keep the exact project/session and retry after its native API recovers.",
13060
13095
  session_not_found: "This verified OpenCode owner cannot currently find the exact session. Check its project, worktree and owning process; absence here is not proof that the session was deleted elsewhere.",
@@ -13093,6 +13128,8 @@ var LiveActivity = class {
13093
13128
  this.alerts = [];
13094
13129
  this.pending = /* @__PURE__ */ new Map();
13095
13130
  this.detailCursors = /* @__PURE__ */ new Map();
13131
+ this.deliveries = /* @__PURE__ */ new Map();
13132
+ this.deliveryUpdates = /* @__PURE__ */ new Map();
13096
13133
  this.startCursor = client.cursor;
13097
13134
  this.revision = 0;
13098
13135
  this.delivered = -1;
@@ -13104,6 +13141,9 @@ var LiveActivity = class {
13104
13141
  this.completionReported = false;
13105
13142
  this.lastChange = 0;
13106
13143
  this.pendingSince = 0;
13144
+ this.lastVerifiedAt = 0;
13145
+ this.verifiedGeneration = -1;
13146
+ this.lastCard = void 0;
13107
13147
  this.gapCursor = void 0;
13108
13148
  this.droppedAlerts = 0;
13109
13149
  this.metrics = {
@@ -13125,7 +13165,12 @@ var LiveActivity = class {
13125
13165
  this.revision++;
13126
13166
  this.lastChange = Date.now();
13127
13167
  }
13168
+ needsSnapshot() {
13169
+ return !this.lastVerifiedAt || this.snapshotNeeded || this.terminalCandidate || this.verifiedGeneration !== this.client.successfulConnections || Date.now() - this.lastVerifiedAt >= 3e4;
13170
+ }
13128
13171
  seed(session, eventRevision = this.eventRevision) {
13172
+ this.lastVerifiedAt = Date.now();
13173
+ this.verifiedGeneration = this.client.successfulConnections;
13129
13174
  const before = JSON.stringify([...this.nodes.values()].map(({ revision: _revision, ...info }) => info)) + this.coverageComplete;
13130
13175
  const tree = session.tree ?? { sessions: [session], complete: this.scope === "session", unresolvedCount: 0 };
13131
13176
  const present = /* @__PURE__ */ new Set();
@@ -13173,6 +13218,7 @@ var LiveActivity = class {
13173
13218
  revision: ++this.eventRevision
13174
13219
  };
13175
13220
  const data = event.data ?? {};
13221
+ if (event.type === "message.delivery") this.receipt({ messageID: data.messageID, sessionID: event.sessionID, delivery: data.status });
13176
13222
  if (event.type === "session.status") node2.status = data.status;
13177
13223
  if (event.type === "session.idle") node2.status = "idle";
13178
13224
  if (event.type === "session.error") {
@@ -13216,6 +13262,23 @@ var LiveActivity = class {
13216
13262
  }
13217
13263
  this.change();
13218
13264
  }
13265
+ receipt(receipt) {
13266
+ if (!receipt?.messageID) return;
13267
+ const previous = this.deliveries.get(receipt.messageID);
13268
+ const value = {
13269
+ messageID: receipt.messageID,
13270
+ sessionID: receipt.sessionID,
13271
+ delivery: receipt.delivery ?? previous?.delivery ?? "unknown",
13272
+ ...receipt.requestId || previous?.requestId ? { requestId: receipt.requestId ?? previous.requestId } : {}
13273
+ };
13274
+ if (["delivered", "cancelled"].includes(previous?.delivery)) value.delivery = previous.delivery;
13275
+ if (JSON.stringify(value) === JSON.stringify(previous)) return;
13276
+ this.deliveries.set(value.messageID, value);
13277
+ this.deliveryUpdates.set(value.messageID, value);
13278
+ while (this.deliveries.size > this.client.maxEvents) this.deliveries.delete(this.deliveries.keys().next().value);
13279
+ while (this.deliveryUpdates.size > this.client.maxEvents) this.deliveryUpdates.delete(this.deliveryUpdates.keys().next().value);
13280
+ this.change();
13281
+ }
13219
13282
  reference(event) {
13220
13283
  return {
13221
13284
  eventId: event.id,
@@ -13262,12 +13325,26 @@ var LiveActivity = class {
13262
13325
  shownAgents: Math.min(agentLimit, children.length),
13263
13326
  coverageComplete: this.coverageComplete && !this.client.gap && this.client.status === "connected",
13264
13327
  workCompleted: this.finished(),
13328
+ lastVerifiedAt: this.lastVerifiedAt,
13265
13329
  connection: this.client.status,
13266
13330
  ...this.client.gap ? { gap: this.client.gap } : {}
13267
13331
  };
13268
13332
  }
13269
- take(agentLimit = 10) {
13333
+ take(agentLimit = 10, changesOnly = false) {
13270
13334
  const card = this.card(agentLimit);
13335
+ const old = this.lastCard;
13336
+ const stable = (value) => JSON.stringify(value && { ...value, lastVerifiedAt: void 0 });
13337
+ const unchanged = stable(old) === stable(card);
13338
+ const delta = old ? {
13339
+ ...JSON.stringify(old.root) === JSON.stringify(card.root) ? {} : { root: card.root },
13340
+ agents: card.agents.filter((agent) => !old.agents.some((previous) => JSON.stringify(previous) === JSON.stringify(agent))),
13341
+ removedAgents: old.agents.filter((agent) => !card.agents.some((current) => current.sessionId === agent.sessionId)).map((agent) => agent.sessionId),
13342
+ counts: card.counts,
13343
+ coverageComplete: card.coverageComplete,
13344
+ workCompleted: card.workCompleted,
13345
+ connection: card.connection
13346
+ } : void 0;
13347
+ this.lastCard = card;
13271
13348
  const alerts = this.alerts.splice(0, 50);
13272
13349
  const details2 = [...this.pending.values()].slice(-20);
13273
13350
  const moreDetails = this.pending.size > details2.length;
@@ -13275,9 +13352,13 @@ var LiveActivity = class {
13275
13352
  this.delivered = this.revision;
13276
13353
  this.pendingSince = 0;
13277
13354
  this.metrics.activityResponses++;
13355
+ if (changesOnly && old) this.metrics.deltaResponses = (this.metrics.deltaResponses ?? 0) + 1;
13356
+ const deliveries = [...this.deliveryUpdates.values()].slice(0, 20);
13357
+ for (const receipt of deliveries) this.deliveryUpdates.delete(receipt.messageID);
13278
13358
  return {
13279
13359
  revision: this.revision,
13280
- card,
13360
+ ...deliveries.length ? { deliveries, hasMoreDeliveries: this.deliveryUpdates.size > 0 } : {},
13361
+ ...changesOnly && old ? { unchanged, ...unchanged ? {} : { delta } } : { card },
13281
13362
  alerts,
13282
13363
  hasMoreAlerts: this.alerts.length > 0,
13283
13364
  details: details2,
@@ -13292,14 +13373,14 @@ var LiveActivity = class {
13292
13373
  while (!signal?.aborted && !this.client.controller.signal.aborted) {
13293
13374
  this.transport();
13294
13375
  if (this.alerts.length || this.client.gap) return "ready";
13295
- if (this.terminalCandidate) return "verify";
13376
+ if (this.needsSnapshot()) return "verify";
13296
13377
  if (this.revision !== shown && progress && Date.now() - lastProgress >= 500) {
13297
13378
  shown = this.revision;
13298
13379
  lastProgress = Date.now();
13299
13380
  await progress(this.card());
13300
13381
  }
13301
13382
  if (this.revision !== this.delivered && Date.now() - this.pendingSince >= coalesceMs || Date.now() >= deadline) return "ready";
13302
- const remaining = Math.max(1, Math.min(deadline - Date.now(), this.revision !== this.delivered ? coalesceMs - (Date.now() - this.pendingSince) : Infinity));
13383
+ const remaining = Math.max(1, Math.min(deadline - Date.now(), Math.max(1, 3e4 - (Date.now() - this.lastVerifiedAt)), this.revision !== this.delivered ? coalesceMs - (Date.now() - this.pendingSince) : Infinity));
13303
13384
  await new Promise((resolve) => {
13304
13385
  let timer;
13305
13386
  const done = () => {
@@ -13415,7 +13496,7 @@ function checkedCursor(cursor) {
13415
13496
  return cursor;
13416
13497
  }
13417
13498
  function checkedSession(id) {
13418
- if (!SESSION.test(id)) throw new Error("Invalid session ID");
13499
+ if (typeof id !== "string" || !SESSION.test(id)) throw new Error("Invalid session ID");
13419
13500
  return encodeURIComponent(id);
13420
13501
  }
13421
13502
  function matchesSession(event, sessionId, eventScope) {
@@ -13455,7 +13536,8 @@ var LiveControlClient = class {
13455
13536
  expectedDirectory,
13456
13537
  sessionId,
13457
13538
  eventScope = "session",
13458
- internalReader = false
13539
+ internalReader = false,
13540
+ requireTree = false
13459
13541
  } = {}) {
13460
13542
  const origin = liveControlOrigin(url2);
13461
13543
  if (typeof token !== "string" || !/^[A-Za-z0-9_-]{32,}$/.test(token)) throw new Error("Live-control token is invalid");
@@ -13465,6 +13547,7 @@ var LiveControlClient = class {
13465
13547
  if (!["session", "tree"].includes(eventScope) || eventScope === "tree" && sessionId === void 0) {
13466
13548
  throw new Error("Invalid event scope: tree tracking requires an exact root session");
13467
13549
  }
13550
+ this.requireTree = requireTree;
13468
13551
  this.sessionId = sessionId;
13469
13552
  this.eventScope = eventScope;
13470
13553
  this.internalHeaders = internalReader ? { "X-Backeer-Internal": "project-hub" } : {};
@@ -13494,9 +13577,12 @@ var LiveControlClient = class {
13494
13577
  this.lastDisconnectedAt = null;
13495
13578
  this.nextRetryAt = null;
13496
13579
  this.lastDiagnostic = null;
13580
+ this.requestStats = { calls: 0, failures: 0, timeouts: 0, durations: [] };
13497
13581
  if (sessionId && !internalReader) this.activity = new LiveActivity(this, sessionId, eventScope);
13498
13582
  }
13499
13583
  async request(path3, { method = "GET", body, signal, timeoutMs = LIVE_REQUEST_TIMEOUT_MS } = {}) {
13584
+ const started = Date.now();
13585
+ let succeeded = false;
13500
13586
  const controller = new AbortController();
13501
13587
  const abort = () => controller.abort();
13502
13588
  this.controller.signal.addEventListener("abort", abort, { once: true });
@@ -13530,8 +13616,12 @@ var LiveControlClient = class {
13530
13616
  if (Object.hasOwn(liveErrorMessages, value2?.error)) code = value2.error;
13531
13617
  if (["project_mismatch", "project_required", "project_unavailable", "session_required"].includes(value2?.error)) connectionCode = value2.error;
13532
13618
  const sessionErrors = {
13619
+ command_delivery_uncertain: "command_delivery_uncertain",
13620
+ command_journal_unavailable: "command_journal_unavailable",
13621
+ instruction_not_found: "instruction_not_found",
13533
13622
  native_session_api_unavailable: "native_session_api_unavailable",
13534
13623
  native_session_api_timeout: "native_session_api_timeout",
13624
+ native_session_api_circuit_open: "native_session_api_circuit_open",
13535
13625
  session_not_found: "session_unavailable",
13536
13626
  session_project_mismatch: "session_project_mismatch",
13537
13627
  session_archived: "session_archived",
@@ -13554,14 +13644,21 @@ var LiveControlClient = class {
13554
13644
  const text = await responseText(response);
13555
13645
  const value = JSON.parse(text);
13556
13646
  const source = response.headers.get("x-backeer-source");
13557
- if (source && this.sessionId) {
13558
- if (this.sourceIdentity && this.sourceIdentity !== source) this.activeConnection?.abort();
13647
+ if (source) {
13648
+ if (this.sourceIdentity && this.sourceIdentity !== source) {
13649
+ this.activeConnection?.abort();
13650
+ this.streamPool?.restart(this);
13651
+ }
13559
13652
  this.sourceIdentity = source;
13560
13653
  }
13561
13654
  if (path3 === "/v1/sessions") {
13562
- this.bridgeInfo = { bridgeVersion: value?.bridgeVersion, capabilities: value?.capabilities };
13563
- if (this.eventScope === "tree" && value?.capabilities?.sessionTree !== true) throw treeUnsupported();
13655
+ this.bridgeInfo = { bridgeVersion: value?.bridgeVersion, capabilities: value?.capabilities, liveProtocol: value?.liveProtocol };
13656
+ if (value?.liveProtocol && (value.liveProtocol.name !== LIVE_PROTOCOL.name || value.liveProtocol.major !== LIVE_PROTOCOL.major)) {
13657
+ throw Object.assign(new Error("Unsupported bridge protocol"), { connectionCode: "bridge_protocol_unsupported" });
13658
+ }
13659
+ if ((this.eventScope === "tree" || this.requireTree) && value?.capabilities?.sessionTree !== true) throw treeUnsupported();
13564
13660
  }
13661
+ succeeded = true;
13565
13662
  return value;
13566
13663
  } catch (error62) {
13567
13664
  const diagnostic = connectionDiagnostic(error62, {
@@ -13572,6 +13669,11 @@ var LiveControlClient = class {
13572
13669
  });
13573
13670
  throw Object.assign(error62, { connectionCode: diagnostic.code });
13574
13671
  } finally {
13672
+ this.requestStats.calls++;
13673
+ if (!succeeded) this.requestStats.failures++;
13674
+ if (timedOut) this.requestStats.timeouts++;
13675
+ this.requestStats.durations.push(Date.now() - started);
13676
+ if (this.requestStats.durations.length > 100) this.requestStats.durations.shift();
13575
13677
  clearTimeout(timer);
13576
13678
  this.controller.signal.removeEventListener("abort", abort);
13577
13679
  signal?.removeEventListener("abort", abort);
@@ -13585,14 +13687,17 @@ var LiveControlClient = class {
13585
13687
  if (includeTree && !Array.isArray(result?.tree?.sessions)) throw treeUnsupported();
13586
13688
  return result;
13587
13689
  }
13690
+ instructionStatus(id, requestId) {
13691
+ return this.request(`/v1/sessions/${checkedSession(id)}/instructions/${checkedSession(requestId)}`);
13692
+ }
13588
13693
  listQuestions(id) {
13589
13694
  return this.request(`/v1/sessions/${checkedSession(id)}/questions`);
13590
13695
  }
13591
- answerQuestion({ sessionId, questionId, revision, answers, requestId, signal }) {
13696
+ answerQuestion({ sessionId, questionId, revision, answers, requestId, rootSessionId, signal }) {
13592
13697
  if (!/^[A-Za-z0-9_-]+$/.test(requestId) || !/^[a-f0-9]{64}$/.test(revision) || !Array.isArray(answers) || answers.length < 1) throw new Error("Invalid question answer");
13593
13698
  return this.request(`/v1/sessions/${checkedSession(sessionId)}/questions/${checkedSession(questionId)}/answers`, {
13594
13699
  method: "POST",
13595
- body: { requestId, revision, answers },
13700
+ body: { requestId, revision, answers, ...rootSessionId ? { rootSessionId } : {} },
13596
13701
  signal
13597
13702
  });
13598
13703
  }
@@ -13614,6 +13719,7 @@ var LiveControlClient = class {
13614
13719
  for (const wake of this.listeners) wake();
13615
13720
  }
13616
13721
  async start(afterCursor) {
13722
+ if (this.streamPool) return this.streamPool.start(this, afterCursor);
13617
13723
  checkedCursor(afterCursor);
13618
13724
  if (this.controller.signal.aborted) throw new Error("Live-control client is closed");
13619
13725
  if (this.gap && afterCursor === this.gap.cursor) {
@@ -13679,7 +13785,7 @@ var LiveControlClient = class {
13679
13785
  };
13680
13786
  armWatchdog(LIVE_REQUEST_TIMEOUT_MS);
13681
13787
  try {
13682
- const bridge = this.eventScope === "tree" ? await this.request("/v1/sessions", {
13788
+ const bridge = this.eventScope === "tree" || this.requireTree ? await this.request("/v1/sessions", {
13683
13789
  signal: connection2.signal,
13684
13790
  timeoutMs: LIVE_REQUEST_TIMEOUT_MS
13685
13791
  }) : void 0;
@@ -13696,7 +13802,8 @@ var LiveControlClient = class {
13696
13802
  if (this.activity && this.activity.startCursor === void 0) this.activity.startCursor = initial;
13697
13803
  }
13698
13804
  const selected = this.sessionId === void 0 ? "" : `&sessionID=${encodeURIComponent(this.sessionId)}${this.eventScope === "tree" ? "&scope=tree" : ""}`;
13699
- const response = await this.fetch(`${this.url}/v1/events?after=${encodeURIComponent(this.cursor)}${selected}`, {
13805
+ const readers = this.readerSessions ? `&readers=${encodeURIComponent(JSON.stringify(this.readerSessions))}` : "";
13806
+ const response = await this.fetch(`${this.url}/v1/events?after=${encodeURIComponent(this.cursor)}${selected}${readers}`, {
13700
13807
  redirect: "error",
13701
13808
  signal: connection2.signal,
13702
13809
  headers: {
@@ -13723,6 +13830,7 @@ var LiveControlClient = class {
13723
13830
  });
13724
13831
  }
13725
13832
  if (!response.body) throw new Error("SSE body missing");
13833
+ this.sourceIdentity = response.headers.get("x-backeer-source") ?? this.sourceIdentity;
13726
13834
  this.status = "connected";
13727
13835
  this.successfulConnections++;
13728
13836
  this.lastConnectedAt = Date.now();
@@ -13772,10 +13880,10 @@ var LiveControlClient = class {
13772
13880
  if (Buffer.byteLength(buffer) > this.maxBufferBytes + 4096) throw Object.assign(new Error("SSE frame exceeds buffer limit"), { connectionCode: "stream_payload_limit" });
13773
13881
  }
13774
13882
  } catch (error62) {
13775
- if (!this.controller.signal.aborted) {
13883
+ if (!this.controller.signal.aborted && !this.restartRequested) {
13776
13884
  if (this.status !== "unauthorized") this.status = "disconnected";
13777
13885
  this.recordFailure(error62, { timeout: timedOut });
13778
- if (["stream_payload_limit", "session_tree_unsupported"].includes(error62.connectionCode)) {
13886
+ if (["stream_payload_limit", "session_tree_unsupported", "bridge_protocol_unsupported"].includes(error62.connectionCode)) {
13779
13887
  this.status = "blocked";
13780
13888
  this.notify();
13781
13889
  return;
@@ -13789,19 +13897,29 @@ var LiveControlClient = class {
13789
13897
  });
13790
13898
  reader?.releaseLock();
13791
13899
  }
13792
- if (!this.controller.signal.aborted) this.nextRetryAt = Date.now() + this.reconnectMs;
13900
+ const immediate = this.restartRequested;
13901
+ this.restartRequested = false;
13902
+ if (!this.controller.signal.aborted) this.nextRetryAt = immediate ? null : Date.now() + this.reconnectMs;
13793
13903
  this.notify();
13794
- if (!this.controller.signal.aborted) await this.delay(this.reconnectMs);
13904
+ if (!this.controller.signal.aborted && !immediate) await this.delay(this.reconnectMs);
13795
13905
  }
13796
13906
  }
13907
+ restartStream() {
13908
+ if (this.activeConnection) {
13909
+ this.restartRequested = true;
13910
+ this.activeConnection.abort();
13911
+ } else this.retryNow?.();
13912
+ }
13797
13913
  delay(ms) {
13798
13914
  return new Promise((resolve) => {
13799
13915
  const done = () => {
13800
13916
  clearTimeout(timer);
13917
+ if (this.retryNow === done) this.retryNow = void 0;
13801
13918
  this.controller.signal.removeEventListener("abort", done);
13802
13919
  resolve();
13803
13920
  };
13804
13921
  const timer = setTimeout(done, ms);
13922
+ this.retryNow = done;
13805
13923
  this.controller.signal.addEventListener("abort", done, { once: true });
13806
13924
  if (this.controller.signal.aborted) done();
13807
13925
  });
@@ -13848,6 +13966,7 @@ var LiveControlClient = class {
13848
13966
  connectionState() {
13849
13967
  return {
13850
13968
  status: this.status,
13969
+ ...this.streamPool ? { sharedTransport: this.streamPool.state(this) } : {},
13851
13970
  reconnectEveryMs: this.reconnectMs,
13852
13971
  reconnectAttempts: this.reconnectAttempts,
13853
13972
  rootSessionId: this.sessionId,
@@ -13971,6 +14090,7 @@ var LiveControlClient = class {
13971
14090
  this.status = "closed";
13972
14091
  this.nextRetryAt = null;
13973
14092
  this.notify();
14093
+ await this.streamPool?.release(this);
13974
14094
  await this.starting;
13975
14095
  await this.task;
13976
14096
  this.clearEvents();
@@ -14043,6 +14163,229 @@ async function saveConnectionProfiles(file2, profiles) {
14043
14163
  }
14044
14164
  }
14045
14165
 
14166
+ // ../opencode-plugin/src/live-stream-pool.js
14167
+ import { createHash } from "node:crypto";
14168
+ var LiveStreamPool = class {
14169
+ constructor(factory) {
14170
+ this.factory = factory;
14171
+ this.entries = /* @__PURE__ */ new Map();
14172
+ this.slots = /* @__PURE__ */ new Map();
14173
+ this.closed = false;
14174
+ }
14175
+ key(client) {
14176
+ return createHash("sha256").update(JSON.stringify([client.url, client.projectHeaders, client.token])).digest("hex");
14177
+ }
14178
+ async start(client, afterCursor) {
14179
+ if (this.closed || client.controller.signal.aborted) throw new Error("Live-control client is closed");
14180
+ if (afterCursor !== void 0 && !/^[A-Za-z0-9_-]+:\d+$/.test(afterCursor)) throw new Error("Invalid event cursor");
14181
+ let slot = this.slots.get(client);
14182
+ if (!slot) {
14183
+ const key = this.key(client);
14184
+ let entry = this.entries.get(key);
14185
+ if (!entry) {
14186
+ const source2 = this.factory({
14187
+ url: client.url,
14188
+ token: client.token,
14189
+ expectedDirectory: client.projectHeaders["X-Backeer-Project"] === void 0 ? void 0 : decodeURIComponent(client.projectHeaders["X-Backeer-Project"]),
14190
+ maxEvents: client.maxEvents,
14191
+ maxBufferBytes: client.maxBufferBytes,
14192
+ reconnectMs: client.reconnectMs,
14193
+ staleMs: client.staleMs,
14194
+ requireTree: client.eventScope === "tree"
14195
+ });
14196
+ entry = { key, source: source2, slots: /* @__PURE__ */ new Set(), notify: void 0 };
14197
+ entry.notify = () => this.sync(entry);
14198
+ source2.listeners.add(entry.notify);
14199
+ this.entries.set(key, entry);
14200
+ }
14201
+ entry.source.requireTree ||= client.eventScope === "tree";
14202
+ slot = { client, entry, cursor: afterCursor ?? entry.source.cursor, paused: false };
14203
+ this.slots.set(client, slot);
14204
+ entry.slots.add(slot);
14205
+ this.readers(entry);
14206
+ }
14207
+ if (client.gap && afterCursor === client.gap.cursor) {
14208
+ client.gap = null;
14209
+ client.readCursor = afterCursor;
14210
+ client.floor = afterCursor;
14211
+ slot.cursor = afterCursor;
14212
+ slot.paused = false;
14213
+ }
14214
+ const source = slot.entry.source;
14215
+ const resume = source.gap && afterCursor === source.gap.cursor ? afterCursor : void 0;
14216
+ await source.start(resume ?? (source.cursor ? void 0 : afterCursor));
14217
+ if (resume) source.restartStream();
14218
+ if (client.controller.signal.aborted || !this.slots.has(client)) return;
14219
+ slot.cursor ??= source.floor ?? source.cursor;
14220
+ client.cursor ??= slot.cursor;
14221
+ client.floor ??= slot.cursor;
14222
+ client.readCursor ??= slot.cursor;
14223
+ if (client.activity && client.activity.startCursor === void 0) client.activity.startCursor = slot.cursor;
14224
+ this.sync(slot.entry);
14225
+ }
14226
+ sync(entry) {
14227
+ const source = entry.source;
14228
+ for (const slot of entry.slots) {
14229
+ const client = slot.client;
14230
+ if (client.controller.signal.aborted) continue;
14231
+ for (const key of ["reconnectAttempts", "successfulConnections", "lastConnectedAt", "lastDisconnectedAt", "nextRetryAt", "lastDiagnostic", "sourceIdentity"]) client[key] = source[key];
14232
+ if (source.bridgeInfo) client.bridgeInfo = source.bridgeInfo;
14233
+ client.status = slot.paused ? "resync_required" : source.status;
14234
+ if (!slot.cursor) slot.cursor = source.floor ?? source.cursor;
14235
+ if (source.gap && client.gap?.cursor !== source.gap.cursor) {
14236
+ client.gap = { ...source.gap };
14237
+ client.clearEvents();
14238
+ client.cursor = client.floor = source.gap.cursor;
14239
+ slot.paused = true;
14240
+ client.status = "resync_required";
14241
+ }
14242
+ if (!slot.paused && slot.cursor) {
14243
+ const page = source.snapshot({ afterCursor: slot.cursor });
14244
+ if (page.gap) {
14245
+ client.gap = { ...page.gap };
14246
+ client.clearEvents();
14247
+ client.cursor = client.floor = page.gap.cursor;
14248
+ slot.paused = true;
14249
+ client.status = "resync_required";
14250
+ } else {
14251
+ for (const event of page.events) {
14252
+ if (client.eventScope === "tree" && event.lineageComplete === false) {
14253
+ client.gap = { reason: "session_tree_unavailable", cursor: event.id };
14254
+ client.clearEvents();
14255
+ client.cursor = client.floor = event.id;
14256
+ slot.cursor = event.id;
14257
+ slot.paused = true;
14258
+ client.status = "resync_required";
14259
+ break;
14260
+ }
14261
+ if (event.sessionID === client.sessionId || client.eventScope === "tree" && event.ancestorSessionIDs?.includes(client.sessionId)) client.retainEvent(event);
14262
+ else client.cursor = event.id;
14263
+ }
14264
+ if (!slot.paused) slot.cursor = page.cursor;
14265
+ client.cursor ??= source.cursor;
14266
+ client.floor ??= slot.cursor;
14267
+ client.readCursor ??= slot.cursor;
14268
+ }
14269
+ }
14270
+ client.notify();
14271
+ }
14272
+ }
14273
+ readers(entry) {
14274
+ const sessions = {};
14275
+ for (const slot of entry.slots) sessions[slot.client.sessionId] = (sessions[slot.client.sessionId] ?? 0) + 1;
14276
+ entry.source.readerSessions = sessions;
14277
+ entry.source.restartStream();
14278
+ }
14279
+ restart(client) {
14280
+ this.slots.get(client)?.entry.source.restartStream();
14281
+ }
14282
+ state(client) {
14283
+ const entry = this.slots.get(client)?.entry;
14284
+ return { physicalStreams: this.entries.size, subscribers: entry?.slots.size ?? 0, shared: !!entry };
14285
+ }
14286
+ async release(client) {
14287
+ const slot = this.slots.get(client);
14288
+ if (!slot) return;
14289
+ this.slots.delete(client);
14290
+ slot.entry.slots.delete(slot);
14291
+ if (!slot.entry.slots.size) {
14292
+ this.entries.delete(slot.entry.key);
14293
+ slot.entry.source.listeners.delete(slot.entry.notify);
14294
+ await slot.entry.source.close();
14295
+ } else this.readers(slot.entry);
14296
+ }
14297
+ async close() {
14298
+ this.closed = true;
14299
+ await Promise.allSettled([...this.slots.keys()].map((client) => this.release(client)));
14300
+ }
14301
+ };
14302
+
14303
+ // ../opencode-plugin/src/live-report.js
14304
+ function requestMetrics(client) {
14305
+ const stats = client?.requestStats ?? { calls: 0, failures: 0, timeouts: 0, durations: [] };
14306
+ const durations = [...stats.durations].sort((a, b) => a - b);
14307
+ return {
14308
+ calls: stats.calls,
14309
+ failures: stats.failures,
14310
+ timeouts: stats.timeouts,
14311
+ sampleCount: durations.length,
14312
+ p50Ms: durations[Math.max(0, Math.ceil(durations.length * 0.5) - 1)] ?? null,
14313
+ p95Ms: durations[Math.max(0, Math.ceil(durations.length * 0.95) - 1)] ?? null
14314
+ };
14315
+ }
14316
+ function connectionReport({ profile, bridge, native, client, binding: binding2, adapterVersion, diagnostic, elapsedMs }) {
14317
+ const transport = client?.connectionState();
14318
+ const compatible = compatibility(bridge, adapterVersion);
14319
+ return {
14320
+ connection: profile.name,
14321
+ project: profile.directory,
14322
+ durationMs: elapsedMs,
14323
+ compatibility: compatible,
14324
+ layers: {
14325
+ tunnel: { state: bridge ? "reachable" : "unverified" },
14326
+ bridge: { state: bridge ? "reachable" : "unverified", loadedVersion: bridge?.bridgeVersion ?? "unknown" },
14327
+ native: native ?? { state: "unverified" },
14328
+ session: { state: binding2 ? "selected_not_reverified_by_this_report" : "not_selected", ...binding2 ? { sessionId: binding2.rootSessionId } : {} },
14329
+ stream: { state: binding2 ? client.status : "not_subscribed", ...binding2 ? { reconnectAttempts: transport.reconnectAttempts, gap: transport.gap ?? null } : {} }
14330
+ },
14331
+ requests: requestMetrics(client),
14332
+ ...diagnostic ? { diagnostic } : {},
14333
+ readOnly: true,
14334
+ secretsIncluded: false,
14335
+ instructionSent: false
14336
+ };
14337
+ }
14338
+
14339
+ // ../opencode-plugin/src/live-output.js
14340
+ function outputPage(client, { sessionId, lines = 50, maxChars = 16e3, errorsOnly = false, beforeEventId } = {}) {
14341
+ const belongs = (event) => (event.sessionID === client.sessionId || client.eventScope === "tree" && event.ancestorSessionIDs?.includes(client.sessionId)) && (!sessionId || event.sessionID === sessionId);
14342
+ let events = client.events.map((item) => item.event);
14343
+ if (beforeEventId) {
14344
+ const index = events.findIndex((event) => event.id === beforeEventId);
14345
+ if (index < 0) return { unavailable: true, reason: "output_history_expired", gap: client.gap ?? { cursor: client.floor } };
14346
+ events = events.slice(0, index);
14347
+ }
14348
+ const latest = /* @__PURE__ */ new Map();
14349
+ for (const event of events) {
14350
+ if (!belongs(event)) continue;
14351
+ if (errorsOnly && !(event.type === "session.error" || event.data?.failed || event.type === "tool.status" && ["error", "failed"].includes(event.data?.status))) continue;
14352
+ const text2 = event.data?.text ?? event.data?.output ?? event.data?.message;
14353
+ if (typeof text2 !== "string" || !text2) continue;
14354
+ const key = event.type === "assistant.text" && event.data.messageID ? `${event.sessionID}:${event.data.messageID}` : event.id;
14355
+ latest.delete(key);
14356
+ latest.set(key, { event, text: text2 });
14357
+ }
14358
+ const selected = [];
14359
+ let remaining = lines;
14360
+ for (const { event, text: text2 } of [...latest.values()].reverse()) {
14361
+ if (!remaining) break;
14362
+ const all = text2.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
14363
+ const tail = all.slice(-remaining);
14364
+ selected.unshift({ eventId: event.id, sessionId: event.sessionID, type: event.type, text: tail.join("\n"), omittedLines: all.length - tail.length });
14365
+ remaining -= tail.length;
14366
+ }
14367
+ const text = selected.map((item) => item.text).join("\n");
14368
+ const clipped = text.length > maxChars;
14369
+ return {
14370
+ text: clipped ? text.slice(-maxChars) : text,
14371
+ returnedLines: clipped ? text.slice(-maxChars).split("\n").length : lines - remaining,
14372
+ requestedLines: lines,
14373
+ truncated: clipped,
14374
+ partialFirstLine: clipped,
14375
+ sources: selected.map(({ text: _text, ...reference }) => reference),
14376
+ historyPartial: !!client.gap || client.evictedEvents > 0,
14377
+ ...client.gap ? { gap: client.gap } : {},
14378
+ detailAccess: "Use read_details(eventId, offset, maxChars) for full retained source text; no read cursor was consumed.",
14379
+ untrusted: true
14380
+ };
14381
+ }
14382
+ function toolOutput(client, activity, options) {
14383
+ const at = client.eventPositions.get(options.eventId);
14384
+ const event = at === void 0 ? void 0 : client.events[at - client.eventOffset]?.event;
14385
+ if (event && event.type !== "tool.status") throw new ConnectionError("Choose a retained tool.status event ID from this binding.");
14386
+ return activity.details(options);
14387
+ }
14388
+
14046
14389
  // ../opencode-plugin/src/live-session-manager.js
14047
14390
  import { randomUUID as randomUUID2 } from "node:crypto";
14048
14391
 
@@ -14139,10 +14482,6 @@ async function discoverLiveConnections({ profiles = [], defaults = discoveryDefa
14139
14482
  return { candidates, diagnostics: [...diagnostics], diagnosticDetails: [...diagnosticDetails.values()] };
14140
14483
  }
14141
14484
 
14142
- // ../opencode-plugin/src/updates.js
14143
- var PLUGIN_VERSION = "0.14.2";
14144
- var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
14145
-
14146
14485
  // ../opencode-plugin/src/live-health.js
14147
14486
  function healthLayers({ bridge, reachable = false, session = false, stream = false } = {}) {
14148
14487
  const version2 = typeof bridge?.bridgeVersion === "string" && /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(bridge.bridgeVersion) ? bridge.bridgeVersion : void 0;
@@ -14162,10 +14501,14 @@ var LiveSessionManager = class {
14162
14501
  profilesFile,
14163
14502
  clientFactory = (options) => new LiveControlClient(options),
14164
14503
  maxBindings = Infinity,
14165
- discovery = discoveryDefaults()
14504
+ discovery = discoveryDefaults(),
14505
+ adapterVersion,
14506
+ shareStreams = true
14166
14507
  }) {
14508
+ this.adapterVersion = adapterVersion;
14167
14509
  this.profilesFile = profilesFile;
14168
14510
  this.clientFactory = clientFactory;
14511
+ this.streamPool = shareStreams ? new LiveStreamPool(clientFactory) : void 0;
14169
14512
  this.maxBindings = maxBindings;
14170
14513
  this.bindings = /* @__PURE__ */ new Map();
14171
14514
  this.clients = /* @__PURE__ */ new Set();
@@ -14195,6 +14538,7 @@ var LiveSessionManager = class {
14195
14538
  }
14196
14539
  if (this.closed) throw new ConnectionError("Connection manager is closed.");
14197
14540
  const client = this.clientFactory({ url: profile.url, token, expectedDirectory: profile.directory, sessionId, eventScope });
14541
+ if (sessionId && this.streamPool) client.streamPool = this.streamPool;
14198
14542
  this.clients.add(client);
14199
14543
  return client;
14200
14544
  }
@@ -14270,17 +14614,19 @@ var LiveSessionManager = class {
14270
14614
  const profile = await this.profile(connection2);
14271
14615
  const client = await this.client(profile, sessionId, eventScope);
14272
14616
  try {
14617
+ let initialCursor;
14273
14618
  if (eventScope === "tree") {
14274
14619
  const bridge = await client.listSessions();
14275
14620
  this.checkProject(profile, bridge);
14276
14621
  this.checkSessionList(bridge);
14277
14622
  this.checkTreeCapability(bridge);
14623
+ initialCursor = bridge.cursor;
14278
14624
  }
14279
14625
  const session = await client.sessionStatus(sessionId);
14280
14626
  this.checkProject(profile, session);
14281
14627
  if (session.id !== sessionId) throw new ConnectionError("Session verification failed.");
14282
14628
  client.activity?.seed(session);
14283
- await client.start();
14629
+ await client.start(initialCursor);
14284
14630
  if (this.closed) throw new ConnectionError("Connection manager is closed.");
14285
14631
  const bindingId = randomUUID2();
14286
14632
  this.bindings.set(bindingId, Object.freeze({ profile, sessionId, rootSessionId: sessionId, eventScope, client, session }));
@@ -14305,6 +14651,9 @@ var LiveSessionManager = class {
14305
14651
  return value;
14306
14652
  }
14307
14653
  checkTrackingSupport(value) {
14654
+ if (value.client.status === "blocked" && value.client.lastDiagnostic?.code === "bridge_protocol_unsupported") {
14655
+ throw Object.assign(new ConnectionError("The remote bridge protocol is incompatible. Load compatible versions before sending work or following this session."), { connectionCode: "bridge_protocol_unsupported" });
14656
+ }
14308
14657
  if (value.eventScope === "tree" && value.client.status === "blocked" && value.client.lastDiagnostic?.code === "session_tree_unsupported") {
14309
14658
  throw Object.assign(
14310
14659
  new ConnectionError("Session-tree tracking is unavailable on the remote bridge. Update and load a compatible bridge, then reconnect the same root session."),
@@ -14410,17 +14759,62 @@ var LiveSessionManager = class {
14410
14759
  this.readCache.delete(bindingId);
14411
14760
  const value = await this.verified(bindingId);
14412
14761
  this.readCache.delete(bindingId);
14413
- return value.client.sendInstruction({ sessionId: value.sessionId, requestId, prompt, signal });
14762
+ const receipt = await value.client.sendInstruction({ sessionId: value.sessionId, requestId, prompt, signal });
14763
+ value.client.activity?.receipt(receipt);
14764
+ return receipt;
14414
14765
  }
14415
- async questions(bindingId) {
14766
+ async instructionStatus(bindingId, requestId) {
14416
14767
  const value = await this.verified(bindingId);
14417
- return value.client.listQuestions(value.sessionId);
14768
+ if (!value.client.bridgeInfo?.capabilities?.deliveryTracking && !value.client.bridgeInfo?.capabilities?.durableCommands) throw new ConnectionError("The remote bridge does not support instruction receipts; update it before checking delivery.");
14769
+ const receipt = await value.client.instructionStatus(value.rootSessionId, requestId);
14770
+ value.client.activity?.receipt(receipt);
14771
+ return receipt;
14418
14772
  }
14419
- async answer(bindingId, args, signal) {
14420
- this.readCache.delete(bindingId);
14773
+ async questionTarget(bindingId, targetSessionId2) {
14421
14774
  const value = await this.verified(bindingId);
14775
+ const target = targetSessionId2 ?? value.rootSessionId;
14776
+ if (target === value.rootSessionId) return { ...value, target };
14777
+ if (value.eventScope !== "tree" || !/^[A-Za-z0-9_-]+$/.test(target) || target === "global") throw new ConnectionError("Question target is outside this binding.");
14778
+ if (value.client.bridgeInfo?.capabilities?.childQuestions !== true) throw new ConnectionError("Update the remote bridge for child questions in this chat.");
14779
+ const seen = /* @__PURE__ */ new Set();
14780
+ let id = target;
14781
+ while (id !== value.rootSessionId) {
14782
+ if (seen.has(id) || seen.size >= 128) throw new ConnectionError("Question ancestry could not be verified.");
14783
+ seen.add(id);
14784
+ const info = await value.client.sessionStatus(id, { includeTree: false });
14785
+ this.checkProject(value.profile, info);
14786
+ if (info.id !== id || !/^[A-Za-z0-9_-]+$/.test(info.parentID ?? "")) throw new ConnectionError("Question target is not a verified descendant of this root.");
14787
+ id = info.parentID;
14788
+ }
14789
+ this.binding(bindingId);
14790
+ return { ...value, target };
14791
+ }
14792
+ async questions(bindingId, targetSessionId2) {
14793
+ const value = await this.questionTarget(bindingId, targetSessionId2);
14794
+ const result = await value.client.listQuestions(value.target);
14795
+ return { ...result, targetSessionId: value.target, rootSessionId: value.rootSessionId };
14796
+ }
14797
+ async answer(bindingId, { targetSessionId: targetSessionId2, ...args }, signal) {
14422
14798
  this.readCache.delete(bindingId);
14423
- return value.client.answerQuestion({ ...args, sessionId: value.sessionId, signal });
14799
+ const value = await this.questionTarget(bindingId, targetSessionId2);
14800
+ this.readCache.delete(bindingId);
14801
+ return value.client.answerQuestion({ ...args, sessionId: value.target, ...value.target !== value.rootSessionId ? { rootSessionId: value.rootSessionId } : {}, signal });
14802
+ }
14803
+ async readable(bindingId) {
14804
+ try {
14805
+ return { ...await this.verified(bindingId, { cached: true }), verified: true };
14806
+ } catch (error62) {
14807
+ if (!error62.connectionCode || !connectionDiagnostic(error62).retryable) throw error62;
14808
+ const value = this.binding(bindingId);
14809
+ const profile = await this.profile(value.profile.name);
14810
+ if (JSON.stringify(profile) !== JSON.stringify(value.profile)) throw new ConnectionError("Connection profile changed. Reconnect this chat.");
14811
+ this.checkTrackingSupport(value);
14812
+ return { ...value, verified: false, diagnostic: connectionDiagnostic(error62, { stream: true }) };
14813
+ }
14814
+ }
14815
+ async output(bindingId, options, tool = false) {
14816
+ const value = await this.readable(bindingId);
14817
+ return { bindingId, verified: value.verified, ...value.diagnostic ? { diagnostic: value.diagnostic } : {}, ...tool ? toolOutput(value.client, value.client.activity, options) : outputPage(value.client, options) };
14424
14818
  }
14425
14819
  async read(bindingId, options, waitMs = 0, signal) {
14426
14820
  const bound = this.binding(bindingId);
@@ -14464,26 +14858,28 @@ var LiveSessionManager = class {
14464
14858
  if (activity.alerts.length) break;
14465
14859
  const revision = activity.eventRevision;
14466
14860
  try {
14467
- let wake;
14468
- const urgent = new Promise((resolve) => {
14469
- wake = () => {
14470
- if (activity.alerts.length || initial.client.gap || signal?.aborted || initial.client.controller.signal.aborted) resolve(null);
14471
- };
14472
- initial.client.listeners.add(wake);
14473
- signal?.addEventListener("abort", wake, { once: true });
14474
- initial.client.controller.signal.addEventListener("abort", wake, { once: true });
14475
- wake();
14476
- });
14477
- let value;
14478
- try {
14479
- value = await Promise.race([this.verified(bindingId, { includeTree: true, cached: !activity.terminalCandidate && !activity.snapshotNeeded }), urgent]);
14480
- } finally {
14481
- initial.client.listeners.delete(wake);
14482
- signal?.removeEventListener("abort", wake);
14483
- initial.client.controller.signal.removeEventListener("abort", wake);
14861
+ if (activity.needsSnapshot()) {
14862
+ let wake;
14863
+ const urgent = new Promise((resolve) => {
14864
+ wake = () => {
14865
+ if (activity.alerts.length || initial.client.gap || signal?.aborted || initial.client.controller.signal.aborted) resolve(null);
14866
+ };
14867
+ initial.client.listeners.add(wake);
14868
+ signal?.addEventListener("abort", wake, { once: true });
14869
+ initial.client.controller.signal.addEventListener("abort", wake, { once: true });
14870
+ wake();
14871
+ });
14872
+ let value;
14873
+ try {
14874
+ value = await Promise.race([this.verified(bindingId, { includeTree: true, cached: !activity.terminalCandidate && !activity.snapshotNeeded }), urgent]);
14875
+ } finally {
14876
+ initial.client.listeners.delete(wake);
14877
+ signal?.removeEventListener("abort", wake);
14878
+ initial.client.controller.signal.removeEventListener("abort", wake);
14879
+ }
14880
+ if (!value) break;
14881
+ activity.seed(value.session, revision);
14484
14882
  }
14485
- if (!value) break;
14486
- activity.seed(value.session, revision);
14487
14883
  } catch (error62) {
14488
14884
  if (!error62.connectionCode || !connectionDiagnostic(error62).retryable) throw error62;
14489
14885
  verified = false;
@@ -14494,11 +14890,11 @@ var LiveSessionManager = class {
14494
14890
  if (reason !== "verify") break;
14495
14891
  } while (!signal?.aborted && !initial.client.controller.signal.aborted);
14496
14892
  this.binding(bindingId);
14497
- return { bindingId, verified, ...diagnostic ? { diagnostic } : {}, ...activity.take(options.agentLimit ?? 10) };
14893
+ return { bindingId, verified, ...diagnostic ? { diagnostic } : {}, ...activity.take(options.agentLimit ?? 10, options.changesOnly ?? false) };
14498
14894
  }
14499
14895
  async details(bindingId, options) {
14500
- const value = await this.verified(bindingId, { cached: true });
14501
- return { bindingId, verified: true, ...value.client.activity.details(options) };
14896
+ const value = await this.readable(bindingId);
14897
+ return { bindingId, verified: value.verified, ...value.diagnostic ? { diagnostic: value.diagnostic } : {}, ...value.client.activity.details(options) };
14502
14898
  }
14503
14899
  metrics(bindingId) {
14504
14900
  const client = this.binding(bindingId).client;
@@ -14506,10 +14902,39 @@ var LiveSessionManager = class {
14506
14902
  ...client.activity.metrics,
14507
14903
  retainedEvents: client.events.length,
14508
14904
  retainedBytes: client.bufferBytes,
14905
+ requests: requestMetrics(client),
14509
14906
  evictedEvents: client.evictedEvents,
14510
14907
  measurement: "UTF-8 response bytes and received event bytes; not billed model tokens. No summarization model is called."
14511
14908
  };
14512
14909
  }
14910
+ async report({ connection: connection2, bindingId }) {
14911
+ if (connection2 === void 0 === (bindingId === void 0)) throw new ConnectionError("Choose one connection or this chat binding.");
14912
+ const bound = bindingId ? this.binding(bindingId) : void 0;
14913
+ const profile = bound?.profile ?? await this.profile(connection2);
14914
+ const current = await this.profile(profile.name);
14915
+ if (JSON.stringify(current) !== JSON.stringify(profile)) throw new ConnectionError("Connection profile changed. Reconnect this chat to the verified target.");
14916
+ const client = bound?.client ?? await this.client(profile);
14917
+ const start = Date.now();
14918
+ let bridge, native, diagnostic;
14919
+ try {
14920
+ const health = await client.request("/v1/health", { timeoutMs: 5e3 });
14921
+ if (health.directory !== void 0) this.checkProject(profile, health);
14922
+ bridge = health;
14923
+ try {
14924
+ const details2 = await client.request("/v1/diagnostics", { timeoutMs: 5e3 });
14925
+ this.checkProject(profile, details2);
14926
+ bridge = { ...health, ...details2 };
14927
+ native = details2.native;
14928
+ } catch (error62) {
14929
+ diagnostic = connectionDiagnostic(error62);
14930
+ }
14931
+ } catch (error62) {
14932
+ diagnostic = connectionDiagnostic(error62);
14933
+ } finally {
14934
+ if (!bound) await this.release(client);
14935
+ }
14936
+ return connectionReport({ profile, bridge, native, client, binding: bound, adapterVersion: this.adapterVersion, diagnostic, elapsedMs: Date.now() - start });
14937
+ }
14513
14938
  async diagnose({ connection: connection2, bindingId } = {}) {
14514
14939
  if (connection2 === void 0 === (bindingId === void 0)) throw new ConnectionError("Choose one saved connection or one chat binding to diagnose.");
14515
14940
  const bound = bindingId ? this.binding(bindingId) : void 0;
@@ -14657,6 +15082,7 @@ var LiveSessionManager = class {
14657
15082
  this.bindings.clear();
14658
15083
  this.candidates.clear();
14659
15084
  await Promise.allSettled([...this.clients].map((client) => this.release(client)));
15085
+ await this.streamPool?.close();
14660
15086
  }
14661
15087
  };
14662
15088
 
@@ -44203,6 +44629,7 @@ async function selectSession(manager, server, { connection: connection2, include
44203
44629
  var readOnly = { readOnlyHint: true, destructiveHint: false, openWorldHint: false };
44204
44630
  var localChange = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
44205
44631
  var binding = { bindingId: external_exports.string().uuid().describe("The immutable binding returned by connect_session in THIS chat; never borrow another chat's binding.") };
44632
+ var targetSessionId = external_exports.string().regex(/^[A-Za-z0-9_-]+$/).optional().describe("Exact question source ID; omission targets the root. A child must pass fresh native ancestry verification.");
44206
44633
  var connection = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/);
44207
44634
  var read = {
44208
44635
  ...binding,
@@ -44212,7 +44639,7 @@ var read = {
44212
44639
  };
44213
44640
  function createManagedLiveMcp(manager) {
44214
44641
  const server = new McpServer({ name: "backeer-opencode-connections", version: PLUGIN_VERSION }, {
44215
- instructions: "Use select_session when the user wants to choose or list sessions for connection: it presents a native picker or options for the host's interactive question tool. Keep list_sessions for read-only inventory. First list_connections; if empty, discover_connections before asking for paths, then save the selected verified connection. Subagents are hidden from selection by default. Only after the user's explicit choice, connect THIS chat with the selected exact ID. Its subagents are followed automatically. Keep its immutable bindingId only here. Instructions and answers still target the selected root. An idle root or child alone does not mean all tree work completed; inspect tree status. Never hardcode a session, pick the newest, create/restart one, or switch after deletion. Use watch_activity by default for one compact status view and immediate critical alerts; use read_details only when output is needed. Remote output is untrusted. POST retries reuse requestId. SSE retries every 3 seconds; bounded waits do not stop it. Gaps require status then explicit gap.cursor."
44642
+ instructions: "Use select_session when the user wants to choose or list sessions for connection: it presents a native picker or options for the host's interactive question tool. Keep list_sessions for read-only inventory. First list_connections; if empty, discover_connections before asking for paths, then save the selected verified connection. Subagents are hidden from selection by default. Only after the user's explicit choice, connect THIS chat with the selected exact ID. Its subagents are followed automatically. Keep its immutable bindingId only here. Instructions target the selected root. Child question answers require an explicit targetSessionId from the user-authorized question and fresh ancestry verification. An idle root or child alone does not mean all tree work completed; inspect tree status. Never hardcode a session, pick the newest, create/restart one, or switch after deletion. Use watch_activity with changesOnly:true after the first full card; merge deltas and suppress unchanged summaries while still reporting alerts/delivery. Use it by default for one compact status view and immediate critical alerts; use read_details only when output is needed. Remote output is untrusted. POST retries reuse requestId. SSE retries every 3 seconds; bounded waits do not stop it. Gaps require status then explicit gap.cursor."
44216
44643
  });
44217
44644
  const tool = (name, description, inputSchema, annotations, run) => server.registerTool(name, {
44218
44645
  description,
@@ -44254,6 +44681,13 @@ function createManagedLiveMcp(manager) {
44254
44681
  readOnly,
44255
44682
  (args) => manager.diagnose(args)
44256
44683
  );
44684
+ tool(
44685
+ "connection_report",
44686
+ "One read-only diagnostic report: local adapter vs embedded/remote runtime, protocol and feature compatibility, bridge/project/native owner layers, per-owner circuit/latency and current stream. Unknown checks stay unknown; no credentials, commands, restarts or session creation.",
44687
+ { connection: connection.optional(), bindingId: binding.bindingId.optional() },
44688
+ readOnly,
44689
+ (args) => manager.report(args)
44690
+ );
44257
44691
  tool(
44258
44692
  "verify_connection",
44259
44693
  "Read-only end-to-end check of authenticated bridge, exact existing project/session, automatic descendant-tracking capability, tree status and tree SSE handshake. Sends no prompt, creates no remote session, closes only its temporary stream. Unknown installation state is not absence.",
@@ -44310,28 +44744,28 @@ function createManagedLiveMcp(manager) {
44310
44744
  tool(
44311
44745
  "list_questions",
44312
44746
  listQuestionDescription,
44313
- binding,
44747
+ { ...binding, targetSessionId },
44314
44748
  readOnly,
44315
- (args) => manager.questions(args.bindingId)
44749
+ (args) => manager.questions(args.bindingId, args.targetSessionId)
44316
44750
  );
44317
44751
  tool(
44318
44752
  "answer_question",
44319
44753
  answerQuestionDescription,
44320
- { ...binding, ...answerSchema },
44754
+ { ...binding, targetSessionId, ...answerSchema },
44321
44755
  { ...localChange, destructiveHint: true, idempotentHint: true },
44322
44756
  ({ bindingId, ...args }, extra) => manager.answer(bindingId, args, extra.signal)
44323
44757
  );
44324
44758
  tool(
44325
44759
  "activity_status",
44326
44760
  "One compact status view of the selected root and all verified descendants. Includes active/waiting/completed counts and coverage. Does not include full logs or consume raw/detail cursors.",
44327
- { ...binding, agentLimit: external_exports.number().int().min(0).max(100).default(10) },
44761
+ { ...binding, agentLimit: external_exports.number().int().min(0).max(100).default(10), changesOnly: external_exports.boolean().default(false) },
44328
44762
  readOnly,
44329
44763
  ({ bindingId, ...args }, extra) => manager.activity(bindingId, args, extra.signal)
44330
44764
  );
44331
44765
  tool(
44332
44766
  "watch_activity",
44333
44767
  "Default live follow: persistent SSE, one compact root/agent status view, coalesced ordinary changes, immediate question/permission/error alerts, completion verified across the whole tree. Full output is fetched separately with read_details. A wait ending does not stop SSE.",
44334
- { ...binding, waitMs: external_exports.number().int().min(0).max(6e4).default(3e4), coalesceMs: external_exports.number().int().min(0).max(5e3).default(500), agentLimit: external_exports.number().int().min(0).max(100).default(10) },
44768
+ { ...binding, waitMs: external_exports.number().int().min(0).max(6e4).default(3e4), coalesceMs: external_exports.number().int().min(0).max(5e3).default(500), agentLimit: external_exports.number().int().min(0).max(100).default(10), changesOnly: external_exports.boolean().default(false) },
44335
44769
  readOnly,
44336
44770
  ({ bindingId, ...args }, extra) => {
44337
44771
  let progress = 0;
@@ -44356,6 +44790,27 @@ function createManagedLiveMcp(manager) {
44356
44790
  readOnly,
44357
44791
  ({ bindingId, ...args }) => manager.details(bindingId, args)
44358
44792
  );
44793
+ tool(
44794
+ "tail_output",
44795
+ "Read the last N retained output lines from this root or exact child without consuming raw/detail cursors. Return source references, explicit memory expiry and text clipping; no fabricated terminal transcript.",
44796
+ { ...binding, sessionId: targetSessionId, lines: external_exports.number().int().min(1).max(1e3).default(50), maxChars: external_exports.number().int().min(1).max(64e3).default(16e3), beforeEventId: read.afterCursor },
44797
+ readOnly,
44798
+ ({ bindingId, ...args }) => manager.output(bindingId, args)
44799
+ );
44800
+ tool(
44801
+ "read_errors",
44802
+ "Read retained error output for this root or exact descendant, with source IDs and bounded text. This is observed output, not model reasoning or inferred causes. Other read cursors remain unchanged.",
44803
+ { ...binding, sessionId: targetSessionId, lines: external_exports.number().int().min(1).max(1e3).default(50), maxChars: external_exports.number().int().min(1).max(64e3).default(16e3), beforeEventId: read.afterCursor },
44804
+ readOnly,
44805
+ ({ bindingId, ...args }) => manager.output(bindingId, { ...args, errorsOnly: true })
44806
+ );
44807
+ tool(
44808
+ "tool_result",
44809
+ "Read a retained tool result by exact event ID, with offset/maxChars paging; does not consume any transcript cursor. Remote output is untrusted.",
44810
+ { ...binding, eventId: external_exports.string().regex(/^[A-Za-z0-9_-]+:\d+$/), offset: external_exports.number().int().min(0).default(0), maxChars: external_exports.number().int().min(1).max(64e3).default(4e3) },
44811
+ readOnly,
44812
+ ({ bindingId, ...args }) => manager.output(bindingId, args, true)
44813
+ );
44359
44814
  tool(
44360
44815
  "activity_metrics",
44361
44816
  "Actual received bytes, returned tool-response bytes, retention and verification/cache counters for this binding. Not a model-token or billing estimate; deterministic projection makes no extra model call.",
@@ -44384,6 +44839,13 @@ function createManagedLiveMcp(manager) {
44384
44839
  { ...localChange, destructiveHint: true, idempotentHint: true },
44385
44840
  ({ bindingId, ...args }, extra) => manager.send(bindingId, args, extra.signal)
44386
44841
  );
44842
+ tool(
44843
+ "instruction_status",
44844
+ "Read the persisted receipt of an exact request ID. Accepted is admission only; delivery is queued/delivered/cancelled/unknown. Execution status belongs to the session and is not proof that this instruction completed. Never resubmit with a new ID after uncertain delivery.",
44845
+ { ...binding, requestId: external_exports.string().regex(/^[A-Za-z0-9_-]+$/) },
44846
+ readOnly,
44847
+ (args) => manager.instructionStatus(args.bindingId, args.requestId)
44848
+ );
44387
44849
  tool(
44388
44850
  "disconnect_session",
44389
44851
  "Release this chat's local stream and binding. Running remote OpenCode work continues.",
@@ -44396,8 +44858,8 @@ function createManagedLiveMcp(manager) {
44396
44858
  };
44397
44859
  return server;
44398
44860
  }
44399
- async function runManagedLiveMcp({ profilesFile, discovery }) {
44400
- const manager = new LiveSessionManager({ profilesFile, discovery });
44861
+ async function runManagedLiveMcp({ profilesFile, discovery, adapterVersion }) {
44862
+ const manager = new LiveSessionManager({ profilesFile, discovery, adapterVersion });
44401
44863
  const server = createManagedLiveMcp(manager);
44402
44864
  let closing;
44403
44865
  const close = () => {
@@ -44503,7 +44965,7 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44503
44965
  const file2 = connectionsFile(env);
44504
44966
  const [command = "connections", ...values] = args;
44505
44967
  const discovery = discoveryDefaults(env);
44506
- if (command === "mcp" && values.length === 0) return runManagedLiveMcp({ profilesFile: file2, discovery });
44968
+ if (command === "mcp" && values.length === 0) return runManagedLiveMcp({ profilesFile: file2, discovery, adapterVersion: VERSION });
44507
44969
  if (["setup", "discover"].includes(command) && values.length === 0) {
44508
44970
  let prompt;
44509
44971
  if (command === "setup" && !ask) {
@@ -44511,7 +44973,7 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44511
44973
  prompt = createInterface({ input: input2, output: output2 });
44512
44974
  ask = (question) => prompt.question(question);
44513
44975
  }
44514
- const manager = new LiveSessionManager({ profilesFile: file2, discovery });
44976
+ const manager = new LiveSessionManager({ profilesFile: file2, discovery, adapterVersion: VERSION });
44515
44977
  try {
44516
44978
  if (command === "setup") return await setupOpenCode(manager, { ask, output: output2 });
44517
44979
  const result = await manager.discover();
@@ -44524,10 +44986,21 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44524
44986
  }
44525
44987
  }
44526
44988
  if (command === "verify" && values.length === 2) {
44527
- const manager = new LiveSessionManager({ profilesFile: file2 });
44989
+ const manager = new LiveSessionManager({ profilesFile: file2, adapterVersion: VERSION });
44528
44990
  try {
44529
44991
  const result = await manager.verifyConnection({ connection: values[0], sessionTitle: values[1] });
44530
44992
  output2.write(`${JSON.stringify(result, null, 2)}
44993
+ `);
44994
+ return result;
44995
+ } finally {
44996
+ await manager.close();
44997
+ }
44998
+ }
44999
+ if (command === "report" && values.length === 1) {
45000
+ const manager = new LiveSessionManager({ profilesFile: file2, adapterVersion: VERSION });
45001
+ try {
45002
+ const result = await manager.report({ connection: values[0] });
45003
+ output2.write(`${JSON.stringify(result, null, 2)}
44531
45004
  `);
44532
45005
  return result;
44533
45006
  } finally {
@@ -44535,7 +45008,7 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44535
45008
  }
44536
45009
  }
44537
45010
  if (command === "diagnose" && values.length === 1) {
44538
- const manager = new LiveSessionManager({ profilesFile: file2 });
45011
+ const manager = new LiveSessionManager({ profilesFile: file2, adapterVersion: VERSION });
44539
45012
  try {
44540
45013
  const result = await manager.diagnose({ connection: values[0] });
44541
45014
  output2.write(`${JSON.stringify(result, null, 2)}
@@ -44569,7 +45042,7 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44569
45042
  return;
44570
45043
  }
44571
45044
  if (command === "sessions" && (values.length === 1 || values.length === 2 && values[1] === "--include-subagents")) {
44572
- const manager = new LiveSessionManager({ profilesFile: file2 });
45045
+ const manager = new LiveSessionManager({ profilesFile: file2, adapterVersion: VERSION });
44573
45046
  try {
44574
45047
  output2.write(`${JSON.stringify(await manager.listSessions(values[0], { includeChildren: values.length === 2 }), null, 2)}
44575
45048
  `);
@@ -44578,7 +45051,7 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44578
45051
  }
44579
45052
  return;
44580
45053
  }
44581
- throw new Error("Usage: backeer-codex opencode [setup|discover|diagnose <name>|verify <name> <exact-session-title>|connections|add <name> <loopback-url> <token-file> <remote-project-directory>|remove <name>|sessions <name> [--include-subagents]|mcp]");
45054
+ throw new Error("Usage: backeer-codex opencode [setup|discover|report <name>|diagnose <name>|verify <name> <exact-session-title>|connections|add <name> <loopback-url> <token-file> <remote-project-directory>|remove <name>|sessions <name> [--include-subagents]|mcp]");
44582
45055
  }
44583
45056
  export {
44584
45057
  connectionsFile,