@evident-ai/cli 3.0.1-dev.e12b2df → 3.0.1-dev.e12d079

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
@@ -470,6 +470,12 @@ import chalk6 from "chalk";
470
470
  import ora3 from "ora";
471
471
  import { select as select3 } from "@inquirer/prompts";
472
472
 
473
+ // ../../packages/types/src/opencode/index.ts
474
+ function opencodeMessageIdFor(queuedMessageId) {
475
+ const sanitized = queuedMessageId.replace(/[^a-zA-Z0-9]/g, "_");
476
+ return `msg_${sanitized}`;
477
+ }
478
+
473
479
  // ../../packages/types/src/telemetry/index.ts
474
480
  var TelemetryEventTypes = {
475
481
  // Agent activity events (shown in web UI activity log)
@@ -484,6 +490,29 @@ var TelemetryEventTypes = {
484
490
  var MAX_FRAME_BYTES = 256 * 1024;
485
491
  var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
486
492
 
493
+ // ../../packages/types/src/logging/index.ts
494
+ var CORRELATION_ID_HEADER = "x-evident-correlation-id";
495
+ function log(level, event, fields) {
496
+ const method = level === "debug" ? "log" : level;
497
+ try {
498
+ console[method]("[evident]", JSON.stringify({ level, event, ...fields }));
499
+ } catch (err) {
500
+ console.error(
501
+ "[evident] log_serialize_failed",
502
+ event,
503
+ err instanceof Error ? err.message : String(err)
504
+ );
505
+ }
506
+ }
507
+ function stripQuery(url) {
508
+ try {
509
+ return new URL(url).pathname;
510
+ } catch {
511
+ const q = url.indexOf("?");
512
+ return q === -1 ? url : url.slice(0, q);
513
+ }
514
+ }
515
+
487
516
  // src/lib/telemetry.ts
488
517
  var CLI_VERSION = process.env.npm_package_version || "unknown";
489
518
  var eventBuffer = [];
@@ -684,6 +713,19 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
684
713
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
685
714
  }
686
715
 
716
+ // src/lib/opencode/opencode-version-gate.ts
717
+ var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11"];
718
+ function isQueueValidatedVersion(version) {
719
+ if (!version) return false;
720
+ return QUEUE_VALIDATED_OPENCODE_VERSIONS.includes(version);
721
+ }
722
+ function buildOpenCodeVersionWarning(version) {
723
+ if (isQueueValidatedVersion(version)) return null;
724
+ const detected = version ? `v${version}` : "unknown";
725
+ const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
726
+ return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack/WhatsApp) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
727
+ }
728
+
687
729
  // src/lib/opencode/process.ts
688
730
  import { execSync, spawn } from "child_process";
689
731
  var OPENCODE_PORT_RANGE = [4096, 4097, 4098, 4099, 4100];
@@ -998,21 +1040,23 @@ function completedOf(m) {
998
1040
  if (!m || typeof m !== "object") return void 0;
999
1041
  return m.info?.time?.completed;
1000
1042
  }
1001
- async function getSessionMessages(port, sessionId) {
1002
- try {
1003
- const res = await fetch(`${opencodeBase(port)}/session/${sessionId}/message`);
1004
- if (!res.ok) return null;
1005
- const body = await res.json();
1006
- return Array.isArray(body) ? body : null;
1007
- } catch {
1008
- return null;
1009
- }
1043
+ function idOf(m) {
1044
+ if (!m || typeof m !== "object") return void 0;
1045
+ if (typeof m.id === "string") return m.id;
1046
+ const infoId = m.info?.id;
1047
+ return typeof infoId === "string" ? infoId : void 0;
1010
1048
  }
1011
- function isTurnComplete(messages) {
1012
- if (!messages || messages.length === 0) return false;
1013
- const last = messages[messages.length - 1];
1014
- if (roleOf(last) !== "assistant") return false;
1015
- return completedOf(last) != null;
1049
+ function parentIdOf(m) {
1050
+ if (!m || typeof m !== "object") return void 0;
1051
+ if (typeof m.parentID === "string") return m.parentID;
1052
+ const infoParent = m.info?.parentID;
1053
+ return typeof infoParent === "string" ? infoParent : void 0;
1054
+ }
1055
+ function finishOf(m) {
1056
+ if (!m || typeof m !== "object") return void 0;
1057
+ if (typeof m.finish === "string") return m.finish;
1058
+ const infoFinish = m.info?.finish;
1059
+ return typeof infoFinish === "string" ? infoFinish : void 0;
1016
1060
  }
1017
1061
  async function createOpenCodeSession(port, directory) {
1018
1062
  const url = new URL(`${opencodeBase(port)}/session`);
@@ -1031,8 +1075,9 @@ async function createOpenCodeSession(port, directory) {
1031
1075
  const data = await response.json();
1032
1076
  return data.id;
1033
1077
  }
1034
- async function sendMessageToOpenCode(port, sessionId, content, options, hooks, maxWaitMs = 10 * 60 * 1e3) {
1078
+ async function sendPromptAsync(port, sessionId, content, options, messageId) {
1035
1079
  const body = {
1080
+ messageID: messageId,
1036
1081
  parts: [{ type: "text", text: content }]
1037
1082
  };
1038
1083
  if (options?.agent) {
@@ -1047,79 +1092,59 @@ async function sendMessageToOpenCode(port, sessionId, content, options, hooks, m
1047
1092
  };
1048
1093
  }
1049
1094
  }
1050
- let pollDone = false;
1051
- const reportedQuestions = /* @__PURE__ */ new Set();
1052
- const reportedPermissions = /* @__PURE__ */ new Set();
1053
- const pollInteractive = async () => {
1054
- while (!pollDone) {
1055
- await new Promise((resolve) => setTimeout(resolve, 1e3));
1056
- if (pollDone) break;
1057
- if (hooks?.onQuestion) {
1058
- try {
1059
- const res = await fetch(`${opencodeBase(port)}/question`);
1060
- if (res.ok) {
1061
- const questions = await res.json();
1062
- for (const q of questions) {
1063
- if (q.sessionID === sessionId && !reportedQuestions.has(q.id)) {
1064
- reportedQuestions.add(q.id);
1065
- await hooks.onQuestion(q);
1066
- }
1067
- }
1068
- }
1069
- } catch {
1070
- }
1071
- }
1072
- if (hooks?.onPermission) {
1073
- try {
1074
- const res = await fetch(`${opencodeBase(port)}/permission`);
1075
- if (res.ok) {
1076
- const permissions = await res.json();
1077
- for (const p of permissions) {
1078
- if (p.sessionID === sessionId && !reportedPermissions.has(p.id)) {
1079
- reportedPermissions.add(p.id);
1080
- await hooks.onPermission(p);
1081
- }
1082
- }
1083
- }
1084
- } catch {
1085
- }
1086
- }
1087
- }
1088
- };
1089
- const sendMessage = async () => {
1090
- const controller = new AbortController();
1091
- const timer = setTimeout(() => controller.abort(), maxWaitMs);
1092
- try {
1093
- const res = await fetch(`${opencodeBase(port)}/session/${sessionId}/message`, {
1094
- method: "POST",
1095
- headers: { "Content-Type": "application/json" },
1096
- body: JSON.stringify(body),
1097
- signal: controller.signal
1098
- });
1099
- if (!res.ok) {
1100
- const text = await res.text().catch(() => "");
1101
- throw new Error(`OpenCode message failed: HTTP ${res.status}${text ? `: ${text}` : ""}`);
1102
- }
1103
- const sessionRes = await fetch(`${opencodeBase(port)}/session/${sessionId}`).catch(
1104
- () => null
1105
- );
1106
- const session = sessionRes?.ok ? await sessionRes.json() : null;
1107
- const reportedInteraction = reportedQuestions.size > 0 || reportedPermissions.size > 0;
1108
- const turnComplete = isTurnComplete(await getSessionMessages(port, sessionId));
1109
- const awaitingInteraction = reportedInteraction && !turnComplete;
1110
- return { title: session?.title, awaitingInteraction };
1111
- } catch (err) {
1112
- if (err instanceof Error && err.name === "AbortError") {
1113
- throw new Error("Message processing timed out");
1114
- }
1115
- throw err;
1116
- } finally {
1117
- clearTimeout(timer);
1118
- pollDone = true;
1119
- }
1120
- };
1121
- const [result] = await Promise.all([sendMessage(), pollInteractive()]);
1122
- return result;
1095
+ const res = await fetch(`${opencodeBase(port)}/session/${sessionId}/prompt_async`, {
1096
+ method: "POST",
1097
+ headers: { "Content-Type": "application/json" },
1098
+ body: JSON.stringify(body)
1099
+ });
1100
+ if (res.status < 200 || res.status >= 300) {
1101
+ const text = await res.text().catch(() => "");
1102
+ throw new Error(`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}`);
1103
+ }
1104
+ }
1105
+ function findAssistantReplyAfter(messages, userMessageId) {
1106
+ if (!messages || messages.length === 0) return null;
1107
+ const byParent = messages.find(
1108
+ (m) => roleOf(m) === "assistant" && parentIdOf(m) === userMessageId
1109
+ );
1110
+ if (byParent) return byParent;
1111
+ const userIndex = messages.findIndex((m) => idOf(m) === userMessageId);
1112
+ if (userIndex === -1) return null;
1113
+ for (let i = userIndex + 1; i < messages.length; i++) {
1114
+ if (roleOf(messages[i]) === "assistant") return messages[i];
1115
+ }
1116
+ return null;
1117
+ }
1118
+ function findLastAssistantReplyFor(messages, userMessageId) {
1119
+ if (!messages || messages.length === 0) return null;
1120
+ for (let i = messages.length - 1; i >= 0; i--) {
1121
+ const m = messages[i];
1122
+ if (roleOf(m) === "assistant" && parentIdOf(m) === userMessageId) return m;
1123
+ }
1124
+ const userIndex = messages.findIndex((m) => idOf(m) === userMessageId);
1125
+ if (userIndex === -1) return null;
1126
+ let last = null;
1127
+ for (let i = userIndex + 1; i < messages.length; i++) {
1128
+ const role = roleOf(messages[i]);
1129
+ if (role === "user") break;
1130
+ if (role === "assistant") last = messages[i];
1131
+ }
1132
+ return last;
1133
+ }
1134
+ function messageRunState(messages, userMessageId) {
1135
+ if (!messages || messages.length === 0) return "unknown";
1136
+ const hasUser = messages.some((m) => idOf(m) === userMessageId);
1137
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
1138
+ if (!hasUser) {
1139
+ if (!reply) return "unknown";
1140
+ }
1141
+ if (!reply) return "queued";
1142
+ if (completedOf(reply) == null) return "running";
1143
+ if (finishOf(reply) === "tool-calls") return "running";
1144
+ return "done";
1145
+ }
1146
+ function opencodeMessageIdFor2(queuedMessageId) {
1147
+ return opencodeMessageIdFor(queuedMessageId);
1123
1148
  }
1124
1149
 
1125
1150
  // src/lib/tunnel/connection.ts
@@ -1190,12 +1215,20 @@ var StreamForwarder = class {
1190
1215
  }
1191
1216
  async handleOpen(frame) {
1192
1217
  const { sid, method, path, headers, has_body } = frame;
1218
+ const correlationId = headers?.[CORRELATION_ID_HEADER];
1219
+ const startedAt = Date.now();
1193
1220
  if (path === TUNNEL_DRAIN_PING_PATH) {
1194
1221
  this.callbacks.onDrainPing?.();
1195
1222
  this.send({ type: "head", sid, status: 204, headers: {} });
1196
1223
  this.send({ type: "res_end", sid });
1197
1224
  return;
1198
1225
  }
1226
+ log("info", "agent_request", {
1227
+ correlation_id: correlationId,
1228
+ sid,
1229
+ method,
1230
+ path: stripQuery(path)
1231
+ });
1199
1232
  const ac = new AbortController();
1200
1233
  let bodyPromise;
1201
1234
  let pushBody;
@@ -1242,6 +1275,12 @@ var StreamForwarder = class {
1242
1275
  if (!STRIP_RES.has(key.toLowerCase())) resHeaders[key] = value;
1243
1276
  });
1244
1277
  this.send({ type: "head", sid, status: upstream.status, headers: resHeaders });
1278
+ log("info", "agent_response", {
1279
+ correlation_id: correlationId,
1280
+ sid,
1281
+ status: upstream.status,
1282
+ duration_ms: Date.now() - startedAt
1283
+ });
1245
1284
  this.callbacks.onHead?.(sid, upstream.status);
1246
1285
  try {
1247
1286
  if (upstream.body) {
@@ -1498,6 +1537,12 @@ var RunnerConnection = class {
1498
1537
  };
1499
1538
 
1500
1539
  // src/lib/channels/driver.ts
1540
+ function messageIdOf(m) {
1541
+ if (!m || typeof m !== "object") return void 0;
1542
+ if (typeof m.id === "string") return m.id;
1543
+ const infoId = m.info?.id;
1544
+ return typeof infoId === "string" ? infoId : void 0;
1545
+ }
1501
1546
  var DEFAULT_RETRY_POLICY = {
1502
1547
  maxAttempts: 6,
1503
1548
  baseDelayMs: 500,
@@ -1505,12 +1550,21 @@ var DEFAULT_RETRY_POLICY = {
1505
1550
  };
1506
1551
  var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
1507
1552
  var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
1553
+ var DEFAULT_DISPATCH_CONFIRM_MS = 6e3;
1508
1554
  var ChannelAuthError = class extends Error {
1509
1555
  constructor(message) {
1510
1556
  super(message);
1511
1557
  this.name = "ChannelAuthError";
1512
1558
  }
1513
1559
  };
1560
+ var ChannelTerminalError = class extends Error {
1561
+ status;
1562
+ constructor(message, status) {
1563
+ super(message);
1564
+ this.name = "ChannelTerminalError";
1565
+ this.status = status;
1566
+ }
1567
+ };
1514
1568
  function backoffDelay(attempt, policy) {
1515
1569
  const exp = policy.baseDelayMs * Math.pow(2, attempt);
1516
1570
  const capped = Math.min(policy.maxDelayMs, exp);
@@ -1531,15 +1585,26 @@ var ChannelDriver = class {
1531
1585
  sleep;
1532
1586
  pausedPollIntervalMs;
1533
1587
  pausedMaxWaitMs;
1588
+ dispatchConfirmMs;
1589
+ now;
1534
1590
  /** Cache of conversationId → opencode sessionId. */
1535
1591
  sessions = /* @__PURE__ */ new Map();
1536
1592
  /**
1537
- * Outstanding paused-session watchers, keyed by `message.id` (WI-2-CLI).
1538
- * Single-flight per message: while a watcher is live for a message we never
1539
- * start a second one. The message stays `processing` for the watcher's lifetime
1540
- * so the `?status=pending` drain cannot double-claim it.
1593
+ * Per-SESSION watchers (WI-3), keyed by opencode sessionId. Single-flight per
1594
+ * session: one polling loop services all of that session's in-flight messages.
1595
+ * A session entry exists while it has any in-flight (dispatched-but-not-done)
1596
+ * message; it is removed once its in-flight set empties.
1541
1597
  */
1542
1598
  watchers = /* @__PURE__ */ new Map();
1599
+ /**
1600
+ * AUTHORITATIVE local dedup (WI-3): Evident message ids that have been
1601
+ * dispatched and are still in-flight. A message in this set is never
1602
+ * re-`prompt_async`-ed by a subsequent poll tick while it is queued/running.
1603
+ * Backed by a stable minted opencode `messageID` whose duplicate re-enqueue is
1604
+ * idempotent on opencode (PoC fact 9) — so even if this set is lost on restart,
1605
+ * a steady-state-poll re-dispatch will not double-run the message.
1606
+ */
1607
+ dispatched = /* @__PURE__ */ new Set();
1543
1608
  /**
1544
1609
  * Cache of the opencode root directory (from `GET /path`). Resolved lazily on
1545
1610
  * first session creation so drain-created sessions are rooted at the project
@@ -1562,6 +1627,8 @@ var ChannelDriver = class {
1562
1627
  this.sleep = config2.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1563
1628
  this.pausedPollIntervalMs = config2.pausedPollIntervalMs ?? DEFAULT_PAUSED_POLL_INTERVAL_MS;
1564
1629
  this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
1630
+ this.dispatchConfirmMs = config2.dispatchConfirmMs ?? DEFAULT_DISPATCH_CONFIRM_MS;
1631
+ this.now = config2.now ?? (() => Date.now());
1565
1632
  }
1566
1633
  /** The IPv4-loopback base URL for the local `opencode serve`. */
1567
1634
  get opencodeBase() {
@@ -1571,16 +1638,16 @@ var ChannelDriver = class {
1571
1638
  // Public API
1572
1639
  // -------------------------------------------------------------------------
1573
1640
  /**
1574
- * Drain all pending channel conversations once: poll → processcallback.
1641
+ * Drain all pending channel conversations once: poll → dispatchregister.
1575
1642
  * Called on tunnel `connected` (WI-CHAN-4) and on each poll tick by `run.ts`.
1576
1643
  * Re-entrant calls while a drain is in flight are skipped (return 0).
1577
1644
  *
1578
- * @returns the number of messages processed.
1645
+ * @returns the number of messages NEWLY dispatched to opencode's native queue.
1579
1646
  */
1580
1647
  async drainPending() {
1581
1648
  if (this.draining) return 0;
1582
1649
  this.draining = true;
1583
- let processed = 0;
1650
+ let dispatched = 0;
1584
1651
  try {
1585
1652
  const conversations = await this.getPendingConversations();
1586
1653
  if (conversations.length > 0) {
@@ -1591,95 +1658,104 @@ var ChannelDriver = class {
1591
1658
  });
1592
1659
  }
1593
1660
  for (const conv of conversations) {
1594
- processed += await this.processConversation(conv);
1661
+ dispatched += await this.processConversation(conv);
1595
1662
  }
1596
1663
  } finally {
1597
1664
  this.draining = false;
1598
1665
  }
1599
- return processed;
1666
+ return dispatched;
1667
+ }
1668
+ /**
1669
+ * True while any per-session watcher has a non-empty in-flight dispatched set
1670
+ * (Task 3.7). `run.ts` treats this as NON-idle so `--idle-timeout` cannot exit
1671
+ * the process while a dispatched message is still queued/running — which would
1672
+ * kill the turn and orphan its reply.
1673
+ */
1674
+ hasInFlightWatchers() {
1675
+ for (const watcher of this.watchers.values()) {
1676
+ if (watcher.inFlight.size > 0) return true;
1677
+ }
1678
+ return false;
1600
1679
  }
1601
1680
  /**
1602
- * Await all outstanding paused-session watchers (WI-2-CLI).
1681
+ * Await all outstanding per-session watchers (WI-3).
1603
1682
  *
1604
- * In production the watchers are deliberately started-not-awaited so the drain
1605
- * loop never blocks on them and process exit is not held up (the cron recovers
1606
- * any abandoned ones). This helper exists primarily for deterministic tests
1607
- * that need to observe the watcher's effect (the `done` PATCH or its giving up)
1608
- * after a non-blocking `drainPending`. Watchers never reject, so this resolves.
1683
+ * In production the watcher loops are deliberately started-not-awaited so the
1684
+ * drain loop never blocks on them and process exit is not held up (the cron
1685
+ * recovers any abandoned ones). This helper exists primarily for deterministic
1686
+ * tests that need to observe a watcher's effect (the `processing`/`done` PATCH
1687
+ * or its giving up) after a non-blocking `drainPending`. Watcher loops never
1688
+ * reject, so this resolves.
1609
1689
  */
1610
1690
  async flushPausedWatchers() {
1611
- await Promise.all([...this.watchers.values()]);
1691
+ while (true) {
1692
+ const loops = [...this.watchers.values()].map((w) => w.loop).filter((l) => l != null);
1693
+ if (loops.length === 0) return;
1694
+ await Promise.all(loops);
1695
+ const stillLive = [...this.watchers.values()].some((w) => w.loop != null);
1696
+ if (!stillLive) return;
1697
+ }
1612
1698
  }
1613
1699
  // -------------------------------------------------------------------------
1614
- // Conversation processing
1700
+ // Conversation processing (WI-3 — async dispatch)
1615
1701
  // -------------------------------------------------------------------------
1702
+ /**
1703
+ * Dispatch each pending message for a conversation to opencode's native queue
1704
+ * via `prompt_async` (Task 3.2) and register it with the conversation's
1705
+ * per-session watcher. Does NOT block on the turn and does NOT call
1706
+ * `markProcessing` here — that fires from the watcher on running-start.
1707
+ *
1708
+ * @returns the count of messages NEWLY dispatched (not already in-flight).
1709
+ */
1616
1710
  async processConversation(conv) {
1617
1711
  const sessionId = await this.ensureSession(conv);
1618
1712
  const messages = await this.getPendingMessages(conv.id);
1619
- let processed = 0;
1713
+ let dispatched = 0;
1714
+ let skippedAlreadyDispatched = 0;
1620
1715
  for (const message of messages) {
1621
- const claimed = await this.markProcessing(conv.id, message.id, sessionId);
1622
- if (!claimed) {
1623
- this.log({
1624
- level: "info",
1625
- message: `Message ${message.id.slice(0, 8)} already claimed \u2014 skipping`,
1626
- conversation_id: conv.id,
1627
- message_id: message.id
1628
- });
1716
+ if (this.dispatched.has(message.id)) {
1717
+ skippedAlreadyDispatched += 1;
1629
1718
  continue;
1630
1719
  }
1720
+ const opencodeMessageId = opencodeMessageIdFor2(message.id);
1721
+ const options = {
1722
+ agent: message.opencode_agent ?? void 0,
1723
+ model: message.opencode_model ?? void 0
1724
+ };
1631
1725
  try {
1632
1726
  this.log({
1633
1727
  level: "info",
1634
- message: `Sending queued message ${message.id.slice(0, 8)} to OpenCode (session ${sessionId.slice(0, 8)})`,
1635
- conversation_id: conv.id,
1636
- message_id: message.id
1637
- });
1638
- const result = await sendMessageToOpenCode(
1639
- this.port,
1640
- sessionId,
1641
- message.content,
1642
- {
1643
- agent: message.opencode_agent ?? void 0,
1644
- model: message.opencode_model ?? void 0
1645
- },
1646
- {
1647
- onQuestion: (question) => this.reportInteraction(conv.id, "question", question),
1648
- onPermission: (permission) => this.reportInteraction(conv.id, "permission", permission)
1649
- }
1650
- );
1651
- if (result.awaitingInteraction) {
1652
- this.log({
1653
- level: "info",
1654
- message: `Message ${message.id.slice(0, 8)} paused awaiting interaction \u2014 watching session for completion`,
1655
- conversation_id: conv.id,
1656
- message_id: message.id
1657
- });
1658
- this.startPausedWatcher(conv, message, sessionId);
1659
- continue;
1660
- }
1661
- await this.confirmCompletion(sessionId);
1662
- await this.markDone(conv.id, message.id, sessionId);
1663
- processed += 1;
1664
- this.log({
1665
- level: "info",
1666
- message: `Message ${message.id.slice(0, 8)} processed`,
1728
+ message: `Dispatching message ${message.id.slice(0, 8)} to OpenCode native queue (session ${sessionId.slice(0, 8)})`,
1667
1729
  conversation_id: conv.id,
1668
1730
  message_id: message.id
1669
1731
  });
1732
+ await sendPromptAsync(this.port, sessionId, message.content, options, opencodeMessageId);
1670
1733
  } catch (err) {
1671
1734
  if (err instanceof ChannelAuthError) throw err;
1735
+ this.dispatched.delete(message.id);
1672
1736
  await this.markFailed(conv.id, message.id).catch(() => {
1673
1737
  });
1674
1738
  this.log({
1675
1739
  level: "error",
1676
- message: `Message ${message.id.slice(0, 8)} failed: ${err instanceof Error ? err.message : String(err)}`,
1740
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${err instanceof Error ? err.message : String(err)}`,
1677
1741
  conversation_id: conv.id,
1678
1742
  message_id: message.id
1679
1743
  });
1744
+ continue;
1680
1745
  }
1746
+ this.dispatched.add(message.id);
1747
+ this.registerInFlight(conv, sessionId, message, opencodeMessageId);
1748
+ dispatched += 1;
1749
+ }
1750
+ if (messages.length > 0 && dispatched === 0 && skippedAlreadyDispatched === messages.length) {
1751
+ this.log({
1752
+ level: "error",
1753
+ message: `Conversation ${conv.id.slice(0, 8)} has ${messages.length} pending message(s) but ALL are already marked dispatched locally (in-flight set: ${this.dispatched.size}) \u2014 none sent to OpenCode this tick. If this repeats, a message may be stuck acknowledged-but-never-dispatched (its watcher never settled).`,
1754
+ conversation_id: conv.id
1755
+ });
1681
1756
  }
1682
- return processed;
1757
+ this.ensureWatcherRunning(sessionId);
1758
+ return dispatched;
1683
1759
  }
1684
1760
  async ensureSession(conv) {
1685
1761
  const cached = this.sessions.get(conv.id);
@@ -1711,111 +1787,349 @@ var ChannelDriver = class {
1711
1787
  }
1712
1788
  return this.opencodeDirectory;
1713
1789
  }
1714
- /**
1715
- * Local reconcile: re-query `GET /session/:id/message` and check whether the
1716
- * last assistant message is message-level complete (`isTurnComplete`).
1717
- *
1718
- * This is a PURE OBSERVABILITY probe on the normal (non-paused) path: the
1719
- * blocking POST already returned, and `markDone` causes the server to re-fetch
1720
- * the messages itself (via `extractTextFromMessages`) when delivering the
1721
- * reply — so this round-trip never gates delivery. We keep it only to surface a
1722
- * truthful diagnostic when opencode hasn't yet recorded a completed assistant
1723
- * turn at reconcile time, then proceed to `markDone` regardless. Uses the
1724
- * injected `fetchImpl` and reuses only the pure `isTurnComplete` predicate.
1725
- */
1726
- async confirmCompletion(sessionId) {
1727
- try {
1728
- const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
1729
- if (!res.ok) return;
1730
- const body = await res.json();
1731
- const messages = Array.isArray(body) ? body : null;
1732
- if (!isTurnComplete(messages)) {
1733
- this.log({
1734
- level: "info",
1735
- message: `Session ${sessionId.slice(0, 8)} messages do not yet show a completed assistant turn on reconcile \u2014 delivering anyway`
1736
- });
1737
- }
1738
- } catch {
1739
- }
1740
- }
1741
1790
  // -------------------------------------------------------------------------
1742
- // Paused-session watcher (WI-2-CLI)
1791
+ // Per-session watcher (WI-3)
1743
1792
  // -------------------------------------------------------------------------
1793
+ /** Register a freshly-dispatched message with its session's watcher state. */
1794
+ registerInFlight(conv, sessionId, message, opencodeMessageId) {
1795
+ let watcher = this.watchers.get(sessionId);
1796
+ if (!watcher) {
1797
+ watcher = {
1798
+ conv,
1799
+ inFlight: /* @__PURE__ */ new Map(),
1800
+ loop: null,
1801
+ reportedQuestions: /* @__PURE__ */ new Set(),
1802
+ reportedPermissions: /* @__PURE__ */ new Set()
1803
+ };
1804
+ this.watchers.set(sessionId, watcher);
1805
+ }
1806
+ const now = this.now();
1807
+ watcher.inFlight.set(message.id, {
1808
+ evidentMessageId: message.id,
1809
+ opencodeMessageId,
1810
+ message,
1811
+ dispatchedAt: now,
1812
+ deadline: now + this.pausedMaxWaitMs,
1813
+ started: false,
1814
+ done: false
1815
+ });
1816
+ }
1744
1817
  /**
1745
- * Start (but do NOT await) a watcher that resumes a paused turn to completion.
1746
- *
1747
- * Single-flight per message: if a watcher is already live for this message we
1748
- * skip. The returned watcher promise is tracked in `this.watchers` and removed
1749
- * when it settles; it never rejects (the body is fully guarded), so a failed
1750
- * poll/markDone can never crash the run loop — the cron stays as the safety net.
1818
+ * Start (but do NOT await) the per-session watcher loop if it has in-flight
1819
+ * work and is not already running. Single-flight per session. The loop is
1820
+ * tracked on the watcher and cleared when it settles; it never rejects (fully
1821
+ * guarded), so a failed poll/callback can never crash the run loop — the cron
1822
+ * stays as the safety net.
1751
1823
  */
1752
- startPausedWatcher(conv, message, sessionId) {
1753
- if (this.watchers.has(message.id)) return;
1754
- const watcher = this.watchPausedSession(conv, message, sessionId).finally(() => {
1755
- this.watchers.delete(message.id);
1824
+ ensureWatcherRunning(sessionId) {
1825
+ const watcher = this.watchers.get(sessionId);
1826
+ if (!watcher) return;
1827
+ if (watcher.loop) return;
1828
+ if (watcher.inFlight.size === 0) {
1829
+ this.watchers.delete(sessionId);
1830
+ return;
1831
+ }
1832
+ const loop = this.runWatcherLoop(sessionId, watcher).finally(() => {
1833
+ watcher.loop = null;
1834
+ if (watcher.inFlight.size === 0) {
1835
+ this.watchers.delete(sessionId);
1836
+ }
1756
1837
  });
1757
- this.watchers.set(message.id, watcher);
1838
+ watcher.loop = loop;
1758
1839
  }
1759
1840
  /**
1760
- * Poll `GET /session/:id/message` until the SAME paused turn is message-level
1761
- * complete the last message is an ASSISTANT message whose
1762
- * `info.time.completed` is set (the user answered the question/permission in
1763
- * opencode web and opencode finished the turn) then complete it via the
1764
- * EXISTING `markDone` PATCH — NO re-send of the original message. The server
1765
- * re-fetches the assistant messages on completion, so the watcher does not
1766
- * pass any reply text.
1767
- *
1768
- * Fetch seam: the poll uses the injected `this.fetchImpl` (preserving the
1769
- * tests' injection) and reuses only the pure `isTurnComplete` predicate from
1770
- * `session.ts` we do NOT call `getSessionMessages` (which uses the global
1771
- * `fetch`) here.
1772
- *
1773
- * Bounded by `pausedMaxWaitMs` (default 10 min, strictly < the 15-min cron
1774
- * reset): on timeout we STOP and leave the message `processing` so the cron
1775
- * remains the last-resort safety net. The whole body is wrapped so any
1776
- * poll/markDone failure is logged and swallowed — a watcher MUST NEVER throw
1777
- * out of the run loop.
1841
+ * The per-session polling loop (WI-3). Once per tick it:
1842
+ * 1. polls `GET /session/:id/message` once and, per in-flight message,
1843
+ * computes `messageRunState` and fires markProcessing (queued→running) /
1844
+ * markDone (done) exactly once per transition;
1845
+ * 2. applies the idle-path re-dispatch guard (a dispatched message that never
1846
+ * APPEARS re-dispatch D1 obligation 2);
1847
+ * 3. polls `/question` + `/permission` (scoped to the session) and surfaces
1848
+ * NEW ones via `reportInteraction`, carrying the PAUSED message's own
1849
+ * `source_message_id`;
1850
+ * 4. drops messages that completed or timed out from the in-flight set.
1851
+ * Exits when the in-flight set empties. Never throws.
1778
1852
  */
1779
- async watchPausedSession(conv, message, sessionId) {
1780
- const deadline = Date.now() + this.pausedMaxWaitMs;
1853
+ async runWatcherLoop(sessionId, watcher) {
1781
1854
  try {
1782
- while (Date.now() < deadline) {
1855
+ while (watcher.inFlight.size > 0) {
1783
1856
  await this.sleep(this.pausedPollIntervalMs);
1784
- let completed = false;
1857
+ let messages = null;
1785
1858
  try {
1786
1859
  const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
1787
1860
  if (res.ok) {
1788
1861
  const body = await res.json();
1789
- const messages = Array.isArray(body) ? body : null;
1790
- completed = isTurnComplete(messages);
1862
+ messages = Array.isArray(body) ? body : null;
1791
1863
  }
1792
1864
  } catch {
1793
1865
  continue;
1794
1866
  }
1795
- if (!completed) continue;
1867
+ for (const inFlight of [...watcher.inFlight.values()]) {
1868
+ await this.serviceInFlightMessage(sessionId, watcher, inFlight, messages);
1869
+ }
1870
+ await this.pollInteractions(sessionId, watcher, messages);
1871
+ }
1872
+ } catch (err) {
1873
+ if (err instanceof ChannelAuthError) {
1796
1874
  this.log({
1797
- level: "info",
1798
- message: `Paused session ${sessionId.slice(0, 8)} completed \u2014 marking message ${message.id.slice(0, 8)} done`,
1875
+ level: "error",
1876
+ message: `Session watcher aborted on auth failure for session ${sessionId.slice(0, 8)} \u2014 clearing in-flight state for re-drive after re-auth: ${err.message}`,
1877
+ conversation_id: watcher.conv.id
1878
+ });
1879
+ for (const evidentMessageId of [...watcher.inFlight.keys()]) {
1880
+ this.removeInFlight(watcher, evidentMessageId);
1881
+ }
1882
+ return;
1883
+ }
1884
+ this.log({
1885
+ level: "error",
1886
+ message: `Session watcher failed for session ${sessionId.slice(0, 8)}: ${err instanceof Error ? err.message : String(err)}`,
1887
+ conversation_id: watcher.conv.id
1888
+ });
1889
+ }
1890
+ }
1891
+ /**
1892
+ * Drive ONE in-flight message's lifecycle from the tick's message snapshot.
1893
+ * Fires markProcessing on queued→running and markDone on done (each once),
1894
+ * applies the idle-path re-dispatch guard, and removes the message from the
1895
+ * in-flight set on completion or timeout.
1896
+ */
1897
+ async serviceInFlightMessage(sessionId, watcher, inFlight, messages) {
1898
+ const conv = watcher.conv;
1899
+ const state = messageRunState(messages, inFlight.opencodeMessageId);
1900
+ if ((state === "running" || state === "done") && !inFlight.started) {
1901
+ let claimed;
1902
+ try {
1903
+ claimed = await this.markProcessing(conv.id, inFlight.evidentMessageId, sessionId);
1904
+ } catch (err) {
1905
+ if (err instanceof ChannelAuthError) throw err;
1906
+ this.log({
1907
+ level: "error",
1908
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
1799
1909
  conversation_id: conv.id,
1800
- message_id: message.id
1910
+ message_id: inFlight.evidentMessageId
1801
1911
  });
1802
- await this.markDone(conv.id, message.id, sessionId);
1803
1912
  return;
1804
1913
  }
1914
+ inFlight.started = true;
1915
+ if (!claimed) {
1916
+ this.log({
1917
+ level: "info",
1918
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
1919
+ conversation_id: conv.id,
1920
+ message_id: inFlight.evidentMessageId
1921
+ });
1922
+ }
1923
+ }
1924
+ if (state === "done") {
1925
+ if (!inFlight.done) {
1926
+ this.log({
1927
+ level: "info",
1928
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
1929
+ conversation_id: conv.id,
1930
+ message_id: inFlight.evidentMessageId
1931
+ });
1932
+ try {
1933
+ await this.markDone(conv.id, inFlight.evidentMessageId, sessionId);
1934
+ } catch (err) {
1935
+ if (err instanceof ChannelAuthError) throw err;
1936
+ if (err instanceof ChannelTerminalError) {
1937
+ this.log({
1938
+ level: "error",
1939
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
1940
+ conversation_id: conv.id,
1941
+ message_id: inFlight.evidentMessageId
1942
+ });
1943
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
1944
+ return;
1945
+ }
1946
+ if (this.now() >= inFlight.deadline) {
1947
+ this.log({
1948
+ level: "error",
1949
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done within the watch window \u2014 leaving for the cron safety net: ${err instanceof Error ? err.message : String(err)}`,
1950
+ conversation_id: conv.id,
1951
+ message_id: inFlight.evidentMessageId
1952
+ });
1953
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
1954
+ return;
1955
+ }
1956
+ this.log({
1957
+ level: "error",
1958
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
1959
+ conversation_id: conv.id,
1960
+ message_id: inFlight.evidentMessageId
1961
+ });
1962
+ return;
1963
+ }
1964
+ inFlight.done = true;
1965
+ }
1966
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
1967
+ return;
1968
+ }
1969
+ if (state === "unknown") {
1970
+ if (this.now() - inFlight.dispatchedAt >= this.dispatchConfirmMs) {
1971
+ await this.redispatchInFlight(sessionId, inFlight);
1972
+ }
1973
+ }
1974
+ if (this.now() >= inFlight.deadline) {
1805
1975
  this.log({
1806
1976
  level: "info",
1807
- message: `Paused session ${sessionId.slice(0, 8)} did not complete within the watch window \u2014 leaving message ${message.id.slice(0, 8)} for the cron safety net`,
1977
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} did not complete within the watch window \u2014 leaving for the cron safety net`,
1808
1978
  conversation_id: conv.id,
1809
- message_id: message.id
1979
+ message_id: inFlight.evidentMessageId
1810
1980
  });
1981
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
1982
+ }
1983
+ }
1984
+ /**
1985
+ * Re-dispatch a message whose user row never appeared (idle-path guard). Safe:
1986
+ * opencode treats a duplicate caller-supplied `messageID` as idempotent (PoC
1987
+ * fact 9) — one user message + one reply even if the original DID land. Resets
1988
+ * the dispatch timestamp so the guard doesn't immediately fire again.
1989
+ */
1990
+ async redispatchInFlight(sessionId, inFlight) {
1991
+ const options = {
1992
+ agent: inFlight.message.opencode_agent ?? void 0,
1993
+ model: inFlight.message.opencode_model ?? void 0
1994
+ };
1995
+ this.log({
1996
+ level: "info",
1997
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} not observed after dispatch \u2014 re-dispatching (idle-path guard)`,
1998
+ message_id: inFlight.evidentMessageId
1999
+ });
2000
+ try {
2001
+ await sendPromptAsync(
2002
+ this.port,
2003
+ sessionId,
2004
+ inFlight.message.content,
2005
+ options,
2006
+ inFlight.opencodeMessageId
2007
+ );
1811
2008
  } catch (err) {
1812
2009
  this.log({
1813
2010
  level: "error",
1814
- message: `Paused-session watcher failed for message ${message.id.slice(0, 8)}: ${err instanceof Error ? err.message : String(err)}`,
1815
- conversation_id: conv.id,
1816
- message_id: message.id
2011
+ message: `Re-dispatch failed for message ${inFlight.evidentMessageId.slice(0, 8)}: ${err instanceof Error ? err.message : String(err)}`,
2012
+ message_id: inFlight.evidentMessageId
2013
+ });
2014
+ }
2015
+ inFlight.dispatchedAt = this.now();
2016
+ }
2017
+ /**
2018
+ * Remove a message from the in-flight set AND the authoritative dispatched
2019
+ * set. Once the in-flight set empties, the watcher loop's `while` guard exits
2020
+ * and its `.finally` removes the session entry from `this.watchers`.
2021
+ */
2022
+ removeInFlight(watcher, evidentMessageId) {
2023
+ watcher.inFlight.delete(evidentMessageId);
2024
+ this.dispatched.delete(evidentMessageId);
2025
+ }
2026
+ /**
2027
+ * Poll `/question` + `/permission` (scoped to the session) and surface NEW ones
2028
+ * via `reportInteraction` (Task 3.5), carrying the PAUSED message's own
2029
+ * `source_message_id` so the server @mentions the correct person under
2030
+ * concurrency. Dedups by interaction id across ticks (reused per-session sets).
2031
+ *
2032
+ * The interaction is attributed to the in-flight message it paused on. opencode
2033
+ * stamps a `messageID` on a permission (and `tool.messageID` on a question) =
2034
+ * the assistant message id, whose `parentID` is the user message id — but the
2035
+ * simplest robust attribution here is: the single in-flight message that is
2036
+ * RUNNING (not done) is the one that paused. With one running message that is
2037
+ * unambiguous; with several we prefer an explicit messageID match, else the
2038
+ * oldest running message.
2039
+ */
2040
+ async pollInteractions(sessionId, watcher, messages) {
2041
+ let questions = [];
2042
+ try {
2043
+ const res = await this.fetchImpl(`${this.opencodeBase}/question`);
2044
+ if (res.ok) {
2045
+ const body = await res.json();
2046
+ questions = Array.isArray(body) ? body : [];
2047
+ }
2048
+ } catch {
2049
+ }
2050
+ for (const q of questions) {
2051
+ if (q.sessionID !== sessionId) continue;
2052
+ if (watcher.reportedQuestions.has(q.id)) continue;
2053
+ const paused = this.attributeInteraction(watcher, q.tool?.messageID, messages);
2054
+ const reported = await this.reportInteraction(
2055
+ watcher.conv.id,
2056
+ "question",
2057
+ q,
2058
+ paused?.message.source_message_id ?? void 0
2059
+ );
2060
+ if (reported) watcher.reportedQuestions.add(q.id);
2061
+ }
2062
+ let permissions = [];
2063
+ try {
2064
+ const res = await this.fetchImpl(`${this.opencodeBase}/permission`);
2065
+ if (res.ok) {
2066
+ const body = await res.json();
2067
+ permissions = Array.isArray(body) ? body : [];
2068
+ }
2069
+ } catch {
2070
+ }
2071
+ for (const p of permissions) {
2072
+ if (p.sessionID !== sessionId) continue;
2073
+ if (watcher.reportedPermissions.has(p.id)) continue;
2074
+ const paused = this.attributeInteraction(watcher, p.messageID, messages);
2075
+ const reported = await this.reportInteraction(
2076
+ watcher.conv.id,
2077
+ "permission",
2078
+ p,
2079
+ paused?.message.source_message_id ?? void 0
2080
+ );
2081
+ if (reported) watcher.reportedPermissions.add(p.id);
2082
+ }
2083
+ }
2084
+ /**
2085
+ * Attribute a surfaced interaction to the in-flight message it paused on (M-1).
2086
+ *
2087
+ * The interaction carries `interactionMessageId` — the ASSISTANT message id
2088
+ * that raised it (a question's `tool.messageID` / a permission's `messageID`).
2089
+ * That assistant message is the reply to ONE of our minted user messages
2090
+ * (correlated by `parentID`, GATE-B). So when we have the tick's message
2091
+ * snapshot, we resolve each running in-flight message's correlated assistant
2092
+ * reply (`findAssistantReplyAfter`) and match its id against
2093
+ * `interactionMessageId` — giving an EXACT attribution even with several
2094
+ * messages in flight concurrently in one session.
2095
+ *
2096
+ * We fall back to the oldest running message ONLY when no exact match is
2097
+ * possible (the id is absent, the snapshot is missing, or the reply has not yet
2098
+ * been correlated). With a single running message either path is exact. Never
2099
+ * throws.
2100
+ *
2101
+ * Attribution must NOT depend on our own `started` PATCH flag: opencode can
2102
+ * START a turn AND raise a question/permission BEFORE our next tick fires
2103
+ * `markProcessing` (which sets `started`). Relying on `started` would leave the
2104
+ * running set empty in that window and let the server fall back to "newest
2105
+ * processing/pending" — possibly @mentioning a FOLLOW-UP author rather than the
2106
+ * person whose active turn actually paused. So we derive "running" from the
2107
+ * tick's `messages` snapshot via `messageRunState` instead.
2108
+ */
2109
+ attributeInteraction(watcher, interactionMessageId, messages) {
2110
+ const inFlight = [...watcher.inFlight.values()].filter((m) => !m.done);
2111
+ if (inFlight.length === 0) return void 0;
2112
+ if (interactionMessageId && messages) {
2113
+ const exact = inFlight.find((m) => {
2114
+ const reply = findAssistantReplyAfter(messages, m.opencodeMessageId);
2115
+ return reply != null && messageIdOf(reply) === interactionMessageId;
1817
2116
  });
2117
+ if (exact) return exact;
2118
+ }
2119
+ const byOldest = (a, b) => a.dispatchedAt - b.dispatchedAt;
2120
+ if (messages) {
2121
+ const runningPerSnapshot = inFlight.filter(
2122
+ (m) => messageRunState(messages, m.opencodeMessageId) === "running"
2123
+ );
2124
+ if (runningPerSnapshot.length > 0) {
2125
+ return runningPerSnapshot.sort(byOldest)[0];
2126
+ }
1818
2127
  }
2128
+ const startedRunning = inFlight.filter((m) => m.started);
2129
+ if (startedRunning.length > 0) {
2130
+ return startedRunning.sort(byOldest)[0];
2131
+ }
2132
+ return inFlight.sort(byOldest)[0];
1819
2133
  }
1820
2134
  // -------------------------------------------------------------------------
1821
2135
  // Evident API calls (combinedAuth thread routes)
@@ -1849,39 +2163,86 @@ var ChannelDriver = class {
1849
2163
  }
1850
2164
  return await res.json();
1851
2165
  }
2166
+ /**
2167
+ * EXISTING combinedAuth route — now fired by the watcher on queued→running
2168
+ * (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
2169
+ * opencode_session_id}` → `notifyMessageStarted` (hourglass→runner swap +
2170
+ * deep-linked "View in Evident" notice).
2171
+ *
2172
+ * Return/throw contract (consumed by the watcher's swap-to-running guard):
2173
+ * - returns `true` → the server transitioned the row to processing;
2174
+ * - returns `false` → the server gave a DEFINITIVE "already-processing"
2175
+ * answer (a non-retryable, non-auth status — e.g. a
2176
+ * conflict because a duplicate already transitioned it),
2177
+ * so the caller treats it as already-started and does NOT
2178
+ * retry;
2179
+ * - throws `ChannelAuthError` on 401/403 (terminal auth failure);
2180
+ * - throws on a TRANSIENT failure (retryable 5xx/429 status, or a
2181
+ * network-level error from `fetch`) — i.e. NO definitive server response —
2182
+ * so the caller leaves the message un-started and retries the swap on the
2183
+ * next tick.
2184
+ * A single attempt (no internal retry): the watcher's per-tick loop is the
2185
+ * retry vehicle for the swap-to-running.
2186
+ */
1852
2187
  async markProcessing(conversationId, messageId, sessionId) {
1853
2188
  const res = await this.fetchImpl(
1854
2189
  `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
1855
2190
  {
1856
2191
  method: "PATCH",
1857
2192
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
1858
- // Include the opencode session id so the server can deep-link the
1859
- // "View in Evident" notice straight to the conversation (the session
1860
- // already exists by now — ensureSession runs before claiming).
1861
2193
  body: JSON.stringify({ status: "processing", opencode_session_id: sessionId })
1862
2194
  }
1863
2195
  );
1864
2196
  this.assertAuth(res, "marking message as processing");
1865
- return res.ok;
2197
+ if (res.ok) return true;
2198
+ if (isRetryableStatus(res.status)) {
2199
+ throw new Error(`marking message as processing: HTTP ${res.status}`);
2200
+ }
2201
+ return false;
1866
2202
  }
1867
2203
  /**
1868
- * EXISTING combinedAuth completion route — idempotent + retried (WI-CHAN-2).
1869
- * `PATCH .../messages/:id {status:'done', opencode_session_id}`. The server's
2204
+ * EXISTING combinedAuth completion route — idempotent (WI-CHAN-2). `PATCH
2205
+ * .../messages/:id {status:'done', opencode_session_id}`. The server's
1870
2206
  * `queued_conversation_messages.status`/`processed_at` gate makes a re-call
1871
- * for an already-`done` message a no-op (no double Slack post).
2207
+ * for an already-`done` message a no-op (no double Slack post). Fired by the
2208
+ * watcher on per-message completion (Task 3.4) — no `confirmCompletion`
2209
+ * round-trip (we already observed completion via the message list).
2210
+ *
2211
+ * SINGLE ATTEMPT (no in-call `callWithRetry` backoff). The per-session watcher
2212
+ * services its in-flight messages SEQUENTIALLY within a tick
2213
+ * (`runWatcherLoop` → `serviceInFlightMessage`), so a long multi-attempt
2214
+ * backoff here would BLOCK sibling messages in the SAME session/tick: while
2215
+ * message A's done PATCH burned its internal retries, message B could not be
2216
+ * swapped to running even though opencode had already started it. Instead this
2217
+ * does ONE PATCH and surfaces the SAME outcome contract the watcher's markDone
2218
+ * handler already relies on, leaning on the per-tick retry across ticks
2219
+ * (bounded by `inFlight.deadline`) rather than an in-call retry:
2220
+ * - resolves (`void`) → the server transitioned the row to done
2221
+ * (or idempotently confirmed already-done);
2222
+ * - throws `ChannelAuthError` → 401/403 (terminal auth failure → loop
2223
+ * cleanup, Finding 1);
2224
+ * - throws `ChannelTerminalError`→ non-retryable, non-auth 4xx (will never
2225
+ * succeed → straight to the cron, Finding 4);
2226
+ * - throws a plain `Error` → TRANSIENT 5xx/429 or a network-level error
2227
+ * (no definitive server response → the
2228
+ * watcher retries next tick within the
2229
+ * deadline, Finding 4).
1872
2230
  */
1873
2231
  async markDone(conversationId, messageId, sessionId) {
1874
- await this.callWithRetry(
1875
- "marking message as done",
1876
- () => this.fetchImpl(
1877
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
1878
- {
1879
- method: "PATCH",
1880
- headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
1881
- body: JSON.stringify({ status: "done", opencode_session_id: sessionId })
1882
- }
1883
- )
2232
+ const res = await this.fetchImpl(
2233
+ `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
2234
+ {
2235
+ method: "PATCH",
2236
+ headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
2237
+ body: JSON.stringify({ status: "done", opencode_session_id: sessionId })
2238
+ }
1884
2239
  );
2240
+ this.assertAuth(res, "marking message as done");
2241
+ if (res.ok) return;
2242
+ if (isRetryableStatus(res.status)) {
2243
+ throw new Error(`marking message as done: HTTP ${res.status}`);
2244
+ }
2245
+ throw new ChannelTerminalError(`marking message as done: HTTP ${res.status}`, res.status);
1885
2246
  }
1886
2247
  async markFailed(conversationId, messageId) {
1887
2248
  await this.callWithRetry(
@@ -1909,10 +2270,17 @@ var ChannelDriver = class {
1909
2270
  }
1910
2271
  /**
1911
2272
  * EXISTING combinedAuth interaction route (WI-CHAN-3) — idempotent + retried.
1912
- * `POST .../interactive-event {type, data}`. The server persists the
1913
- * interaction and posts a link to the proxied opencode-web conversation.
2273
+ * `POST .../interactive-event {type, data, source_message_id?}`. The server
2274
+ * persists the interaction and posts a link to the proxied opencode-web
2275
+ * conversation, @mentioning the user who triggered THIS message's turn.
2276
+ *
2277
+ * WI-3 / WI-4 contract: `source_message_id` is the PAUSED message's own Slack
2278
+ * ts (`message.source_message_id`). The server resolves the @mention from that
2279
+ * message's user FIRST (falling back to the old "newest processing" precedence
2280
+ * only when absent), so the correct person is mentioned under concurrency. It
2281
+ * is OPTIONAL for back-compat with older clients / legacy rows.
1914
2282
  */
1915
- async reportInteraction(conversationId, type, data) {
2283
+ async reportInteraction(conversationId, type, data, sourceMessageId) {
1916
2284
  try {
1917
2285
  await this.callWithRetry(
1918
2286
  "reporting interactive event",
@@ -1921,7 +2289,9 @@ var ChannelDriver = class {
1921
2289
  {
1922
2290
  method: "POST",
1923
2291
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
1924
- body: JSON.stringify({ type, data })
2292
+ body: JSON.stringify(
2293
+ sourceMessageId ? { type, data, source_message_id: sourceMessageId } : { type, data }
2294
+ )
1925
2295
  }
1926
2296
  )
1927
2297
  );
@@ -1930,6 +2300,7 @@ var ChannelDriver = class {
1930
2300
  message: `${type} surfaced to channel (id: ${data.id.slice(0, 8)})`,
1931
2301
  conversation_id: conversationId
1932
2302
  });
2303
+ return true;
1933
2304
  } catch (err) {
1934
2305
  if (err instanceof ChannelAuthError) throw err;
1935
2306
  this.log({
@@ -1937,6 +2308,7 @@ var ChannelDriver = class {
1937
2308
  message: `Failed to surface ${type}: ${err instanceof Error ? err.message : String(err)}`,
1938
2309
  conversation_id: conversationId
1939
2310
  });
2311
+ return false;
1940
2312
  }
1941
2313
  }
1942
2314
  // -------------------------------------------------------------------------
@@ -1975,8 +2347,9 @@ var ChannelDriver = class {
1975
2347
  await this.sleep(backoffDelay(attempt, this.retry));
1976
2348
  continue;
1977
2349
  }
2350
+ break;
1978
2351
  }
1979
- throw new Error(`${context}: HTTP ${res.status}`);
2352
+ throw new ChannelTerminalError(`${context}: HTTP ${res.status}`, res.status);
1980
2353
  }
1981
2354
  throw lastError instanceof Error ? lastError : new Error(`${context}: exhausted retries`);
1982
2355
  }
@@ -2199,7 +2572,7 @@ async function getAgentInfo(agentId, authHeader) {
2199
2572
  // src/commands/run.ts
2200
2573
  var MAX_ACTIVITY_LOG_ENTRIES = 10;
2201
2574
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
2202
- function log(state, message, isError = false) {
2575
+ function log2(state, message, isError = false) {
2203
2576
  if (state.json) {
2204
2577
  console.log(
2205
2578
  JSON.stringify({
@@ -2224,9 +2597,9 @@ function logActivity(state, entry) {
2224
2597
  }
2225
2598
  if (!state.interactive) {
2226
2599
  if (entry.type === "error") {
2227
- log(state, entry.error ?? "Unknown error", true);
2600
+ log2(state, entry.error ?? "Unknown error", true);
2228
2601
  } else if (entry.type === "info" && entry.message) {
2229
- log(state, entry.message);
2602
+ log2(state, entry.message);
2230
2603
  }
2231
2604
  }
2232
2605
  }
@@ -2321,9 +2694,9 @@ async function driveChannels(state, driver) {
2321
2694
  try {
2322
2695
  const processed = await driver.drainPending();
2323
2696
  state.messageCount += processed;
2324
- if (processed > 0) {
2697
+ if (processed > 0 || driver.hasInFlightWatchers()) {
2325
2698
  idlePolls = 0;
2326
- if (state.interactive) displayStatus(state);
2699
+ if (processed > 0 && state.interactive) displayStatus(state);
2327
2700
  } else if (state.idleTimeout !== null) {
2328
2701
  idlePolls++;
2329
2702
  if (idlePolls === 1) {
@@ -2373,7 +2746,7 @@ async function cleanup(state) {
2373
2746
  logActivity(state, { type: "info", message: "Stopped OpenCode process" });
2374
2747
  displayStatus(state);
2375
2748
  } else {
2376
- log(state, "Stopped OpenCode process");
2749
+ log2(state, "Stopped OpenCode process");
2377
2750
  }
2378
2751
  state.opencodeProcess = null;
2379
2752
  }
@@ -2399,7 +2772,7 @@ async function run(options) {
2399
2772
  authHeader: ""
2400
2773
  };
2401
2774
  if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
2402
- log(
2775
+ log2(
2403
2776
  state,
2404
2777
  "Warning: No --idle-timeout set in CI environment. The runner will poll indefinitely until the job times out. Consider adding --idle-timeout 30 to avoid wasting runner minutes.",
2405
2778
  false
@@ -2410,7 +2783,7 @@ async function run(options) {
2410
2783
  logActivity(state, { type: "info", message: "Shutting down..." });
2411
2784
  displayStatus(state);
2412
2785
  } else {
2413
- log(state, "Shutting down...");
2786
+ log2(state, "Shutting down...");
2414
2787
  }
2415
2788
  await cleanup(state);
2416
2789
  await shutdownTelemetry();
@@ -2443,7 +2816,7 @@ async function run(options) {
2443
2816
  const resolved = await resolveAgentIdFromKey(state.authHeader);
2444
2817
  if (resolved.agent_id) {
2445
2818
  state.agentId = resolved.agent_id;
2446
- log(state, `Resolved agent ID from key: ${state.agentId}`);
2819
+ log2(state, `Resolved agent ID from key: ${state.agentId}`);
2447
2820
  if (state.interactive && !state.json) {
2448
2821
  logActivity(state, {
2449
2822
  type: "info",
@@ -2506,7 +2879,7 @@ async function run(options) {
2506
2879
  port: state.port,
2507
2880
  interactive: state.interactive,
2508
2881
  agentId: state.agentId,
2509
- log: (message) => log(state, message)
2882
+ log: (message) => log2(state, message)
2510
2883
  });
2511
2884
  state.port = oc.port;
2512
2885
  state.opencodeProcess = oc.process;
@@ -2514,6 +2887,13 @@ async function run(options) {
2514
2887
  state.opencodeConnected = oc.process !== null || oc.version !== null;
2515
2888
  const version = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
2516
2889
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version}`);
2890
+ const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
2891
+ if (versionWarning) {
2892
+ log2(state, versionWarning, false);
2893
+ if (state.interactive && !state.json) {
2894
+ logActivity(state, { type: "info", message: versionWarning });
2895
+ }
2896
+ }
2517
2897
  } catch (error2) {
2518
2898
  ocSpinner?.fail(error2.message);
2519
2899
  throw error2;
@@ -2619,7 +2999,7 @@ async function run(options) {
2619
2999
  throw error2;
2620
3000
  }
2621
3001
  if (!interactive || state.json) {
2622
- log(state, "Driving channel messages...");
3002
+ log2(state, "Driving channel messages...");
2623
3003
  }
2624
3004
  await driveChannels(state, channelDriver);
2625
3005
  await cleanup(state);
@@ -2631,7 +3011,7 @@ async function run(options) {
2631
3011
  })
2632
3012
  );
2633
3013
  } else if (!interactive) {
2634
- log(state, `Completed. Processed ${state.messageCount} message(s).`);
3014
+ log2(state, `Completed. Processed ${state.messageCount} message(s).`);
2635
3015
  }
2636
3016
  await shutdownTelemetry();
2637
3017
  process.exit(0);