backeer-codex 0.11.0 → 0.12.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.12.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,31 @@ 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.15.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
+
12987
+ // ../opencode-plugin/src/live-timeouts.js
12988
+ var LIVE_REQUEST_TIMEOUT_MS = 45e3;
12989
+
12962
12990
  // ../opencode-plugin/src/live-control-client.js
12963
12991
  import { constants } from "node:fs";
12964
12992
  import { open, lstat } from "node:fs/promises";
@@ -13013,6 +13041,12 @@ var details = Object.freeze({
13013
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],
13014
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],
13015
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],
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],
13016
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],
13017
13051
  bridge_unavailable: ["The remote bridge endpoint is unavailable.", "Check the existing bridge and its version without restarting the active session.", true],
13018
13052
  bridge_busy: ["The remote bridge is temporarily busy.", "Keep the current binding and retry the read later. Never automatically repeat an instruction.", true],
@@ -13051,6 +13085,12 @@ function safeConnectionMessage(error62) {
13051
13085
 
13052
13086
  // ../opencode-plugin/src/live-errors.js
13053
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.",
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.",
13054
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.",
13055
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.",
13056
13096
  session_project_mismatch: "The exact session exists but is outside this connection's verified project/worktree scope. Choose its actual project connection; do not recreate or replace the session.",
@@ -13088,6 +13128,8 @@ var LiveActivity = class {
13088
13128
  this.alerts = [];
13089
13129
  this.pending = /* @__PURE__ */ new Map();
13090
13130
  this.detailCursors = /* @__PURE__ */ new Map();
13131
+ this.deliveries = /* @__PURE__ */ new Map();
13132
+ this.deliveryUpdates = /* @__PURE__ */ new Map();
13091
13133
  this.startCursor = client.cursor;
13092
13134
  this.revision = 0;
13093
13135
  this.delivered = -1;
@@ -13099,6 +13141,9 @@ var LiveActivity = class {
13099
13141
  this.completionReported = false;
13100
13142
  this.lastChange = 0;
13101
13143
  this.pendingSince = 0;
13144
+ this.lastVerifiedAt = 0;
13145
+ this.verifiedGeneration = -1;
13146
+ this.lastCard = void 0;
13102
13147
  this.gapCursor = void 0;
13103
13148
  this.droppedAlerts = 0;
13104
13149
  this.metrics = {
@@ -13120,7 +13165,12 @@ var LiveActivity = class {
13120
13165
  this.revision++;
13121
13166
  this.lastChange = Date.now();
13122
13167
  }
13168
+ needsSnapshot() {
13169
+ return !this.lastVerifiedAt || this.snapshotNeeded || this.terminalCandidate || this.verifiedGeneration !== this.client.successfulConnections || Date.now() - this.lastVerifiedAt >= 3e4;
13170
+ }
13123
13171
  seed(session, eventRevision = this.eventRevision) {
13172
+ this.lastVerifiedAt = Date.now();
13173
+ this.verifiedGeneration = this.client.successfulConnections;
13124
13174
  const before = JSON.stringify([...this.nodes.values()].map(({ revision: _revision, ...info }) => info)) + this.coverageComplete;
13125
13175
  const tree = session.tree ?? { sessions: [session], complete: this.scope === "session", unresolvedCount: 0 };
13126
13176
  const present = /* @__PURE__ */ new Set();
@@ -13168,6 +13218,7 @@ var LiveActivity = class {
13168
13218
  revision: ++this.eventRevision
13169
13219
  };
13170
13220
  const data = event.data ?? {};
13221
+ if (event.type === "message.delivery") this.receipt({ messageID: data.messageID, sessionID: event.sessionID, delivery: data.status });
13171
13222
  if (event.type === "session.status") node2.status = data.status;
13172
13223
  if (event.type === "session.idle") node2.status = "idle";
13173
13224
  if (event.type === "session.error") {
@@ -13211,6 +13262,23 @@ var LiveActivity = class {
13211
13262
  }
13212
13263
  this.change();
13213
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
+ }
13214
13282
  reference(event) {
13215
13283
  return {
13216
13284
  eventId: event.id,
@@ -13257,12 +13325,26 @@ var LiveActivity = class {
13257
13325
  shownAgents: Math.min(agentLimit, children.length),
13258
13326
  coverageComplete: this.coverageComplete && !this.client.gap && this.client.status === "connected",
13259
13327
  workCompleted: this.finished(),
13328
+ lastVerifiedAt: this.lastVerifiedAt,
13260
13329
  connection: this.client.status,
13261
13330
  ...this.client.gap ? { gap: this.client.gap } : {}
13262
13331
  };
13263
13332
  }
13264
- take(agentLimit = 10) {
13333
+ take(agentLimit = 10, changesOnly = false) {
13265
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;
13266
13348
  const alerts = this.alerts.splice(0, 50);
13267
13349
  const details2 = [...this.pending.values()].slice(-20);
13268
13350
  const moreDetails = this.pending.size > details2.length;
@@ -13270,9 +13352,13 @@ var LiveActivity = class {
13270
13352
  this.delivered = this.revision;
13271
13353
  this.pendingSince = 0;
13272
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);
13273
13358
  return {
13274
13359
  revision: this.revision,
13275
- card,
13360
+ ...deliveries.length ? { deliveries, hasMoreDeliveries: this.deliveryUpdates.size > 0 } : {},
13361
+ ...changesOnly && old ? { unchanged, ...unchanged ? {} : { delta } } : { card },
13276
13362
  alerts,
13277
13363
  hasMoreAlerts: this.alerts.length > 0,
13278
13364
  details: details2,
@@ -13287,14 +13373,14 @@ var LiveActivity = class {
13287
13373
  while (!signal?.aborted && !this.client.controller.signal.aborted) {
13288
13374
  this.transport();
13289
13375
  if (this.alerts.length || this.client.gap) return "ready";
13290
- if (this.terminalCandidate) return "verify";
13376
+ if (this.needsSnapshot()) return "verify";
13291
13377
  if (this.revision !== shown && progress && Date.now() - lastProgress >= 500) {
13292
13378
  shown = this.revision;
13293
13379
  lastProgress = Date.now();
13294
13380
  await progress(this.card());
13295
13381
  }
13296
13382
  if (this.revision !== this.delivered && Date.now() - this.pendingSince >= coalesceMs || Date.now() >= deadline) return "ready";
13297
- 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));
13298
13384
  await new Promise((resolve) => {
13299
13385
  let timer;
13300
13386
  const done = () => {
@@ -13410,7 +13496,7 @@ function checkedCursor(cursor) {
13410
13496
  return cursor;
13411
13497
  }
13412
13498
  function checkedSession(id) {
13413
- if (!SESSION.test(id)) throw new Error("Invalid session ID");
13499
+ if (typeof id !== "string" || !SESSION.test(id)) throw new Error("Invalid session ID");
13414
13500
  return encodeURIComponent(id);
13415
13501
  }
13416
13502
  function matchesSession(event, sessionId, eventScope) {
@@ -13450,7 +13536,8 @@ var LiveControlClient = class {
13450
13536
  expectedDirectory,
13451
13537
  sessionId,
13452
13538
  eventScope = "session",
13453
- internalReader = false
13539
+ internalReader = false,
13540
+ requireTree = false
13454
13541
  } = {}) {
13455
13542
  const origin = liveControlOrigin(url2);
13456
13543
  if (typeof token !== "string" || !/^[A-Za-z0-9_-]{32,}$/.test(token)) throw new Error("Live-control token is invalid");
@@ -13460,6 +13547,7 @@ var LiveControlClient = class {
13460
13547
  if (!["session", "tree"].includes(eventScope) || eventScope === "tree" && sessionId === void 0) {
13461
13548
  throw new Error("Invalid event scope: tree tracking requires an exact root session");
13462
13549
  }
13550
+ this.requireTree = requireTree;
13463
13551
  this.sessionId = sessionId;
13464
13552
  this.eventScope = eventScope;
13465
13553
  this.internalHeaders = internalReader ? { "X-Backeer-Internal": "project-hub" } : {};
@@ -13489,9 +13577,12 @@ var LiveControlClient = class {
13489
13577
  this.lastDisconnectedAt = null;
13490
13578
  this.nextRetryAt = null;
13491
13579
  this.lastDiagnostic = null;
13580
+ this.requestStats = { calls: 0, failures: 0, timeouts: 0, durations: [] };
13492
13581
  if (sessionId && !internalReader) this.activity = new LiveActivity(this, sessionId, eventScope);
13493
13582
  }
13494
- async request(path3, { method = "GET", body, signal, timeoutMs = 1e4 } = {}) {
13583
+ async request(path3, { method = "GET", body, signal, timeoutMs = LIVE_REQUEST_TIMEOUT_MS } = {}) {
13584
+ const started = Date.now();
13585
+ let succeeded = false;
13495
13586
  const controller = new AbortController();
13496
13587
  const abort = () => controller.abort();
13497
13588
  this.controller.signal.addEventListener("abort", abort, { once: true });
@@ -13525,7 +13616,12 @@ var LiveControlClient = class {
13525
13616
  if (Object.hasOwn(liveErrorMessages, value2?.error)) code = value2.error;
13526
13617
  if (["project_mismatch", "project_required", "project_unavailable", "session_required"].includes(value2?.error)) connectionCode = value2.error;
13527
13618
  const sessionErrors = {
13619
+ command_delivery_uncertain: "command_delivery_uncertain",
13620
+ command_journal_unavailable: "command_journal_unavailable",
13621
+ instruction_not_found: "instruction_not_found",
13528
13622
  native_session_api_unavailable: "native_session_api_unavailable",
13623
+ native_session_api_timeout: "native_session_api_timeout",
13624
+ native_session_api_circuit_open: "native_session_api_circuit_open",
13529
13625
  session_not_found: "session_unavailable",
13530
13626
  session_project_mismatch: "session_project_mismatch",
13531
13627
  session_archived: "session_archived",
@@ -13548,14 +13644,21 @@ var LiveControlClient = class {
13548
13644
  const text = await responseText(response);
13549
13645
  const value = JSON.parse(text);
13550
13646
  const source = response.headers.get("x-backeer-source");
13551
- if (source && this.sessionId) {
13552
- 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
+ }
13553
13652
  this.sourceIdentity = source;
13554
13653
  }
13555
13654
  if (path3 === "/v1/sessions") {
13556
- this.bridgeInfo = { bridgeVersion: value?.bridgeVersion, capabilities: value?.capabilities };
13557
- 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();
13558
13660
  }
13661
+ succeeded = true;
13559
13662
  return value;
13560
13663
  } catch (error62) {
13561
13664
  const diagnostic = connectionDiagnostic(error62, {
@@ -13566,6 +13669,11 @@ var LiveControlClient = class {
13566
13669
  });
13567
13670
  throw Object.assign(error62, { connectionCode: diagnostic.code });
13568
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();
13569
13677
  clearTimeout(timer);
13570
13678
  this.controller.signal.removeEventListener("abort", abort);
13571
13679
  signal?.removeEventListener("abort", abort);
@@ -13579,14 +13687,17 @@ var LiveControlClient = class {
13579
13687
  if (includeTree && !Array.isArray(result?.tree?.sessions)) throw treeUnsupported();
13580
13688
  return result;
13581
13689
  }
13690
+ instructionStatus(id, requestId) {
13691
+ return this.request(`/v1/sessions/${checkedSession(id)}/instructions/${checkedSession(requestId)}`);
13692
+ }
13582
13693
  listQuestions(id) {
13583
13694
  return this.request(`/v1/sessions/${checkedSession(id)}/questions`);
13584
13695
  }
13585
- answerQuestion({ sessionId, questionId, revision, answers, requestId, signal }) {
13696
+ answerQuestion({ sessionId, questionId, revision, answers, requestId, rootSessionId, signal }) {
13586
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");
13587
13698
  return this.request(`/v1/sessions/${checkedSession(sessionId)}/questions/${checkedSession(questionId)}/answers`, {
13588
13699
  method: "POST",
13589
- body: { requestId, revision, answers },
13700
+ body: { requestId, revision, answers, ...rootSessionId ? { rootSessionId } : {} },
13590
13701
  signal
13591
13702
  });
13592
13703
  }
@@ -13608,6 +13719,7 @@ var LiveControlClient = class {
13608
13719
  for (const wake of this.listeners) wake();
13609
13720
  }
13610
13721
  async start(afterCursor) {
13722
+ if (this.streamPool) return this.streamPool.start(this, afterCursor);
13611
13723
  checkedCursor(afterCursor);
13612
13724
  if (this.controller.signal.aborted) throw new Error("Live-control client is closed");
13613
13725
  if (this.gap && afterCursor === this.gap.cursor) {
@@ -13620,7 +13732,7 @@ var LiveControlClient = class {
13620
13732
  this.starting = (async () => {
13621
13733
  try {
13622
13734
  const initial = afterCursor ?? checkedCursor((await this.request("/v1/sessions", {
13623
- timeoutMs: this.reconnectMs
13735
+ timeoutMs: LIVE_REQUEST_TIMEOUT_MS
13624
13736
  })).cursor);
13625
13737
  if (!initial) throw new Error("Live-control bridge did not provide a cursor");
13626
13738
  if (this.controller.signal.aborted) return;
@@ -13671,16 +13783,16 @@ var LiveControlClient = class {
13671
13783
  abort();
13672
13784
  }, ms);
13673
13785
  };
13674
- armWatchdog(this.reconnectMs);
13786
+ armWatchdog(LIVE_REQUEST_TIMEOUT_MS);
13675
13787
  try {
13676
- const bridge = this.eventScope === "tree" ? await this.request("/v1/sessions", {
13788
+ const bridge = this.eventScope === "tree" || this.requireTree ? await this.request("/v1/sessions", {
13677
13789
  signal: connection2.signal,
13678
- timeoutMs: this.reconnectMs
13790
+ timeoutMs: LIVE_REQUEST_TIMEOUT_MS
13679
13791
  }) : void 0;
13680
13792
  if (!this.cursor) {
13681
13793
  const initial = checkedCursor((bridge ?? await this.request("/v1/sessions", {
13682
13794
  signal: connection2.signal,
13683
- timeoutMs: this.reconnectMs
13795
+ timeoutMs: LIVE_REQUEST_TIMEOUT_MS
13684
13796
  })).cursor);
13685
13797
  if (!initial) throw new Error("Live-control bridge did not provide a cursor");
13686
13798
  if (this.controller.signal.aborted) return;
@@ -13690,7 +13802,8 @@ var LiveControlClient = class {
13690
13802
  if (this.activity && this.activity.startCursor === void 0) this.activity.startCursor = initial;
13691
13803
  }
13692
13804
  const selected = this.sessionId === void 0 ? "" : `&sessionID=${encodeURIComponent(this.sessionId)}${this.eventScope === "tree" ? "&scope=tree" : ""}`;
13693
- 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}`, {
13694
13807
  redirect: "error",
13695
13808
  signal: connection2.signal,
13696
13809
  headers: {
@@ -13717,6 +13830,7 @@ var LiveControlClient = class {
13717
13830
  });
13718
13831
  }
13719
13832
  if (!response.body) throw new Error("SSE body missing");
13833
+ this.sourceIdentity = response.headers.get("x-backeer-source") ?? this.sourceIdentity;
13720
13834
  this.status = "connected";
13721
13835
  this.successfulConnections++;
13722
13836
  this.lastConnectedAt = Date.now();
@@ -13766,10 +13880,10 @@ var LiveControlClient = class {
13766
13880
  if (Buffer.byteLength(buffer) > this.maxBufferBytes + 4096) throw Object.assign(new Error("SSE frame exceeds buffer limit"), { connectionCode: "stream_payload_limit" });
13767
13881
  }
13768
13882
  } catch (error62) {
13769
- if (!this.controller.signal.aborted) {
13883
+ if (!this.controller.signal.aborted && !this.restartRequested) {
13770
13884
  if (this.status !== "unauthorized") this.status = "disconnected";
13771
13885
  this.recordFailure(error62, { timeout: timedOut });
13772
- if (["stream_payload_limit", "session_tree_unsupported"].includes(error62.connectionCode)) {
13886
+ if (["stream_payload_limit", "session_tree_unsupported", "bridge_protocol_unsupported"].includes(error62.connectionCode)) {
13773
13887
  this.status = "blocked";
13774
13888
  this.notify();
13775
13889
  return;
@@ -13783,19 +13897,29 @@ var LiveControlClient = class {
13783
13897
  });
13784
13898
  reader?.releaseLock();
13785
13899
  }
13786
- 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;
13787
13903
  this.notify();
13788
- if (!this.controller.signal.aborted) await this.delay(this.reconnectMs);
13904
+ if (!this.controller.signal.aborted && !immediate) await this.delay(this.reconnectMs);
13789
13905
  }
13790
13906
  }
13907
+ restartStream() {
13908
+ if (this.activeConnection) {
13909
+ this.restartRequested = true;
13910
+ this.activeConnection.abort();
13911
+ } else this.retryNow?.();
13912
+ }
13791
13913
  delay(ms) {
13792
13914
  return new Promise((resolve) => {
13793
13915
  const done = () => {
13794
13916
  clearTimeout(timer);
13917
+ if (this.retryNow === done) this.retryNow = void 0;
13795
13918
  this.controller.signal.removeEventListener("abort", done);
13796
13919
  resolve();
13797
13920
  };
13798
13921
  const timer = setTimeout(done, ms);
13922
+ this.retryNow = done;
13799
13923
  this.controller.signal.addEventListener("abort", done, { once: true });
13800
13924
  if (this.controller.signal.aborted) done();
13801
13925
  });
@@ -13842,6 +13966,7 @@ var LiveControlClient = class {
13842
13966
  connectionState() {
13843
13967
  return {
13844
13968
  status: this.status,
13969
+ ...this.streamPool ? { sharedTransport: this.streamPool.state(this) } : {},
13845
13970
  reconnectEveryMs: this.reconnectMs,
13846
13971
  reconnectAttempts: this.reconnectAttempts,
13847
13972
  rootSessionId: this.sessionId,
@@ -13965,6 +14090,7 @@ var LiveControlClient = class {
13965
14090
  this.status = "closed";
13966
14091
  this.nextRetryAt = null;
13967
14092
  this.notify();
14093
+ await this.streamPool?.release(this);
13968
14094
  await this.starting;
13969
14095
  await this.task;
13970
14096
  this.clearEvents();
@@ -14037,6 +14163,229 @@ async function saveConnectionProfiles(file2, profiles) {
14037
14163
  }
14038
14164
  }
14039
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
+
14040
14389
  // ../opencode-plugin/src/live-session-manager.js
14041
14390
  import { randomUUID as randomUUID2 } from "node:crypto";
14042
14391
 
@@ -14097,7 +14446,7 @@ async function discoverLiveConnections({ profiles = [], defaults = discoveryDefa
14097
14446
  try {
14098
14447
  let directories = [known?.directory];
14099
14448
  try {
14100
- const catalog = await client.request("/v1/projects", { timeoutMs: 3e3, signal });
14449
+ const catalog = await client.request("/v1/projects", { timeoutMs: LIVE_REQUEST_TIMEOUT_MS, signal });
14101
14450
  if (catalog.capabilities?.multiProject === true) {
14102
14451
  if (!["backeer-project-gateway/v1", "backeer-project-gateway/v2"].includes(catalog.protocol) || !Array.isArray(catalog.projects) || catalog.projects.some((item) => typeof item?.directory !== "string" || !isAbsolute3(item.directory))) {
14103
14452
  throw new Error("Invalid project catalog");
@@ -14110,7 +14459,7 @@ async function discoverLiveConnections({ profiles = [], defaults = discoveryDefa
14110
14459
  for (const directory of directories) {
14111
14460
  const selected = new LiveControlClient({ url: origin, token, expectedDirectory: directory });
14112
14461
  try {
14113
- const result = await selected.request("/v1/sessions", { timeoutMs: 3e3, signal });
14462
+ const result = await selected.request("/v1/sessions", { timeoutMs: LIVE_REQUEST_TIMEOUT_MS, signal });
14114
14463
  if (directory !== void 0 && result.directory !== directory) throw new ConnectionError("Project verification failed");
14115
14464
  const saved = profiles.find((item) => item.url === origin && item.tokenFile === file2 && item.directory === result.directory);
14116
14465
  const profile = connectionProfile({ name: saved?.name || "discovered", url: origin, tokenFile: file2, directory: result.directory });
@@ -14133,10 +14482,6 @@ async function discoverLiveConnections({ profiles = [], defaults = discoveryDefa
14133
14482
  return { candidates, diagnostics: [...diagnostics], diagnosticDetails: [...diagnosticDetails.values()] };
14134
14483
  }
14135
14484
 
14136
- // ../opencode-plugin/src/updates.js
14137
- var PLUGIN_VERSION = "0.14.0";
14138
- var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
14139
-
14140
14485
  // ../opencode-plugin/src/live-health.js
14141
14486
  function healthLayers({ bridge, reachable = false, session = false, stream = false } = {}) {
14142
14487
  const version2 = typeof bridge?.bridgeVersion === "string" && /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(bridge.bridgeVersion) ? bridge.bridgeVersion : void 0;
@@ -14156,10 +14501,14 @@ var LiveSessionManager = class {
14156
14501
  profilesFile,
14157
14502
  clientFactory = (options) => new LiveControlClient(options),
14158
14503
  maxBindings = Infinity,
14159
- discovery = discoveryDefaults()
14504
+ discovery = discoveryDefaults(),
14505
+ adapterVersion,
14506
+ shareStreams = true
14160
14507
  }) {
14508
+ this.adapterVersion = adapterVersion;
14161
14509
  this.profilesFile = profilesFile;
14162
14510
  this.clientFactory = clientFactory;
14511
+ this.streamPool = shareStreams ? new LiveStreamPool(clientFactory) : void 0;
14163
14512
  this.maxBindings = maxBindings;
14164
14513
  this.bindings = /* @__PURE__ */ new Map();
14165
14514
  this.clients = /* @__PURE__ */ new Set();
@@ -14189,6 +14538,7 @@ var LiveSessionManager = class {
14189
14538
  }
14190
14539
  if (this.closed) throw new ConnectionError("Connection manager is closed.");
14191
14540
  const client = this.clientFactory({ url: profile.url, token, expectedDirectory: profile.directory, sessionId, eventScope });
14541
+ if (sessionId && this.streamPool) client.streamPool = this.streamPool;
14192
14542
  this.clients.add(client);
14193
14543
  return client;
14194
14544
  }
@@ -14264,17 +14614,19 @@ var LiveSessionManager = class {
14264
14614
  const profile = await this.profile(connection2);
14265
14615
  const client = await this.client(profile, sessionId, eventScope);
14266
14616
  try {
14617
+ let initialCursor;
14267
14618
  if (eventScope === "tree") {
14268
14619
  const bridge = await client.listSessions();
14269
14620
  this.checkProject(profile, bridge);
14270
14621
  this.checkSessionList(bridge);
14271
14622
  this.checkTreeCapability(bridge);
14623
+ initialCursor = bridge.cursor;
14272
14624
  }
14273
14625
  const session = await client.sessionStatus(sessionId);
14274
14626
  this.checkProject(profile, session);
14275
14627
  if (session.id !== sessionId) throw new ConnectionError("Session verification failed.");
14276
14628
  client.activity?.seed(session);
14277
- await client.start();
14629
+ await client.start(initialCursor);
14278
14630
  if (this.closed) throw new ConnectionError("Connection manager is closed.");
14279
14631
  const bindingId = randomUUID2();
14280
14632
  this.bindings.set(bindingId, Object.freeze({ profile, sessionId, rootSessionId: sessionId, eventScope, client, session }));
@@ -14299,6 +14651,9 @@ var LiveSessionManager = class {
14299
14651
  return value;
14300
14652
  }
14301
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
+ }
14302
14657
  if (value.eventScope === "tree" && value.client.status === "blocked" && value.client.lastDiagnostic?.code === "session_tree_unsupported") {
14303
14658
  throw Object.assign(
14304
14659
  new ConnectionError("Session-tree tracking is unavailable on the remote bridge. Update and load a compatible bridge, then reconnect the same root session."),
@@ -14328,7 +14683,7 @@ var LiveSessionManager = class {
14328
14683
  this.readCache.set(bindingId, { stamp, time: Date.now(), session });
14329
14684
  return { ...value, session };
14330
14685
  }
14331
- async verifyConnection({ connection: connection2, sessionId, sessionTitle, timeoutMs = 5e3 }, signal) {
14686
+ async verifyConnection({ connection: connection2, sessionId, sessionTitle, timeoutMs = 3e4 }, signal) {
14332
14687
  if (sessionId === void 0 === (sessionTitle === void 0)) throw new ConnectionError("Choose exactly one session ID or exact session title.");
14333
14688
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 3e4) throw new ConnectionError("Verification timeout must be between 1 and 30000 ms.");
14334
14689
  const profile = await this.profile(connection2);
@@ -14404,17 +14759,62 @@ var LiveSessionManager = class {
14404
14759
  this.readCache.delete(bindingId);
14405
14760
  const value = await this.verified(bindingId);
14406
14761
  this.readCache.delete(bindingId);
14407
- 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;
14408
14765
  }
14409
- async questions(bindingId) {
14766
+ async instructionStatus(bindingId, requestId) {
14410
14767
  const value = await this.verified(bindingId);
14411
- 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;
14412
14772
  }
14413
- async answer(bindingId, args, signal) {
14414
- this.readCache.delete(bindingId);
14773
+ async questionTarget(bindingId, targetSessionId2) {
14415
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) {
14798
+ this.readCache.delete(bindingId);
14799
+ const value = await this.questionTarget(bindingId, targetSessionId2);
14416
14800
  this.readCache.delete(bindingId);
14417
- return value.client.answerQuestion({ ...args, sessionId: value.sessionId, signal });
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) };
14418
14818
  }
14419
14819
  async read(bindingId, options, waitMs = 0, signal) {
14420
14820
  const bound = this.binding(bindingId);
@@ -14458,26 +14858,28 @@ var LiveSessionManager = class {
14458
14858
  if (activity.alerts.length) break;
14459
14859
  const revision = activity.eventRevision;
14460
14860
  try {
14461
- let wake;
14462
- const urgent = new Promise((resolve) => {
14463
- wake = () => {
14464
- if (activity.alerts.length || initial.client.gap || signal?.aborted || initial.client.controller.signal.aborted) resolve(null);
14465
- };
14466
- initial.client.listeners.add(wake);
14467
- signal?.addEventListener("abort", wake, { once: true });
14468
- initial.client.controller.signal.addEventListener("abort", wake, { once: true });
14469
- wake();
14470
- });
14471
- let value;
14472
- try {
14473
- value = await Promise.race([this.verified(bindingId, { includeTree: true, cached: !activity.terminalCandidate && !activity.snapshotNeeded }), urgent]);
14474
- } finally {
14475
- initial.client.listeners.delete(wake);
14476
- signal?.removeEventListener("abort", wake);
14477
- 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);
14478
14882
  }
14479
- if (!value) break;
14480
- activity.seed(value.session, revision);
14481
14883
  } catch (error62) {
14482
14884
  if (!error62.connectionCode || !connectionDiagnostic(error62).retryable) throw error62;
14483
14885
  verified = false;
@@ -14488,11 +14890,11 @@ var LiveSessionManager = class {
14488
14890
  if (reason !== "verify") break;
14489
14891
  } while (!signal?.aborted && !initial.client.controller.signal.aborted);
14490
14892
  this.binding(bindingId);
14491
- return { bindingId, verified, ...diagnostic ? { diagnostic } : {}, ...activity.take(options.agentLimit ?? 10) };
14893
+ return { bindingId, verified, ...diagnostic ? { diagnostic } : {}, ...activity.take(options.agentLimit ?? 10, options.changesOnly ?? false) };
14492
14894
  }
14493
14895
  async details(bindingId, options) {
14494
- const value = await this.verified(bindingId, { cached: true });
14495
- 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) };
14496
14898
  }
14497
14899
  metrics(bindingId) {
14498
14900
  const client = this.binding(bindingId).client;
@@ -14500,10 +14902,39 @@ var LiveSessionManager = class {
14500
14902
  ...client.activity.metrics,
14501
14903
  retainedEvents: client.events.length,
14502
14904
  retainedBytes: client.bufferBytes,
14905
+ requests: requestMetrics(client),
14503
14906
  evictedEvents: client.evictedEvents,
14504
14907
  measurement: "UTF-8 response bytes and received event bytes; not billed model tokens. No summarization model is called."
14505
14908
  };
14506
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
+ }
14507
14938
  async diagnose({ connection: connection2, bindingId } = {}) {
14508
14939
  if (connection2 === void 0 === (bindingId === void 0)) throw new ConnectionError("Choose one saved connection or one chat binding to diagnose.");
14509
14940
  const bound = bindingId ? this.binding(bindingId) : void 0;
@@ -14651,6 +15082,7 @@ var LiveSessionManager = class {
14651
15082
  this.bindings.clear();
14652
15083
  this.candidates.clear();
14653
15084
  await Promise.allSettled([...this.clients].map((client) => this.release(client)));
15085
+ await this.streamPool?.close();
14654
15086
  }
14655
15087
  };
14656
15088
 
@@ -44197,6 +44629,7 @@ async function selectSession(manager, server, { connection: connection2, include
44197
44629
  var readOnly = { readOnlyHint: true, destructiveHint: false, openWorldHint: false };
44198
44630
  var localChange = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
44199
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.");
44200
44633
  var connection = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/);
44201
44634
  var read = {
44202
44635
  ...binding,
@@ -44206,7 +44639,7 @@ var read = {
44206
44639
  };
44207
44640
  function createManagedLiveMcp(manager) {
44208
44641
  const server = new McpServer({ name: "backeer-opencode-connections", version: PLUGIN_VERSION }, {
44209
- 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."
44210
44643
  });
44211
44644
  const tool = (name, description, inputSchema, annotations, run) => server.registerTool(name, {
44212
44645
  description,
@@ -44248,10 +44681,17 @@ function createManagedLiveMcp(manager) {
44248
44681
  readOnly,
44249
44682
  (args) => manager.diagnose(args)
44250
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
+ );
44251
44691
  tool(
44252
44692
  "verify_connection",
44253
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.",
44254
- { connection, sessionId: external_exports.string().regex(/^[A-Za-z0-9_-]+$/).optional(), sessionTitle: external_exports.string().trim().min(1).optional(), timeoutMs: external_exports.number().int().min(1).max(3e4).default(5e3) },
44694
+ { connection, sessionId: external_exports.string().regex(/^[A-Za-z0-9_-]+$/).optional(), sessionTitle: external_exports.string().trim().min(1).optional(), timeoutMs: external_exports.number().int().min(1).max(3e4).default(3e4) },
44255
44695
  readOnly,
44256
44696
  (args, extra) => manager.verifyConnection(args, extra.signal)
44257
44697
  );
@@ -44304,28 +44744,28 @@ function createManagedLiveMcp(manager) {
44304
44744
  tool(
44305
44745
  "list_questions",
44306
44746
  listQuestionDescription,
44307
- binding,
44747
+ { ...binding, targetSessionId },
44308
44748
  readOnly,
44309
- (args) => manager.questions(args.bindingId)
44749
+ (args) => manager.questions(args.bindingId, args.targetSessionId)
44310
44750
  );
44311
44751
  tool(
44312
44752
  "answer_question",
44313
44753
  answerQuestionDescription,
44314
- { ...binding, ...answerSchema },
44754
+ { ...binding, targetSessionId, ...answerSchema },
44315
44755
  { ...localChange, destructiveHint: true, idempotentHint: true },
44316
44756
  ({ bindingId, ...args }, extra) => manager.answer(bindingId, args, extra.signal)
44317
44757
  );
44318
44758
  tool(
44319
44759
  "activity_status",
44320
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.",
44321
- { ...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) },
44322
44762
  readOnly,
44323
44763
  ({ bindingId, ...args }, extra) => manager.activity(bindingId, args, extra.signal)
44324
44764
  );
44325
44765
  tool(
44326
44766
  "watch_activity",
44327
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.",
44328
- { ...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) },
44329
44769
  readOnly,
44330
44770
  ({ bindingId, ...args }, extra) => {
44331
44771
  let progress = 0;
@@ -44350,6 +44790,27 @@ function createManagedLiveMcp(manager) {
44350
44790
  readOnly,
44351
44791
  ({ bindingId, ...args }) => manager.details(bindingId, args)
44352
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
+ );
44353
44814
  tool(
44354
44815
  "activity_metrics",
44355
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.",
@@ -44378,6 +44839,13 @@ function createManagedLiveMcp(manager) {
44378
44839
  { ...localChange, destructiveHint: true, idempotentHint: true },
44379
44840
  ({ bindingId, ...args }, extra) => manager.send(bindingId, args, extra.signal)
44380
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
+ );
44381
44849
  tool(
44382
44850
  "disconnect_session",
44383
44851
  "Release this chat's local stream and binding. Running remote OpenCode work continues.",
@@ -44390,8 +44858,8 @@ function createManagedLiveMcp(manager) {
44390
44858
  };
44391
44859
  return server;
44392
44860
  }
44393
- async function runManagedLiveMcp({ profilesFile, discovery }) {
44394
- const manager = new LiveSessionManager({ profilesFile, discovery });
44861
+ async function runManagedLiveMcp({ profilesFile, discovery, adapterVersion }) {
44862
+ const manager = new LiveSessionManager({ profilesFile, discovery, adapterVersion });
44395
44863
  const server = createManagedLiveMcp(manager);
44396
44864
  let closing;
44397
44865
  const close = () => {
@@ -44497,7 +44965,7 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44497
44965
  const file2 = connectionsFile(env);
44498
44966
  const [command = "connections", ...values] = args;
44499
44967
  const discovery = discoveryDefaults(env);
44500
- 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 });
44501
44969
  if (["setup", "discover"].includes(command) && values.length === 0) {
44502
44970
  let prompt;
44503
44971
  if (command === "setup" && !ask) {
@@ -44505,7 +44973,7 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44505
44973
  prompt = createInterface({ input: input2, output: output2 });
44506
44974
  ask = (question) => prompt.question(question);
44507
44975
  }
44508
- const manager = new LiveSessionManager({ profilesFile: file2, discovery });
44976
+ const manager = new LiveSessionManager({ profilesFile: file2, discovery, adapterVersion: VERSION });
44509
44977
  try {
44510
44978
  if (command === "setup") return await setupOpenCode(manager, { ask, output: output2 });
44511
44979
  const result = await manager.discover();
@@ -44518,10 +44986,21 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44518
44986
  }
44519
44987
  }
44520
44988
  if (command === "verify" && values.length === 2) {
44521
- const manager = new LiveSessionManager({ profilesFile: file2 });
44989
+ const manager = new LiveSessionManager({ profilesFile: file2, adapterVersion: VERSION });
44522
44990
  try {
44523
44991
  const result = await manager.verifyConnection({ connection: values[0], sessionTitle: values[1] });
44524
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)}
44525
45004
  `);
44526
45005
  return result;
44527
45006
  } finally {
@@ -44529,7 +45008,7 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44529
45008
  }
44530
45009
  }
44531
45010
  if (command === "diagnose" && values.length === 1) {
44532
- const manager = new LiveSessionManager({ profilesFile: file2 });
45011
+ const manager = new LiveSessionManager({ profilesFile: file2, adapterVersion: VERSION });
44533
45012
  try {
44534
45013
  const result = await manager.diagnose({ connection: values[0] });
44535
45014
  output2.write(`${JSON.stringify(result, null, 2)}
@@ -44563,7 +45042,7 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44563
45042
  return;
44564
45043
  }
44565
45044
  if (command === "sessions" && (values.length === 1 || values.length === 2 && values[1] === "--include-subagents")) {
44566
- const manager = new LiveSessionManager({ profilesFile: file2 });
45045
+ const manager = new LiveSessionManager({ profilesFile: file2, adapterVersion: VERSION });
44567
45046
  try {
44568
45047
  output2.write(`${JSON.stringify(await manager.listSessions(values[0], { includeChildren: values.length === 2 }), null, 2)}
44569
45048
  `);
@@ -44572,7 +45051,7 @@ async function runOpenCodeCLI(args, { env = process.env, output: output2 = proce
44572
45051
  }
44573
45052
  return;
44574
45053
  }
44575
- 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]");
44576
45055
  }
44577
45056
  export {
44578
45057
  connectionsFile,