@evident-ai/cli 3.0.1-dev.a748d55 → 3.0.1-dev.a7dab7b

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/index.js CHANGED
@@ -471,12 +471,6 @@ import chalk6 from "chalk";
471
471
  import ora3 from "ora";
472
472
  import { select as select3 } from "@inquirer/prompts";
473
473
 
474
- // ../../packages/types/src/opencode/index.ts
475
- function opencodeMessageIdFor(queuedMessageId) {
476
- const sanitized = queuedMessageId.replace(/[^a-zA-Z0-9]/g, "_");
477
- return `msg_${sanitized}`;
478
- }
479
-
480
474
  // ../../packages/types/src/telemetry/index.ts
481
475
  var TelemetryEventTypes = {
482
476
  // Agent activity events (shown in web UI activity log)
@@ -515,7 +509,10 @@ function stripQuery(url) {
515
509
  }
516
510
 
517
511
  // src/lib/telemetry.ts
518
- var CLI_VERSION = process.env.npm_package_version || "unknown";
512
+ var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
513
+ function getCliVersion() {
514
+ return CLI_VERSION;
515
+ }
519
516
  var eventBuffer = [];
520
517
  var flushTimeout = null;
521
518
  var isShuttingDown = false;
@@ -715,7 +712,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
715
712
  }
716
713
 
717
714
  // src/lib/opencode/opencode-version-gate.ts
718
- var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11"];
715
+ var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
719
716
  function isQueueValidatedVersion(version2) {
720
717
  if (!version2) return false;
721
718
  return QUEUE_VALIDATED_OPENCODE_VERSIONS.includes(version2);
@@ -1071,6 +1068,16 @@ function isAssistantInFlight(m) {
1071
1068
  if (completedOf(m) == null) return true;
1072
1069
  return finishOf(m) === "tool-calls";
1073
1070
  }
1071
+ async function getSessionMessages(port, sessionId) {
1072
+ try {
1073
+ const res = await fetch(`${opencodeBase(port)}/session/${sessionId}/message`);
1074
+ if (!res.ok) return null;
1075
+ const body = await res.json();
1076
+ return Array.isArray(body) ? body : null;
1077
+ } catch {
1078
+ return null;
1079
+ }
1080
+ }
1074
1081
  async function createOpenCodeSession(port, directory) {
1075
1082
  const url = new URL(`${opencodeBase(port)}/session`);
1076
1083
  if (directory && directory.trim()) {
@@ -1088,9 +1095,16 @@ async function createOpenCodeSession(port, directory) {
1088
1095
  const data = await response.json();
1089
1096
  return data.id;
1090
1097
  }
1091
- async function sendPromptAsync(port, sessionId, content, options, messageId) {
1098
+ function messageText(m) {
1099
+ if (!m || !Array.isArray(m.parts)) return "";
1100
+ return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
1101
+ }
1102
+ async function sendPromptAsync(port, sessionId, content, options) {
1103
+ const before = await getSessionMessages(port, sessionId);
1104
+ const knownUserIds = new Set(
1105
+ (before ?? []).filter((m) => roleOf(m) === "user").map((m) => idOf(m)).filter((id) => typeof id === "string")
1106
+ );
1092
1107
  const body = {
1093
- messageID: messageId,
1094
1108
  parts: [{ type: "text", text: content }]
1095
1109
  };
1096
1110
  if (options?.agent) {
@@ -1114,6 +1128,29 @@ async function sendPromptAsync(port, sessionId, content, options, messageId) {
1114
1128
  const text = await res.text().catch(() => "");
1115
1129
  throw new Error(`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}`);
1116
1130
  }
1131
+ const READ_BACK_ATTEMPTS = 5;
1132
+ const READ_BACK_DELAY_MS = 150;
1133
+ for (let attempt = 0; attempt < READ_BACK_ATTEMPTS; attempt++) {
1134
+ const after = await getSessionMessages(port, sessionId);
1135
+ if (after) {
1136
+ let best = null;
1137
+ for (const m of after) {
1138
+ if (roleOf(m) !== "user") continue;
1139
+ const id = idOf(m);
1140
+ if (typeof id !== "string" || knownUserIds.has(id)) continue;
1141
+ if (messageText(m) !== content) continue;
1142
+ const created = createdOf(m) ?? 0;
1143
+ if (best === null || created > best.created) {
1144
+ best = { id, created };
1145
+ }
1146
+ }
1147
+ if (best) return best.id;
1148
+ }
1149
+ if (attempt < READ_BACK_ATTEMPTS - 1) {
1150
+ await new Promise((resolve) => setTimeout(resolve, READ_BACK_DELAY_MS));
1151
+ }
1152
+ }
1153
+ return null;
1117
1154
  }
1118
1155
  function findAssistantReplyAfter(messages, userMessageId) {
1119
1156
  if (!messages || messages.length === 0) return null;
@@ -1186,31 +1223,6 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1186
1223
  (m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
1187
1224
  );
1188
1225
  }
1189
- function isSessionSettled(messages, now, settleMs) {
1190
- if (!messages || messages.length === 0) return true;
1191
- let newestAssistantCreated = null;
1192
- for (const m of messages) {
1193
- if (roleOf(m) !== "assistant") continue;
1194
- if (isAssistantInFlight(m)) return false;
1195
- const created = createdOf(m);
1196
- if (typeof created === "number" && (newestAssistantCreated === null || created > newestAssistantCreated)) {
1197
- newestAssistantCreated = created;
1198
- }
1199
- }
1200
- if (newestAssistantCreated === null) return true;
1201
- return now - newestAssistantCreated >= settleMs;
1202
- }
1203
- function opencodeMessageIdFor2(queuedMessageId) {
1204
- return opencodeMessageIdFor(queuedMessageId);
1205
- }
1206
- var NATIVE_ID_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1207
- function nativeOpencodeMessageId() {
1208
- let id = "msg_";
1209
- for (let i = 0; i < 24; i++) {
1210
- id += NATIVE_ID_ALPHABET[Math.floor(Math.random() * NATIVE_ID_ALPHABET.length)];
1211
- }
1212
- return id;
1213
- }
1214
1226
 
1215
1227
  // src/lib/tunnel/connection.ts
1216
1228
  import WebSocket2 from "ws";
@@ -1288,12 +1300,14 @@ var StreamForwarder = class {
1288
1300
  this.send({ type: "res_end", sid });
1289
1301
  return;
1290
1302
  }
1291
- log("info", "agent_request", {
1292
- correlation_id: correlationId,
1293
- sid,
1294
- method,
1295
- path: stripQuery(path)
1296
- });
1303
+ if (process.env.DEBUG) {
1304
+ log("debug", "agent_request", {
1305
+ correlation_id: correlationId,
1306
+ sid,
1307
+ method,
1308
+ path: stripQuery(path)
1309
+ });
1310
+ }
1297
1311
  const ac = new AbortController();
1298
1312
  let bodyPromise;
1299
1313
  let pushBody;
@@ -1340,12 +1354,14 @@ var StreamForwarder = class {
1340
1354
  if (!STRIP_RES.has(key.toLowerCase())) resHeaders[key] = value;
1341
1355
  });
1342
1356
  this.send({ type: "head", sid, status: upstream.status, headers: resHeaders });
1343
- log("info", "agent_response", {
1344
- correlation_id: correlationId,
1345
- sid,
1346
- status: upstream.status,
1347
- duration_ms: Date.now() - startedAt
1348
- });
1357
+ if (process.env.DEBUG) {
1358
+ log("debug", "agent_response", {
1359
+ correlation_id: correlationId,
1360
+ sid,
1361
+ status: upstream.status,
1362
+ duration_ms: Date.now() - startedAt
1363
+ });
1364
+ }
1349
1365
  this.callbacks.onHead?.(sid, upstream.status);
1350
1366
  try {
1351
1367
  if (upstream.body) {
@@ -1615,10 +1631,7 @@ var DEFAULT_RETRY_POLICY = {
1615
1631
  };
1616
1632
  var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
1617
1633
  var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
1618
- var DEFAULT_DISPATCH_CONFIRM_MS = 6e3;
1619
1634
  var DEFAULT_STUCK_QUEUED_MS = 6e4;
1620
- var DEFAULT_STUCK_QUEUED_REDRIVE_MAX = 3;
1621
- var DEFAULT_SETTLE_MS = 3500;
1622
1635
  var ChannelAuthError = class extends Error {
1623
1636
  constructor(message) {
1624
1637
  super(message);
@@ -1653,13 +1666,18 @@ var ChannelDriver = class {
1653
1666
  sleep;
1654
1667
  pausedPollIntervalMs;
1655
1668
  pausedMaxWaitMs;
1656
- dispatchConfirmMs;
1657
1669
  stuckQueuedMs;
1658
- stuckQueuedRedriveMax;
1659
- settleMs;
1660
1670
  now;
1661
1671
  /** Cache of conversationId → opencode sessionId. */
1662
1672
  sessions = /* @__PURE__ */ new Map();
1673
+ /**
1674
+ * Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
1675
+ * longer idempotent (no caller-supplied `messageID`), and its read-back picks
1676
+ * "the one new user row" — which is only unambiguous if no OTHER dispatch into
1677
+ * the SAME session interleaves its snapshot→POST→read-back. This map chains each
1678
+ * session's dispatches so they run serially; distinct sessions stay concurrent.
1679
+ */
1680
+ sessionDispatchLocks = /* @__PURE__ */ new Map();
1663
1681
  /**
1664
1682
  * Per-SESSION watchers (WI-3), keyed by opencode sessionId. Single-flight per
1665
1683
  * session: one polling loop services all of that session's in-flight messages.
@@ -1710,6 +1728,20 @@ var ChannelDriver = class {
1710
1728
  * the row leaves the processing list, exactly like `dontRedispatch`.
1711
1729
  */
1712
1730
  doneUndeliverable = /* @__PURE__ */ new Set();
1731
+ /**
1732
+ * "A null-id re-adopt re-dispatch is in flight, awaiting its read-back" (WI-5
1733
+ * Task 5.4, High-2). Since we no longer send a caller-supplied id, a re-dispatch
1734
+ * is NOT idempotent: if `forceReadoptRun` dispatches on tick N but the read-back +
1735
+ * persist hasn't landed before tick N+1 re-reads the still-null
1736
+ * `row.opencode_message_id`, tick N+1 would dispatch AGAIN → duplicate user turns.
1737
+ * A row is added here right before its `sendPromptAsync` and `forceReadoptRun`
1738
+ * short-circuits while it is present, so a null-id row is re-dispatched AT MOST
1739
+ * ONCE per outstanding read-back. Cleared on a SUCCESSFUL dispatch+read-back (the
1740
+ * row is then tracked in `dispatched`, so `readoptOne`'s early skip prevents
1741
+ * re-entry) OR on a failed/unresolved dispatch (the message is genuinely un-sent,
1742
+ * so the NEXT tick may retry exactly once more).
1743
+ */
1744
+ awaitingReadopt = /* @__PURE__ */ new Set();
1713
1745
  /**
1714
1746
  * Cache of the opencode root directory (from `GET /path`). Resolved lazily on
1715
1747
  * first session creation so drain-created sessions are rooted at the project
@@ -1732,10 +1764,7 @@ var ChannelDriver = class {
1732
1764
  this.sleep = config2.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1733
1765
  this.pausedPollIntervalMs = config2.pausedPollIntervalMs ?? DEFAULT_PAUSED_POLL_INTERVAL_MS;
1734
1766
  this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
1735
- this.dispatchConfirmMs = config2.dispatchConfirmMs ?? DEFAULT_DISPATCH_CONFIRM_MS;
1736
1767
  this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
1737
- this.stuckQueuedRedriveMax = config2.stuckQueuedRedriveMax ?? DEFAULT_STUCK_QUEUED_REDRIVE_MAX;
1738
- this.settleMs = config2.settleMs ?? DEFAULT_SETTLE_MS;
1739
1768
  this.now = config2.now ?? (() => Date.now());
1740
1769
  }
1741
1770
  /** The IPv4-loopback base URL for the local `opencode serve`. */
@@ -1826,11 +1855,11 @@ var ChannelDriver = class {
1826
1855
  skippedAlreadyDispatched += 1;
1827
1856
  continue;
1828
1857
  }
1829
- const opencodeMessageId = opencodeMessageIdFor2(message.id);
1830
1858
  const options = {
1831
1859
  agent: message.opencode_agent ?? void 0,
1832
1860
  model: message.opencode_model ?? void 0
1833
1861
  };
1862
+ let opencodeMessageId;
1834
1863
  try {
1835
1864
  this.log({
1836
1865
  level: "info",
@@ -1838,7 +1867,10 @@ var ChannelDriver = class {
1838
1867
  conversation_id: conv.id,
1839
1868
  message_id: message.id
1840
1869
  });
1841
- await sendPromptAsync(this.port, sessionId, message.content, options, opencodeMessageId);
1870
+ opencodeMessageId = await this.dispatchLocked(
1871
+ sessionId,
1872
+ () => sendPromptAsync(this.port, sessionId, message.content, options)
1873
+ );
1842
1874
  } catch (err) {
1843
1875
  if (err instanceof ChannelAuthError) throw err;
1844
1876
  this.dispatched.delete(message.id);
@@ -1852,6 +1884,15 @@ var ChannelDriver = class {
1852
1884
  });
1853
1885
  continue;
1854
1886
  }
1887
+ if (opencodeMessageId === null) {
1888
+ this.log({
1889
+ level: "error",
1890
+ message: `Message ${message.id.slice(0, 8)} dispatched but its opencode id could not be read back \u2014 leaving un-tracked to retry next tick`,
1891
+ conversation_id: conv.id,
1892
+ message_id: message.id
1893
+ });
1894
+ continue;
1895
+ }
1855
1896
  this.dispatched.add(message.id);
1856
1897
  this.registerInFlight(conv, sessionId, message, opencodeMessageId);
1857
1898
  dispatched += 1;
@@ -1900,6 +1941,25 @@ var ChannelDriver = class {
1900
1941
  // -------------------------------------------------------------------------
1901
1942
  // Per-session watcher (WI-3)
1902
1943
  // -------------------------------------------------------------------------
1944
+ /**
1945
+ * Run one dispatch (`sendPromptAsync` snapshot→POST→read-back) serialized per
1946
+ * opencode session (Task 2.1a), so two dispatches into the SAME session can
1947
+ * never interleave and mis-correlate their read-backs. Distinct sessions run
1948
+ * concurrently. The chained tail intentionally ignores the prior result/error
1949
+ * (each dispatch reports its own outcome to its caller).
1950
+ */
1951
+ dispatchLocked(sessionId, fn) {
1952
+ const prior = this.sessionDispatchLocks.get(sessionId) ?? Promise.resolve();
1953
+ const run2 = prior.then(fn, fn);
1954
+ this.sessionDispatchLocks.set(
1955
+ sessionId,
1956
+ run2.then(
1957
+ () => void 0,
1958
+ () => void 0
1959
+ )
1960
+ );
1961
+ return run2;
1962
+ }
1903
1963
  /** Register a freshly-dispatched message with its session's watcher state. */
1904
1964
  registerInFlight(conv, sessionId, message, opencodeMessageId) {
1905
1965
  let watcher = this.watchers.get(sessionId);
@@ -1922,11 +1982,7 @@ var ChannelDriver = class {
1922
1982
  deadline: now + this.pausedMaxWaitMs,
1923
1983
  started: false,
1924
1984
  done: false,
1925
- stuckReported: false,
1926
- redriveAttempts: 0,
1927
- lastRedriveAt: null,
1928
- redriveOpencodeMessageId: null,
1929
- attemptedOpencodeMessageIds: [opencodeMessageId]
1985
+ stuckReported: false
1930
1986
  });
1931
1987
  }
1932
1988
  /**
@@ -1946,7 +2002,7 @@ var ChannelDriver = class {
1946
2002
  * server already flipped to `processing`; the running/done transitions still
1947
2003
  * fire from the watcher's normal branches.
1948
2004
  */
1949
- registerReadopted(conv, sessionId, message, opencodeMessageId, processedAtMs, redriveOpencodeMessageId = null) {
2005
+ registerReadopted(conv, sessionId, message, opencodeMessageId, processedAtMs) {
1950
2006
  let watcher = this.watchers.get(sessionId);
1951
2007
  if (!watcher) {
1952
2008
  watcher = {
@@ -1968,17 +2024,11 @@ var ChannelDriver = class {
1968
2024
  started: true,
1969
2025
  done: false,
1970
2026
  // Not yet reported stuck-queued. The once-guard (`stuckReported`) applies,
1971
- // AND the stuck-queued observer now INCLUDES re-adopted queued wedges: it
1972
- // gates on `state === 'queued'` (turn produced no reply), not on `started`,
1973
- // so a re-adopted row left wedged in `queued` still emits the signal once
1974
- // (queued-followup-redrive, #210). A re-adopted `queued` wedge is ALSO
1975
- // re-driven by the same path (ADR-0046 §c deferred the live-session redrive
1976
- // to here) — `redriveAttempts` starts fresh so it gets the full budget.
1977
- stuckReported: false,
1978
- redriveAttempts: 0,
1979
- lastRedriveAt: null,
1980
- redriveOpencodeMessageId,
1981
- attemptedOpencodeMessageIds: [opencodeMessageId]
2027
+ // AND the stuck-queued observer INCLUDES re-adopted queued wedges: it gates
2028
+ // on `state === 'queued'` (turn produced no reply), not on `started`, so a
2029
+ // re-adopted row left wedged in `queued` still emits the signal once
2030
+ // (#210/#220 observability).
2031
+ stuckReported: false
1982
2032
  });
1983
2033
  }
1984
2034
  /**
@@ -2072,7 +2122,7 @@ var ChannelDriver = class {
2072
2122
  conv.id,
2073
2123
  inFlight.evidentMessageId,
2074
2124
  sessionId,
2075
- inFlight.redriveOpencodeMessageId
2125
+ inFlight.opencodeMessageId
2076
2126
  );
2077
2127
  } catch (err) {
2078
2128
  if (err instanceof ChannelAuthError) throw err;
@@ -2107,7 +2157,7 @@ var ChannelDriver = class {
2107
2157
  conv.id,
2108
2158
  inFlight.evidentMessageId,
2109
2159
  sessionId,
2110
- inFlight.redriveOpencodeMessageId
2160
+ inFlight.opencodeMessageId
2111
2161
  );
2112
2162
  } catch (err) {
2113
2163
  if (err instanceof ChannelAuthError) throw err;
@@ -2190,25 +2240,13 @@ var ChannelDriver = class {
2190
2240
  this.removeInFlight(watcher, inFlight.evidentMessageId);
2191
2241
  return;
2192
2242
  }
2193
- if (state === "unknown") {
2194
- if (this.now() - inFlight.dispatchedAt >= this.dispatchConfirmMs) {
2195
- await this.redispatchInFlight(sessionId, inFlight);
2196
- }
2197
- }
2198
2243
  const pastStuckBound = this.now() - inFlight.dispatchedAt >= this.stuckQueuedMs;
2199
2244
  const sessionIdle = state === "queued" && !hasRunningAssistantExcept(messages, inFlight.opencodeMessageId);
2200
- if (state === "queued" && pastStuckBound && sessionIdle) {
2201
- if (!inFlight.stuckReported) {
2202
- inFlight.stuckReported = true;
2203
- void this.postSignal(conv.id, inFlight.evidentMessageId, "stuck_queued", {
2204
- stuck_for_ms: this.now() - inFlight.dispatchedAt
2205
- });
2206
- }
2207
- const dueForRedrive = inFlight.lastRedriveAt == null || this.now() - inFlight.lastRedriveAt >= this.stuckQueuedMs;
2208
- if (dueForRedrive && isSessionSettled(messages, this.now(), this.settleMs)) {
2209
- const removed = await this.redriveStuckQueued(sessionId, watcher, inFlight, messages);
2210
- if (removed) return;
2211
- }
2245
+ if (state === "queued" && pastStuckBound && sessionIdle && !inFlight.stuckReported) {
2246
+ inFlight.stuckReported = true;
2247
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "stuck_queued", {
2248
+ stuck_for_ms: this.now() - inFlight.dispatchedAt
2249
+ });
2212
2250
  }
2213
2251
  if (this.now() >= inFlight.deadline) {
2214
2252
  this.log({
@@ -2217,184 +2255,11 @@ var ChannelDriver = class {
2217
2255
  conversation_id: conv.id,
2218
2256
  message_id: inFlight.evidentMessageId
2219
2257
  });
2220
- this.removeInFlight(watcher, inFlight.evidentMessageId);
2221
- }
2222
- }
2223
- /**
2224
- * Re-dispatch a message whose user row never appeared (idle-path guard). Safe:
2225
- * opencode treats a duplicate caller-supplied `messageID` as idempotent (PoC
2226
- * fact 9) — one user message + one reply even if the original DID land. Resets
2227
- * the dispatch timestamp so the guard doesn't immediately fire again.
2228
- */
2229
- async redispatchInFlight(sessionId, inFlight) {
2230
- const options = {
2231
- agent: inFlight.message.opencode_agent ?? void 0,
2232
- model: inFlight.message.opencode_model ?? void 0
2233
- };
2234
- this.log({
2235
- level: "info",
2236
- message: `Message ${inFlight.evidentMessageId.slice(0, 8)} not observed after dispatch \u2014 re-dispatching (idle-path guard)`,
2237
- message_id: inFlight.evidentMessageId
2238
- });
2239
- try {
2240
- await sendPromptAsync(
2241
- this.port,
2242
- sessionId,
2243
- inFlight.message.content,
2244
- options,
2245
- inFlight.opencodeMessageId
2246
- );
2247
- } catch (err) {
2248
- this.log({
2249
- level: "error",
2250
- message: `Re-dispatch failed for message ${inFlight.evidentMessageId.slice(0, 8)}: ${err instanceof Error ? err.message : String(err)}`,
2251
- message_id: inFlight.evidentMessageId
2252
- });
2253
- }
2254
- inFlight.dispatchedAt = this.now();
2255
- }
2256
- /**
2257
- * RE-DRIVE a stuck-`queued` follow-up so opencode actually runs it
2258
- * (queued-followup-redrive; the fix for the 2026-07-18 dev incident).
2259
- *
2260
- * The wedge: a follow-up `prompt_async`'d mid-turn / in the post-turn settling
2261
- * window is orphaned — its user message persists but the turn never runs
2262
- * (`messageRunState === 'queued'`). Proven against real opencode 1.18.3 by an
2263
- * isolated, interleaved experiment (`.harness/followup-send-mechanism-finding.md`):
2264
- * the un-sticking variable is the `messageID` FORMAT. A follow-up carrying the
2265
- * runner's CUSTOM underscore id (`msg_<sanitized-uuid>`) is NEVER picked up mid-
2266
- * turn (0/24 trials); the SAME follow-up carrying a NATIVE-format id
2267
- * (`msg_`+24 base62) runs once the prior turn settles (~50% locally, reliably on
2268
- * dev). `parts[].id` and `agent`/`model` were proven IRRELEVANT.
2269
- *
2270
- * So we re-`prompt_async` into the SAME opencode session (opencode-web does
2271
- * exactly this and it works — UPDATE 2 in the investigation doc), preserving the
2272
- * conversation's history/continuity: we do NOT create a fresh session and we do
2273
- * NOT overwrite the conversation's `opencode_session_id`. Only the opencode
2274
- * user-message id changes — to a fresh native id per attempt (opencode's
2275
- * caller-supplied id dedup is global+permanent, so each attempt needs a never-
2276
- * seen id).
2277
- *
2278
- * Reply correlation is PRESERVED: the native id is random and NOT re-derivable
2279
- * from the row id, so the runner carries it to the server (on markProcessing/
2280
- * markDone via `redriveOpencodeMessageId`), which persists it on the row and
2281
- * correlates the reply by THAT id (`conversation-notification.ts`). A normal,
2282
- * never-re-driven message still correlates by the derived stable id — unchanged.
2283
- *
2284
- * Bounded to `stuckQueuedRedriveMax` attempts. On exhaustion the row is marked
2285
- * FAILED (existing channel failure affordance) so the user is TOLD it could not
2286
- * be answered rather than left silent, and it is removed from the in-flight set.
2287
- *
2288
- * @returns true if the message LEFT this watcher's in-flight set (gave up +
2289
- * marked failed) — the caller then stops servicing it this tick. Returns false
2290
- * when the follow-up stays in THIS watcher (re-driven in place, or the re-drive
2291
- * send failed and the next window retries).
2292
- */
2293
- async redriveStuckQueued(sessionId, watcher, inFlight, messages) {
2294
- if (await this.deliverIfAnyAttemptCompleted(sessionId, watcher, inFlight, messages)) {
2295
- return true;
2296
- }
2297
- if (inFlight.redriveAttempts >= this.stuckQueuedRedriveMax) {
2298
- this.log({
2299
- level: "error",
2300
- message: `Message ${inFlight.evidentMessageId.slice(0, 8)} stuck queued after ${inFlight.redriveAttempts} re-drive attempt(s) \u2014 marking failed`,
2301
- conversation_id: watcher.conv.id,
2302
- message_id: inFlight.evidentMessageId
2303
- });
2304
- try {
2305
- await this.markFailed(watcher.conv.id, inFlight.evidentMessageId);
2306
- } catch (err) {
2307
- if (err instanceof ChannelAuthError) throw err;
2308
- this.log({
2309
- level: "error",
2310
- message: `Failed to mark stuck message ${inFlight.evidentMessageId.slice(0, 8)} failed (leaving for the cron safety net): ${err instanceof Error ? err.message : String(err)}`,
2311
- conversation_id: watcher.conv.id,
2312
- message_id: inFlight.evidentMessageId
2313
- });
2314
- }
2315
- this.removeInFlight(watcher, inFlight.evidentMessageId);
2316
- return true;
2317
- }
2318
- inFlight.redriveAttempts += 1;
2319
- inFlight.lastRedriveAt = this.now();
2320
- this.log({
2321
- level: "info",
2322
- message: `Message ${inFlight.evidentMessageId.slice(0, 8)} stuck queued on an idle session \u2014 re-driving into the SAME session with a native id (attempt ${inFlight.redriveAttempts}/${this.stuckQueuedRedriveMax})`,
2323
- conversation_id: watcher.conv.id,
2324
- message_id: inFlight.evidentMessageId
2325
- });
2326
- void this.postSignal(watcher.conv.id, inFlight.evidentMessageId, "redriven", {
2327
- redrive_attempt: inFlight.redriveAttempts
2328
- });
2329
- const options = {
2330
- agent: inFlight.message.opencode_agent ?? void 0,
2331
- model: inFlight.message.opencode_model ?? void 0
2332
- };
2333
- const nativeId = nativeOpencodeMessageId();
2334
- try {
2335
- await sendPromptAsync(this.port, sessionId, inFlight.message.content, options, nativeId);
2336
- } catch (err) {
2337
- if (err instanceof ChannelAuthError) throw err;
2338
- inFlight.redriveAttempts -= 1;
2339
- this.log({
2340
- level: "error",
2341
- message: `Re-drive failed for stuck message ${inFlight.evidentMessageId.slice(0, 8)} (will retry next window): ${err instanceof Error ? err.message : String(err)}`,
2342
- conversation_id: watcher.conv.id,
2343
- message_id: inFlight.evidentMessageId
2344
- });
2345
- return false;
2346
- }
2347
- inFlight.opencodeMessageId = nativeId;
2348
- inFlight.redriveOpencodeMessageId = nativeId;
2349
- inFlight.attemptedOpencodeMessageIds.push(nativeId);
2350
- inFlight.started = false;
2351
- return false;
2352
- }
2353
- /**
2354
- * Finding 2 (Bugbot #217): scan EVERY opencode id this stuck message has been
2355
- * driven under (`attemptedOpencodeMessageIds`) for a COMPLETED correlated reply
2356
- * in the tick's snapshot; if one is found, markDone off THAT id (so the reply an
2357
- * earlier re-drive attempt eventually produced is delivered) instead of
2358
- * re-driving again or marking failed. Idempotent + guarded like the watcher's
2359
- * done branch. `@returns` true when the message left the in-flight set (delivered
2360
- * or terminally-undeliverable) — the caller then stops servicing it this tick.
2361
- *
2362
- * The LATEST id is normally handled by `serviceInFlightMessage`'s own `done`
2363
- * branch; this covers the ids a re-drive OVERWROTE, which that branch no longer
2364
- * polls. `messageRunState === 'done'` means a completed, non-errored correlated
2365
- * reply exists for that id.
2366
- */
2367
- async deliverIfAnyAttemptCompleted(sessionId, watcher, inFlight, messages) {
2368
- const completedId = inFlight.attemptedOpencodeMessageIds.find(
2369
- (id) => messageRunState(messages, id) === "done"
2370
- );
2371
- if (!completedId) return false;
2372
- if (inFlight.done) {
2373
- this.removeInFlight(watcher, inFlight.evidentMessageId);
2374
- return true;
2375
- }
2376
- this.log({
2377
- level: "info",
2378
- message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed under an earlier re-drive attempt's id \u2014 marking done (not re-driving/failing)`,
2379
- conversation_id: watcher.conv.id,
2380
- message_id: inFlight.evidentMessageId
2381
- });
2382
- try {
2383
- await this.markDone(watcher.conv.id, inFlight.evidentMessageId, sessionId, completedId);
2384
- } catch (err) {
2385
- if (err instanceof ChannelAuthError) throw err;
2386
- this.log({
2387
- level: "error",
2388
- message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done off an earlier re-drive attempt (leaving for the cron safety net): ${err instanceof Error ? err.message : String(err)}`,
2389
- conversation_id: watcher.conv.id,
2390
- message_id: inFlight.evidentMessageId
2258
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "gave_up", {
2259
+ watched_for_ms: this.now() - inFlight.dispatchedAt
2391
2260
  });
2392
2261
  this.removeInFlight(watcher, inFlight.evidentMessageId);
2393
- return true;
2394
2262
  }
2395
- inFlight.done = true;
2396
- this.removeInFlight(watcher, inFlight.evidentMessageId);
2397
- return true;
2398
2263
  }
2399
2264
  // -------------------------------------------------------------------------
2400
2265
  // Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
@@ -2483,19 +2348,17 @@ var ChannelDriver = class {
2483
2348
  * Re-adopt ONE `processing` row against the tick's session message snapshot
2484
2349
  * (ADR-0046 Decision §1/§2). Idempotent: skips a row already being driven.
2485
2350
  *
2486
- * Branches on `messageRunState(messages, effectiveId)`, where `effectiveId` is
2487
- * the NATIVE id a prior lifetime's re-drive ran this row under
2488
- * (`row.opencode_message_id`) if present, else the STABLE derived id
2489
- * (`opencodeMessageIdFor(row.id)`). Consulting the native id is what makes a
2490
- * re-driven row that ALREADY ran/completed resolve correctly on restart instead
2491
- * of looking `queued` under the (never-run) stable id and being re-driven AGAIN
2492
- * (Bugbot #217 Finding 3 — the duplicate-turn bug):
2351
+ * Branches on `messageRunState(messages, row.opencode_message_id)` the
2352
+ * opencode-assigned user-message id persisted on the first `processing` PATCH
2353
+ * (#218). A row with a NULL stored id (dispatched but the read-back never landed
2354
+ * before the restart) has no id to correlate treated as an orphan and
2355
+ * re-dispatched (at most once, see `forceReadoptRun`):
2493
2356
  * - `done` → `markDone` now (guarded like the watcher's done branch);
2494
2357
  * - `failed` → `markFailed` with the surfaced error (issue #182), so an
2495
2358
  * errored turn is reported failed on restart, NOT re-dispatched;
2496
2359
  * - `running`/`queued` → re-attach a watcher via `registerReadopted` (no re-dispatch),
2497
- * tracking the effective id so the reply correlates by it;
2498
- * - `unknown` → re-dispatch the STABLE id + attach a watcher (orphan).
2360
+ * tracking the stored id so the reply correlates by it;
2361
+ * - `unknown`/null id → re-dispatch (opencode assigns a fresh id) + attach a watcher.
2499
2362
  *
2500
2363
  * Only `ChannelAuthError` propagates.
2501
2364
  */
@@ -2509,10 +2372,8 @@ var ChannelDriver = class {
2509
2372
  });
2510
2373
  return;
2511
2374
  }
2512
- const stableId = opencodeMessageIdFor2(row.id);
2513
- const nativeRedriveId = row.opencode_message_id;
2514
- const ocId = nativeRedriveId ?? stableId;
2515
- const state = messageRunState(messages, ocId);
2375
+ const ocId = row.opencode_message_id;
2376
+ const state = messageRunState(messages, ocId ?? "");
2516
2377
  if (state === "done") {
2517
2378
  if (this.doneUndeliverable.has(row.id)) {
2518
2379
  this.log({
@@ -2530,7 +2391,7 @@ var ChannelDriver = class {
2530
2391
  message_id: row.id
2531
2392
  });
2532
2393
  try {
2533
- await this.markDone(row.conversation_id, row.id, sessionId, nativeRedriveId);
2394
+ await this.markDone(row.conversation_id, row.id, sessionId, ocId);
2534
2395
  } catch (err) {
2535
2396
  if (err instanceof ChannelAuthError) throw err;
2536
2397
  if (err instanceof ChannelTerminalError) {
@@ -2555,7 +2416,7 @@ var ChannelDriver = class {
2555
2416
  return;
2556
2417
  }
2557
2418
  if (state === "failed") {
2558
- const error2 = messageError(messages, ocId) ?? void 0;
2419
+ const error2 = messageError(messages, ocId ?? "") ?? void 0;
2559
2420
  this.log({
2560
2421
  level: "error",
2561
2422
  message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
@@ -2596,23 +2457,16 @@ var ChannelDriver = class {
2596
2457
  });
2597
2458
  return;
2598
2459
  }
2599
- if (state === "running" || state === "queued") {
2460
+ if ((state === "running" || state === "queued") && ocId) {
2600
2461
  const conv = this.convForRow(sessionId, row);
2601
2462
  const message = this.queuedMessageForRow(row);
2602
- this.registerReadopted(
2603
- conv,
2604
- sessionId,
2605
- message,
2606
- ocId,
2607
- this.processedAtMs(row),
2608
- nativeRedriveId
2609
- );
2463
+ this.registerReadopted(conv, sessionId, message, ocId, this.processedAtMs(row));
2610
2464
  this.dispatched.add(row.id);
2611
2465
  this.readopted.add(row.id);
2612
2466
  this.ensureWatcherRunning(sessionId);
2613
2467
  this.log({
2614
2468
  level: "info",
2615
- message: `Re-adopt: message ${row.id.slice(0, 8)} ${state} \u2014 re-attached watcher (${nativeRedriveId ? "native re-drive id" : "stable id"}, no re-dispatch)`,
2469
+ message: `Re-adopt: message ${row.id.slice(0, 8)} ${state} \u2014 re-attached watcher (stored id, no re-dispatch)`,
2616
2470
  conversation_id: row.conversation_id,
2617
2471
  message_id: row.id
2618
2472
  });
@@ -2621,23 +2475,36 @@ var ChannelDriver = class {
2621
2475
  await this.forceReadoptRun(sessionId, row);
2622
2476
  }
2623
2477
  /**
2624
- * Re-dispatch an orphaned (`unknown`) `processing` row (ADR-0046 Decision §2).
2478
+ * Re-dispatch an orphaned (`unknown`/null-id) `processing` row (ADR-0046 §2).
2479
+ *
2480
+ * #218/WI-5: the row's user message is absent (never kept, or a null stored id),
2481
+ * so we re-`prompt_async` WITHOUT a caller id (opencode assigns a monotonic one),
2482
+ * read it back, and register the watcher under the assigned id so the reply
2483
+ * correlates server-side.
2625
2484
  *
2626
- * The stable-id user message is absent from the session, so we (re-)dispatch with
2627
- * the STABLE id (`opencodeMessageIdFor(row.id)`) NOT a divergent per-attempt id.
2628
- * This is what keeps the reply correlatable: the server's completion
2629
- * notification looks for the reply under the stable id, so the fresh turn's reply
2630
- * (which hangs off the stable id) is found and delivered. The residual
2631
- * duplicate-incomplete-turn semantics (ADR §2, `.harness/restart-recovery-orphan-finding.md`)
2632
- * are unchanged and, for an ABSENT id, cannot bite there is no existing turn
2633
- * to swallow the duplicate.
2485
+ * ⚠️ AT-MOST-ONCE (High-2): dispatch is no longer idempotent (no caller-supplied
2486
+ * id). Without a guard, if this dispatches on tick N but the read-back+persist
2487
+ * hasn't landed before tick N+1 re-reads the still-null `opencode_message_id`,
2488
+ * tick N+1 would dispatch AGAIN duplicate user turns. The `awaitingReadopt`
2489
+ * latch makes a null-id row re-dispatched AT MOST ONCE per outstanding read-back:
2490
+ * short-circuit while the row is latched; clear it on a successful dispatch (the
2491
+ * row is then tracked in `dispatched`, so `readoptOne`'s early skip prevents
2492
+ * re-entry) OR on a failed/unresolved dispatch (genuinely un-sent → the next tick
2493
+ * may retry exactly once more).
2634
2494
  *
2635
- * `evidentMessageId = row.id` addresses the SERVER row; the stable
2636
- * `opencodeMessageId` is what the watcher polls. Deadline anchored to
2495
+ * `evidentMessageId = row.id` addresses the SERVER row. Deadline anchored to
2637
2496
  * `processed_at` (Invariant 1).
2638
2497
  */
2639
2498
  async forceReadoptRun(sessionId, row) {
2640
- const ocId = opencodeMessageIdFor2(row.id);
2499
+ if (this.awaitingReadopt.has(row.id)) {
2500
+ this.log({
2501
+ level: "info",
2502
+ message: `Re-adopt: message ${row.id.slice(0, 8)} already has a re-dispatch awaiting read-back \u2014 skipping (at most once)`,
2503
+ conversation_id: row.conversation_id,
2504
+ message_id: row.id
2505
+ });
2506
+ return;
2507
+ }
2641
2508
  if (this.processedAtMs(row) + this.pausedMaxWaitMs <= this.now()) {
2642
2509
  this.dontRedispatch.add(row.id);
2643
2510
  this.log({
@@ -2654,13 +2521,19 @@ var ChannelDriver = class {
2654
2521
  };
2655
2522
  this.log({
2656
2523
  level: "info",
2657
- message: `Re-adopt: message ${row.id.slice(0, 8)} orphaned (user message absent) \u2014 re-dispatching with the stable id`,
2524
+ message: `Re-adopt: message ${row.id.slice(0, 8)} orphaned (user message absent) \u2014 re-dispatching (opencode assigns a fresh id)`,
2658
2525
  conversation_id: row.conversation_id,
2659
2526
  message_id: row.id
2660
2527
  });
2528
+ this.awaitingReadopt.add(row.id);
2529
+ let ocId;
2661
2530
  try {
2662
- await sendPromptAsync(this.port, sessionId, row.content, options, ocId);
2531
+ ocId = await this.dispatchLocked(
2532
+ sessionId,
2533
+ () => sendPromptAsync(this.port, sessionId, row.content, options)
2534
+ );
2663
2535
  } catch (err) {
2536
+ this.awaitingReadopt.delete(row.id);
2664
2537
  if (err instanceof ChannelAuthError) throw err;
2665
2538
  this.log({
2666
2539
  level: "error",
@@ -2670,11 +2543,22 @@ var ChannelDriver = class {
2670
2543
  });
2671
2544
  return;
2672
2545
  }
2546
+ if (ocId === null) {
2547
+ this.awaitingReadopt.delete(row.id);
2548
+ this.log({
2549
+ level: "error",
2550
+ message: `Re-adopt: message ${row.id.slice(0, 8)} re-dispatched but its opencode id could not be read back \u2014 leaving un-tracked to retry next drain`,
2551
+ conversation_id: row.conversation_id,
2552
+ message_id: row.id
2553
+ });
2554
+ return;
2555
+ }
2673
2556
  const conv = this.convForRow(sessionId, row);
2674
2557
  const message = this.queuedMessageForRow(row);
2675
2558
  this.registerReadopted(conv, sessionId, message, ocId, this.processedAtMs(row));
2676
2559
  this.dispatched.add(row.id);
2677
2560
  this.readopted.add(row.id);
2561
+ this.awaitingReadopt.delete(row.id);
2678
2562
  this.ensureWatcherRunning(sessionId);
2679
2563
  }
2680
2564
  /**
@@ -3387,7 +3271,6 @@ async function getAgentInfo(agentId, authHeader) {
3387
3271
  var MAX_ACTIVITY_LOG_ENTRIES = 10;
3388
3272
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
3389
3273
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
3390
- var CHANNEL_SETTLE_MS = Number(process.env.EVIDENT_SETTLE_MS) || void 0;
3391
3274
  function log2(state, message, isError = false) {
3392
3275
  if (state.json) {
3393
3276
  console.log(
@@ -3726,7 +3609,6 @@ async function run(options) {
3726
3609
  getAuthHeader: () => state.authHeader,
3727
3610
  conversationFilter: state.conversationFilter,
3728
3611
  stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
3729
- settleMs: CHANNEL_SETTLE_MS,
3730
3612
  log: (entry) => logActivity(state, {
3731
3613
  type: entry.level === "error" ? "error" : "info",
3732
3614
  message: entry.message,
@@ -3746,7 +3628,11 @@ async function run(options) {
3746
3628
  type: "info",
3747
3629
  message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (agent: ${agentId})`
3748
3630
  });
3749
- emitAgentConnected(state.agentId, { port: state.port });
3631
+ emitAgentConnected(state.agentId, {
3632
+ port: state.port,
3633
+ cli_version: getCliVersion(),
3634
+ opencode_version: state.opencodeVersion
3635
+ });
3750
3636
  if (!isReconnect) tunnelSpinner?.succeed("Tunnel connected");
3751
3637
  if (state.interactive) displayStatus(state);
3752
3638
  channelDriver.drainPending().then((processed) => {