@evident-ai/cli 3.0.1-dev.500bff4 → 3.0.1-dev.51bb855
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/README.md +131 -87
- package/dist/index.js +589 -246
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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)
|
|
@@ -684,6 +690,19 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
684
690
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
685
691
|
}
|
|
686
692
|
|
|
693
|
+
// src/lib/opencode/opencode-version-gate.ts
|
|
694
|
+
var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11"];
|
|
695
|
+
function isQueueValidatedVersion(version) {
|
|
696
|
+
if (!version) return false;
|
|
697
|
+
return QUEUE_VALIDATED_OPENCODE_VERSIONS.includes(version);
|
|
698
|
+
}
|
|
699
|
+
function buildOpenCodeVersionWarning(version) {
|
|
700
|
+
if (isQueueValidatedVersion(version)) return null;
|
|
701
|
+
const detected = version ? `v${version}` : "unknown";
|
|
702
|
+
const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
|
|
703
|
+
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.`;
|
|
704
|
+
}
|
|
705
|
+
|
|
687
706
|
// src/lib/opencode/process.ts
|
|
688
707
|
import { execSync, spawn } from "child_process";
|
|
689
708
|
var OPENCODE_PORT_RANGE = [4096, 4097, 4098, 4099, 4100];
|
|
@@ -998,21 +1017,23 @@ function completedOf(m) {
|
|
|
998
1017
|
if (!m || typeof m !== "object") return void 0;
|
|
999
1018
|
return m.info?.time?.completed;
|
|
1000
1019
|
}
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
return Array.isArray(body) ? body : null;
|
|
1007
|
-
} catch {
|
|
1008
|
-
return null;
|
|
1009
|
-
}
|
|
1020
|
+
function idOf(m) {
|
|
1021
|
+
if (!m || typeof m !== "object") return void 0;
|
|
1022
|
+
if (typeof m.id === "string") return m.id;
|
|
1023
|
+
const infoId = m.info?.id;
|
|
1024
|
+
return typeof infoId === "string" ? infoId : void 0;
|
|
1010
1025
|
}
|
|
1011
|
-
function
|
|
1012
|
-
if (!
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
return
|
|
1026
|
+
function parentIdOf(m) {
|
|
1027
|
+
if (!m || typeof m !== "object") return void 0;
|
|
1028
|
+
if (typeof m.parentID === "string") return m.parentID;
|
|
1029
|
+
const infoParent = m.info?.parentID;
|
|
1030
|
+
return typeof infoParent === "string" ? infoParent : void 0;
|
|
1031
|
+
}
|
|
1032
|
+
function finishOf(m) {
|
|
1033
|
+
if (!m || typeof m !== "object") return void 0;
|
|
1034
|
+
if (typeof m.finish === "string") return m.finish;
|
|
1035
|
+
const infoFinish = m.info?.finish;
|
|
1036
|
+
return typeof infoFinish === "string" ? infoFinish : void 0;
|
|
1016
1037
|
}
|
|
1017
1038
|
async function createOpenCodeSession(port, directory) {
|
|
1018
1039
|
const url = new URL(`${opencodeBase(port)}/session`);
|
|
@@ -1031,8 +1052,9 @@ async function createOpenCodeSession(port, directory) {
|
|
|
1031
1052
|
const data = await response.json();
|
|
1032
1053
|
return data.id;
|
|
1033
1054
|
}
|
|
1034
|
-
async function
|
|
1055
|
+
async function sendPromptAsync(port, sessionId, content, options, messageId) {
|
|
1035
1056
|
const body = {
|
|
1057
|
+
messageID: messageId,
|
|
1036
1058
|
parts: [{ type: "text", text: content }]
|
|
1037
1059
|
};
|
|
1038
1060
|
if (options?.agent) {
|
|
@@ -1047,79 +1069,59 @@ async function sendMessageToOpenCode(port, sessionId, content, options, hooks, m
|
|
|
1047
1069
|
};
|
|
1048
1070
|
}
|
|
1049
1071
|
}
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
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;
|
|
1072
|
+
const res = await fetch(`${opencodeBase(port)}/session/${sessionId}/prompt_async`, {
|
|
1073
|
+
method: "POST",
|
|
1074
|
+
headers: { "Content-Type": "application/json" },
|
|
1075
|
+
body: JSON.stringify(body)
|
|
1076
|
+
});
|
|
1077
|
+
if (res.status < 200 || res.status >= 300) {
|
|
1078
|
+
const text = await res.text().catch(() => "");
|
|
1079
|
+
throw new Error(`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}`);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
function findAssistantReplyAfter(messages, userMessageId) {
|
|
1083
|
+
if (!messages || messages.length === 0) return null;
|
|
1084
|
+
const byParent = messages.find(
|
|
1085
|
+
(m) => roleOf(m) === "assistant" && parentIdOf(m) === userMessageId
|
|
1086
|
+
);
|
|
1087
|
+
if (byParent) return byParent;
|
|
1088
|
+
const userIndex = messages.findIndex((m) => idOf(m) === userMessageId);
|
|
1089
|
+
if (userIndex === -1) return null;
|
|
1090
|
+
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
1091
|
+
if (roleOf(messages[i]) === "assistant") return messages[i];
|
|
1092
|
+
}
|
|
1093
|
+
return null;
|
|
1094
|
+
}
|
|
1095
|
+
function findLastAssistantReplyFor(messages, userMessageId) {
|
|
1096
|
+
if (!messages || messages.length === 0) return null;
|
|
1097
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1098
|
+
const m = messages[i];
|
|
1099
|
+
if (roleOf(m) === "assistant" && parentIdOf(m) === userMessageId) return m;
|
|
1100
|
+
}
|
|
1101
|
+
const userIndex = messages.findIndex((m) => idOf(m) === userMessageId);
|
|
1102
|
+
if (userIndex === -1) return null;
|
|
1103
|
+
let last = null;
|
|
1104
|
+
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
1105
|
+
const role = roleOf(messages[i]);
|
|
1106
|
+
if (role === "user") break;
|
|
1107
|
+
if (role === "assistant") last = messages[i];
|
|
1108
|
+
}
|
|
1109
|
+
return last;
|
|
1110
|
+
}
|
|
1111
|
+
function messageRunState(messages, userMessageId) {
|
|
1112
|
+
if (!messages || messages.length === 0) return "unknown";
|
|
1113
|
+
const hasUser = messages.some((m) => idOf(m) === userMessageId);
|
|
1114
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1115
|
+
if (!hasUser) {
|
|
1116
|
+
if (!reply) return "unknown";
|
|
1117
|
+
}
|
|
1118
|
+
if (!reply) return "queued";
|
|
1119
|
+
if (completedOf(reply) == null) return "running";
|
|
1120
|
+
if (finishOf(reply) === "tool-calls") return "running";
|
|
1121
|
+
return "done";
|
|
1122
|
+
}
|
|
1123
|
+
function opencodeMessageIdFor2(queuedMessageId) {
|
|
1124
|
+
return opencodeMessageIdFor(queuedMessageId);
|
|
1123
1125
|
}
|
|
1124
1126
|
|
|
1125
1127
|
// src/lib/tunnel/connection.ts
|
|
@@ -1498,6 +1500,12 @@ var RunnerConnection = class {
|
|
|
1498
1500
|
};
|
|
1499
1501
|
|
|
1500
1502
|
// src/lib/channels/driver.ts
|
|
1503
|
+
function messageIdOf(m) {
|
|
1504
|
+
if (!m || typeof m !== "object") return void 0;
|
|
1505
|
+
if (typeof m.id === "string") return m.id;
|
|
1506
|
+
const infoId = m.info?.id;
|
|
1507
|
+
return typeof infoId === "string" ? infoId : void 0;
|
|
1508
|
+
}
|
|
1501
1509
|
var DEFAULT_RETRY_POLICY = {
|
|
1502
1510
|
maxAttempts: 6,
|
|
1503
1511
|
baseDelayMs: 500,
|
|
@@ -1505,12 +1513,21 @@ var DEFAULT_RETRY_POLICY = {
|
|
|
1505
1513
|
};
|
|
1506
1514
|
var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
|
|
1507
1515
|
var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
1516
|
+
var DEFAULT_DISPATCH_CONFIRM_MS = 6e3;
|
|
1508
1517
|
var ChannelAuthError = class extends Error {
|
|
1509
1518
|
constructor(message) {
|
|
1510
1519
|
super(message);
|
|
1511
1520
|
this.name = "ChannelAuthError";
|
|
1512
1521
|
}
|
|
1513
1522
|
};
|
|
1523
|
+
var ChannelTerminalError = class extends Error {
|
|
1524
|
+
status;
|
|
1525
|
+
constructor(message, status) {
|
|
1526
|
+
super(message);
|
|
1527
|
+
this.name = "ChannelTerminalError";
|
|
1528
|
+
this.status = status;
|
|
1529
|
+
}
|
|
1530
|
+
};
|
|
1514
1531
|
function backoffDelay(attempt, policy) {
|
|
1515
1532
|
const exp = policy.baseDelayMs * Math.pow(2, attempt);
|
|
1516
1533
|
const capped = Math.min(policy.maxDelayMs, exp);
|
|
@@ -1531,15 +1548,26 @@ var ChannelDriver = class {
|
|
|
1531
1548
|
sleep;
|
|
1532
1549
|
pausedPollIntervalMs;
|
|
1533
1550
|
pausedMaxWaitMs;
|
|
1551
|
+
dispatchConfirmMs;
|
|
1552
|
+
now;
|
|
1534
1553
|
/** Cache of conversationId → opencode sessionId. */
|
|
1535
1554
|
sessions = /* @__PURE__ */ new Map();
|
|
1536
1555
|
/**
|
|
1537
|
-
*
|
|
1538
|
-
*
|
|
1539
|
-
*
|
|
1540
|
-
*
|
|
1556
|
+
* Per-SESSION watchers (WI-3), keyed by opencode sessionId. Single-flight per
|
|
1557
|
+
* session: one polling loop services all of that session's in-flight messages.
|
|
1558
|
+
* A session entry exists while it has any in-flight (dispatched-but-not-done)
|
|
1559
|
+
* message; it is removed once its in-flight set empties.
|
|
1541
1560
|
*/
|
|
1542
1561
|
watchers = /* @__PURE__ */ new Map();
|
|
1562
|
+
/**
|
|
1563
|
+
* AUTHORITATIVE local dedup (WI-3): Evident message ids that have been
|
|
1564
|
+
* dispatched and are still in-flight. A message in this set is never
|
|
1565
|
+
* re-`prompt_async`-ed by a subsequent poll tick while it is queued/running.
|
|
1566
|
+
* Backed by a stable minted opencode `messageID` whose duplicate re-enqueue is
|
|
1567
|
+
* idempotent on opencode (PoC fact 9) — so even if this set is lost on restart,
|
|
1568
|
+
* a steady-state-poll re-dispatch will not double-run the message.
|
|
1569
|
+
*/
|
|
1570
|
+
dispatched = /* @__PURE__ */ new Set();
|
|
1543
1571
|
/**
|
|
1544
1572
|
* Cache of the opencode root directory (from `GET /path`). Resolved lazily on
|
|
1545
1573
|
* first session creation so drain-created sessions are rooted at the project
|
|
@@ -1562,6 +1590,8 @@ var ChannelDriver = class {
|
|
|
1562
1590
|
this.sleep = config2.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
1563
1591
|
this.pausedPollIntervalMs = config2.pausedPollIntervalMs ?? DEFAULT_PAUSED_POLL_INTERVAL_MS;
|
|
1564
1592
|
this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
1593
|
+
this.dispatchConfirmMs = config2.dispatchConfirmMs ?? DEFAULT_DISPATCH_CONFIRM_MS;
|
|
1594
|
+
this.now = config2.now ?? (() => Date.now());
|
|
1565
1595
|
}
|
|
1566
1596
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
1567
1597
|
get opencodeBase() {
|
|
@@ -1571,16 +1601,16 @@ var ChannelDriver = class {
|
|
|
1571
1601
|
// Public API
|
|
1572
1602
|
// -------------------------------------------------------------------------
|
|
1573
1603
|
/**
|
|
1574
|
-
* Drain all pending channel conversations once: poll →
|
|
1604
|
+
* Drain all pending channel conversations once: poll → dispatch → register.
|
|
1575
1605
|
* Called on tunnel `connected` (WI-CHAN-4) and on each poll tick by `run.ts`.
|
|
1576
1606
|
* Re-entrant calls while a drain is in flight are skipped (return 0).
|
|
1577
1607
|
*
|
|
1578
|
-
* @returns the number of messages
|
|
1608
|
+
* @returns the number of messages NEWLY dispatched to opencode's native queue.
|
|
1579
1609
|
*/
|
|
1580
1610
|
async drainPending() {
|
|
1581
1611
|
if (this.draining) return 0;
|
|
1582
1612
|
this.draining = true;
|
|
1583
|
-
let
|
|
1613
|
+
let dispatched = 0;
|
|
1584
1614
|
try {
|
|
1585
1615
|
const conversations = await this.getPendingConversations();
|
|
1586
1616
|
if (conversations.length > 0) {
|
|
@@ -1591,95 +1621,104 @@ var ChannelDriver = class {
|
|
|
1591
1621
|
});
|
|
1592
1622
|
}
|
|
1593
1623
|
for (const conv of conversations) {
|
|
1594
|
-
|
|
1624
|
+
dispatched += await this.processConversation(conv);
|
|
1595
1625
|
}
|
|
1596
1626
|
} finally {
|
|
1597
1627
|
this.draining = false;
|
|
1598
1628
|
}
|
|
1599
|
-
return
|
|
1629
|
+
return dispatched;
|
|
1630
|
+
}
|
|
1631
|
+
/**
|
|
1632
|
+
* True while any per-session watcher has a non-empty in-flight dispatched set
|
|
1633
|
+
* (Task 3.7). `run.ts` treats this as NON-idle so `--idle-timeout` cannot exit
|
|
1634
|
+
* the process while a dispatched message is still queued/running — which would
|
|
1635
|
+
* kill the turn and orphan its reply.
|
|
1636
|
+
*/
|
|
1637
|
+
hasInFlightWatchers() {
|
|
1638
|
+
for (const watcher of this.watchers.values()) {
|
|
1639
|
+
if (watcher.inFlight.size > 0) return true;
|
|
1640
|
+
}
|
|
1641
|
+
return false;
|
|
1600
1642
|
}
|
|
1601
1643
|
/**
|
|
1602
|
-
* Await all outstanding
|
|
1644
|
+
* Await all outstanding per-session watchers (WI-3).
|
|
1603
1645
|
*
|
|
1604
|
-
* In production the
|
|
1605
|
-
* loop never blocks on them and process exit is not held up (the cron
|
|
1606
|
-
* any abandoned ones). This helper exists primarily for deterministic
|
|
1607
|
-
* that need to observe
|
|
1608
|
-
* after a non-blocking `drainPending`.
|
|
1646
|
+
* In production the watcher loops are deliberately started-not-awaited so the
|
|
1647
|
+
* drain loop never blocks on them and process exit is not held up (the cron
|
|
1648
|
+
* recovers any abandoned ones). This helper exists primarily for deterministic
|
|
1649
|
+
* tests that need to observe a watcher's effect (the `processing`/`done` PATCH
|
|
1650
|
+
* or its giving up) after a non-blocking `drainPending`. Watcher loops never
|
|
1651
|
+
* reject, so this resolves.
|
|
1609
1652
|
*/
|
|
1610
1653
|
async flushPausedWatchers() {
|
|
1611
|
-
|
|
1654
|
+
while (true) {
|
|
1655
|
+
const loops = [...this.watchers.values()].map((w) => w.loop).filter((l) => l != null);
|
|
1656
|
+
if (loops.length === 0) return;
|
|
1657
|
+
await Promise.all(loops);
|
|
1658
|
+
const stillLive = [...this.watchers.values()].some((w) => w.loop != null);
|
|
1659
|
+
if (!stillLive) return;
|
|
1660
|
+
}
|
|
1612
1661
|
}
|
|
1613
1662
|
// -------------------------------------------------------------------------
|
|
1614
|
-
// Conversation processing
|
|
1663
|
+
// Conversation processing (WI-3 — async dispatch)
|
|
1615
1664
|
// -------------------------------------------------------------------------
|
|
1665
|
+
/**
|
|
1666
|
+
* Dispatch each pending message for a conversation to opencode's native queue
|
|
1667
|
+
* via `prompt_async` (Task 3.2) and register it with the conversation's
|
|
1668
|
+
* per-session watcher. Does NOT block on the turn and does NOT call
|
|
1669
|
+
* `markProcessing` here — that fires from the watcher on running-start.
|
|
1670
|
+
*
|
|
1671
|
+
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
1672
|
+
*/
|
|
1616
1673
|
async processConversation(conv) {
|
|
1617
1674
|
const sessionId = await this.ensureSession(conv);
|
|
1618
1675
|
const messages = await this.getPendingMessages(conv.id);
|
|
1619
|
-
let
|
|
1676
|
+
let dispatched = 0;
|
|
1677
|
+
let skippedAlreadyDispatched = 0;
|
|
1620
1678
|
for (const message of messages) {
|
|
1621
|
-
|
|
1622
|
-
|
|
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
|
-
});
|
|
1679
|
+
if (this.dispatched.has(message.id)) {
|
|
1680
|
+
skippedAlreadyDispatched += 1;
|
|
1629
1681
|
continue;
|
|
1630
1682
|
}
|
|
1683
|
+
const opencodeMessageId = opencodeMessageIdFor2(message.id);
|
|
1684
|
+
const options = {
|
|
1685
|
+
agent: message.opencode_agent ?? void 0,
|
|
1686
|
+
model: message.opencode_model ?? void 0
|
|
1687
|
+
};
|
|
1631
1688
|
try {
|
|
1632
1689
|
this.log({
|
|
1633
1690
|
level: "info",
|
|
1634
|
-
message: `
|
|
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`,
|
|
1691
|
+
message: `Dispatching message ${message.id.slice(0, 8)} to OpenCode native queue (session ${sessionId.slice(0, 8)})`,
|
|
1667
1692
|
conversation_id: conv.id,
|
|
1668
1693
|
message_id: message.id
|
|
1669
1694
|
});
|
|
1695
|
+
await sendPromptAsync(this.port, sessionId, message.content, options, opencodeMessageId);
|
|
1670
1696
|
} catch (err) {
|
|
1671
1697
|
if (err instanceof ChannelAuthError) throw err;
|
|
1698
|
+
this.dispatched.delete(message.id);
|
|
1672
1699
|
await this.markFailed(conv.id, message.id).catch(() => {
|
|
1673
1700
|
});
|
|
1674
1701
|
this.log({
|
|
1675
1702
|
level: "error",
|
|
1676
|
-
message: `Message ${message.id.slice(0, 8)} failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
1703
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
1677
1704
|
conversation_id: conv.id,
|
|
1678
1705
|
message_id: message.id
|
|
1679
1706
|
});
|
|
1707
|
+
continue;
|
|
1680
1708
|
}
|
|
1709
|
+
this.dispatched.add(message.id);
|
|
1710
|
+
this.registerInFlight(conv, sessionId, message, opencodeMessageId);
|
|
1711
|
+
dispatched += 1;
|
|
1712
|
+
}
|
|
1713
|
+
if (messages.length > 0 && dispatched === 0 && skippedAlreadyDispatched === messages.length) {
|
|
1714
|
+
this.log({
|
|
1715
|
+
level: "error",
|
|
1716
|
+
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).`,
|
|
1717
|
+
conversation_id: conv.id
|
|
1718
|
+
});
|
|
1681
1719
|
}
|
|
1682
|
-
|
|
1720
|
+
this.ensureWatcherRunning(sessionId);
|
|
1721
|
+
return dispatched;
|
|
1683
1722
|
}
|
|
1684
1723
|
async ensureSession(conv) {
|
|
1685
1724
|
const cached = this.sessions.get(conv.id);
|
|
@@ -1711,111 +1750,349 @@ var ChannelDriver = class {
|
|
|
1711
1750
|
}
|
|
1712
1751
|
return this.opencodeDirectory;
|
|
1713
1752
|
}
|
|
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
1753
|
// -------------------------------------------------------------------------
|
|
1742
|
-
//
|
|
1754
|
+
// Per-session watcher (WI-3)
|
|
1743
1755
|
// -------------------------------------------------------------------------
|
|
1756
|
+
/** Register a freshly-dispatched message with its session's watcher state. */
|
|
1757
|
+
registerInFlight(conv, sessionId, message, opencodeMessageId) {
|
|
1758
|
+
let watcher = this.watchers.get(sessionId);
|
|
1759
|
+
if (!watcher) {
|
|
1760
|
+
watcher = {
|
|
1761
|
+
conv,
|
|
1762
|
+
inFlight: /* @__PURE__ */ new Map(),
|
|
1763
|
+
loop: null,
|
|
1764
|
+
reportedQuestions: /* @__PURE__ */ new Set(),
|
|
1765
|
+
reportedPermissions: /* @__PURE__ */ new Set()
|
|
1766
|
+
};
|
|
1767
|
+
this.watchers.set(sessionId, watcher);
|
|
1768
|
+
}
|
|
1769
|
+
const now = this.now();
|
|
1770
|
+
watcher.inFlight.set(message.id, {
|
|
1771
|
+
evidentMessageId: message.id,
|
|
1772
|
+
opencodeMessageId,
|
|
1773
|
+
message,
|
|
1774
|
+
dispatchedAt: now,
|
|
1775
|
+
deadline: now + this.pausedMaxWaitMs,
|
|
1776
|
+
started: false,
|
|
1777
|
+
done: false
|
|
1778
|
+
});
|
|
1779
|
+
}
|
|
1744
1780
|
/**
|
|
1745
|
-
* Start (but do NOT await)
|
|
1746
|
-
*
|
|
1747
|
-
*
|
|
1748
|
-
*
|
|
1749
|
-
*
|
|
1750
|
-
* poll/markDone can never crash the run loop — the cron stays as the safety net.
|
|
1781
|
+
* Start (but do NOT await) the per-session watcher loop if it has in-flight
|
|
1782
|
+
* work and is not already running. Single-flight per session. The loop is
|
|
1783
|
+
* tracked on the watcher and cleared when it settles; it never rejects (fully
|
|
1784
|
+
* guarded), so a failed poll/callback can never crash the run loop — the cron
|
|
1785
|
+
* stays as the safety net.
|
|
1751
1786
|
*/
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1787
|
+
ensureWatcherRunning(sessionId) {
|
|
1788
|
+
const watcher = this.watchers.get(sessionId);
|
|
1789
|
+
if (!watcher) return;
|
|
1790
|
+
if (watcher.loop) return;
|
|
1791
|
+
if (watcher.inFlight.size === 0) {
|
|
1792
|
+
this.watchers.delete(sessionId);
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
const loop = this.runWatcherLoop(sessionId, watcher).finally(() => {
|
|
1796
|
+
watcher.loop = null;
|
|
1797
|
+
if (watcher.inFlight.size === 0) {
|
|
1798
|
+
this.watchers.delete(sessionId);
|
|
1799
|
+
}
|
|
1756
1800
|
});
|
|
1757
|
-
|
|
1801
|
+
watcher.loop = loop;
|
|
1758
1802
|
}
|
|
1759
1803
|
/**
|
|
1760
|
-
*
|
|
1761
|
-
*
|
|
1762
|
-
* `
|
|
1763
|
-
*
|
|
1764
|
-
*
|
|
1765
|
-
* re-
|
|
1766
|
-
*
|
|
1767
|
-
*
|
|
1768
|
-
*
|
|
1769
|
-
*
|
|
1770
|
-
*
|
|
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.
|
|
1804
|
+
* The per-session polling loop (WI-3). Once per tick it:
|
|
1805
|
+
* 1. polls `GET /session/:id/message` once and, per in-flight message,
|
|
1806
|
+
* computes `messageRunState` and fires markProcessing (queued→running) /
|
|
1807
|
+
* markDone (done) exactly once per transition;
|
|
1808
|
+
* 2. applies the idle-path re-dispatch guard (a dispatched message that never
|
|
1809
|
+
* APPEARS → re-dispatch — D1 obligation 2);
|
|
1810
|
+
* 3. polls `/question` + `/permission` (scoped to the session) and surfaces
|
|
1811
|
+
* NEW ones via `reportInteraction`, carrying the PAUSED message's own
|
|
1812
|
+
* `source_message_id`;
|
|
1813
|
+
* 4. drops messages that completed or timed out from the in-flight set.
|
|
1814
|
+
* Exits when the in-flight set empties. Never throws.
|
|
1778
1815
|
*/
|
|
1779
|
-
async
|
|
1780
|
-
const deadline = Date.now() + this.pausedMaxWaitMs;
|
|
1816
|
+
async runWatcherLoop(sessionId, watcher) {
|
|
1781
1817
|
try {
|
|
1782
|
-
while (
|
|
1818
|
+
while (watcher.inFlight.size > 0) {
|
|
1783
1819
|
await this.sleep(this.pausedPollIntervalMs);
|
|
1784
|
-
let
|
|
1820
|
+
let messages = null;
|
|
1785
1821
|
try {
|
|
1786
1822
|
const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
|
|
1787
1823
|
if (res.ok) {
|
|
1788
1824
|
const body = await res.json();
|
|
1789
|
-
|
|
1790
|
-
completed = isTurnComplete(messages);
|
|
1825
|
+
messages = Array.isArray(body) ? body : null;
|
|
1791
1826
|
}
|
|
1792
1827
|
} catch {
|
|
1793
1828
|
continue;
|
|
1794
1829
|
}
|
|
1795
|
-
|
|
1830
|
+
for (const inFlight of [...watcher.inFlight.values()]) {
|
|
1831
|
+
await this.serviceInFlightMessage(sessionId, watcher, inFlight, messages);
|
|
1832
|
+
}
|
|
1833
|
+
await this.pollInteractions(sessionId, watcher, messages);
|
|
1834
|
+
}
|
|
1835
|
+
} catch (err) {
|
|
1836
|
+
if (err instanceof ChannelAuthError) {
|
|
1796
1837
|
this.log({
|
|
1797
|
-
level: "
|
|
1798
|
-
message: `
|
|
1838
|
+
level: "error",
|
|
1839
|
+
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}`,
|
|
1840
|
+
conversation_id: watcher.conv.id
|
|
1841
|
+
});
|
|
1842
|
+
for (const evidentMessageId of [...watcher.inFlight.keys()]) {
|
|
1843
|
+
this.removeInFlight(watcher, evidentMessageId);
|
|
1844
|
+
}
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
this.log({
|
|
1848
|
+
level: "error",
|
|
1849
|
+
message: `Session watcher failed for session ${sessionId.slice(0, 8)}: ${err instanceof Error ? err.message : String(err)}`,
|
|
1850
|
+
conversation_id: watcher.conv.id
|
|
1851
|
+
});
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
/**
|
|
1855
|
+
* Drive ONE in-flight message's lifecycle from the tick's message snapshot.
|
|
1856
|
+
* Fires markProcessing on queued→running and markDone on done (each once),
|
|
1857
|
+
* applies the idle-path re-dispatch guard, and removes the message from the
|
|
1858
|
+
* in-flight set on completion or timeout.
|
|
1859
|
+
*/
|
|
1860
|
+
async serviceInFlightMessage(sessionId, watcher, inFlight, messages) {
|
|
1861
|
+
const conv = watcher.conv;
|
|
1862
|
+
const state = messageRunState(messages, inFlight.opencodeMessageId);
|
|
1863
|
+
if ((state === "running" || state === "done") && !inFlight.started) {
|
|
1864
|
+
let claimed;
|
|
1865
|
+
try {
|
|
1866
|
+
claimed = await this.markProcessing(conv.id, inFlight.evidentMessageId, sessionId);
|
|
1867
|
+
} catch (err) {
|
|
1868
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
1869
|
+
this.log({
|
|
1870
|
+
level: "error",
|
|
1871
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
1799
1872
|
conversation_id: conv.id,
|
|
1800
|
-
message_id:
|
|
1873
|
+
message_id: inFlight.evidentMessageId
|
|
1801
1874
|
});
|
|
1802
|
-
await this.markDone(conv.id, message.id, sessionId);
|
|
1803
1875
|
return;
|
|
1804
1876
|
}
|
|
1877
|
+
inFlight.started = true;
|
|
1878
|
+
if (!claimed) {
|
|
1879
|
+
this.log({
|
|
1880
|
+
level: "info",
|
|
1881
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
|
|
1882
|
+
conversation_id: conv.id,
|
|
1883
|
+
message_id: inFlight.evidentMessageId
|
|
1884
|
+
});
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
if (state === "done") {
|
|
1888
|
+
if (!inFlight.done) {
|
|
1889
|
+
this.log({
|
|
1890
|
+
level: "info",
|
|
1891
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
1892
|
+
conversation_id: conv.id,
|
|
1893
|
+
message_id: inFlight.evidentMessageId
|
|
1894
|
+
});
|
|
1895
|
+
try {
|
|
1896
|
+
await this.markDone(conv.id, inFlight.evidentMessageId, sessionId);
|
|
1897
|
+
} catch (err) {
|
|
1898
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
1899
|
+
if (err instanceof ChannelTerminalError) {
|
|
1900
|
+
this.log({
|
|
1901
|
+
level: "error",
|
|
1902
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
1903
|
+
conversation_id: conv.id,
|
|
1904
|
+
message_id: inFlight.evidentMessageId
|
|
1905
|
+
});
|
|
1906
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
1907
|
+
return;
|
|
1908
|
+
}
|
|
1909
|
+
if (this.now() >= inFlight.deadline) {
|
|
1910
|
+
this.log({
|
|
1911
|
+
level: "error",
|
|
1912
|
+
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)}`,
|
|
1913
|
+
conversation_id: conv.id,
|
|
1914
|
+
message_id: inFlight.evidentMessageId
|
|
1915
|
+
});
|
|
1916
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
1917
|
+
return;
|
|
1918
|
+
}
|
|
1919
|
+
this.log({
|
|
1920
|
+
level: "error",
|
|
1921
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
1922
|
+
conversation_id: conv.id,
|
|
1923
|
+
message_id: inFlight.evidentMessageId
|
|
1924
|
+
});
|
|
1925
|
+
return;
|
|
1926
|
+
}
|
|
1927
|
+
inFlight.done = true;
|
|
1928
|
+
}
|
|
1929
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
1930
|
+
return;
|
|
1931
|
+
}
|
|
1932
|
+
if (state === "unknown") {
|
|
1933
|
+
if (this.now() - inFlight.dispatchedAt >= this.dispatchConfirmMs) {
|
|
1934
|
+
await this.redispatchInFlight(sessionId, inFlight);
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
if (this.now() >= inFlight.deadline) {
|
|
1805
1938
|
this.log({
|
|
1806
1939
|
level: "info",
|
|
1807
|
-
message: `
|
|
1940
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} did not complete within the watch window \u2014 leaving for the cron safety net`,
|
|
1808
1941
|
conversation_id: conv.id,
|
|
1809
|
-
message_id:
|
|
1942
|
+
message_id: inFlight.evidentMessageId
|
|
1810
1943
|
});
|
|
1944
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
/**
|
|
1948
|
+
* Re-dispatch a message whose user row never appeared (idle-path guard). Safe:
|
|
1949
|
+
* opencode treats a duplicate caller-supplied `messageID` as idempotent (PoC
|
|
1950
|
+
* fact 9) — one user message + one reply even if the original DID land. Resets
|
|
1951
|
+
* the dispatch timestamp so the guard doesn't immediately fire again.
|
|
1952
|
+
*/
|
|
1953
|
+
async redispatchInFlight(sessionId, inFlight) {
|
|
1954
|
+
const options = {
|
|
1955
|
+
agent: inFlight.message.opencode_agent ?? void 0,
|
|
1956
|
+
model: inFlight.message.opencode_model ?? void 0
|
|
1957
|
+
};
|
|
1958
|
+
this.log({
|
|
1959
|
+
level: "info",
|
|
1960
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} not observed after dispatch \u2014 re-dispatching (idle-path guard)`,
|
|
1961
|
+
message_id: inFlight.evidentMessageId
|
|
1962
|
+
});
|
|
1963
|
+
try {
|
|
1964
|
+
await sendPromptAsync(
|
|
1965
|
+
this.port,
|
|
1966
|
+
sessionId,
|
|
1967
|
+
inFlight.message.content,
|
|
1968
|
+
options,
|
|
1969
|
+
inFlight.opencodeMessageId
|
|
1970
|
+
);
|
|
1811
1971
|
} catch (err) {
|
|
1812
1972
|
this.log({
|
|
1813
1973
|
level: "error",
|
|
1814
|
-
message: `
|
|
1815
|
-
|
|
1816
|
-
message_id: message.id
|
|
1974
|
+
message: `Re-dispatch failed for message ${inFlight.evidentMessageId.slice(0, 8)}: ${err instanceof Error ? err.message : String(err)}`,
|
|
1975
|
+
message_id: inFlight.evidentMessageId
|
|
1817
1976
|
});
|
|
1818
1977
|
}
|
|
1978
|
+
inFlight.dispatchedAt = this.now();
|
|
1979
|
+
}
|
|
1980
|
+
/**
|
|
1981
|
+
* Remove a message from the in-flight set AND the authoritative dispatched
|
|
1982
|
+
* set. Once the in-flight set empties, the watcher loop's `while` guard exits
|
|
1983
|
+
* and its `.finally` removes the session entry from `this.watchers`.
|
|
1984
|
+
*/
|
|
1985
|
+
removeInFlight(watcher, evidentMessageId) {
|
|
1986
|
+
watcher.inFlight.delete(evidentMessageId);
|
|
1987
|
+
this.dispatched.delete(evidentMessageId);
|
|
1988
|
+
}
|
|
1989
|
+
/**
|
|
1990
|
+
* Poll `/question` + `/permission` (scoped to the session) and surface NEW ones
|
|
1991
|
+
* via `reportInteraction` (Task 3.5), carrying the PAUSED message's own
|
|
1992
|
+
* `source_message_id` so the server @mentions the correct person under
|
|
1993
|
+
* concurrency. Dedups by interaction id across ticks (reused per-session sets).
|
|
1994
|
+
*
|
|
1995
|
+
* The interaction is attributed to the in-flight message it paused on. opencode
|
|
1996
|
+
* stamps a `messageID` on a permission (and `tool.messageID` on a question) =
|
|
1997
|
+
* the assistant message id, whose `parentID` is the user message id — but the
|
|
1998
|
+
* simplest robust attribution here is: the single in-flight message that is
|
|
1999
|
+
* RUNNING (not done) is the one that paused. With one running message that is
|
|
2000
|
+
* unambiguous; with several we prefer an explicit messageID match, else the
|
|
2001
|
+
* oldest running message.
|
|
2002
|
+
*/
|
|
2003
|
+
async pollInteractions(sessionId, watcher, messages) {
|
|
2004
|
+
let questions = [];
|
|
2005
|
+
try {
|
|
2006
|
+
const res = await this.fetchImpl(`${this.opencodeBase}/question`);
|
|
2007
|
+
if (res.ok) {
|
|
2008
|
+
const body = await res.json();
|
|
2009
|
+
questions = Array.isArray(body) ? body : [];
|
|
2010
|
+
}
|
|
2011
|
+
} catch {
|
|
2012
|
+
}
|
|
2013
|
+
for (const q of questions) {
|
|
2014
|
+
if (q.sessionID !== sessionId) continue;
|
|
2015
|
+
if (watcher.reportedQuestions.has(q.id)) continue;
|
|
2016
|
+
const paused = this.attributeInteraction(watcher, q.tool?.messageID, messages);
|
|
2017
|
+
const reported = await this.reportInteraction(
|
|
2018
|
+
watcher.conv.id,
|
|
2019
|
+
"question",
|
|
2020
|
+
q,
|
|
2021
|
+
paused?.message.source_message_id ?? void 0
|
|
2022
|
+
);
|
|
2023
|
+
if (reported) watcher.reportedQuestions.add(q.id);
|
|
2024
|
+
}
|
|
2025
|
+
let permissions = [];
|
|
2026
|
+
try {
|
|
2027
|
+
const res = await this.fetchImpl(`${this.opencodeBase}/permission`);
|
|
2028
|
+
if (res.ok) {
|
|
2029
|
+
const body = await res.json();
|
|
2030
|
+
permissions = Array.isArray(body) ? body : [];
|
|
2031
|
+
}
|
|
2032
|
+
} catch {
|
|
2033
|
+
}
|
|
2034
|
+
for (const p of permissions) {
|
|
2035
|
+
if (p.sessionID !== sessionId) continue;
|
|
2036
|
+
if (watcher.reportedPermissions.has(p.id)) continue;
|
|
2037
|
+
const paused = this.attributeInteraction(watcher, p.messageID, messages);
|
|
2038
|
+
const reported = await this.reportInteraction(
|
|
2039
|
+
watcher.conv.id,
|
|
2040
|
+
"permission",
|
|
2041
|
+
p,
|
|
2042
|
+
paused?.message.source_message_id ?? void 0
|
|
2043
|
+
);
|
|
2044
|
+
if (reported) watcher.reportedPermissions.add(p.id);
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
/**
|
|
2048
|
+
* Attribute a surfaced interaction to the in-flight message it paused on (M-1).
|
|
2049
|
+
*
|
|
2050
|
+
* The interaction carries `interactionMessageId` — the ASSISTANT message id
|
|
2051
|
+
* that raised it (a question's `tool.messageID` / a permission's `messageID`).
|
|
2052
|
+
* That assistant message is the reply to ONE of our minted user messages
|
|
2053
|
+
* (correlated by `parentID`, GATE-B). So when we have the tick's message
|
|
2054
|
+
* snapshot, we resolve each running in-flight message's correlated assistant
|
|
2055
|
+
* reply (`findAssistantReplyAfter`) and match its id against
|
|
2056
|
+
* `interactionMessageId` — giving an EXACT attribution even with several
|
|
2057
|
+
* messages in flight concurrently in one session.
|
|
2058
|
+
*
|
|
2059
|
+
* We fall back to the oldest running message ONLY when no exact match is
|
|
2060
|
+
* possible (the id is absent, the snapshot is missing, or the reply has not yet
|
|
2061
|
+
* been correlated). With a single running message either path is exact. Never
|
|
2062
|
+
* throws.
|
|
2063
|
+
*
|
|
2064
|
+
* Attribution must NOT depend on our own `started` PATCH flag: opencode can
|
|
2065
|
+
* START a turn AND raise a question/permission BEFORE our next tick fires
|
|
2066
|
+
* `markProcessing` (which sets `started`). Relying on `started` would leave the
|
|
2067
|
+
* running set empty in that window and let the server fall back to "newest
|
|
2068
|
+
* processing/pending" — possibly @mentioning a FOLLOW-UP author rather than the
|
|
2069
|
+
* person whose active turn actually paused. So we derive "running" from the
|
|
2070
|
+
* tick's `messages` snapshot via `messageRunState` instead.
|
|
2071
|
+
*/
|
|
2072
|
+
attributeInteraction(watcher, interactionMessageId, messages) {
|
|
2073
|
+
const inFlight = [...watcher.inFlight.values()].filter((m) => !m.done);
|
|
2074
|
+
if (inFlight.length === 0) return void 0;
|
|
2075
|
+
if (interactionMessageId && messages) {
|
|
2076
|
+
const exact = inFlight.find((m) => {
|
|
2077
|
+
const reply = findAssistantReplyAfter(messages, m.opencodeMessageId);
|
|
2078
|
+
return reply != null && messageIdOf(reply) === interactionMessageId;
|
|
2079
|
+
});
|
|
2080
|
+
if (exact) return exact;
|
|
2081
|
+
}
|
|
2082
|
+
const byOldest = (a, b) => a.dispatchedAt - b.dispatchedAt;
|
|
2083
|
+
if (messages) {
|
|
2084
|
+
const runningPerSnapshot = inFlight.filter(
|
|
2085
|
+
(m) => messageRunState(messages, m.opencodeMessageId) === "running"
|
|
2086
|
+
);
|
|
2087
|
+
if (runningPerSnapshot.length > 0) {
|
|
2088
|
+
return runningPerSnapshot.sort(byOldest)[0];
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
const startedRunning = inFlight.filter((m) => m.started);
|
|
2092
|
+
if (startedRunning.length > 0) {
|
|
2093
|
+
return startedRunning.sort(byOldest)[0];
|
|
2094
|
+
}
|
|
2095
|
+
return inFlight.sort(byOldest)[0];
|
|
1819
2096
|
}
|
|
1820
2097
|
// -------------------------------------------------------------------------
|
|
1821
2098
|
// Evident API calls (combinedAuth thread routes)
|
|
@@ -1849,39 +2126,86 @@ var ChannelDriver = class {
|
|
|
1849
2126
|
}
|
|
1850
2127
|
return await res.json();
|
|
1851
2128
|
}
|
|
2129
|
+
/**
|
|
2130
|
+
* EXISTING combinedAuth route — now fired by the watcher on queued→running
|
|
2131
|
+
* (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
|
|
2132
|
+
* opencode_session_id}` → `notifyMessageStarted` (hourglass→runner swap +
|
|
2133
|
+
* deep-linked "View in Evident" notice).
|
|
2134
|
+
*
|
|
2135
|
+
* Return/throw contract (consumed by the watcher's swap-to-running guard):
|
|
2136
|
+
* - returns `true` → the server transitioned the row to processing;
|
|
2137
|
+
* - returns `false` → the server gave a DEFINITIVE "already-processing"
|
|
2138
|
+
* answer (a non-retryable, non-auth status — e.g. a
|
|
2139
|
+
* conflict because a duplicate already transitioned it),
|
|
2140
|
+
* so the caller treats it as already-started and does NOT
|
|
2141
|
+
* retry;
|
|
2142
|
+
* - throws `ChannelAuthError` on 401/403 (terminal auth failure);
|
|
2143
|
+
* - throws on a TRANSIENT failure (retryable 5xx/429 status, or a
|
|
2144
|
+
* network-level error from `fetch`) — i.e. NO definitive server response —
|
|
2145
|
+
* so the caller leaves the message un-started and retries the swap on the
|
|
2146
|
+
* next tick.
|
|
2147
|
+
* A single attempt (no internal retry): the watcher's per-tick loop is the
|
|
2148
|
+
* retry vehicle for the swap-to-running.
|
|
2149
|
+
*/
|
|
1852
2150
|
async markProcessing(conversationId, messageId, sessionId) {
|
|
1853
2151
|
const res = await this.fetchImpl(
|
|
1854
2152
|
`${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
1855
2153
|
{
|
|
1856
2154
|
method: "PATCH",
|
|
1857
2155
|
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
2156
|
body: JSON.stringify({ status: "processing", opencode_session_id: sessionId })
|
|
1862
2157
|
}
|
|
1863
2158
|
);
|
|
1864
2159
|
this.assertAuth(res, "marking message as processing");
|
|
1865
|
-
|
|
2160
|
+
if (res.ok) return true;
|
|
2161
|
+
if (isRetryableStatus(res.status)) {
|
|
2162
|
+
throw new Error(`marking message as processing: HTTP ${res.status}`);
|
|
2163
|
+
}
|
|
2164
|
+
return false;
|
|
1866
2165
|
}
|
|
1867
2166
|
/**
|
|
1868
|
-
* EXISTING combinedAuth completion route — idempotent
|
|
1869
|
-
*
|
|
2167
|
+
* EXISTING combinedAuth completion route — idempotent (WI-CHAN-2). `PATCH
|
|
2168
|
+
* .../messages/:id {status:'done', opencode_session_id}`. The server's
|
|
1870
2169
|
* `queued_conversation_messages.status`/`processed_at` gate makes a re-call
|
|
1871
|
-
* for an already-`done` message a no-op (no double Slack post).
|
|
2170
|
+
* for an already-`done` message a no-op (no double Slack post). Fired by the
|
|
2171
|
+
* watcher on per-message completion (Task 3.4) — no `confirmCompletion`
|
|
2172
|
+
* round-trip (we already observed completion via the message list).
|
|
2173
|
+
*
|
|
2174
|
+
* SINGLE ATTEMPT (no in-call `callWithRetry` backoff). The per-session watcher
|
|
2175
|
+
* services its in-flight messages SEQUENTIALLY within a tick
|
|
2176
|
+
* (`runWatcherLoop` → `serviceInFlightMessage`), so a long multi-attempt
|
|
2177
|
+
* backoff here would BLOCK sibling messages in the SAME session/tick: while
|
|
2178
|
+
* message A's done PATCH burned its internal retries, message B could not be
|
|
2179
|
+
* swapped to running even though opencode had already started it. Instead this
|
|
2180
|
+
* does ONE PATCH and surfaces the SAME outcome contract the watcher's markDone
|
|
2181
|
+
* handler already relies on, leaning on the per-tick retry across ticks
|
|
2182
|
+
* (bounded by `inFlight.deadline`) rather than an in-call retry:
|
|
2183
|
+
* - resolves (`void`) → the server transitioned the row to done
|
|
2184
|
+
* (or idempotently confirmed already-done);
|
|
2185
|
+
* - throws `ChannelAuthError` → 401/403 (terminal auth failure → loop
|
|
2186
|
+
* cleanup, Finding 1);
|
|
2187
|
+
* - throws `ChannelTerminalError`→ non-retryable, non-auth 4xx (will never
|
|
2188
|
+
* succeed → straight to the cron, Finding 4);
|
|
2189
|
+
* - throws a plain `Error` → TRANSIENT 5xx/429 or a network-level error
|
|
2190
|
+
* (no definitive server response → the
|
|
2191
|
+
* watcher retries next tick within the
|
|
2192
|
+
* deadline, Finding 4).
|
|
1872
2193
|
*/
|
|
1873
2194
|
async markDone(conversationId, messageId, sessionId) {
|
|
1874
|
-
await this.
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
{
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
body: JSON.stringify({ status: "done", opencode_session_id: sessionId })
|
|
1882
|
-
}
|
|
1883
|
-
)
|
|
2195
|
+
const res = await this.fetchImpl(
|
|
2196
|
+
`${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
2197
|
+
{
|
|
2198
|
+
method: "PATCH",
|
|
2199
|
+
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
2200
|
+
body: JSON.stringify({ status: "done", opencode_session_id: sessionId })
|
|
2201
|
+
}
|
|
1884
2202
|
);
|
|
2203
|
+
this.assertAuth(res, "marking message as done");
|
|
2204
|
+
if (res.ok) return;
|
|
2205
|
+
if (isRetryableStatus(res.status)) {
|
|
2206
|
+
throw new Error(`marking message as done: HTTP ${res.status}`);
|
|
2207
|
+
}
|
|
2208
|
+
throw new ChannelTerminalError(`marking message as done: HTTP ${res.status}`, res.status);
|
|
1885
2209
|
}
|
|
1886
2210
|
async markFailed(conversationId, messageId) {
|
|
1887
2211
|
await this.callWithRetry(
|
|
@@ -1909,10 +2233,17 @@ var ChannelDriver = class {
|
|
|
1909
2233
|
}
|
|
1910
2234
|
/**
|
|
1911
2235
|
* EXISTING combinedAuth interaction route (WI-CHAN-3) — idempotent + retried.
|
|
1912
|
-
* `POST .../interactive-event {type, data}`. The server
|
|
1913
|
-
* interaction and posts a link to the proxied opencode-web
|
|
2236
|
+
* `POST .../interactive-event {type, data, source_message_id?}`. The server
|
|
2237
|
+
* persists the interaction and posts a link to the proxied opencode-web
|
|
2238
|
+
* conversation, @mentioning the user who triggered THIS message's turn.
|
|
2239
|
+
*
|
|
2240
|
+
* WI-3 / WI-4 contract: `source_message_id` is the PAUSED message's own Slack
|
|
2241
|
+
* ts (`message.source_message_id`). The server resolves the @mention from that
|
|
2242
|
+
* message's user FIRST (falling back to the old "newest processing" precedence
|
|
2243
|
+
* only when absent), so the correct person is mentioned under concurrency. It
|
|
2244
|
+
* is OPTIONAL for back-compat with older clients / legacy rows.
|
|
1914
2245
|
*/
|
|
1915
|
-
async reportInteraction(conversationId, type, data) {
|
|
2246
|
+
async reportInteraction(conversationId, type, data, sourceMessageId) {
|
|
1916
2247
|
try {
|
|
1917
2248
|
await this.callWithRetry(
|
|
1918
2249
|
"reporting interactive event",
|
|
@@ -1921,7 +2252,9 @@ var ChannelDriver = class {
|
|
|
1921
2252
|
{
|
|
1922
2253
|
method: "POST",
|
|
1923
2254
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
1924
|
-
body: JSON.stringify(
|
|
2255
|
+
body: JSON.stringify(
|
|
2256
|
+
sourceMessageId ? { type, data, source_message_id: sourceMessageId } : { type, data }
|
|
2257
|
+
)
|
|
1925
2258
|
}
|
|
1926
2259
|
)
|
|
1927
2260
|
);
|
|
@@ -1930,6 +2263,7 @@ var ChannelDriver = class {
|
|
|
1930
2263
|
message: `${type} surfaced to channel (id: ${data.id.slice(0, 8)})`,
|
|
1931
2264
|
conversation_id: conversationId
|
|
1932
2265
|
});
|
|
2266
|
+
return true;
|
|
1933
2267
|
} catch (err) {
|
|
1934
2268
|
if (err instanceof ChannelAuthError) throw err;
|
|
1935
2269
|
this.log({
|
|
@@ -1937,6 +2271,7 @@ var ChannelDriver = class {
|
|
|
1937
2271
|
message: `Failed to surface ${type}: ${err instanceof Error ? err.message : String(err)}`,
|
|
1938
2272
|
conversation_id: conversationId
|
|
1939
2273
|
});
|
|
2274
|
+
return false;
|
|
1940
2275
|
}
|
|
1941
2276
|
}
|
|
1942
2277
|
// -------------------------------------------------------------------------
|
|
@@ -1975,8 +2310,9 @@ var ChannelDriver = class {
|
|
|
1975
2310
|
await this.sleep(backoffDelay(attempt, this.retry));
|
|
1976
2311
|
continue;
|
|
1977
2312
|
}
|
|
2313
|
+
break;
|
|
1978
2314
|
}
|
|
1979
|
-
throw new
|
|
2315
|
+
throw new ChannelTerminalError(`${context}: HTTP ${res.status}`, res.status);
|
|
1980
2316
|
}
|
|
1981
2317
|
throw lastError instanceof Error ? lastError : new Error(`${context}: exhausted retries`);
|
|
1982
2318
|
}
|
|
@@ -2321,9 +2657,9 @@ async function driveChannels(state, driver) {
|
|
|
2321
2657
|
try {
|
|
2322
2658
|
const processed = await driver.drainPending();
|
|
2323
2659
|
state.messageCount += processed;
|
|
2324
|
-
if (processed > 0) {
|
|
2660
|
+
if (processed > 0 || driver.hasInFlightWatchers()) {
|
|
2325
2661
|
idlePolls = 0;
|
|
2326
|
-
if (state.interactive) displayStatus(state);
|
|
2662
|
+
if (processed > 0 && state.interactive) displayStatus(state);
|
|
2327
2663
|
} else if (state.idleTimeout !== null) {
|
|
2328
2664
|
idlePolls++;
|
|
2329
2665
|
if (idlePolls === 1) {
|
|
@@ -2514,6 +2850,13 @@ async function run(options) {
|
|
|
2514
2850
|
state.opencodeConnected = oc.process !== null || oc.version !== null;
|
|
2515
2851
|
const version = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
2516
2852
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version}`);
|
|
2853
|
+
const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
|
|
2854
|
+
if (versionWarning) {
|
|
2855
|
+
log(state, versionWarning, false);
|
|
2856
|
+
if (state.interactive && !state.json) {
|
|
2857
|
+
logActivity(state, { type: "info", message: versionWarning });
|
|
2858
|
+
}
|
|
2859
|
+
}
|
|
2517
2860
|
} catch (error2) {
|
|
2518
2861
|
ocSpinner?.fail(error2.message);
|
|
2519
2862
|
throw error2;
|