@evident-ai/cli 3.0.1-dev.116734c → 3.0.1-dev.18aac68

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
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
+ import { createRequire } from "module";
4
5
  import { Command } from "commander";
5
6
 
6
7
  // src/commands/login.ts
@@ -284,14 +285,14 @@ function blank() {
284
285
  console.log();
285
286
  }
286
287
  function waitForEnter(prompt = "Press Enter to continue...") {
287
- return new Promise((resolve) => {
288
+ return new Promise((resolve2) => {
288
289
  process.stdout.write(chalk.dim(prompt));
289
290
  const handler = () => {
290
291
  process.stdin.removeListener("data", handler);
291
292
  process.stdin.setRawMode?.(false);
292
293
  process.stdin.pause();
293
294
  console.log();
294
- resolve();
295
+ resolve2();
295
296
  };
296
297
  if (process.stdin.isTTY) {
297
298
  process.stdin.setRawMode?.(true);
@@ -301,7 +302,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
301
302
  });
302
303
  }
303
304
  function sleep(ms) {
304
- return new Promise((resolve) => setTimeout(resolve, ms));
305
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
305
306
  }
306
307
 
307
308
  // src/commands/login.ts
@@ -375,19 +376,19 @@ async function tokenLogin() {
375
376
  console.log("Visit your Evident dashboard to generate a CLI token.");
376
377
  blank();
377
378
  process.stdout.write("Paste token: ");
378
- const token = await new Promise((resolve) => {
379
+ const token = await new Promise((resolve2) => {
379
380
  let data = "";
380
381
  process.stdin.setEncoding("utf8");
381
382
  process.stdin.on("data", (chunk) => {
382
383
  data += chunk;
383
384
  });
384
385
  process.stdin.on("end", () => {
385
- resolve(data.trim());
386
+ resolve2(data.trim());
386
387
  });
387
388
  if (process.stdin.isTTY) {
388
389
  process.stdin.once("data", (chunk) => {
389
390
  process.stdin.pause();
390
- resolve(chunk.toString().trim());
391
+ resolve2(chunk.toString().trim());
391
392
  });
392
393
  process.stdin.resume();
393
394
  }
@@ -484,8 +485,34 @@ var TelemetryEventTypes = {
484
485
  var MAX_FRAME_BYTES = 256 * 1024;
485
486
  var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
486
487
 
488
+ // ../../packages/types/src/logging/index.ts
489
+ var CORRELATION_ID_HEADER = "x-evident-correlation-id";
490
+ function log(level, event, fields) {
491
+ const method = level === "debug" ? "log" : level;
492
+ try {
493
+ console[method]("[evident]", JSON.stringify({ level, event, ...fields }));
494
+ } catch (err) {
495
+ console.error(
496
+ "[evident] log_serialize_failed",
497
+ event,
498
+ err instanceof Error ? err.message : String(err)
499
+ );
500
+ }
501
+ }
502
+ function stripQuery(url) {
503
+ try {
504
+ return new URL(url).pathname;
505
+ } catch {
506
+ const q = url.indexOf("?");
507
+ return q === -1 ? url : url.slice(0, q);
508
+ }
509
+ }
510
+
487
511
  // src/lib/telemetry.ts
488
- var CLI_VERSION = process.env.npm_package_version || "unknown";
512
+ var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
513
+ function getCliVersion() {
514
+ return CLI_VERSION;
515
+ }
489
516
  var eventBuffer = [];
490
517
  var flushTimeout = null;
491
518
  var isShuttingDown = false;
@@ -679,11 +706,24 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
679
706
  if (health.healthy) {
680
707
  return health;
681
708
  }
682
- await new Promise((resolve) => setTimeout(resolve, 1e3));
709
+ await new Promise((resolve2) => setTimeout(resolve2, 1e3));
683
710
  }
684
711
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
685
712
  }
686
713
 
714
+ // src/lib/opencode/opencode-version-gate.ts
715
+ var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
716
+ function isQueueValidatedVersion(version2) {
717
+ if (!version2) return false;
718
+ return QUEUE_VALIDATED_OPENCODE_VERSIONS.includes(version2);
719
+ }
720
+ function buildOpenCodeVersionWarning(version2) {
721
+ if (isQueueValidatedVersion(version2)) return null;
722
+ const detected = version2 ? `v${version2}` : "unknown";
723
+ const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
724
+ 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.`;
725
+ }
726
+
687
727
  // src/lib/opencode/process.ts
688
728
  import { execSync, spawn } from "child_process";
689
729
  var OPENCODE_PORT_RANGE = [4096, 4097, 4098, 4099, 4100];
@@ -996,7 +1036,37 @@ function roleOf(m) {
996
1036
  }
997
1037
  function completedOf(m) {
998
1038
  if (!m || typeof m !== "object") return void 0;
999
- return m.info?.time?.completed;
1039
+ return m.info?.time?.completed ?? m.time?.completed;
1040
+ }
1041
+ function createdOf(m) {
1042
+ if (!m || typeof m !== "object") return void 0;
1043
+ return m.info?.time?.created ?? m.time?.created;
1044
+ }
1045
+ function idOf(m) {
1046
+ if (!m || typeof m !== "object") return void 0;
1047
+ if (typeof m.id === "string") return m.id;
1048
+ const infoId = m.info?.id;
1049
+ return typeof infoId === "string" ? infoId : void 0;
1050
+ }
1051
+ function parentIdOf(m) {
1052
+ if (!m || typeof m !== "object") return void 0;
1053
+ if (typeof m.parentID === "string") return m.parentID;
1054
+ const infoParent = m.info?.parentID;
1055
+ return typeof infoParent === "string" ? infoParent : void 0;
1056
+ }
1057
+ function finishOf(m) {
1058
+ if (!m || typeof m !== "object") return void 0;
1059
+ if (typeof m.finish === "string") return m.finish;
1060
+ const infoFinish = m.info?.finish;
1061
+ return typeof infoFinish === "string" ? infoFinish : void 0;
1062
+ }
1063
+ function errorOf(m) {
1064
+ if (!m || typeof m !== "object") return void 0;
1065
+ return m.info?.error ?? m.error;
1066
+ }
1067
+ function isAssistantInFlight(m) {
1068
+ if (completedOf(m) == null) return true;
1069
+ return finishOf(m) === "tool-calls";
1000
1070
  }
1001
1071
  async function getSessionMessages(port, sessionId) {
1002
1072
  try {
@@ -1008,11 +1078,83 @@ async function getSessionMessages(port, sessionId) {
1008
1078
  return null;
1009
1079
  }
1010
1080
  }
1011
- function isTurnComplete(messages) {
1081
+ function isSessionActivelyGenerating(messages) {
1012
1082
  if (!messages || messages.length === 0) return false;
1013
1083
  const last = messages[messages.length - 1];
1014
1084
  if (roleOf(last) !== "assistant") return false;
1015
- return completedOf(last) != null;
1085
+ return completedOf(last) == null;
1086
+ }
1087
+ function sessionLastActivityMs(session) {
1088
+ const candidates = [
1089
+ session.time?.updated,
1090
+ session.time?.created,
1091
+ session.time_updated,
1092
+ session.time_created,
1093
+ session.updated,
1094
+ session.created
1095
+ ];
1096
+ for (const c of candidates) {
1097
+ if (typeof c === "number" && Number.isFinite(c)) return c;
1098
+ }
1099
+ return null;
1100
+ }
1101
+ async function listSessions(port) {
1102
+ try {
1103
+ const res = await fetch(`${opencodeBase(port)}/session`);
1104
+ if (!res.ok) return null;
1105
+ const body = await res.json();
1106
+ return Array.isArray(body) ? body : null;
1107
+ } catch {
1108
+ return null;
1109
+ }
1110
+ }
1111
+ async function deleteSession(port, id) {
1112
+ try {
1113
+ const res = await fetch(`${opencodeBase(port)}/session/${id}`, { method: "DELETE" });
1114
+ return res.status >= 200 && res.status < 300;
1115
+ } catch {
1116
+ return false;
1117
+ }
1118
+ }
1119
+ async function sessionExists(port, id) {
1120
+ try {
1121
+ const res = await fetch(`${opencodeBase(port)}/session/${id}`);
1122
+ if (res.status >= 200 && res.status < 300) return true;
1123
+ if (res.status === 404) return false;
1124
+ return null;
1125
+ } catch {
1126
+ return null;
1127
+ }
1128
+ }
1129
+ async function getSessionStatuses(port) {
1130
+ try {
1131
+ const res = await fetch(`${opencodeBase(port)}/session/status`);
1132
+ if (!res.ok) {
1133
+ console.error(
1134
+ `[getSessionStatuses] GET /session/status returned HTTP ${res.status} (port ${port})`
1135
+ );
1136
+ return null;
1137
+ }
1138
+ const body = await res.json();
1139
+ if (body == null || typeof body !== "object" || Array.isArray(body)) {
1140
+ console.error(
1141
+ `[getSessionStatuses] GET /session/status body was not a plain object (port ${port})`
1142
+ );
1143
+ return null;
1144
+ }
1145
+ return body;
1146
+ } catch (err) {
1147
+ console.error(
1148
+ `[getSessionStatuses] GET /session/status failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
1149
+ );
1150
+ return null;
1151
+ }
1152
+ }
1153
+ async function isSessionOngoing(port, id) {
1154
+ const map = await getSessionStatuses(port);
1155
+ if (map == null) return null;
1156
+ const entry = map[id];
1157
+ return entry != null && entry.type !== "idle";
1016
1158
  }
1017
1159
  async function createOpenCodeSession(port, directory) {
1018
1160
  const url = new URL(`${opencodeBase(port)}/session`);
@@ -1031,9 +1173,113 @@ async function createOpenCodeSession(port, directory) {
1031
1173
  const data = await response.json();
1032
1174
  return data.id;
1033
1175
  }
1034
- async function sendMessageToOpenCode(port, sessionId, content, options, hooks, maxWaitMs = 10 * 60 * 1e3) {
1176
+ async function getModelAttachmentCapability(port, model) {
1177
+ try {
1178
+ const res = await fetch(`${opencodeBase(port)}/config/providers`);
1179
+ if (!res.ok) {
1180
+ console.error(
1181
+ `[getModelAttachmentCapability] GET /config/providers returned HTTP ${res.status} (port ${port})`
1182
+ );
1183
+ return null;
1184
+ }
1185
+ const body = await res.json();
1186
+ const providers = Array.isArray(body?.providers) ? body.providers : null;
1187
+ if (!providers) {
1188
+ console.error(
1189
+ `[getModelAttachmentCapability] GET /config/providers body had no providers array (port ${port})`
1190
+ );
1191
+ return null;
1192
+ }
1193
+ const slash = model ? model.indexOf("/") : -1;
1194
+ const providerId = slash > 0 ? model.slice(0, slash) : void 0;
1195
+ let modelId = slash > 0 ? model.slice(slash + 1) : void 0;
1196
+ const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
1197
+ let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
1198
+ if (!provider && !providerId) {
1199
+ const defaultProviderIds = defaults2 ? Object.keys(defaults2) : [];
1200
+ if (defaultProviderIds.length === 1) {
1201
+ provider = providers.find((p) => p?.id === defaultProviderIds[0]);
1202
+ }
1203
+ }
1204
+ if (!provider || !provider.models) return null;
1205
+ if (!modelId && defaults2 && typeof provider.id === "string") {
1206
+ const def = defaults2[provider.id];
1207
+ if (typeof def === "string") modelId = def;
1208
+ }
1209
+ if (!modelId) {
1210
+ if (providerId) {
1211
+ const keys = Object.keys(provider.models);
1212
+ if (keys.length === 1) modelId = keys[0];
1213
+ }
1214
+ if (!modelId) return null;
1215
+ }
1216
+ const entry = provider.models[modelId];
1217
+ if (!entry || typeof entry !== "object") return null;
1218
+ return typeof entry.attachment === "boolean" ? entry.attachment : null;
1219
+ } catch (err) {
1220
+ console.error(
1221
+ `[getModelAttachmentCapability] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
1222
+ );
1223
+ return null;
1224
+ }
1225
+ }
1226
+ async function buildFileParts(attachments, capable) {
1227
+ const outcomes = [];
1228
+ const parts = [];
1229
+ const capabilityUnknown = capable === null;
1230
+ if (capable !== true) {
1231
+ for (const a of attachments.inputs) {
1232
+ outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "skipped" });
1233
+ }
1234
+ return { parts, outcomes, capabilityUnknown };
1235
+ }
1236
+ for (const a of attachments.inputs) {
1237
+ let dataUrl = null;
1238
+ try {
1239
+ dataUrl = await attachments.fetchDataUrl(a.index);
1240
+ } catch (err) {
1241
+ console.error(
1242
+ `[buildFileParts] attachment ${a.index} (${a.mime}) fetch threw \u2014 omitting: ${err instanceof Error ? err.message : String(err)}`
1243
+ );
1244
+ dataUrl = null;
1245
+ }
1246
+ if (dataUrl == null) {
1247
+ outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
1248
+ continue;
1249
+ }
1250
+ parts.push({
1251
+ type: "file",
1252
+ mime: a.mime,
1253
+ url: dataUrl,
1254
+ ...a.filename ? { filename: a.filename } : {}
1255
+ });
1256
+ outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "sent" });
1257
+ }
1258
+ return { parts, outcomes, capabilityUnknown };
1259
+ }
1260
+ function messageText(m) {
1261
+ if (!m || !Array.isArray(m.parts)) return "";
1262
+ return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
1263
+ }
1264
+ async function sendPromptAsync(port, sessionId, content, options, attachments) {
1265
+ const before = await getSessionMessages(port, sessionId);
1266
+ const knownUserIds = new Set(
1267
+ (before ?? []).filter((m) => roleOf(m) === "user").map((m) => idOf(m)).filter((id) => typeof id === "string")
1268
+ );
1269
+ const parts = [{ type: "text", text: content }];
1270
+ let pendingOutcomes = null;
1271
+ if (attachments && attachments.inputs.length > 0) {
1272
+ const capable = await getModelAttachmentCapability(port, options?.model);
1273
+ const {
1274
+ parts: fileParts,
1275
+ outcomes,
1276
+ capabilityUnknown
1277
+ } = await buildFileParts(attachments, capable);
1278
+ parts.push(...fileParts);
1279
+ if (attachments.onOutcomes) pendingOutcomes = { outcomes, capabilityUnknown };
1280
+ }
1035
1281
  const body = {
1036
- parts: [{ type: "text", text: content }]
1282
+ parts
1037
1283
  };
1038
1284
  if (options?.agent) {
1039
1285
  body.agent = options.agent;
@@ -1047,79 +1293,221 @@ async function sendMessageToOpenCode(port, sessionId, content, options, hooks, m
1047
1293
  };
1048
1294
  }
1049
1295
  }
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 {
1296
+ const res = await fetch(`${opencodeBase(port)}/session/${sessionId}/prompt_async`, {
1297
+ method: "POST",
1298
+ headers: { "Content-Type": "application/json" },
1299
+ body: JSON.stringify(body)
1300
+ });
1301
+ if (res.status < 200 || res.status >= 300) {
1302
+ const text = await res.text().catch(() => "");
1303
+ throw new Error(`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}`);
1304
+ }
1305
+ const READ_BACK_ATTEMPTS = 5;
1306
+ const READ_BACK_DELAY_MS = 150;
1307
+ for (let attempt = 0; attempt < READ_BACK_ATTEMPTS; attempt++) {
1308
+ const after = await getSessionMessages(port, sessionId);
1309
+ if (after) {
1310
+ let best = null;
1311
+ for (const m of after) {
1312
+ if (roleOf(m) !== "user") continue;
1313
+ const id = idOf(m);
1314
+ if (typeof id !== "string" || knownUserIds.has(id)) continue;
1315
+ if (messageText(m) !== content) continue;
1316
+ const created = createdOf(m) ?? 0;
1317
+ if (best === null || created > best.created) {
1318
+ best = { id, created };
1070
1319
  }
1071
1320
  }
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
- }
1321
+ if (best) {
1322
+ if (pendingOutcomes && attachments?.onOutcomes) attachments.onOutcomes(pendingOutcomes);
1323
+ return best.id;
1086
1324
  }
1087
1325
  }
1326
+ if (attempt < READ_BACK_ATTEMPTS - 1) {
1327
+ await new Promise((resolve2) => setTimeout(resolve2, READ_BACK_DELAY_MS));
1328
+ }
1329
+ }
1330
+ return null;
1331
+ }
1332
+ function findAssistantReplyAfter(messages, userMessageId) {
1333
+ if (!messages || messages.length === 0) return null;
1334
+ const byParent = messages.find(
1335
+ (m) => roleOf(m) === "assistant" && parentIdOf(m) === userMessageId
1336
+ );
1337
+ if (byParent) return byParent;
1338
+ const userIndex = messages.findIndex((m) => idOf(m) === userMessageId);
1339
+ if (userIndex === -1) return null;
1340
+ for (let i = userIndex + 1; i < messages.length; i++) {
1341
+ if (roleOf(messages[i]) === "assistant") return messages[i];
1342
+ }
1343
+ return null;
1344
+ }
1345
+ function findLastAssistantReplyFor(messages, userMessageId) {
1346
+ if (!messages || messages.length === 0) return null;
1347
+ let lastCorrelated = null;
1348
+ let lastNonErrored = null;
1349
+ for (let i = messages.length - 1; i >= 0; i--) {
1350
+ const m = messages[i];
1351
+ if (roleOf(m) !== "assistant" || parentIdOf(m) !== userMessageId) continue;
1352
+ if (lastCorrelated === null) lastCorrelated = m;
1353
+ if (errorOf(m) == null) {
1354
+ lastNonErrored = m;
1355
+ break;
1356
+ }
1357
+ }
1358
+ if (lastCorrelated) return lastNonErrored ?? lastCorrelated;
1359
+ const userIndex = messages.findIndex((m) => idOf(m) === userMessageId);
1360
+ if (userIndex === -1) return null;
1361
+ let last = null;
1362
+ let lastOk = null;
1363
+ for (let i = userIndex + 1; i < messages.length; i++) {
1364
+ const role = roleOf(messages[i]);
1365
+ if (role === "user") break;
1366
+ if (role === "assistant") {
1367
+ last = messages[i];
1368
+ if (errorOf(messages[i]) == null) lastOk = messages[i];
1369
+ }
1370
+ }
1371
+ return lastOk ?? last;
1372
+ }
1373
+ function messageRunState(messages, userMessageId) {
1374
+ if (!messages || messages.length === 0) return "unknown";
1375
+ const hasUser = messages.some((m) => idOf(m) === userMessageId);
1376
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
1377
+ if (!hasUser) {
1378
+ if (!reply) return "unknown";
1379
+ }
1380
+ if (!reply) return "queued";
1381
+ if (isAssistantInFlight(reply)) return "running";
1382
+ return errorOf(reply) != null ? "failed" : "done";
1383
+ }
1384
+ function isPreamblePinnedRunning(messages, userMessageId) {
1385
+ if (messageRunState(messages, userMessageId) !== "running") return false;
1386
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
1387
+ return completedOf(reply) != null && finishOf(reply) === "tool-calls";
1388
+ }
1389
+ function messageError(messages, userMessageId) {
1390
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
1391
+ const error2 = errorOf(reply);
1392
+ if (error2 == null) return null;
1393
+ if (typeof error2 === "string") return error2;
1394
+ if (typeof error2 === "object") {
1395
+ const e = error2;
1396
+ const dataMessage = e.data?.message;
1397
+ if (typeof dataMessage === "string") return dataMessage;
1398
+ if (typeof e.message === "string") return e.message;
1399
+ }
1400
+ return "The agent run failed.";
1401
+ }
1402
+ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1403
+ if (!messages || messages.length === 0) return false;
1404
+ return messages.some(
1405
+ (m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
1406
+ );
1407
+ }
1408
+
1409
+ // src/lib/opencode/session-cleanup.ts
1410
+ var DURATION_UNIT_MS = {
1411
+ s: 1e3,
1412
+ m: 60 * 1e3,
1413
+ h: 60 * 60 * 1e3,
1414
+ d: 24 * 60 * 60 * 1e3
1415
+ };
1416
+ function parseDurationMs(input) {
1417
+ const trimmed = input.trim();
1418
+ const match = /^(\d+)([smhd])$/.exec(trimmed);
1419
+ if (!match) {
1420
+ throw new Error(
1421
+ `Invalid duration "${input}": expected <number><unit> where unit is one of s, m, h, d (e.g. "7d", "24h", "30m", "90s").`
1422
+ );
1423
+ }
1424
+ const value = Number(match[1]);
1425
+ if (value <= 0) {
1426
+ throw new Error(`Invalid duration "${input}": must be a positive value.`);
1427
+ }
1428
+ return value * DURATION_UNIT_MS[match[2]];
1429
+ }
1430
+ function selectSessionsToDelete(sessions, opts) {
1431
+ const { maxAgeMs, maxCount, nowMs, protectedIds } = opts;
1432
+ if (maxAgeMs === void 0 && maxCount === void 0) return [];
1433
+ const ageEligible = (s) => {
1434
+ if (maxAgeMs === void 0) return false;
1435
+ if (s.lastActivityMs === null) return true;
1436
+ return nowMs - s.lastActivityMs > maxAgeMs;
1088
1437
  };
1089
- const sendMessage = async () => {
1090
- const controller = new AbortController();
1091
- const timer = setTimeout(() => controller.abort(), maxWaitMs);
1438
+ const countEligibleIds = /* @__PURE__ */ new Set();
1439
+ if (maxCount !== void 0) {
1440
+ const byActivityDesc = [...sessions].sort(
1441
+ (a, b) => (b.lastActivityMs ?? -Infinity) - (a.lastActivityMs ?? -Infinity)
1442
+ );
1443
+ for (const s of byActivityDesc.slice(maxCount)) {
1444
+ countEligibleIds.add(s.id);
1445
+ }
1446
+ }
1447
+ const toDelete = [];
1448
+ for (const s of sessions) {
1449
+ if (protectedIds.has(s.id)) continue;
1450
+ if (ageEligible(s) || countEligibleIds.has(s.id)) {
1451
+ toDelete.push(s.id);
1452
+ }
1453
+ }
1454
+ return toDelete;
1455
+ }
1456
+ var DEFAULT_INTERVAL = "1h";
1457
+ function resolve(flag, envValue, fallback) {
1458
+ return flag ?? envValue ?? fallback;
1459
+ }
1460
+ function parseMaxCount(input) {
1461
+ const trimmed = input.trim();
1462
+ if (!/^\d+$/.test(trimmed)) {
1463
+ throw new Error(`Invalid max-count "${input}": expected a positive integer.`);
1464
+ }
1465
+ const value = Number(trimmed);
1466
+ if (value <= 0) {
1467
+ throw new Error(`Invalid max-count "${input}": must be greater than 0.`);
1468
+ }
1469
+ return value;
1470
+ }
1471
+ function resolveSessionCleanupConfig(flags, env = process.env) {
1472
+ const warnings = [];
1473
+ const maxAgeRaw = resolve(flags.maxAge, env.EVIDENT_SESSION_CLEANUP_MAX_AGE);
1474
+ const maxCountRaw = resolve(flags.maxCount, env.EVIDENT_SESSION_CLEANUP_MAX_COUNT);
1475
+ const intervalRaw = resolve(
1476
+ flags.interval,
1477
+ env.EVIDENT_SESSION_CLEANUP_INTERVAL,
1478
+ DEFAULT_INTERVAL
1479
+ );
1480
+ let maxAgeMs;
1481
+ if (maxAgeRaw !== void 0) {
1092
1482
  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
1483
+ maxAgeMs = parseDurationMs(maxAgeRaw);
1484
+ } catch (err) {
1485
+ warnings.push(
1486
+ `Ignoring invalid --session-cleanup-max-age: ${err instanceof Error ? err.message : String(err)}`
1105
1487
  );
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 };
1488
+ }
1489
+ }
1490
+ let maxCount;
1491
+ if (maxCountRaw !== void 0) {
1492
+ try {
1493
+ maxCount = parseMaxCount(maxCountRaw);
1111
1494
  } 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;
1495
+ warnings.push(
1496
+ `Ignoring invalid --session-cleanup-max-count: ${err instanceof Error ? err.message : String(err)}`
1497
+ );
1119
1498
  }
1120
- };
1121
- const [result] = await Promise.all([sendMessage(), pollInteractive()]);
1122
- return result;
1499
+ }
1500
+ let intervalMs;
1501
+ try {
1502
+ intervalMs = parseDurationMs(intervalRaw ?? DEFAULT_INTERVAL);
1503
+ } catch (err) {
1504
+ warnings.push(
1505
+ `Ignoring invalid --session-cleanup-interval, using default ${DEFAULT_INTERVAL}: ${err instanceof Error ? err.message : String(err)}`
1506
+ );
1507
+ intervalMs = parseDurationMs(DEFAULT_INTERVAL);
1508
+ }
1509
+ const enabled = maxAgeMs !== void 0 || maxCount !== void 0;
1510
+ return { enabled, maxAgeMs, maxCount, intervalMs, warnings };
1123
1511
  }
1124
1512
 
1125
1513
  // src/lib/tunnel/connection.ts
@@ -1190,24 +1578,34 @@ var StreamForwarder = class {
1190
1578
  }
1191
1579
  async handleOpen(frame) {
1192
1580
  const { sid, method, path, headers, has_body } = frame;
1581
+ const correlationId = headers?.[CORRELATION_ID_HEADER];
1582
+ const startedAt = Date.now();
1193
1583
  if (path === TUNNEL_DRAIN_PING_PATH) {
1194
1584
  this.callbacks.onDrainPing?.();
1195
1585
  this.send({ type: "head", sid, status: 204, headers: {} });
1196
1586
  this.send({ type: "res_end", sid });
1197
1587
  return;
1198
1588
  }
1589
+ if (process.env.DEBUG) {
1590
+ log("debug", "agent_request", {
1591
+ correlation_id: correlationId,
1592
+ sid,
1593
+ method,
1594
+ path: stripQuery(path)
1595
+ });
1596
+ }
1199
1597
  const ac = new AbortController();
1200
1598
  let bodyPromise;
1201
1599
  let pushBody;
1202
1600
  let endBody;
1203
1601
  if (has_body) {
1204
1602
  const chunks = [];
1205
- bodyPromise = new Promise((resolve) => {
1603
+ bodyPromise = new Promise((resolve2) => {
1206
1604
  pushBody = (buf) => {
1207
1605
  chunks.push(buf);
1208
1606
  };
1209
1607
  endBody = () => {
1210
- resolve(Buffer.concat(chunks));
1608
+ resolve2(Buffer.concat(chunks));
1211
1609
  };
1212
1610
  });
1213
1611
  }
@@ -1242,6 +1640,14 @@ var StreamForwarder = class {
1242
1640
  if (!STRIP_RES.has(key.toLowerCase())) resHeaders[key] = value;
1243
1641
  });
1244
1642
  this.send({ type: "head", sid, status: upstream.status, headers: resHeaders });
1643
+ if (process.env.DEBUG) {
1644
+ log("debug", "agent_response", {
1645
+ correlation_id: correlationId,
1646
+ sid,
1647
+ status: upstream.status,
1648
+ duration_ms: Date.now() - startedAt
1649
+ });
1650
+ }
1245
1651
  this.callbacks.onHead?.(sid, upstream.status);
1246
1652
  try {
1247
1653
  if (upstream.body) {
@@ -1317,7 +1723,7 @@ function connectTunnel(options) {
1317
1723
  } = options;
1318
1724
  const tunnelUrl = getTunnelUrlConfig();
1319
1725
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
1320
- return new Promise((resolve, reject) => {
1726
+ return new Promise((resolve2, reject) => {
1321
1727
  const ws = new WebSocket2(url, {
1322
1728
  headers: {
1323
1729
  Authorization: authHeader
@@ -1382,7 +1788,7 @@ function connectTunnel(options) {
1382
1788
  clearTimeout(connectionTimeout);
1383
1789
  const connectedAgentId = message.agent_id ?? agentId;
1384
1790
  onConnected?.(connectedAgentId);
1385
- resolve({
1791
+ resolve2({
1386
1792
  ws,
1387
1793
  close: () => ws.close(1e3, "CLI shutdown")
1388
1794
  });
@@ -1498,6 +1904,23 @@ var RunnerConnection = class {
1498
1904
  };
1499
1905
 
1500
1906
  // src/lib/channels/driver.ts
1907
+ function messageIdOf(m) {
1908
+ if (!m || typeof m !== "object") return void 0;
1909
+ if (typeof m.id === "string") return m.id;
1910
+ const infoId = m.info?.id;
1911
+ return typeof infoId === "string" ? infoId : void 0;
1912
+ }
1913
+ function cleanImageMime(contentType) {
1914
+ if (!contentType) return null;
1915
+ const media = contentType.split(";")[0].trim().toLowerCase();
1916
+ return /^image\/[a-z0-9.+-]+$/.test(media) ? media : null;
1917
+ }
1918
+ var LOG_LEVELS = {
1919
+ debug: 0,
1920
+ info: 1,
1921
+ warn: 2,
1922
+ error: 3
1923
+ };
1501
1924
  var DEFAULT_RETRY_POLICY = {
1502
1925
  maxAttempts: 6,
1503
1926
  baseDelayMs: 500,
@@ -1505,12 +1928,24 @@ var DEFAULT_RETRY_POLICY = {
1505
1928
  };
1506
1929
  var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
1507
1930
  var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
1931
+ var DEFAULT_STUCK_QUEUED_MS = 6e4;
1932
+ var HEARTBEAT_MS = 6e4;
1933
+ var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
1934
+ var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
1508
1935
  var ChannelAuthError = class extends Error {
1509
1936
  constructor(message) {
1510
1937
  super(message);
1511
1938
  this.name = "ChannelAuthError";
1512
1939
  }
1513
1940
  };
1941
+ var ChannelTerminalError = class extends Error {
1942
+ status;
1943
+ constructor(message, status) {
1944
+ super(message);
1945
+ this.name = "ChannelTerminalError";
1946
+ this.status = status;
1947
+ }
1948
+ };
1514
1949
  function backoffDelay(attempt, policy) {
1515
1950
  const exp = policy.baseDelayMs * Math.pow(2, attempt);
1516
1951
  const capped = Math.min(policy.maxDelayMs, exp);
@@ -1531,15 +1966,100 @@ var ChannelDriver = class {
1531
1966
  sleep;
1532
1967
  pausedPollIntervalMs;
1533
1968
  pausedMaxWaitMs;
1969
+ stuckQueuedMs;
1970
+ now;
1534
1971
  /** Cache of conversationId → opencode sessionId. */
1535
1972
  sessions = /* @__PURE__ */ new Map();
1536
1973
  /**
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.
1974
+ * Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
1975
+ * longer idempotent (no caller-supplied `messageID`), and its read-back picks
1976
+ * "the one new user row" which is only unambiguous if no OTHER dispatch into
1977
+ * the SAME session interleaves its snapshot→POST→read-back. This map chains each
1978
+ * session's dispatches so they run serially; distinct sessions stay concurrent.
1979
+ */
1980
+ sessionDispatchLocks = /* @__PURE__ */ new Map();
1981
+ /**
1982
+ * Per-SESSION watchers (WI-3), keyed by opencode sessionId. Single-flight per
1983
+ * session: one polling loop services all of that session's in-flight messages.
1984
+ * A session entry exists while it has any in-flight (dispatched-but-not-done)
1985
+ * message; it is removed once its in-flight set empties.
1541
1986
  */
1542
1987
  watchers = /* @__PURE__ */ new Map();
1988
+ /**
1989
+ * AUTHORITATIVE local dedup (WI-3): Evident message ids that have been
1990
+ * dispatched and are still in-flight. A message in this set is never
1991
+ * re-`prompt_async`-ed by a subsequent poll tick while it is queued/running.
1992
+ * Backed by a stable minted opencode `messageID` whose duplicate re-enqueue is
1993
+ * idempotent on opencode (PoC fact 9) — so even if this set is lost on restart,
1994
+ * a steady-state-poll re-dispatch will not double-run the message.
1995
+ */
1996
+ dispatched = /* @__PURE__ */ new Set();
1997
+ /**
1998
+ * Re-adopted (ADR-0046) Evident message ids currently tracked by a watcher.
1999
+ * Used only to distinguish a RE-ADOPTED give-up from a normal-dispatch give-up
2000
+ * so the former can be parked in `dontRedispatch` (Bug 2). A row is added when
2001
+ * it is re-adopted and removed when its watcher settles or it is observed off
2002
+ * the processing list.
2003
+ */
2004
+ readopted = /* @__PURE__ */ new Set();
2005
+ /**
2006
+ * "Don't re-DISPATCH / re-attach this orphan again" (Bug 2/5). Set when a
2007
+ * re-adopted running/orphan row's watcher hit its `processed_at`-anchored
2008
+ * deadline (or an orphan whose window already elapsed): the still-`processing`
2009
+ * server row would otherwise be re-adopted (and re-dispatched) on EVERY ~2s
2010
+ * drain until the 15-min cron resets it — spamming new turns.
2011
+ *
2012
+ * CRITICAL (Bugbot #202): this suppresses ONLY the dispatch/re-attach paths, it
2013
+ * does NOT suppress DONE delivery. A row parked here whose reply later COMPLETES
2014
+ * in opencode must still be delivered via `markDone` on the next drain — so
2015
+ * `readoptOne` computes `state` FIRST and this set is checked only on the
2016
+ * non-done path. It is cleared once the row leaves the processing list (cron
2017
+ * reset → it drains normally as `pending`), so it can never leak.
2018
+ */
2019
+ dontRedispatch = /* @__PURE__ */ new Set();
2020
+ /**
2021
+ * "markDone for this row is TERMINALLY undeliverable" (Bug 4). Set ONLY when a
2022
+ * re-adopted DONE row's `markDone` returned a terminal 4xx (a status that will
2023
+ * never succeed). Checked at the TOP of the `done` branch so we do NOT re-attempt
2024
+ * that markDone every ~2s drain while the row stays `processing`. A TRANSIENT
2025
+ * markDone failure must NOT land here (it must still retry next drain). Separate
2026
+ * from `dontRedispatch` because the two concerns are independent: a row can need
2027
+ * "stop re-dispatching" without "stop delivering", and vice versa. Cleared once
2028
+ * the row leaves the processing list, exactly like `dontRedispatch`.
2029
+ */
2030
+ doneUndeliverable = /* @__PURE__ */ new Set();
2031
+ /**
2032
+ * "Already emitted `readopt_poll_unresolved` for this row" (#229). The b1 /
2033
+ * unreadable-status re-evaluate leaf leaves the row UN-tracked so it is re-read
2034
+ * every ~2s drain until the status map becomes readable — but the server-visible
2035
+ * signal is an OUTCOME, so it must fire at most ONCE per row, not once per drain
2036
+ * (Bugbot "Re-adopt signals flood every drain"). Cleared when the row leaves the
2037
+ * processing list, exactly like `dontRedispatch`/`doneUndeliverable`.
2038
+ */
2039
+ readoptPollUnresolvedSignalled = /* @__PURE__ */ new Set();
2040
+ /**
2041
+ * "A null-id re-adopt re-dispatch is in flight, awaiting its read-back" (WI-5
2042
+ * Task 5.4, High-2). Since we no longer send a caller-supplied id, a re-dispatch
2043
+ * is NOT idempotent: if `forceReadoptRun` dispatches on tick N but the read-back +
2044
+ * persist hasn't landed before tick N+1 re-reads the still-null
2045
+ * `row.opencode_message_id`, tick N+1 would dispatch AGAIN → duplicate user turns.
2046
+ * A row is added here right before its `sendPromptAsync` and `forceReadoptRun`
2047
+ * short-circuits while it is present, so a null-id row is re-dispatched AT MOST
2048
+ * ONCE per outstanding read-back. Cleared on a SUCCESSFUL dispatch+read-back (the
2049
+ * row is then tracked in `dispatched`, so `readoptOne`'s early skip prevents
2050
+ * re-entry) OR on a failed/unresolved dispatch (the message is genuinely un-sent,
2051
+ * so the NEXT tick may retry exactly once more).
2052
+ */
2053
+ awaitingReadopt = /* @__PURE__ */ new Set();
2054
+ /**
2055
+ * "Already signalled `attachments_skipped` for this Evident message id" (#376).
2056
+ * The in-thread skip note is an OUTCOME, so it must fire AT MOST ONCE per message
2057
+ * — never re-post on a re-dispatch of the same row (`forceReadoptRun` or the
2058
+ * next-tick null-id retry both re-run `sendPromptAsync`, which re-fires
2059
+ * `onOutcomes`). Mirrors `readoptPollUnresolvedSignalled`: a local dedup on the
2060
+ * outcome, not the dispatch. Not cleared (a message is signalled once for life).
2061
+ */
2062
+ attachmentsSkippedSignalled = /* @__PURE__ */ new Set();
1543
2063
  /**
1544
2064
  * Cache of the opencode root directory (from `GET /path`). Resolved lazily on
1545
2065
  * first session creation so drain-created sessions are rooted at the project
@@ -1547,8 +2067,43 @@ var ChannelDriver = class {
1547
2067
  * not yet resolved; `null` = resolved-but-unavailable (don't keep retrying).
1548
2068
  */
1549
2069
  opencodeDirectory = void 0;
2070
+ /**
2071
+ * Cache of opencode `sessionId → parentID` (its parent session, or `null` when
2072
+ * the session is a root with no parent). Sub-agents spawned via the `task` tool
2073
+ * run in CHILD sessions whose `parentID` chains up to the Evident-created
2074
+ * (watched) session; we resolve this once per session so a child-session
2075
+ * question/permission can be attributed to the watched session's subtree
2076
+ * (`sessionBelongsTo`) instead of being dropped by an exact-id filter. A missing
2077
+ * entry = not yet resolved; `null` = resolved root (stop walking).
2078
+ */
2079
+ sessionParents = /* @__PURE__ */ new Map();
2080
+ /**
2081
+ * Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
2082
+ * NON-EMPTY name is stored (terminal — a real session name won't later un-name),
2083
+ * so we do NOT re-GET `/session/:id` every tick. A missing entry = not yet
2084
+ * resolved OR resolved-but-still-empty → re-fetch on next need, since OpenCode
2085
+ * names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
2086
+ * the watcher completion path AND the restart-recovery re-adopt path (which has
2087
+ * no watcher) can resolve the title.
2088
+ */
2089
+ sessionTitles = /* @__PURE__ */ new Map();
1550
2090
  /** Serialises drains so a reconnect during a drain doesn't double-process. */
1551
2091
  draining = false;
2092
+ /**
2093
+ * The currently-executing `drainPending()` promise, or null when idle. Lets a
2094
+ * graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
2095
+ * is about to dispatch is not missed by the `hasInFlightWatchers()` check (a
2096
+ * drain that entered before `stop()` still registers its watcher).
2097
+ */
2098
+ activeDrain = null;
2099
+ /**
2100
+ * Set by `stop()` on graceful shutdown. Once stopped, `drainPending` no longer
2101
+ * dispatches NEW work (it returns 0 immediately) — but the per-session watcher
2102
+ * loops already running keep going so in-flight turns can finish and deliver
2103
+ * their reply. `run.ts` awaits `waitForInFlight()` before it closes the tunnel
2104
+ * and stops opencode.
2105
+ */
2106
+ stopped = false;
1552
2107
  constructor(config2) {
1553
2108
  this.agentId = config2.agentId;
1554
2109
  this.port = config2.port;
@@ -1562,6 +2117,8 @@ var ChannelDriver = class {
1562
2117
  this.sleep = config2.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1563
2118
  this.pausedPollIntervalMs = config2.pausedPollIntervalMs ?? DEFAULT_PAUSED_POLL_INTERVAL_MS;
1564
2119
  this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
2120
+ this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
2121
+ this.now = config2.now ?? (() => Date.now());
1565
2122
  }
1566
2123
  /** The IPv4-loopback base URL for the local `opencode serve`. */
1567
2124
  get opencodeBase() {
@@ -1571,16 +2128,29 @@ var ChannelDriver = class {
1571
2128
  // Public API
1572
2129
  // -------------------------------------------------------------------------
1573
2130
  /**
1574
- * Drain all pending channel conversations once: poll → processcallback.
2131
+ * Drain all pending channel conversations once: poll → dispatchregister.
1575
2132
  * Called on tunnel `connected` (WI-CHAN-4) and on each poll tick by `run.ts`.
1576
2133
  * Re-entrant calls while a drain is in flight are skipped (return 0).
1577
2134
  *
1578
- * @returns the number of messages processed.
2135
+ * @returns the number of messages NEWLY dispatched to opencode's native queue.
1579
2136
  */
1580
2137
  async drainPending() {
2138
+ if (this.stopped) return 0;
1581
2139
  if (this.draining) return 0;
1582
2140
  this.draining = true;
1583
- let processed = 0;
2141
+ const run2 = this.runDrain();
2142
+ this.activeDrain = run2.then(
2143
+ () => {
2144
+ this.activeDrain = null;
2145
+ },
2146
+ () => {
2147
+ this.activeDrain = null;
2148
+ }
2149
+ );
2150
+ return run2;
2151
+ }
2152
+ async runDrain() {
2153
+ let dispatched = 0;
1584
2154
  try {
1585
2155
  const conversations = await this.getPendingConversations();
1586
2156
  if (conversations.length > 0) {
@@ -1591,231 +2161,1571 @@ var ChannelDriver = class {
1591
2161
  });
1592
2162
  }
1593
2163
  for (const conv of conversations) {
1594
- processed += await this.processConversation(conv);
2164
+ if (this.stopped) break;
2165
+ dispatched += await this.processConversation(conv);
1595
2166
  }
2167
+ await this.readoptProcessing();
1596
2168
  } finally {
1597
2169
  this.draining = false;
1598
2170
  }
1599
- return processed;
2171
+ return dispatched;
2172
+ }
2173
+ /**
2174
+ * True while any per-session watcher has a non-empty in-flight dispatched set
2175
+ * (Task 3.7). `run.ts` treats this as NON-idle so `--idle-timeout` cannot exit
2176
+ * the process while a dispatched message is still queued/running — which would
2177
+ * kill the turn and orphan its reply.
2178
+ */
2179
+ hasInFlightWatchers() {
2180
+ for (const watcher of this.watchers.values()) {
2181
+ if (watcher.inFlight.size > 0) return true;
2182
+ }
2183
+ return false;
2184
+ }
2185
+ /**
2186
+ * OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
2187
+ * exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
2188
+ * `watchers` entry whose `inFlight` set is non-empty — the same predicate
2189
+ * `hasInFlightWatchers()` uses, lifted to return the ids.
2190
+ *
2191
+ * Deliberately does NOT include `this.sessions` (the permanent, never-pruned
2192
+ * conversation→session cache). Protecting every bound-but-idle session there
2193
+ * would shield nearly every session and defeat cleanup — AND it is unnecessary:
2194
+ * `ensureSession` is self-healing (it recreates a session whose id no longer
2195
+ * exists), so deleting an idle bound session is harmless — the conversation's
2196
+ * next turn transparently rebinds a fresh one. The only thing worth protecting
2197
+ * is a session with a turn ACTIVELY in flight right now: tearing that down
2198
+ * mid-turn would strand the running `prompt_async`. Idle sessions are fair game.
2199
+ */
2200
+ protectedSessionIds() {
2201
+ const ids = /* @__PURE__ */ new Set();
2202
+ for (const [sessionId, watcher] of this.watchers) {
2203
+ if (watcher.inFlight.size > 0) ids.add(sessionId);
2204
+ }
2205
+ return ids;
2206
+ }
2207
+ /**
2208
+ * Begin a graceful stop: stop accepting NEW channel work. Idempotent. After
2209
+ * this, `drainPending()` is a no-op (returns 0), so no new message is dispatched
2210
+ * — but the watcher loops already tracking in-flight turns keep running, so a
2211
+ * turn that has finished (or is about to) still fires `markDone` and delivers
2212
+ * its reply. Pair with `waitForInFlight()` to bound how long shutdown waits.
2213
+ */
2214
+ stop() {
2215
+ this.stopped = true;
2216
+ }
2217
+ /**
2218
+ * Wait (up to `timeoutMs`) for in-flight watcher work to settle during a
2219
+ * graceful shutdown, so a turn whose reply is ready — or completes within the
2220
+ * window — is delivered before the process exits, instead of being cut off and
2221
+ * left for the ADR-0046 restart-recovery path.
2222
+ *
2223
+ * Bounded on purpose: the watcher's own give-up deadline is up to 10 minutes,
2224
+ * far longer than a shutdown grace period (e.g. Fargate's SIGTERM→SIGKILL
2225
+ * window). We poll `hasInFlightWatchers()` and return as soon as the in-flight
2226
+ * set empties OR the timeout elapses. Anything still in flight at the timeout is
2227
+ * safe to abandon — it stays `processing` server-side and is re-adopted on the
2228
+ * next runner start (ADR-0046).
2229
+ *
2230
+ * @returns true if all in-flight work settled within the window; false if the
2231
+ * timeout elapsed with work still in flight.
2232
+ */
2233
+ async waitForInFlight(timeoutMs) {
2234
+ const deadline = this.now() + timeoutMs;
2235
+ const step = Math.min(this.pausedPollIntervalMs, 250);
2236
+ if (this.activeDrain) {
2237
+ let drainSettled = false;
2238
+ void this.activeDrain.then(() => {
2239
+ drainSettled = true;
2240
+ });
2241
+ while (!drainSettled) {
2242
+ if (this.now() >= deadline) return false;
2243
+ await this.sleep(step);
2244
+ }
2245
+ }
2246
+ while (this.hasInFlightWatchers()) {
2247
+ if (this.now() >= deadline) return false;
2248
+ await this.sleep(step);
2249
+ }
2250
+ return true;
1600
2251
  }
1601
2252
  /**
1602
- * Await all outstanding paused-session watchers (WI-2-CLI).
2253
+ * Await all outstanding per-session watchers (WI-3).
1603
2254
  *
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.
2255
+ * In production the watcher loops are deliberately started-not-awaited so the
2256
+ * drain loop never blocks on them and process exit is not held up (the cron
2257
+ * recovers any abandoned ones). This helper exists primarily for deterministic
2258
+ * tests that need to observe a watcher's effect (the `processing`/`done` PATCH
2259
+ * or its giving up) after a non-blocking `drainPending`. Watcher loops never
2260
+ * reject, so this resolves.
1609
2261
  */
1610
2262
  async flushPausedWatchers() {
1611
- await Promise.all([...this.watchers.values()]);
2263
+ while (true) {
2264
+ const loops = [...this.watchers.values()].map((w) => w.loop).filter((l) => l != null);
2265
+ if (loops.length === 0) return;
2266
+ await Promise.all(loops);
2267
+ const stillLive = [...this.watchers.values()].some((w) => w.loop != null);
2268
+ if (!stillLive) return;
2269
+ }
1612
2270
  }
1613
2271
  // -------------------------------------------------------------------------
1614
- // Conversation processing
2272
+ // Conversation processing (WI-3 — async dispatch)
1615
2273
  // -------------------------------------------------------------------------
2274
+ /**
2275
+ * Dispatch each pending message for a conversation to opencode's native queue
2276
+ * via `prompt_async` (Task 3.2) and register it with the conversation's
2277
+ * per-session watcher. Does NOT block on the turn and does NOT call
2278
+ * `markProcessing` here — that fires from the watcher on running-start.
2279
+ *
2280
+ * @returns the count of messages NEWLY dispatched (not already in-flight).
2281
+ */
1616
2282
  async processConversation(conv) {
1617
2283
  const sessionId = await this.ensureSession(conv);
1618
2284
  const messages = await this.getPendingMessages(conv.id);
1619
- let processed = 0;
2285
+ let dispatched = 0;
2286
+ let skippedAlreadyDispatched = 0;
1620
2287
  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
- });
2288
+ if (this.stopped) break;
2289
+ if (this.dispatched.has(message.id)) {
2290
+ skippedAlreadyDispatched += 1;
1629
2291
  continue;
1630
2292
  }
2293
+ const options = {
2294
+ agent: message.opencode_agent ?? void 0,
2295
+ model: message.opencode_model ?? void 0
2296
+ };
2297
+ let opencodeMessageId;
1631
2298
  try {
1632
2299
  this.log({
1633
2300
  level: "info",
1634
- message: `Sending queued message ${message.id.slice(0, 8)} to OpenCode (session ${sessionId.slice(0, 8)})`,
2301
+ message: `Dispatching message ${message.id.slice(0, 8)} to OpenCode native queue (session ${sessionId.slice(0, 8)})`,
1635
2302
  conversation_id: conv.id,
1636
2303
  message_id: message.id
1637
2304
  });
1638
- const result = await sendMessageToOpenCode(
1639
- this.port,
2305
+ const sendAttachments = this.buildSendAttachments(conv, message);
2306
+ opencodeMessageId = await this.dispatchLocked(
1640
2307
  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
- }
2308
+ () => sendPromptAsync(this.port, sessionId, message.content, options, sendAttachments)
1650
2309
  );
1651
- if (result.awaitingInteraction) {
2310
+ } catch (err) {
2311
+ if (err instanceof ChannelAuthError) throw err;
2312
+ this.dispatched.delete(message.id);
2313
+ if (await sessionExists(this.port, sessionId) === false) {
2314
+ this.sessions.delete(conv.id);
1652
2315
  this.log({
1653
- level: "info",
1654
- message: `Message ${message.id.slice(0, 8)} paused awaiting interaction \u2014 watching session for completion`,
2316
+ level: "warn",
2317
+ message: `Message ${message.id.slice(0, 8)} dispatch hit a session (${sessionId.slice(0, 8)}) that was deleted mid-dispatch (cleanup race) \u2014 deferring this and later messages for conversation ${conv.id.slice(0, 8)} to the next tick (recreated then, in order). Already-dispatched turns keep their watcher.`,
1655
2318
  conversation_id: conv.id,
1656
2319
  message_id: message.id
1657
2320
  });
1658
- this.startPausedWatcher(conv, message, sessionId);
1659
- continue;
2321
+ break;
1660
2322
  }
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`,
1667
- conversation_id: conv.id,
1668
- message_id: message.id
1669
- });
1670
- } catch (err) {
1671
- if (err instanceof ChannelAuthError) throw err;
1672
2323
  await this.markFailed(conv.id, message.id).catch(() => {
1673
2324
  });
1674
2325
  this.log({
1675
2326
  level: "error",
1676
- message: `Message ${message.id.slice(0, 8)} failed: ${err instanceof Error ? err.message : String(err)}`,
2327
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${err instanceof Error ? err.message : String(err)}`,
1677
2328
  conversation_id: conv.id,
1678
2329
  message_id: message.id
1679
2330
  });
2331
+ continue;
2332
+ }
2333
+ if (opencodeMessageId === null) {
2334
+ this.log({
2335
+ level: "warn",
2336
+ message: `Message ${message.id.slice(0, 8)} dispatched but its opencode id could not be read back \u2014 leaving un-tracked to retry next tick`,
2337
+ conversation_id: conv.id,
2338
+ message_id: message.id
2339
+ });
2340
+ continue;
2341
+ }
2342
+ this.dispatched.add(message.id);
2343
+ this.registerInFlight(conv, sessionId, message, opencodeMessageId);
2344
+ dispatched += 1;
2345
+ void this.postSignal(conv.id, message.id, "dispatched");
2346
+ }
2347
+ if (messages.length > 0 && dispatched === 0 && skippedAlreadyDispatched === messages.length) {
2348
+ this.log({
2349
+ level: "warn",
2350
+ 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).`,
2351
+ conversation_id: conv.id
2352
+ });
2353
+ }
2354
+ this.ensureWatcherRunning(sessionId);
2355
+ return dispatched;
2356
+ }
2357
+ async ensureSession(conv) {
2358
+ const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
2359
+ if (bound) {
2360
+ const exists = await sessionExists(this.port, bound);
2361
+ if (exists === false) {
2362
+ this.log({
2363
+ level: "debug",
2364
+ message: `OpenCode session ${bound} for conversation ${conv.id.slice(0, 8)} no longer exists (deleted or DB reset) \u2014 creating a fresh session and rebinding.`,
2365
+ conversation_id: conv.id
2366
+ });
2367
+ this.sessions.delete(conv.id);
2368
+ return this.createAndBindSession(conv.id);
2369
+ }
2370
+ this.sessions.set(conv.id, bound);
2371
+ return bound;
2372
+ }
2373
+ return this.createAndBindSession(conv.id);
2374
+ }
2375
+ /**
2376
+ * Create a fresh OpenCode session for a conversation, cache the binding, and
2377
+ * best-effort persist it server-side. Shared by the first-ever bind and the
2378
+ * self-heal recreate path in `ensureSession`.
2379
+ */
2380
+ async createAndBindSession(conversationId) {
2381
+ const directory = await this.resolveOpenCodeDirectory();
2382
+ const sessionId = await createOpenCodeSession(this.port, directory);
2383
+ this.sessions.set(conversationId, sessionId);
2384
+ await this.persistSession(conversationId, sessionId).catch(() => {
2385
+ });
2386
+ return sessionId;
2387
+ }
2388
+ /**
2389
+ * Lazily resolve (and cache) opencode's root directory via `GET /path`.
2390
+ * Resolved once per driver: `undefined` until first lookup, then the directory
2391
+ * string or `null` if unavailable (we don't keep retrying a missing `/path`).
2392
+ */
2393
+ async resolveOpenCodeDirectory() {
2394
+ if (this.opencodeDirectory !== void 0) return this.opencodeDirectory;
2395
+ this.opencodeDirectory = await getOpenCodeDirectory(this.port);
2396
+ if (!this.opencodeDirectory) {
2397
+ this.log({
2398
+ level: "warn",
2399
+ message: "Could not determine opencode directory (GET /path) \u2014 new sessions may not appear in opencode web"
2400
+ });
2401
+ }
2402
+ return this.opencodeDirectory;
2403
+ }
2404
+ // -------------------------------------------------------------------------
2405
+ // Per-session watcher (WI-3)
2406
+ // -------------------------------------------------------------------------
2407
+ /**
2408
+ * Run one dispatch (`sendPromptAsync` snapshot→POST→read-back) serialized per
2409
+ * opencode session (Task 2.1a), so two dispatches into the SAME session can
2410
+ * never interleave and mis-correlate their read-backs. Distinct sessions run
2411
+ * concurrently. The chained tail intentionally ignores the prior result/error
2412
+ * (each dispatch reports its own outcome to its caller).
2413
+ */
2414
+ dispatchLocked(sessionId, fn) {
2415
+ const prior = this.sessionDispatchLocks.get(sessionId) ?? Promise.resolve();
2416
+ const run2 = prior.then(fn, fn);
2417
+ this.sessionDispatchLocks.set(
2418
+ sessionId,
2419
+ run2.then(
2420
+ () => void 0,
2421
+ () => void 0
2422
+ )
2423
+ );
2424
+ return run2;
2425
+ }
2426
+ // -------------------------------------------------------------------------
2427
+ // Inbound image attachments (#255, WI-8)
2428
+ // -------------------------------------------------------------------------
2429
+ /**
2430
+ * Build the `SendAttachmentsInput` for a message's inbound images, or
2431
+ * `undefined` when the message has none (so a text-only turn is unchanged).
2432
+ *
2433
+ * The driver OWNS the two channel-facing concerns the session module cannot:
2434
+ * - the AUTHENTICATED byte fetch through Evident's WI-6 endpoint
2435
+ * (`fetchAttachmentDataUrl`), using the SAME `getAuthHeader()` as every
2436
+ * other combinedAuth callback — the CLI NEVER talks to Slack directly;
2437
+ * - the in-thread SKIP NOTE (`signalAttachmentsSkipped`) posted over the
2438
+ * existing callback surface when any image was skipped/failed.
2439
+ * `sendPromptAsync` applies the capability gate + appends the `file` parts and
2440
+ * reports outcomes back via `onOutcomes`.
2441
+ */
2442
+ buildSendAttachments(conv, message) {
2443
+ const refs = message.attachments;
2444
+ if (!refs || refs.length === 0) return void 0;
2445
+ return {
2446
+ inputs: refs.map((a, index) => ({
2447
+ index,
2448
+ mime: a.mime,
2449
+ ...a.filename ? { filename: a.filename } : {}
2450
+ })),
2451
+ fetchDataUrl: (index) => this.fetchAttachmentDataUrl(message.id, index, refs[index].mime),
2452
+ onOutcomes: ({ outcomes, capabilityUnknown }) => this.signalAttachmentsSkipped(conv.id, message.id, outcomes, capabilityUnknown)
2453
+ };
2454
+ }
2455
+ /**
2456
+ * Fetch ONE inbound image's bytes through Evident's WI-6 endpoint
2457
+ * (`GET {apiUrl}/agents/{agentId}/attachments/{messageId}/{index}`) using the
2458
+ * existing authenticated fetch, and base64-encode into a
2459
+ * `data:<mime>;base64,<…>` URL for the opencode `file` part's `url`.
2460
+ *
2461
+ * The endpoint streams the source bytes verbatim (200), or returns 404
2462
+ * (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
2463
+ * (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
2464
+ * OMITS that one image and the text turn still sends — NEVER throws the turn.
2465
+ * Failures are logged with context (no silent swallow).
2466
+ */
2467
+ async fetchAttachmentDataUrl(messageId, index, mime) {
2468
+ try {
2469
+ const res = await this.fetchImpl(
2470
+ `${this.apiUrl}/agents/${this.agentId}/attachments/${messageId}/${index}`,
2471
+ { headers: { Authorization: this.getAuthHeader() } }
2472
+ );
2473
+ if (!res.ok) {
2474
+ this.log({
2475
+ level: "error",
2476
+ message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
2477
+ message_id: messageId
2478
+ });
2479
+ return null;
2480
+ }
2481
+ const buf = await res.arrayBuffer();
2482
+ const base64 = Buffer.from(buf).toString("base64");
2483
+ const dataMime = cleanImageMime(res.headers.get("content-type")) || mime;
2484
+ return `data:${dataMime};base64,${base64}`;
2485
+ } catch (err) {
2486
+ this.log({
2487
+ level: "error",
2488
+ message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} failed \u2014 omitting this image (text turn proceeds): ${err instanceof Error ? err.message : String(err)}`,
2489
+ message_id: messageId
2490
+ });
2491
+ return null;
2492
+ }
2493
+ }
2494
+ /**
2495
+ * On any skipped/failed image, post an in-thread note to Evident over the
2496
+ * EXISTING combinedAuth callback surface — the CLI NEVER posts to Slack directly.
2497
+ * Evident routes the note to source via `conversation.deliver`.
2498
+ *
2499
+ * The `POST .../messages/:id/signal` route accepts `attachments_skipped` (in
2500
+ * `messageSignalSchema`) and turns it into an in-thread note delivered through
2501
+ * `conversation.deliver` (e.g. "N image(s) couldn't be forwarded"), so the note
2502
+ * reaches the channel.
2503
+ *
2504
+ * Fire-and-forget: never throws into the send/tick (logs its own failure).
2505
+ */
2506
+ signalAttachmentsSkipped(conversationId, messageId, outcomes, capabilityUnknown) {
2507
+ const skipped = outcomes.filter((o) => o.status === "skipped").length;
2508
+ const failed = outcomes.filter((o) => o.status === "failed").length;
2509
+ if (skipped === 0 && failed === 0) return;
2510
+ if (this.attachmentsSkippedSignalled.has(messageId)) return;
2511
+ this.attachmentsSkippedSignalled.add(messageId);
2512
+ const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
2513
+ this.log({
2514
+ level: "info",
2515
+ message: `Message ${messageId.slice(0, 8)}: ${skipped} image(s) skipped (${capabilityUnknown ? "capability was unreadable \u2014 failed open to text-only" : "model not attachment-capable"}), ${failed} image(s) unavailable (deleted-at-source or fetch failure) \u2014 noting to Evident`,
2516
+ conversation_id: conversationId,
2517
+ message_id: messageId
2518
+ });
2519
+ void this.postSignal(conversationId, messageId, "attachments_skipped", {
2520
+ skipped,
2521
+ failed,
2522
+ ...skipped > 0 ? { skipped_reason: skippedReason } : {}
2523
+ });
2524
+ }
2525
+ /** Register a freshly-dispatched message with its session's watcher state. */
2526
+ registerInFlight(conv, sessionId, message, opencodeMessageId) {
2527
+ let watcher = this.watchers.get(sessionId);
2528
+ if (!watcher) {
2529
+ watcher = {
2530
+ conv,
2531
+ inFlight: /* @__PURE__ */ new Map(),
2532
+ loop: null,
2533
+ reportedQuestions: /* @__PURE__ */ new Set(),
2534
+ reportedPermissions: /* @__PURE__ */ new Set(),
2535
+ lastGoodPollAt: this.now(),
2536
+ hadUsablePoll: false
2537
+ };
2538
+ this.watchers.set(sessionId, watcher);
2539
+ }
2540
+ const now = this.now();
2541
+ watcher.inFlight.set(message.id, {
2542
+ evidentMessageId: message.id,
2543
+ opencodeMessageId,
2544
+ message,
2545
+ dispatchedAt: now,
2546
+ processingAnchorMs: now,
2547
+ deadline: now + this.pausedMaxWaitMs,
2548
+ started: false,
2549
+ done: false,
2550
+ stuckReported: false,
2551
+ lastAliveAt: 0,
2552
+ aliveInFlight: false,
2553
+ awaitingHumanLatched: false,
2554
+ pausedOnQuestion: false,
2555
+ pausedOnPermission: false,
2556
+ pausedClearConfirmed: false,
2557
+ pausedInFlight: false,
2558
+ deliveryDeadlineAnchored: false
2559
+ });
2560
+ }
2561
+ /**
2562
+ * Register a RE-ADOPTED `processing` message with its session watcher
2563
+ * (ADR-0046, WI-4). Mirrors `registerInFlight` but anchors the give-up
2564
+ * `deadline` to the row's SERVER-SIDE `processed_at` (Invariant 1), NEVER to
2565
+ * `now`, so the paused/queued/unreachable cases settle on the same wall-clock a
2566
+ * fresh dispatch would (10 min after `processed_at`, not 10 min from now).
2567
+ *
2568
+ * This re-attaches into the SAME watcher, so the ADR-0047 progressing-vs-paused
2569
+ * give-up (`serviceInFlightMessage`) applies unchanged: a re-adopted turn
2570
+ * opencode reports ACTIVELY `running` is watched to completion (its liveness
2571
+ * heartbeat keeps the cron off its row), while a re-adopted turn that is paused
2572
+ * awaiting a human — or queued/unreachable — is still bounded by `deadline` and
2573
+ * handed to the cron. The old "the `deadline` must settle before the ~15-min
2574
+ * cron or they double-drive" reasoning is superseded: liveness now settles the
2575
+ * actively-running case; `deadline` settles the rest. `dispatchedAt` stays `now`
2576
+ * (only the appear-guard uses it).
2577
+ *
2578
+ * `evidentMessageId` addresses the SERVER row (for markProcessing/markDone);
2579
+ * `opencodeMessageId` is the id the watcher polls for a reply — for the orphan
2580
+ * fresh-run path these differ (a fresh opencode id under the same server row).
2581
+ *
2582
+ * `started` is set true so the watcher does NOT re-`markProcessing` a row the
2583
+ * server already flipped to `processing`; the running/done transitions still
2584
+ * fire from the watcher's normal branches.
2585
+ */
2586
+ registerReadopted(conv, sessionId, message, opencodeMessageId, processedAtMs) {
2587
+ let watcher = this.watchers.get(sessionId);
2588
+ if (!watcher) {
2589
+ watcher = {
2590
+ conv,
2591
+ inFlight: /* @__PURE__ */ new Map(),
2592
+ loop: null,
2593
+ reportedQuestions: /* @__PURE__ */ new Set(),
2594
+ reportedPermissions: /* @__PURE__ */ new Set(),
2595
+ lastGoodPollAt: this.now(),
2596
+ hadUsablePoll: false
2597
+ };
2598
+ this.watchers.set(sessionId, watcher);
2599
+ }
2600
+ watcher.inFlight.set(message.id, {
2601
+ evidentMessageId: message.id,
2602
+ opencodeMessageId,
2603
+ message,
2604
+ dispatchedAt: this.now(),
2605
+ // Anchor the absolute-age ceiling to the SERVER-SIDE `processed_at` (the same
2606
+ // value seeding `deadline`), NOT `dispatchedAt` — so a re-adopted zombie's age
2607
+ // reflects the real turn duration and the ceiling fires on the ORIGINAL turn.
2608
+ processingAnchorMs: processedAtMs,
2609
+ deadline: processedAtMs + this.pausedMaxWaitMs,
2610
+ // The server row is ALREADY `processing`; do not re-fire markProcessing.
2611
+ started: true,
2612
+ done: false,
2613
+ // Not yet reported stuck-queued. The once-guard (`stuckReported`) applies,
2614
+ // AND the stuck-queued observer INCLUDES re-adopted queued wedges: it gates
2615
+ // on `state === 'queued'` (turn produced no reply), not on `started`, so a
2616
+ // re-adopted row left wedged in `queued` still emits the signal once
2617
+ // (#210/#220 observability).
2618
+ stuckReported: false,
2619
+ // Task 5.2: a re-adopted actively-running row re-attaches into the SAME
2620
+ // watcher and so hits the SAME actively-running heartbeat branch in
2621
+ // `serviceInFlightMessage` as a fresh dispatch — monitoring observes "runner
2622
+ // re-adopted and is confirming this row alive" via that `alive` heartbeat,
2623
+ // with no extra `re_adopted` signal needed (folds old WI-6).
2624
+ lastAliveAt: 0,
2625
+ aliveInFlight: false,
2626
+ awaitingHumanLatched: false,
2627
+ pausedOnQuestion: false,
2628
+ pausedOnPermission: false,
2629
+ pausedClearConfirmed: false,
2630
+ pausedInFlight: false,
2631
+ deliveryDeadlineAnchored: false
2632
+ });
2633
+ }
2634
+ /**
2635
+ * Start (but do NOT await) the per-session watcher loop if it has in-flight
2636
+ * work and is not already running. Single-flight per session. The loop is
2637
+ * tracked on the watcher and cleared when it settles; it never rejects (fully
2638
+ * guarded), so a failed poll/callback can never crash the run loop — the cron
2639
+ * stays as the safety net.
2640
+ */
2641
+ ensureWatcherRunning(sessionId) {
2642
+ const watcher = this.watchers.get(sessionId);
2643
+ if (!watcher) return;
2644
+ if (watcher.loop) return;
2645
+ if (watcher.inFlight.size === 0) {
2646
+ this.watchers.delete(sessionId);
2647
+ return;
2648
+ }
2649
+ const loop = this.runWatcherLoop(sessionId, watcher).finally(() => {
2650
+ watcher.loop = null;
2651
+ if (watcher.inFlight.size === 0) {
2652
+ this.watchers.delete(sessionId);
2653
+ }
2654
+ });
2655
+ watcher.loop = loop;
2656
+ }
2657
+ /**
2658
+ * The per-session polling loop (WI-3). Once per tick it:
2659
+ * 1. polls `GET /session/:id/message` once and, per in-flight message,
2660
+ * computes `messageRunState` and fires markProcessing (queued→running) /
2661
+ * markDone (done) exactly once per transition;
2662
+ * 2. applies the idle-path re-dispatch guard (a dispatched message that never
2663
+ * APPEARS → re-dispatch — D1 obligation 2);
2664
+ * 3. polls `/question` + `/permission` (scoped to the session) and surfaces
2665
+ * NEW ones via `reportInteraction`, carrying the PAUSED message's own
2666
+ * `source_message_id`;
2667
+ * 4. drops messages that completed or timed out from the in-flight set.
2668
+ * Exits when the in-flight set empties. Never throws.
2669
+ */
2670
+ async runWatcherLoop(sessionId, watcher) {
2671
+ try {
2672
+ while (watcher.inFlight.size > 0) {
2673
+ await this.sleep(this.pausedPollIntervalMs);
2674
+ let messages = null;
2675
+ try {
2676
+ const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
2677
+ if (res.ok) {
2678
+ const body = await res.json();
2679
+ messages = Array.isArray(body) ? body : null;
2680
+ }
2681
+ } catch {
2682
+ }
2683
+ if (messages != null && messages.length > 0) {
2684
+ watcher.lastGoodPollAt = this.now();
2685
+ watcher.hadUsablePoll = true;
2686
+ } else {
2687
+ const emptyButReachable = messages != null;
2688
+ const graceApplies = !emptyButReachable || watcher.hadUsablePoll;
2689
+ if (graceApplies && this.now() - watcher.lastGoodPollAt < POLL_MISS_GRACE_MS) {
2690
+ continue;
2691
+ }
2692
+ }
2693
+ const { openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk } = await this.pollInteractions(sessionId, watcher, messages);
2694
+ for (const inFlight of [...watcher.inFlight.values()]) {
2695
+ await this.serviceInFlightMessage(
2696
+ sessionId,
2697
+ watcher,
2698
+ inFlight,
2699
+ messages,
2700
+ openQuestions,
2701
+ openPermissions,
2702
+ questionsPolledOk,
2703
+ permissionsPolledOk
2704
+ );
2705
+ }
2706
+ }
2707
+ } catch (err) {
2708
+ if (err instanceof ChannelAuthError) {
2709
+ this.log({
2710
+ level: "error",
2711
+ 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}`,
2712
+ conversation_id: watcher.conv.id
2713
+ });
2714
+ for (const evidentMessageId of [...watcher.inFlight.keys()]) {
2715
+ this.readopted.delete(evidentMessageId);
2716
+ this.removeInFlight(watcher, evidentMessageId);
2717
+ }
2718
+ return;
2719
+ }
2720
+ this.log({
2721
+ level: "error",
2722
+ message: `Session watcher failed for session ${sessionId.slice(0, 8)}: ${err instanceof Error ? err.message : String(err)}`,
2723
+ conversation_id: watcher.conv.id
2724
+ });
2725
+ }
2726
+ }
2727
+ /**
2728
+ * On FIRST observing a terminal (done/failed) state, ensure the delivery
2729
+ * (markDone/markFailed) transient-retry path has a real window. A long
2730
+ * ACTIVELY-running turn is kept past its original `deadline`, so by completion
2731
+ * `now >= deadline` already holds and the retry bound below would fire on the
2732
+ * first transient PATCH failure — dropping the message before its reply lands
2733
+ * (Bugbot "Stale deadline aborts long-turn delivery"). Re-anchor once (latched)
2734
+ * to a fresh `pausedMaxWaitMs` window; only extend if the current deadline is at
2735
+ * or past now, so a still-ample window is left untouched.
2736
+ */
2737
+ anchorDeliveryDeadline(inFlight) {
2738
+ if (inFlight.deliveryDeadlineAnchored) return;
2739
+ inFlight.deliveryDeadlineAnchored = true;
2740
+ if (this.now() >= inFlight.deadline) {
2741
+ inFlight.deadline = this.now() + this.pausedMaxWaitMs;
2742
+ }
2743
+ }
2744
+ /**
2745
+ * Drive ONE in-flight message's lifecycle from the tick's message snapshot.
2746
+ * Fires markProcessing on queued→running and markDone on done (each once),
2747
+ * applies the idle-path re-dispatch guard, and removes the message from the
2748
+ * in-flight set on completion or timeout.
2749
+ */
2750
+ async serviceInFlightMessage(sessionId, watcher, inFlight, messages, openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk) {
2751
+ const conv = watcher.conv;
2752
+ const state = messageRunState(messages, inFlight.opencodeMessageId);
2753
+ const id = inFlight.evidentMessageId;
2754
+ if (openQuestions.has(id)) inFlight.pausedOnQuestion = true;
2755
+ else if (questionsPolledOk) inFlight.pausedOnQuestion = false;
2756
+ if (openPermissions.has(id)) inFlight.pausedOnPermission = true;
2757
+ else if (permissionsPolledOk) inFlight.pausedOnPermission = false;
2758
+ const observedOpen = openQuestions.has(id) || openPermissions.has(id);
2759
+ const latchedPaused = inFlight.pausedOnQuestion || inFlight.pausedOnPermission;
2760
+ const awaitingHuman = observedOpen || latchedPaused;
2761
+ if ((state === "running" || state === "done" || state === "failed") && !inFlight.started) {
2762
+ const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
2763
+ let claimed;
2764
+ try {
2765
+ claimed = await this.markProcessing(
2766
+ conv.id,
2767
+ inFlight.evidentMessageId,
2768
+ sessionId,
2769
+ inFlight.opencodeMessageId,
2770
+ title
2771
+ );
2772
+ } catch (err) {
2773
+ if (err instanceof ChannelAuthError) throw err;
2774
+ this.log({
2775
+ level: "warn",
2776
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2777
+ conversation_id: conv.id,
2778
+ message_id: inFlight.evidentMessageId
2779
+ });
2780
+ return;
2781
+ }
2782
+ inFlight.started = true;
2783
+ if (!claimed) {
2784
+ this.log({
2785
+ level: "debug",
2786
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
2787
+ conversation_id: conv.id,
2788
+ message_id: inFlight.evidentMessageId
2789
+ });
2790
+ }
2791
+ }
2792
+ if (state === "done") {
2793
+ this.anchorDeliveryDeadline(inFlight);
2794
+ if (!inFlight.done) {
2795
+ this.log({
2796
+ level: "info",
2797
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
2798
+ conversation_id: conv.id,
2799
+ message_id: inFlight.evidentMessageId
2800
+ });
2801
+ const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
2802
+ try {
2803
+ await this.markDone(
2804
+ conv.id,
2805
+ inFlight.evidentMessageId,
2806
+ sessionId,
2807
+ inFlight.opencodeMessageId,
2808
+ title
2809
+ );
2810
+ } catch (err) {
2811
+ if (err instanceof ChannelAuthError) throw err;
2812
+ if (err instanceof ChannelTerminalError) {
2813
+ this.log({
2814
+ level: "warn",
2815
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
2816
+ conversation_id: conv.id,
2817
+ message_id: inFlight.evidentMessageId
2818
+ });
2819
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
2820
+ return;
2821
+ }
2822
+ if (this.now() >= inFlight.deadline) {
2823
+ this.log({
2824
+ level: "warn",
2825
+ 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)}`,
2826
+ conversation_id: conv.id,
2827
+ message_id: inFlight.evidentMessageId
2828
+ });
2829
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
2830
+ return;
2831
+ }
2832
+ this.log({
2833
+ level: "warn",
2834
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2835
+ conversation_id: conv.id,
2836
+ message_id: inFlight.evidentMessageId
2837
+ });
2838
+ return;
2839
+ }
2840
+ inFlight.done = true;
2841
+ }
2842
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
2843
+ return;
2844
+ }
2845
+ if (state === "failed") {
2846
+ this.anchorDeliveryDeadline(inFlight);
2847
+ if (!inFlight.done) {
2848
+ const error2 = messageError(messages, inFlight.opencodeMessageId) ?? void 0;
2849
+ this.log({
2850
+ level: "error",
2851
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} errored \u2014 marking failed: ${error2 ?? "(no error text)"}`,
2852
+ conversation_id: conv.id,
2853
+ message_id: inFlight.evidentMessageId
2854
+ });
2855
+ try {
2856
+ await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2);
2857
+ } catch (err) {
2858
+ if (err instanceof ChannelAuthError) throw err;
2859
+ if (err instanceof ChannelTerminalError) {
2860
+ this.log({
2861
+ level: "warn",
2862
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} failed (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
2863
+ conversation_id: conv.id,
2864
+ message_id: inFlight.evidentMessageId
2865
+ });
2866
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
2867
+ return;
2868
+ }
2869
+ if (this.now() >= inFlight.deadline) {
2870
+ this.log({
2871
+ level: "warn",
2872
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} failed within the watch window \u2014 leaving for the cron safety net: ${err instanceof Error ? err.message : String(err)}`,
2873
+ conversation_id: conv.id,
2874
+ message_id: inFlight.evidentMessageId
2875
+ });
2876
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
2877
+ return;
2878
+ }
2879
+ this.log({
2880
+ level: "warn",
2881
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} failed (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2882
+ conversation_id: conv.id,
2883
+ message_id: inFlight.evidentMessageId
2884
+ });
2885
+ return;
2886
+ }
2887
+ inFlight.done = true;
2888
+ }
2889
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
2890
+ return;
2891
+ }
2892
+ const pastStuckBound = this.now() - inFlight.dispatchedAt >= this.stuckQueuedMs;
2893
+ const sessionIdle = state === "queued" && !hasRunningAssistantExcept(messages, inFlight.opencodeMessageId);
2894
+ if (state === "queued" && pastStuckBound && sessionIdle && !inFlight.stuckReported) {
2895
+ inFlight.stuckReported = true;
2896
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "stuck_queued", {
2897
+ stuck_for_ms: this.now() - inFlight.dispatchedAt
2898
+ });
2899
+ }
2900
+ const activelyRunning = state === "running" && !awaitingHuman;
2901
+ if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
2902
+ this.log({
2903
+ level: "warn",
2904
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} exceeded the absolute processing ceiling (${Math.round((this.now() - inFlight.processingAnchorMs) / 6e4)}min, session ${sessionId}) while still actively running \u2014 releasing so the cron can reclaim it`,
2905
+ conversation_id: conv.id,
2906
+ message_id: inFlight.evidentMessageId
2907
+ });
2908
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "gave_up", {
2909
+ watched_for_ms: this.now() - inFlight.processingAnchorMs
2910
+ });
2911
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
2912
+ return;
2913
+ }
2914
+ if (activelyRunning && !inFlight.awaitingHumanLatched && !inFlight.aliveInFlight && this.now() - inFlight.lastAliveAt >= HEARTBEAT_MS) {
2915
+ inFlight.aliveInFlight = true;
2916
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "alive").then((ok) => {
2917
+ inFlight.aliveInFlight = false;
2918
+ if (ok) inFlight.lastAliveAt = this.now();
2919
+ });
2920
+ }
2921
+ if (awaitingHuman) {
2922
+ if (!inFlight.awaitingHumanLatched) {
2923
+ inFlight.deadline = this.now() + this.pausedMaxWaitMs;
2924
+ inFlight.awaitingHumanLatched = true;
2925
+ }
2926
+ if (!inFlight.pausedClearConfirmed && !inFlight.pausedInFlight) {
2927
+ inFlight.pausedInFlight = true;
2928
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "paused").then((ok) => {
2929
+ inFlight.pausedInFlight = false;
2930
+ if (ok && inFlight.awaitingHumanLatched) inFlight.pausedClearConfirmed = true;
2931
+ });
2932
+ }
2933
+ } else if (inFlight.awaitingHumanLatched) {
2934
+ inFlight.awaitingHumanLatched = false;
2935
+ inFlight.pausedOnQuestion = false;
2936
+ inFlight.pausedOnPermission = false;
2937
+ inFlight.pausedClearConfirmed = false;
2938
+ }
2939
+ const siblingPaused = (sib) => openQuestions.has(sib.evidentMessageId) || openPermissions.has(sib.evidentMessageId) || sib.awaitingHumanLatched || sib.pausedOnQuestion || sib.pausedOnPermission;
2940
+ const hasActivelyRunningSibling = [...watcher.inFlight.values()].some(
2941
+ (sib) => sib.evidentMessageId !== inFlight.evidentMessageId && messageRunState(messages, sib.opencodeMessageId) === "running" && !siblingPaused(sib)
2942
+ );
2943
+ const queuedBehindRunningSibling = state === "queued" && hasActivelyRunningSibling;
2944
+ if (!activelyRunning && !queuedBehindRunningSibling && this.now() >= inFlight.deadline) {
2945
+ this.log({
2946
+ level: "debug",
2947
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} did not complete within the watch window \u2014 leaving for the cron safety net`,
2948
+ conversation_id: conv.id,
2949
+ message_id: inFlight.evidentMessageId
2950
+ });
2951
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "gave_up", {
2952
+ watched_for_ms: this.now() - inFlight.dispatchedAt
2953
+ });
2954
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
2955
+ }
2956
+ }
2957
+ // -------------------------------------------------------------------------
2958
+ // Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
2959
+ // -------------------------------------------------------------------------
2960
+ /**
2961
+ * Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
2962
+ *
2963
+ * The pending drain only re-drives `pending` rows; a message already flipped to
2964
+ * `processing` before the runner died is watched by nobody until the 15-min
2965
+ * cron resets it. Here we fetch those rows, and per row resolve its correlated
2966
+ * reply against opencode's OWN session store — completing, re-attaching, or
2967
+ * (for an orphan) forcing a genuine fresh run. Runs on EVERY drain tick, so it
2968
+ * is idempotent per message (Invariant 2): a row a watcher already tracks is
2969
+ * skipped in `readoptOne` — one driver, no double-drive.
2970
+ *
2971
+ * Only `ChannelAuthError` propagates (to `drainPending`, like the pending
2972
+ * path); every other early return LOGS a reason with context — no silent drop.
2973
+ */
2974
+ async readoptProcessing() {
2975
+ const rows = await this.getProcessingMessages();
2976
+ if (this.dontRedispatch.size > 0 || this.doneUndeliverable.size > 0 || this.readoptPollUnresolvedSignalled.size > 0) {
2977
+ const stillProcessing = new Set(rows.map((r) => r.id));
2978
+ for (const id of [
2979
+ ...this.dontRedispatch,
2980
+ ...this.doneUndeliverable,
2981
+ ...this.readoptPollUnresolvedSignalled
2982
+ ]) {
2983
+ if (!stillProcessing.has(id)) {
2984
+ const cleared = this.dontRedispatch.delete(id);
2985
+ const clearedUndeliverable = this.doneUndeliverable.delete(id);
2986
+ this.readoptPollUnresolvedSignalled.delete(id);
2987
+ if (cleared || clearedUndeliverable) {
2988
+ this.log({
2989
+ level: "debug",
2990
+ message: `Re-adopt: message ${id.slice(0, 8)} left the processing list (cron reset) \u2014 cleared gave-up marker`,
2991
+ message_id: id
2992
+ });
2993
+ }
2994
+ }
2995
+ }
2996
+ }
2997
+ if (rows.length === 0) return;
2998
+ const bySession = /* @__PURE__ */ new Map();
2999
+ for (const row of rows) {
3000
+ if (!row.opencode_session_id) {
3001
+ this.log({
3002
+ level: "warn",
3003
+ message: `Cannot re-adopt processing message ${row.id.slice(0, 8)} \u2014 no opencode session id; leaving for the cron safety net`,
3004
+ conversation_id: row.conversation_id,
3005
+ message_id: row.id
3006
+ });
3007
+ continue;
3008
+ }
3009
+ const list = bySession.get(row.opencode_session_id) ?? [];
3010
+ list.push(row);
3011
+ bySession.set(row.opencode_session_id, list);
3012
+ }
3013
+ for (const [sessionId, sessionRows] of bySession) {
3014
+ let messages;
3015
+ try {
3016
+ const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
3017
+ if (!res.ok) {
3018
+ this.log({
3019
+ level: "warn",
3020
+ message: `Re-adopt: polling session ${sessionId.slice(0, 8)} returned HTTP ${res.status} \u2014 skipping this session this tick`
3021
+ });
3022
+ continue;
3023
+ }
3024
+ const body = await res.json();
3025
+ if (!Array.isArray(body)) {
3026
+ this.log({
3027
+ level: "warn",
3028
+ message: `Re-adopt: polling session ${sessionId.slice(0, 8)} returned a non-array message body \u2014 skipping this session this tick`
3029
+ });
3030
+ continue;
3031
+ }
3032
+ messages = body;
3033
+ } catch (err) {
3034
+ this.log({
3035
+ level: "warn",
3036
+ message: `Re-adopt: failed to poll session ${sessionId.slice(0, 8)} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`
3037
+ });
3038
+ continue;
3039
+ }
3040
+ const anyUntracked = sessionRows.some((row) => !this.isTracked(sessionId, row.id));
3041
+ const sessionOngoing = anyUntracked ? await isSessionOngoing(this.port, sessionId) : null;
3042
+ for (const row of sessionRows) {
3043
+ await this.readoptOne(sessionId, row, messages, sessionOngoing);
3044
+ }
3045
+ }
3046
+ }
3047
+ /**
3048
+ * Re-adopt ONE `processing` row against the tick's session message snapshot
3049
+ * (ADR-0046 Decision §1/§2). Idempotent: skips a row already being driven.
3050
+ *
3051
+ * Branches on `messageRunState(messages, row.opencode_message_id)` — the
3052
+ * opencode-assigned user-message id persisted on the first `processing` PATCH
3053
+ * (#218). A row with a NULL stored id (dispatched but the read-back never landed
3054
+ * before the restart) has no id to correlate → treated as an orphan and
3055
+ * re-dispatched (at most once, see `forceReadoptRun`):
3056
+ * - `done` → `markDone` now (guarded like the watcher's done branch);
3057
+ * - `failed` → `markFailed` with the surfaced error (issue #182), so an
3058
+ * errored turn is reported failed on restart, NOT re-dispatched;
3059
+ * - `running`/`queued` → re-attach a watcher via `registerReadopted` (no re-dispatch),
3060
+ * tracking the stored id so the reply correlates by it;
3061
+ * - `unknown`/null id → re-dispatch (opencode assigns a fresh id) + attach a watcher.
3062
+ *
3063
+ * Only `ChannelAuthError` propagates.
3064
+ */
3065
+ async readoptOne(sessionId, row, messages, sessionOngoing) {
3066
+ if (this.isTracked(sessionId, row.id)) {
3067
+ this.log({
3068
+ level: "debug",
3069
+ message: `Re-adopt: message ${row.id.slice(0, 8)} already tracked in-flight \u2014 skipping (owned by the watcher loop)`,
3070
+ conversation_id: row.conversation_id,
3071
+ message_id: row.id
3072
+ });
3073
+ return;
3074
+ }
3075
+ const ocId = row.opencode_message_id;
3076
+ const state = messageRunState(messages, ocId ?? "");
3077
+ if (state === "done") {
3078
+ if (this.doneUndeliverable.has(row.id)) {
3079
+ this.log({
3080
+ level: "debug",
3081
+ message: `Re-adopt: message ${row.id.slice(0, 8)} markDone is terminally undeliverable \u2014 left to the cron; skipping until it leaves processing`,
3082
+ conversation_id: row.conversation_id,
3083
+ message_id: row.id
3084
+ });
3085
+ return;
1680
3086
  }
3087
+ this.log({
3088
+ level: "info",
3089
+ message: `Re-adopt: message ${row.id.slice(0, 8)} completed while unwatched \u2014 marking done`,
3090
+ conversation_id: row.conversation_id,
3091
+ message_id: row.id
3092
+ });
3093
+ try {
3094
+ const title = await this.resolveSessionTitle(sessionId, row.conversation_id);
3095
+ await this.markDone(row.conversation_id, row.id, sessionId, ocId, title);
3096
+ } catch (err) {
3097
+ if (err instanceof ChannelAuthError) throw err;
3098
+ if (err instanceof ChannelTerminalError) {
3099
+ this.doneUndeliverable.add(row.id);
3100
+ this.log({
3101
+ level: "warn",
3102
+ message: `Re-adopt: failed to mark message ${row.id.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 parking until it leaves processing; leaving for the cron safety net: ${err.message}`,
3103
+ conversation_id: row.conversation_id,
3104
+ message_id: row.id
3105
+ });
3106
+ void this.postSignal(row.conversation_id, row.id, "readopt_undeliverable");
3107
+ return;
3108
+ }
3109
+ this.log({
3110
+ level: "warn",
3111
+ message: `Re-adopt: failed to mark message ${row.id.slice(0, 8)} done (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
3112
+ conversation_id: row.conversation_id,
3113
+ message_id: row.id
3114
+ });
3115
+ return;
3116
+ }
3117
+ this.dontRedispatch.delete(row.id);
3118
+ void this.postSignal(row.conversation_id, row.id, "readopt_done");
3119
+ return;
3120
+ }
3121
+ if (state === "failed") {
3122
+ const error2 = messageError(messages, ocId ?? "") ?? void 0;
3123
+ this.log({
3124
+ level: "error",
3125
+ message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
3126
+ conversation_id: row.conversation_id,
3127
+ message_id: row.id
3128
+ });
3129
+ try {
3130
+ await this.markFailed(row.conversation_id, row.id, sessionId, error2);
3131
+ } catch (err) {
3132
+ if (err instanceof ChannelAuthError) throw err;
3133
+ if (err instanceof ChannelTerminalError) {
3134
+ this.doneUndeliverable.add(row.id);
3135
+ this.log({
3136
+ level: "warn",
3137
+ message: `Re-adopt: failed to mark message ${row.id.slice(0, 8)} failed (terminal HTTP ${err.status}) \u2014 parking until it leaves processing; leaving for the cron safety net: ${err.message}`,
3138
+ conversation_id: row.conversation_id,
3139
+ message_id: row.id
3140
+ });
3141
+ void this.postSignal(row.conversation_id, row.id, "readopt_undeliverable");
3142
+ return;
3143
+ }
3144
+ this.log({
3145
+ level: "warn",
3146
+ message: `Re-adopt: failed to mark message ${row.id.slice(0, 8)} failed (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
3147
+ conversation_id: row.conversation_id,
3148
+ message_id: row.id
3149
+ });
3150
+ return;
3151
+ }
3152
+ this.dontRedispatch.delete(row.id);
3153
+ void this.postSignal(row.conversation_id, row.id, "readopt_failed");
3154
+ return;
3155
+ }
3156
+ if (this.dontRedispatch.has(row.id)) {
3157
+ this.log({
3158
+ level: "debug",
3159
+ message: `Re-adopt: message ${row.id.slice(0, 8)} already gave up \u2014 left to the cron; skipping until it leaves processing`,
3160
+ conversation_id: row.conversation_id,
3161
+ message_id: row.id
3162
+ });
3163
+ return;
3164
+ }
3165
+ let statusReadableOngoing = null;
3166
+ if (state === "running" && ocId) {
3167
+ const reply = findLastAssistantReplyFor(messages, ocId);
3168
+ const shape = this.replyCompletionShape(reply);
3169
+ const ongoing = sessionOngoing;
3170
+ statusReadableOngoing = ongoing;
3171
+ if (ongoing === false) {
3172
+ this.log({
3173
+ level: "info",
3174
+ message: `Re-adopt: message ${row.id.slice(0, 8)} running/${shape} but session ${sessionId.slice(0, 8)} is not-ongoing per GET /session/status (absent/idle) \u2014 re-dispatching from scratch (status-gated recovery)`,
3175
+ conversation_id: row.conversation_id,
3176
+ message_id: row.id
3177
+ });
3178
+ await this.forceReadoptRun(sessionId, row);
3179
+ return;
3180
+ }
3181
+ if (ongoing === true) {
3182
+ this.log({
3183
+ level: "debug",
3184
+ message: `Re-adopt: message ${row.id.slice(0, 8)} running/${shape} and session ${sessionId.slice(0, 8)} is ongoing per GET /session/status (busy/retry) \u2014 re-attaching watcher (no re-dispatch)`,
3185
+ conversation_id: row.conversation_id,
3186
+ message_id: row.id
3187
+ });
3188
+ } else {
3189
+ if (shape === "b1") {
3190
+ this.log({
3191
+ level: "debug",
3192
+ message: `Re-adopt: message ${row.id.slice(0, 8)} running/b1 but GET /session/status was unreadable (null) for session ${sessionId.slice(0, 8)} \u2014 NOT latching a b1 row on a transient status blip; leaving it un-tracked to re-evaluate on the next drain`,
3193
+ conversation_id: row.conversation_id,
3194
+ message_id: row.id
3195
+ });
3196
+ if (!this.readoptPollUnresolvedSignalled.has(row.id)) {
3197
+ this.readoptPollUnresolvedSignalled.add(row.id);
3198
+ void this.postSignal(row.conversation_id, row.id, "readopt_poll_unresolved");
3199
+ }
3200
+ return;
3201
+ }
3202
+ this.log({
3203
+ level: "debug",
3204
+ message: `Re-adopt: message ${row.id.slice(0, 8)} running/${shape} but GET /session/status was unreadable (null) for session ${sessionId.slice(0, 8)} \u2014 falling back to the #253 preamble + descendant cross-check`,
3205
+ conversation_id: row.conversation_id,
3206
+ message_id: row.id
3207
+ });
3208
+ }
3209
+ }
3210
+ if (statusReadableOngoing === null && state === "running" && ocId && isPreamblePinnedRunning(messages, ocId)) {
3211
+ const descendantAlive = await this.isAnyDescendantSessionAlive(sessionId);
3212
+ if (descendantAlive === true) {
3213
+ this.log({
3214
+ level: "debug",
3215
+ message: `Re-adopt: message ${row.id.slice(0, 8)} preamble-pinned running (root ${sessionId.slice(0, 8)}) but a live descendant sub-agent session was found \u2014 treating as still running, re-attaching watcher (no re-dispatch)`,
3216
+ conversation_id: row.conversation_id,
3217
+ message_id: row.id
3218
+ });
3219
+ } else {
3220
+ this.log({
3221
+ level: "info",
3222
+ message: `Re-adopt: message ${row.id.slice(0, 8)} preamble-pinned on recovery (root ${sessionId.slice(0, 8)}), no live descendant runner \u2014 re-dispatching from scratch${descendantAlive === null ? " (descendant liveness indeterminate; a restart guarantees no live runner, so this does NOT block the re-dispatch)" : ""}`,
3223
+ conversation_id: row.conversation_id,
3224
+ message_id: row.id
3225
+ });
3226
+ await this.forceReadoptRun(sessionId, row);
3227
+ return;
3228
+ }
3229
+ }
3230
+ if ((state === "running" || state === "queued") && ocId) {
3231
+ const conv = this.convForRow(sessionId, row);
3232
+ const message = this.queuedMessageForRow(row);
3233
+ this.registerReadopted(conv, sessionId, message, ocId, this.processedAtMs(row));
3234
+ this.dispatched.add(row.id);
3235
+ this.readopted.add(row.id);
3236
+ this.ensureWatcherRunning(sessionId);
3237
+ this.log({
3238
+ level: "debug",
3239
+ message: `Re-adopt: message ${row.id.slice(0, 8)} ${state} \u2014 re-attached watcher (stored id, no re-dispatch)`,
3240
+ conversation_id: row.conversation_id,
3241
+ message_id: row.id
3242
+ });
3243
+ void this.postSignal(row.conversation_id, row.id, "readopt_reattached");
3244
+ return;
3245
+ }
3246
+ await this.forceReadoptRun(sessionId, row);
3247
+ }
3248
+ /**
3249
+ * Re-dispatch an orphaned (`unknown`/null-id) `processing` row (ADR-0046 §2).
3250
+ *
3251
+ * #218/WI-5: the row's user message is absent (never kept, or a null stored id),
3252
+ * so we re-`prompt_async` WITHOUT a caller id (opencode assigns a monotonic one),
3253
+ * read it back, and register the watcher under the assigned id so the reply
3254
+ * correlates server-side.
3255
+ *
3256
+ * ⚠️ AT-MOST-ONCE (High-2): dispatch is no longer idempotent (no caller-supplied
3257
+ * id). Without a guard, if this dispatches on tick N but the read-back+persist
3258
+ * hasn't landed before tick N+1 re-reads the still-null `opencode_message_id`,
3259
+ * tick N+1 would dispatch AGAIN → duplicate user turns. The `awaitingReadopt`
3260
+ * latch makes a null-id row re-dispatched AT MOST ONCE per outstanding read-back:
3261
+ * short-circuit while the row is latched; clear it on a successful dispatch (the
3262
+ * row is then tracked in `dispatched`, so `readoptOne`'s early skip prevents
3263
+ * re-entry) OR on a failed/unresolved dispatch (genuinely un-sent → the next tick
3264
+ * may retry exactly once more).
3265
+ *
3266
+ * `evidentMessageId = row.id` addresses the SERVER row. Deadline anchored to
3267
+ * `processed_at` (Invariant 1).
3268
+ */
3269
+ async forceReadoptRun(sessionId, row) {
3270
+ if (this.stopped) {
3271
+ this.log({
3272
+ level: "debug",
3273
+ message: `Re-adopt: message ${row.id.slice(0, 8)} orphaned but the runner is stopping \u2014 not starting a fresh turn; leaving for restart recovery`,
3274
+ conversation_id: row.conversation_id,
3275
+ message_id: row.id
3276
+ });
3277
+ return;
3278
+ }
3279
+ if (this.awaitingReadopt.has(row.id)) {
3280
+ this.log({
3281
+ level: "debug",
3282
+ message: `Re-adopt: message ${row.id.slice(0, 8)} already has a re-dispatch awaiting read-back \u2014 skipping (at most once)`,
3283
+ conversation_id: row.conversation_id,
3284
+ message_id: row.id
3285
+ });
3286
+ return;
3287
+ }
3288
+ if (this.processedAtMs(row) + this.pausedMaxWaitMs <= this.now()) {
3289
+ this.dontRedispatch.add(row.id);
3290
+ this.log({
3291
+ level: "debug",
3292
+ message: `Re-adopt: message ${row.id.slice(0, 8)} orphaned but its re-adopt window has already elapsed \u2014 not dispatching an unwatchable turn; parking until it leaves processing (cron will reset it)`,
3293
+ conversation_id: row.conversation_id,
3294
+ message_id: row.id
3295
+ });
3296
+ void this.postSignal(row.conversation_id, row.id, "readopt_window_elapsed");
3297
+ return;
3298
+ }
3299
+ const options = {
3300
+ agent: row.opencode_agent ?? void 0,
3301
+ model: row.opencode_model ?? void 0
3302
+ };
3303
+ this.log({
3304
+ level: "info",
3305
+ message: `Re-adopt: message ${row.id.slice(0, 8)} orphaned (user message absent) \u2014 re-dispatching (opencode assigns a fresh id)`,
3306
+ conversation_id: row.conversation_id,
3307
+ message_id: row.id
3308
+ });
3309
+ this.awaitingReadopt.add(row.id);
3310
+ const readoptConv = this.convForRow(sessionId, row);
3311
+ const readoptMessage = this.queuedMessageForRow(row);
3312
+ const sendAttachments = this.buildSendAttachments(readoptConv, readoptMessage);
3313
+ let ocId;
3314
+ try {
3315
+ ocId = await this.dispatchLocked(
3316
+ sessionId,
3317
+ () => sendPromptAsync(this.port, sessionId, row.content, options, sendAttachments)
3318
+ );
3319
+ } catch (err) {
3320
+ this.awaitingReadopt.delete(row.id);
3321
+ if (err instanceof ChannelAuthError) throw err;
3322
+ this.log({
3323
+ level: "warn",
3324
+ message: `Re-adopt: re-dispatch failed for message ${row.id.slice(0, 8)} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
3325
+ conversation_id: row.conversation_id,
3326
+ message_id: row.id
3327
+ });
3328
+ void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
3329
+ return;
1681
3330
  }
1682
- return processed;
1683
- }
1684
- async ensureSession(conv) {
1685
- const cached = this.sessions.get(conv.id);
1686
- if (cached) return cached;
1687
- if (conv.opencode_session_id) {
1688
- this.sessions.set(conv.id, conv.opencode_session_id);
1689
- return conv.opencode_session_id;
3331
+ if (ocId === null) {
3332
+ this.awaitingReadopt.delete(row.id);
3333
+ this.log({
3334
+ level: "warn",
3335
+ message: `Re-adopt: message ${row.id.slice(0, 8)} re-dispatched but its opencode id could not be read back \u2014 leaving un-tracked to retry next drain`,
3336
+ conversation_id: row.conversation_id,
3337
+ message_id: row.id
3338
+ });
3339
+ void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
3340
+ return;
1690
3341
  }
1691
- const directory = await this.resolveOpenCodeDirectory();
1692
- const sessionId = await createOpenCodeSession(this.port, directory);
1693
- this.sessions.set(conv.id, sessionId);
1694
- await this.persistSession(conv.id, sessionId).catch(() => {
3342
+ this.registerReadopted(readoptConv, sessionId, readoptMessage, ocId, this.processedAtMs(row));
3343
+ this.dispatched.add(row.id);
3344
+ this.readopted.add(row.id);
3345
+ this.awaitingReadopt.delete(row.id);
3346
+ this.ensureWatcherRunning(sessionId);
3347
+ void this.postSignal(row.conversation_id, row.id, "readopt_redispatched");
3348
+ }
3349
+ /**
3350
+ * True if `evidentMessageId` is already being driven — either in the
3351
+ * authoritative `dispatched` set or a live watcher's in-flight set for this
3352
+ * session (Invariant 2, WI-5). Either signal means a watcher owns the row.
3353
+ */
3354
+ isTracked(sessionId, evidentMessageId) {
3355
+ if (this.dispatched.has(evidentMessageId)) return true;
3356
+ const watcher = this.watchers.get(sessionId);
3357
+ return watcher?.inFlight.has(evidentMessageId) ?? false;
3358
+ }
3359
+ /**
3360
+ * Parse a re-adopt row's `processed_at` (ISO string) to epoch ms for the
3361
+ * deadline anchor (Invariant 1). The endpoint guarantees `processed_at` is set
3362
+ * for `processing` rows, but if it is somehow null/unparseable fall back to
3363
+ * `now` (defensive) AND log — a fallback means the anchor is weaker than
3364
+ * intended, which is worth surfacing.
3365
+ */
3366
+ processedAtMs(row) {
3367
+ const parsed = row.processed_at ? Date.parse(row.processed_at) : NaN;
3368
+ if (!Number.isNaN(parsed)) return parsed;
3369
+ this.log({
3370
+ level: "error",
3371
+ message: `Re-adopt: message ${row.id.slice(0, 8)} has null/unparseable processed_at (${String(row.processed_at)}) \u2014 anchoring deadline to now (defensive)`,
3372
+ conversation_id: row.conversation_id,
3373
+ message_id: row.id
1695
3374
  });
1696
- return sessionId;
3375
+ return this.now();
3376
+ }
3377
+ /** Build the `PendingConversation` shape the watcher needs from a re-adopt row. */
3378
+ convForRow(sessionId, row) {
3379
+ return {
3380
+ id: row.conversation_id,
3381
+ agent_id: this.agentId,
3382
+ opencode_session_id: sessionId,
3383
+ pending_message_count: 0,
3384
+ oldest_pending_at: row.processed_at
3385
+ };
3386
+ }
3387
+ /** Build the `QueuedMessage` shape the watcher/re-dispatch needs from a re-adopt row. */
3388
+ queuedMessageForRow(row) {
3389
+ return {
3390
+ id: row.id,
3391
+ content: row.content,
3392
+ status: "processing",
3393
+ opencode_agent: row.opencode_agent,
3394
+ opencode_model: row.opencode_model,
3395
+ source_message_id: row.source_message_id,
3396
+ slack_user_id: row.slack_user_id,
3397
+ attachments: row.attachments ?? null
3398
+ };
1697
3399
  }
1698
3400
  /**
1699
- * Lazily resolve (and cache) opencode's root directory via `GET /path`.
1700
- * Resolved once per driver: `undefined` until first lookup, then the directory
1701
- * string or `null` if unavailable (we don't keep retrying a missing `/path`).
3401
+ * Remove a message from the in-flight set AND the authoritative dispatched
3402
+ * set. Once the in-flight set empties, the watcher loop's `while` guard exits
3403
+ * and its `.finally` removes the session entry from `this.watchers`.
3404
+ *
3405
+ * Bug 2: if a RE-ADOPTED message is removed WITHOUT having completed
3406
+ * (`!inFlight.done` — i.e. a give-up: deadline reached, or markDone left to the
3407
+ * cron), park it in `dontRedispatch` so the next drain does NOT re-adopt (and
3408
+ * re-dispatch) the still-`processing` row every ~2s until the 15-min cron. A
3409
+ * re-adopted message that completed (`done`) needs no marker — it's leaving
3410
+ * `processing`. This suppresses only re-dispatch: if its reply later completes,
3411
+ * the done branch still delivers it (Bugbot #202).
1702
3412
  */
1703
- async resolveOpenCodeDirectory() {
1704
- if (this.opencodeDirectory !== void 0) return this.opencodeDirectory;
1705
- this.opencodeDirectory = await getOpenCodeDirectory(this.port);
1706
- if (!this.opencodeDirectory) {
3413
+ removeInFlight(watcher, evidentMessageId) {
3414
+ const inFlight = watcher.inFlight.get(evidentMessageId);
3415
+ if (this.readopted.delete(evidentMessageId) && inFlight && !inFlight.done) {
3416
+ this.dontRedispatch.add(evidentMessageId);
1707
3417
  this.log({
1708
- level: "info",
1709
- message: "Could not determine opencode directory (GET /path) \u2014 new sessions may not appear in opencode web"
3418
+ level: "debug",
3419
+ message: `Re-adopt: message ${evidentMessageId.slice(0, 8)} gave up \u2014 parking until it leaves the processing list (cron reset)`,
3420
+ conversation_id: watcher.conv.id,
3421
+ message_id: evidentMessageId
1710
3422
  });
1711
3423
  }
1712
- return this.opencodeDirectory;
3424
+ watcher.inFlight.delete(evidentMessageId);
3425
+ this.dispatched.delete(evidentMessageId);
1713
3426
  }
1714
3427
  /**
1715
- * Local reconcile: re-query `GET /session/:id/message` and check whether the
1716
- * last assistant message is message-level complete (`isTurnComplete`).
3428
+ * Poll `/question` + `/permission` (scoped to the session) and surface NEW ones
3429
+ * via `reportInteraction` (Task 3.5), carrying the PAUSED message's own
3430
+ * `source_message_id` so the server @mentions the correct person under
3431
+ * concurrency. Dedups by interaction id across ticks (reused per-session sets).
3432
+ *
3433
+ * The interaction is attributed to the in-flight message it paused on. opencode
3434
+ * stamps a `messageID` on a permission (and `tool.messageID` on a question) =
3435
+ * the assistant message id, whose `parentID` is the user message id — but the
3436
+ * simplest robust attribution here is: the single in-flight message that is
3437
+ * RUNNING (not done) is the one that paused. With one running message that is
3438
+ * unambiguous; with several we prefer an explicit messageID match, else the
3439
+ * oldest running message.
1717
3440
  *
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.
3441
+ * Returns the set of in-flight Evident message ids that are paused awaiting a
3442
+ * human an outstanding (still-open) question/permission is attributed to them.
3443
+ * `serviceInFlightMessage` uses this to keep an actively-running turn watched
3444
+ * forever (ADR-0047) while still bounding a turn merely blocked on a person who
3445
+ * may never answer. Attribution here covers ALL open interactions, not just
3446
+ * NEW (un-deduped) ones a question stays "awaiting a human" until answered,
3447
+ * even after it was already surfaced to the channel.
1725
3448
  */
1726
- async confirmCompletion(sessionId) {
3449
+ async pollInteractions(sessionId, watcher, messages) {
3450
+ const openQuestions = /* @__PURE__ */ new Set();
3451
+ const openPermissions = /* @__PURE__ */ new Set();
3452
+ let questionsPolledOk = true;
3453
+ let permissionsPolledOk = true;
3454
+ let questions = [];
1727
3455
  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
- });
3456
+ const res = await this.fetchImpl(`${this.opencodeBase}/question`);
3457
+ if (res.ok) {
3458
+ const body = await res.json();
3459
+ if (Array.isArray(body)) {
3460
+ questions = body;
3461
+ } else {
3462
+ questionsPolledOk = false;
3463
+ }
3464
+ } else {
3465
+ questionsPolledOk = false;
3466
+ }
3467
+ } catch {
3468
+ questionsPolledOk = false;
3469
+ }
3470
+ for (const q of questions) {
3471
+ if (!await this.sessionBelongsTo(q.sessionID, sessionId)) continue;
3472
+ const paused = this.attributeInteraction(watcher, q.tool?.messageID, messages);
3473
+ if (paused) openQuestions.add(paused.evidentMessageId);
3474
+ if (watcher.reportedQuestions.has(q.id)) continue;
3475
+ const reported = await this.reportInteraction(
3476
+ watcher.conv.id,
3477
+ "question",
3478
+ q,
3479
+ paused?.message.source_message_id ?? void 0
3480
+ );
3481
+ if (reported) watcher.reportedQuestions.add(q.id);
3482
+ }
3483
+ let permissions = [];
3484
+ try {
3485
+ const res = await this.fetchImpl(`${this.opencodeBase}/permission`);
3486
+ if (res.ok) {
3487
+ const body = await res.json();
3488
+ if (Array.isArray(body)) {
3489
+ permissions = body;
3490
+ } else {
3491
+ permissionsPolledOk = false;
3492
+ }
3493
+ } else {
3494
+ permissionsPolledOk = false;
1737
3495
  }
1738
3496
  } catch {
3497
+ permissionsPolledOk = false;
3498
+ }
3499
+ for (const p of permissions) {
3500
+ if (!await this.sessionBelongsTo(p.sessionID, sessionId)) continue;
3501
+ const paused = this.attributeInteraction(watcher, p.messageID, messages);
3502
+ if (paused) openPermissions.add(paused.evidentMessageId);
3503
+ if (watcher.reportedPermissions.has(p.id)) continue;
3504
+ const reported = await this.reportInteraction(
3505
+ watcher.conv.id,
3506
+ "permission",
3507
+ p,
3508
+ paused?.message.source_message_id ?? void 0
3509
+ );
3510
+ if (reported) watcher.reportedPermissions.add(p.id);
1739
3511
  }
3512
+ return { openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk };
1740
3513
  }
1741
- // -------------------------------------------------------------------------
1742
- // Paused-session watcher (WI-2-CLI)
1743
- // -------------------------------------------------------------------------
1744
3514
  /**
1745
- * Start (but do NOT await) a watcher that resumes a paused turn to completion.
3515
+ * True when `sessionId` is the `rootSessionId` itself OR a descendant of it
3516
+ * i.e. its `parentID` chain (resolved via `GET /session/:id`) reaches the
3517
+ * watched root. Sub-agents spawned via the `task` tool run in child sessions,
3518
+ * so their questions/permissions live under a different `sessionID` that must
3519
+ * still be attributed to the root conversation the watcher owns.
1746
3520
  *
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.
3521
+ * Parents are cached in `sessionParents` so we walk each session at most once;
3522
+ * a bounded depth cap guards against a cycle or a pathological chain, and any
3523
+ * fetch failure is treated as "not a descendant" (best-effort the interaction
3524
+ * simply isn't surfaced this tick and is retried next tick once resolvable).
1751
3525
  */
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);
1756
- });
1757
- this.watchers.set(message.id, watcher);
3526
+ async sessionBelongsTo(sessionId, rootSessionId) {
3527
+ let current = sessionId;
3528
+ for (let depth = 0; current && depth < 32; depth++) {
3529
+ if (current === rootSessionId) return true;
3530
+ const parent = await this.resolveSessionParent(current);
3531
+ if (parent === null || parent === void 0) return false;
3532
+ current = parent;
3533
+ }
3534
+ return false;
1758
3535
  }
1759
3536
  /**
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.
3537
+ * Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
3538
+ * `null` for a root session (no parent) and `undefined` when opencode is
3539
+ * unreachable / the session can't be read (so the caller stops walking without
3540
+ * caching a wrong answer the next tick retries).
1778
3541
  */
1779
- async watchPausedSession(conv, message, sessionId) {
1780
- const deadline = Date.now() + this.pausedMaxWaitMs;
3542
+ async resolveSessionParent(sessionId) {
3543
+ const cached = this.sessionParents.get(sessionId);
3544
+ if (cached !== void 0) return cached;
3545
+ let parent = void 0;
1781
3546
  try {
1782
- while (Date.now() < deadline) {
1783
- await this.sleep(this.pausedPollIntervalMs);
1784
- let completed = false;
1785
- try {
1786
- const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
1787
- if (res.ok) {
1788
- const body = await res.json();
1789
- const messages = Array.isArray(body) ? body : null;
1790
- completed = isTurnComplete(messages);
1791
- }
1792
- } catch {
1793
- continue;
3547
+ const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}`);
3548
+ if (res.ok) {
3549
+ const body = await res.json();
3550
+ parent = body && typeof body.parentID === "string" ? body.parentID : null;
3551
+ }
3552
+ } catch {
3553
+ parent = void 0;
3554
+ }
3555
+ if (parent !== void 0) this.sessionParents.set(sessionId, parent);
3556
+ return parent;
3557
+ }
3558
+ /**
3559
+ * Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
3560
+ * status PATCH can carry it into the "Live sessions" list. Driver-level cache so
3561
+ * BOTH the watcher completion path and the restart-recovery re-adopt path (which
3562
+ * has no watcher) can use it. `conversationId` is passed only for log context.
3563
+ * Best-effort:
3564
+ * - a resolved NON-EMPTY title is cached and terminal (a real session name
3565
+ * won't later un-name), so we do NOT re-GET `/session/:id` every tick;
3566
+ * - while the title is still absent/empty we do NOT latch it — OpenCode names
3567
+ * sessions asynchronously mid-turn, so an early call (e.g. at `processing`)
3568
+ * must leave the cache unresolved and re-fetch on the next need so a later
3569
+ * call (e.g. at `done`) picks up the name assigned in the meantime. Such a
3570
+ * call returns `null` (omit the title on THIS PATCH) without caching;
3571
+ * - a failed request likewise leaves the cache unresolved (retry next need)
3572
+ * and returns `null` — it must NEVER throw or block completion.
3573
+ * A failure is logged with agent/session context (no silent catch).
3574
+ */
3575
+ async resolveSessionTitle(sessionId, conversationId) {
3576
+ const cached = this.sessionTitles.get(sessionId);
3577
+ if (cached != null) return cached;
3578
+ try {
3579
+ const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}`);
3580
+ if (res.ok) {
3581
+ const body = await res.json();
3582
+ const title = body && typeof body.title === "string" ? body.title.trim() : "";
3583
+ if (title.length > 0) {
3584
+ this.sessionTitles.set(sessionId, title);
3585
+ return title;
1794
3586
  }
1795
- if (!completed) continue;
1796
- this.log({
1797
- level: "info",
1798
- message: `Paused session ${sessionId.slice(0, 8)} completed \u2014 marking message ${message.id.slice(0, 8)} done`,
1799
- conversation_id: conv.id,
1800
- message_id: message.id
1801
- });
1802
- await this.markDone(conv.id, message.id, sessionId);
1803
- return;
3587
+ return null;
1804
3588
  }
1805
3589
  this.log({
1806
- 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`,
1808
- conversation_id: conv.id,
1809
- message_id: message.id
3590
+ level: "debug",
3591
+ message: `Session title fetch for session ${sessionId.slice(0, 8)} (agent ${this.agentId.slice(0, 8)}) returned HTTP ${res.status} \u2014 omitting title`,
3592
+ conversation_id: conversationId
1810
3593
  });
1811
3594
  } catch (err) {
1812
3595
  this.log({
1813
- 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
3596
+ level: "debug",
3597
+ message: `Best-effort session title fetch failed for session ${sessionId.slice(0, 8)} (agent ${this.agentId.slice(0, 8)}) \u2014 omitting title: ${err instanceof Error ? err.message : String(err)}`,
3598
+ conversation_id: conversationId
3599
+ });
3600
+ }
3601
+ return null;
3602
+ }
3603
+ /**
3604
+ * DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
3605
+ * (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
3606
+ *
3607
+ * The PRIMARY recovery trigger is "preamble-pinned on recovery ⇒ idle" — a
3608
+ * runner restart wipes OpenCode's in-memory `SessionStatus`/`Runner`, so a
3609
+ * completed `finish: "tool-calls"` root reply encountered during re-adoption is
3610
+ * idle by OpenCode's own definition and is re-dispatched. This method exists only
3611
+ * so the WI-3 caller can VETO that re-dispatch in the rare case a descendant is
3612
+ * provably in flight at the exact moment of recovery.
3613
+ *
3614
+ * "Alive" criterion (TIGHTENED): a descendant is alive only when it is PROVABLY,
3615
+ * ACTIVELY generating — its LAST message is an assistant still mid-generation
3616
+ * (`completed == null`, via `isSessionActivelyGenerating`). An
3617
+ * INCOMPLETE-BUT-NOT-GENERATING child — last message a user message, or a
3618
+ * completed `finish: "tool-calls"` step — is NOT alive after a restart (nothing
3619
+ * is generating once the runner is gone), so it does NOT veto. (This is
3620
+ * deliberately NOT `!isTurnComplete`, which also matches those dead-but-non-terminal
3621
+ * shapes and would falsely veto — re-hanging the very turn this path recovers.)
3622
+ *
3623
+ * Return contract (encoded so WI-3 need not re-derive it):
3624
+ * - `true` → a descendant is provably, actively generating (veto re-dispatch).
3625
+ * - `false` → descendants exist but none is actively generating (the restart
3626
+ * case), OR no descendant is found at all.
3627
+ * - `null` → liveness is INDETERMINATE (enumeration via `listSessions` failed).
3628
+ *
3629
+ * ⚠️ `null` (UNKNOWN) MUST NOT be treated as "alive": WI-3 treats `null` the same
3630
+ * as `false` and does NOT veto — a restart guarantees no live runner, so an
3631
+ * indeterminate cross-check almost always means "couldn't reach a child that no
3632
+ * longer exists". The inversion lives in the caller; this method just reports
3633
+ * true/false/null faithfully.
3634
+ *
3635
+ * VERIFY-BEFORE-DEPEND: we depend ONLY on (a) `parentID` from `GET /session/:id`
3636
+ * (already proven by the existing child-session interaction tests, via
3637
+ * `resolveSessionParent`/`sessionBelongsTo`) and (b) the child's own message-list
3638
+ * terminal state. We do NOT depend on any session-level `busy`/`idle` field —
3639
+ * there is none on `GET /session/:id`; OpenCode's busy state is in-memory
3640
+ * `SessionStatus` only.
3641
+ */
3642
+ async isAnyDescendantSessionAlive(rootSessionId) {
3643
+ const sessions = await listSessions(this.port);
3644
+ if (!sessions) {
3645
+ this.log({
3646
+ level: "warn",
3647
+ message: `Re-adopt: could not enumerate sessions to cross-check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating child liveness as indeterminate`
3648
+ });
3649
+ return null;
3650
+ }
3651
+ for (const candidate of sessions) {
3652
+ if (!candidate?.id || candidate.id === rootSessionId) continue;
3653
+ if (!await this.sessionBelongsTo(candidate.id, rootSessionId)) continue;
3654
+ const childMsgs = await getSessionMessages(this.port, candidate.id);
3655
+ if (isSessionActivelyGenerating(childMsgs)) {
3656
+ return true;
3657
+ }
3658
+ }
3659
+ return false;
3660
+ }
3661
+ /**
3662
+ * Cheap decision-telemetry label for a running row's LAST correlated reply
3663
+ * (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
3664
+ * - `b1` — the reply itself is still in flight (`time.completed == null`) —
3665
+ * the aborted-in-flight production bug after a restart.
3666
+ * - `b2` — a COMPLETED reply pinned running only by `finish === "tool-calls"`
3667
+ * (the sub-agent preamble — #253's shape).
3668
+ * - `other` — any other shape (defensive; a running row is normally b1 or b2).
3669
+ * Reads `info.time.completed` / `info.finish` (tolerating the legacy top-level
3670
+ * shape) directly rather than re-importing the module-private `completedOf`/
3671
+ * `finishOf` — this is a display label only, not a correctness predicate.
3672
+ */
3673
+ replyCompletionShape(reply) {
3674
+ if (!reply) return "other";
3675
+ const completed = reply.info?.time?.completed ?? reply.time?.completed;
3676
+ if (completed == null) return "b1";
3677
+ const finish = reply.info?.finish ?? reply.finish;
3678
+ return finish === "tool-calls" ? "b2" : "other";
3679
+ }
3680
+ /**
3681
+ * Attribute a surfaced interaction to the in-flight message it paused on (M-1).
3682
+ *
3683
+ * The interaction carries `interactionMessageId` — the ASSISTANT message id
3684
+ * that raised it (a question's `tool.messageID` / a permission's `messageID`).
3685
+ * That assistant message is the reply to ONE of our minted user messages
3686
+ * (correlated by `parentID`, GATE-B). So when we have the tick's message
3687
+ * snapshot, we resolve each running in-flight message's correlated assistant
3688
+ * reply (`findAssistantReplyAfter`) and match its id against
3689
+ * `interactionMessageId` — giving an EXACT attribution even with several
3690
+ * messages in flight concurrently in one session.
3691
+ *
3692
+ * We fall back to the oldest running message ONLY when no exact match is
3693
+ * possible (the id is absent, the snapshot is missing, or the reply has not yet
3694
+ * been correlated). With a single running message either path is exact. Never
3695
+ * throws.
3696
+ *
3697
+ * Attribution must NOT depend on our own `started` PATCH flag: opencode can
3698
+ * START a turn AND raise a question/permission BEFORE our next tick fires
3699
+ * `markProcessing` (which sets `started`). Relying on `started` would leave the
3700
+ * running set empty in that window and let the server fall back to "newest
3701
+ * processing/pending" — possibly @mentioning a FOLLOW-UP author rather than the
3702
+ * person whose active turn actually paused. So we derive "running" from the
3703
+ * tick's `messages` snapshot via `messageRunState` instead.
3704
+ */
3705
+ attributeInteraction(watcher, interactionMessageId, messages) {
3706
+ const inFlight = [...watcher.inFlight.values()].filter((m) => !m.done);
3707
+ if (inFlight.length === 0) return void 0;
3708
+ if (interactionMessageId && messages) {
3709
+ const exact = inFlight.find((m) => {
3710
+ const reply = findAssistantReplyAfter(messages, m.opencodeMessageId);
3711
+ return reply != null && messageIdOf(reply) === interactionMessageId;
1817
3712
  });
3713
+ if (exact) return exact;
3714
+ }
3715
+ const byOldest = (a, b) => a.dispatchedAt - b.dispatchedAt;
3716
+ if (messages) {
3717
+ const runningPerSnapshot = inFlight.filter(
3718
+ (m) => messageRunState(messages, m.opencodeMessageId) === "running"
3719
+ );
3720
+ if (runningPerSnapshot.length > 0) {
3721
+ return runningPerSnapshot.sort(byOldest)[0];
3722
+ }
1818
3723
  }
3724
+ const startedRunning = inFlight.filter((m) => m.started);
3725
+ if (startedRunning.length > 0) {
3726
+ return startedRunning.sort(byOldest)[0];
3727
+ }
3728
+ return inFlight.sort(byOldest)[0];
1819
3729
  }
1820
3730
  // -------------------------------------------------------------------------
1821
3731
  // Evident API calls (combinedAuth thread routes)
@@ -1849,52 +3759,193 @@ var ChannelDriver = class {
1849
3759
  }
1850
3760
  return await res.json();
1851
3761
  }
1852
- async markProcessing(conversationId, messageId, sessionId) {
3762
+ /**
3763
+ * Fetch this agent's `processing` messages for re-adoption (ADR-0046, WI-1).
3764
+ * The pending path (`getPendingConversations`/`getPendingMessages`) only
3765
+ * surfaces `pending` rows, so a message already `processing` when the runner
3766
+ * died is invisible to it — this dedicated endpoint returns exactly those rows
3767
+ * with the fields the re-adopt path needs (`processed_at`,
3768
+ * `opencode_session_id`, routing).
3769
+ *
3770
+ * Response is an OBJECT WRAPPER `{ messages: [...] }` (snake_case) — NOT a bare
3771
+ * array. Propagates `ChannelAuthError` on 401/403; throws a plain `Error` on
3772
+ * other non-ok so `drainPending`'s try/finally leaves `draining` false and the
3773
+ * next tick retries.
3774
+ */
3775
+ async getProcessingMessages() {
3776
+ const res = await this.fetchImpl(
3777
+ `${this.apiUrl}/agents/${this.agentId}/conversations/processing`,
3778
+ { headers: { Authorization: this.getAuthHeader() } }
3779
+ );
3780
+ this.assertAuth(res, "fetching processing messages");
3781
+ if (!res.ok) {
3782
+ throw new Error(`Failed to get processing messages: HTTP ${res.status}`);
3783
+ }
3784
+ const data = await res.json();
3785
+ let messages = data.messages ?? [];
3786
+ if (this.conversationFilter) {
3787
+ messages = messages.filter((m) => m.conversation_id === this.conversationFilter);
3788
+ }
3789
+ return messages;
3790
+ }
3791
+ /**
3792
+ * EXISTING combinedAuth route — now fired by the watcher on queued→running
3793
+ * (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
3794
+ * opencode_session_id}` → `notifyMessageStarted` (hourglass→runner swap +
3795
+ * deep-linked "View in Evident" notice).
3796
+ *
3797
+ * Return/throw contract (consumed by the watcher's swap-to-running guard):
3798
+ * - returns `true` → the server transitioned the row to processing;
3799
+ * - returns `false` → the server gave a DEFINITIVE "already-processing"
3800
+ * answer (a non-retryable, non-auth status — e.g. a
3801
+ * conflict because a duplicate already transitioned it),
3802
+ * so the caller treats it as already-started and does NOT
3803
+ * retry;
3804
+ * - throws `ChannelAuthError` on 401/403 (terminal auth failure);
3805
+ * - throws on a TRANSIENT failure (retryable 5xx/429 status, or a
3806
+ * network-level error from `fetch`) — i.e. NO definitive server response —
3807
+ * so the caller leaves the message un-started and retries the swap on the
3808
+ * next tick.
3809
+ * A single attempt (no internal retry): the watcher's per-tick loop is the
3810
+ * retry vehicle for the swap-to-running.
3811
+ */
3812
+ async markProcessing(conversationId, messageId, sessionId, opencodeMessageId, title) {
1853
3813
  const res = await this.fetchImpl(
1854
3814
  `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
1855
3815
  {
1856
3816
  method: "PATCH",
1857
3817
  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
- body: JSON.stringify({ status: "processing", opencode_session_id: sessionId })
3818
+ body: JSON.stringify({
3819
+ status: "processing",
3820
+ opencode_session_id: sessionId,
3821
+ ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3822
+ ...title ? { title } : {}
3823
+ })
1862
3824
  }
1863
3825
  );
1864
3826
  this.assertAuth(res, "marking message as processing");
1865
- return res.ok;
3827
+ if (res.ok) return true;
3828
+ if (isRetryableStatus(res.status)) {
3829
+ throw new Error(`marking message as processing: HTTP ${res.status}`);
3830
+ }
3831
+ return false;
1866
3832
  }
1867
3833
  /**
1868
- * EXISTING combinedAuth completion route — idempotent + retried (WI-CHAN-2).
1869
- * `PATCH .../messages/:id {status:'done', opencode_session_id}`. The server's
3834
+ * EXISTING combinedAuth completion route — idempotent (WI-CHAN-2). `PATCH
3835
+ * .../messages/:id {status:'done', opencode_session_id}`. The server's
1870
3836
  * `queued_conversation_messages.status`/`processed_at` gate makes a re-call
1871
- * for an already-`done` message a no-op (no double Slack post).
3837
+ * for an already-`done` message a no-op (no double Slack post). Fired by the
3838
+ * watcher on per-message completion (Task 3.4) — no `confirmCompletion`
3839
+ * round-trip (we already observed completion via the message list).
3840
+ *
3841
+ * SINGLE ATTEMPT (no in-call `callWithRetry` backoff). The per-session watcher
3842
+ * services its in-flight messages SEQUENTIALLY within a tick
3843
+ * (`runWatcherLoop` → `serviceInFlightMessage`), so a long multi-attempt
3844
+ * backoff here would BLOCK sibling messages in the SAME session/tick: while
3845
+ * message A's done PATCH burned its internal retries, message B could not be
3846
+ * swapped to running even though opencode had already started it. Instead this
3847
+ * does ONE PATCH and surfaces the SAME outcome contract the watcher's markDone
3848
+ * handler already relies on, leaning on the per-tick retry across ticks
3849
+ * (bounded by `inFlight.deadline`) rather than an in-call retry:
3850
+ * - resolves (`void`) → the server transitioned the row to done
3851
+ * (or idempotently confirmed already-done);
3852
+ * - throws `ChannelAuthError` → 401/403 (terminal auth failure → loop
3853
+ * cleanup, Finding 1);
3854
+ * - throws `ChannelTerminalError`→ non-retryable, non-auth 4xx (will never
3855
+ * succeed → straight to the cron, Finding 4);
3856
+ * - throws a plain `Error` → TRANSIENT 5xx/429 or a network-level error
3857
+ * (no definitive server response → the
3858
+ * watcher retries next tick within the
3859
+ * deadline, Finding 4).
3860
+ */
3861
+ async markDone(conversationId, messageId, sessionId, opencodeMessageId, title) {
3862
+ const res = await this.fetchImpl(
3863
+ `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
3864
+ {
3865
+ method: "PATCH",
3866
+ headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3867
+ body: JSON.stringify({
3868
+ status: "done",
3869
+ opencode_session_id: sessionId,
3870
+ ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3871
+ ...title ? { title } : {}
3872
+ })
3873
+ }
3874
+ );
3875
+ this.assertAuth(res, "marking message as done");
3876
+ if (res.ok) return;
3877
+ if (isRetryableStatus(res.status)) {
3878
+ throw new Error(`marking message as done: HTTP ${res.status}`);
3879
+ }
3880
+ throw new ChannelTerminalError(`marking message as done: HTTP ${res.status}`, res.status);
3881
+ }
3882
+ /**
3883
+ * Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
3884
+ * when provided (issue #182): a bare `markFailed(conv, msg)` sends
3885
+ * `{status:'failed'}` unchanged (the dispatch-failure path), while an errored
3886
+ * OpenCode turn sends `{status:'failed', opencode_session_id, error}` so the
3887
+ * failure reason reaches the channel.
1872
3888
  */
1873
- async markDone(conversationId, messageId, sessionId) {
3889
+ async markFailed(conversationId, messageId, sessionId, error2) {
3890
+ const body = { status: "failed" };
3891
+ if (sessionId !== void 0) body.opencode_session_id = sessionId;
3892
+ if (error2 !== void 0) body.error = error2;
1874
3893
  await this.callWithRetry(
1875
- "marking message as done",
3894
+ "marking message as failed",
1876
3895
  () => this.fetchImpl(
1877
3896
  `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
1878
3897
  {
1879
3898
  method: "PATCH",
1880
3899
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
1881
- body: JSON.stringify({ status: "done", opencode_session_id: sessionId })
3900
+ body: JSON.stringify(body)
1882
3901
  }
1883
3902
  )
1884
3903
  );
1885
3904
  }
1886
- async markFailed(conversationId, messageId) {
1887
- await this.callWithRetry(
1888
- "marking message as failed",
1889
- () => this.fetchImpl(
1890
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
3905
+ /**
3906
+ * Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
3907
+ * (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
3908
+ * — the server records it via `log()` (no DB write, no notification). This is
3909
+ * fire-and-forget: it MUST NEVER throw into the drain or the watcher tick, and
3910
+ * MUST NOT use `callWithRetry` (a telemetry ping must not block the sequential
3911
+ * watcher tick — one attempt is enough). A failure is SWALLOWED but LOGGED with
3912
+ * context (no silent catch, per development-workflow).
3913
+ *
3914
+ * Returns whether the POST SUCCEEDED (2xx). Most callers ignore this (pure
3915
+ * telemetry), but the `paused` liveness-clear uses it to know whether to
3916
+ * RE-ASSERT on a later tick — a single dropped `paused` POST must not leave a
3917
+ * stale `last_seen_alive_at` on a still-paused row (Bugbot "Failed paused signal
3918
+ * leaves liveness").
3919
+ */
3920
+ async postSignal(conversationId, messageId, signal, extra) {
3921
+ try {
3922
+ const res = await this.fetchImpl(
3923
+ `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
1891
3924
  {
1892
- method: "PATCH",
3925
+ method: "POST",
1893
3926
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
1894
- body: JSON.stringify({ status: "failed" })
3927
+ body: JSON.stringify({ signal, ...extra })
1895
3928
  }
1896
- )
1897
- );
3929
+ );
3930
+ if (!res.ok) {
3931
+ this.log({
3932
+ level: "warn",
3933
+ message: `Signal '${signal}' for message ${messageId.slice(0, 8)} returned HTTP ${res.status} (telemetry-only, ignored)`,
3934
+ conversation_id: conversationId,
3935
+ message_id: messageId
3936
+ });
3937
+ return false;
3938
+ }
3939
+ return true;
3940
+ } catch (err) {
3941
+ this.log({
3942
+ level: "warn",
3943
+ message: `Signal '${signal}' for message ${messageId.slice(0, 8)} failed (telemetry-only, ignored): ${err instanceof Error ? err.message : String(err)}`,
3944
+ conversation_id: conversationId,
3945
+ message_id: messageId
3946
+ });
3947
+ return false;
3948
+ }
1898
3949
  }
1899
3950
  async persistSession(conversationId, sessionId) {
1900
3951
  const res = await this.fetchImpl(
@@ -1909,10 +3960,17 @@ var ChannelDriver = class {
1909
3960
  }
1910
3961
  /**
1911
3962
  * 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.
3963
+ * `POST .../interactive-event {type, data, source_message_id?}`. The server
3964
+ * persists the interaction and posts a link to the proxied opencode-web
3965
+ * conversation, @mentioning the user who triggered THIS message's turn.
3966
+ *
3967
+ * WI-3 / WI-4 contract: `source_message_id` is the PAUSED message's own Slack
3968
+ * ts (`message.source_message_id`). The server resolves the @mention from that
3969
+ * message's user FIRST (falling back to the old "newest processing" precedence
3970
+ * only when absent), so the correct person is mentioned under concurrency. It
3971
+ * is OPTIONAL for back-compat with older clients / legacy rows.
1914
3972
  */
1915
- async reportInteraction(conversationId, type, data) {
3973
+ async reportInteraction(conversationId, type, data, sourceMessageId) {
1916
3974
  try {
1917
3975
  await this.callWithRetry(
1918
3976
  "reporting interactive event",
@@ -1921,7 +3979,9 @@ var ChannelDriver = class {
1921
3979
  {
1922
3980
  method: "POST",
1923
3981
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
1924
- body: JSON.stringify({ type, data })
3982
+ body: JSON.stringify(
3983
+ sourceMessageId ? { type, data, source_message_id: sourceMessageId } : { type, data }
3984
+ )
1925
3985
  }
1926
3986
  )
1927
3987
  );
@@ -1930,6 +3990,7 @@ var ChannelDriver = class {
1930
3990
  message: `${type} surfaced to channel (id: ${data.id.slice(0, 8)})`,
1931
3991
  conversation_id: conversationId
1932
3992
  });
3993
+ return true;
1933
3994
  } catch (err) {
1934
3995
  if (err instanceof ChannelAuthError) throw err;
1935
3996
  this.log({
@@ -1937,6 +3998,7 @@ var ChannelDriver = class {
1937
3998
  message: `Failed to surface ${type}: ${err instanceof Error ? err.message : String(err)}`,
1938
3999
  conversation_id: conversationId
1939
4000
  });
4001
+ return false;
1940
4002
  }
1941
4003
  }
1942
4004
  // -------------------------------------------------------------------------
@@ -1975,8 +4037,9 @@ var ChannelDriver = class {
1975
4037
  await this.sleep(backoffDelay(attempt, this.retry));
1976
4038
  continue;
1977
4039
  }
4040
+ break;
1978
4041
  }
1979
- throw new Error(`${context}: HTTP ${res.status}`);
4042
+ throw new ChannelTerminalError(`${context}: HTTP ${res.status}`, res.status);
1980
4043
  }
1981
4044
  throw lastError instanceof Error ? lastError : new Error(`${context}: exhausted retries`);
1982
4045
  }
@@ -2154,6 +4217,25 @@ async function resolveAgentIdFromKey(authHeader) {
2154
4217
  return { error: `Failed to resolve agent from key: ${message}` };
2155
4218
  }
2156
4219
  }
4220
+ async function notifyAgentDisconnected(agentId, authHeader) {
4221
+ const apiUrl = getApiUrlConfig();
4222
+ try {
4223
+ const response = await fetch(`${apiUrl}/agents/${agentId}/disconnect`, {
4224
+ method: "POST",
4225
+ headers: { Authorization: authHeader }
4226
+ });
4227
+ if (!response.ok) {
4228
+ const serverMessage = await readErrorMessage(response);
4229
+ return {
4230
+ ok: false,
4231
+ error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
4232
+ };
4233
+ }
4234
+ return { ok: true };
4235
+ } catch (error2) {
4236
+ return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
4237
+ }
4238
+ }
2157
4239
  async function getAgentInfo(agentId, authHeader) {
2158
4240
  const apiUrl = getApiUrlConfig();
2159
4241
  try {
@@ -2199,23 +4281,55 @@ async function getAgentInfo(agentId, authHeader) {
2199
4281
  // src/commands/run.ts
2200
4282
  var MAX_ACTIVITY_LOG_ENTRIES = 10;
2201
4283
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
2202
- function log(state, message, isError = false) {
4284
+ var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
4285
+ var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
4286
+ function resolveLogLevel(options) {
4287
+ const accepted = Object.keys(LOG_LEVELS);
4288
+ const validate = (value, source) => {
4289
+ const normalized = value.trim().toLowerCase();
4290
+ if (!accepted.includes(normalized)) {
4291
+ throw new Error(
4292
+ `Invalid log level "${value}"${source}; expected one of ${accepted.join(", ")}`
4293
+ );
4294
+ }
4295
+ return normalized;
4296
+ };
4297
+ if (options.logLevel !== void 0) {
4298
+ return validate(options.logLevel, " (--log-level)");
4299
+ }
4300
+ if (options.verbose) {
4301
+ return "debug";
4302
+ }
4303
+ const env = process.env.EVIDENT_LOG_LEVEL;
4304
+ if (env !== void 0 && env !== "") {
4305
+ return validate(env, " (EVIDENT_LOG_LEVEL)");
4306
+ }
4307
+ return "info";
4308
+ }
4309
+ function meetsThreshold(state, level) {
4310
+ return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
4311
+ }
4312
+ function log2(state, message, level = "info") {
4313
+ if (!meetsThreshold(state, level)) return;
2203
4314
  if (state.json) {
2204
4315
  console.log(
2205
4316
  JSON.stringify({
2206
4317
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2207
- level: isError ? "error" : "info",
4318
+ level,
2208
4319
  message
2209
4320
  })
2210
4321
  );
2211
4322
  } else if (!state.interactive) {
2212
- const prefix = isError ? chalk6.red("\u2717") : chalk6.green("\u2022");
4323
+ const prefix = level === "error" ? chalk6.red("\u2717") : level === "warn" ? chalk6.yellow("!") : level === "debug" ? chalk6.dim("\xB7") : chalk6.green("\u2022");
2213
4324
  console.log(`${prefix} ${message}`);
2214
4325
  }
2215
4326
  }
2216
4327
  function logActivity(state, entry) {
4328
+ const level = entry.level ?? (entry.type === "error" ? "error" : "info");
4329
+ if (!meetsThreshold(state, level)) return;
2217
4330
  const fullEntry = {
2218
4331
  ...entry,
4332
+ level,
2219
4333
  timestamp: /* @__PURE__ */ new Date()
2220
4334
  };
2221
4335
  state.activityLog.push(fullEntry);
@@ -2224,9 +4338,9 @@ function logActivity(state, entry) {
2224
4338
  }
2225
4339
  if (!state.interactive) {
2226
4340
  if (entry.type === "error") {
2227
- log(state, entry.error ?? "Unknown error", true);
2228
- } else if (entry.type === "info" && entry.message) {
2229
- log(state, entry.message);
4341
+ log2(state, entry.error ?? "Unknown error", level);
4342
+ } else if (entry.message) {
4343
+ log2(state, entry.message, level);
2230
4344
  }
2231
4345
  }
2232
4346
  }
@@ -2312,6 +4426,7 @@ async function handleAuthError(state, error2) {
2312
4426
  }
2313
4427
  async function driveChannels(state, driver) {
2314
4428
  let idlePolls = 0;
4429
+ let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
2315
4430
  while (state.running) {
2316
4431
  if (state.connection?.reconnecting && state.connection.reconnectPromise) {
2317
4432
  logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
@@ -2321,9 +4436,11 @@ async function driveChannels(state, driver) {
2321
4436
  try {
2322
4437
  const processed = await driver.drainPending();
2323
4438
  state.messageCount += processed;
2324
- if (processed > 0) {
4439
+ const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
4440
+ lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
4441
+ if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity) {
2325
4442
  idlePolls = 0;
2326
- if (state.interactive) displayStatus(state);
4443
+ if (processed > 0 && state.interactive) displayStatus(state);
2327
4444
  } else if (state.idleTimeout !== null) {
2328
4445
  idlePolls++;
2329
4446
  if (idlePolls === 1) {
@@ -2350,7 +4467,7 @@ async function driveChannels(state, driver) {
2350
4467
  logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
2351
4468
  if (state.interactive) displayStatus(state);
2352
4469
  }
2353
- await new Promise((resolve) => setTimeout(resolve, CHANNEL_POLL_INTERVAL_MS));
4470
+ await new Promise((resolve2) => setTimeout(resolve2, CHANNEL_POLL_INTERVAL_MS));
2354
4471
  if (state.idleTimeout !== null && idlePolls >= 2) {
2355
4472
  const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
2356
4473
  if (idleMs > state.idleTimeout * 1e3) {
@@ -2361,8 +4478,122 @@ async function driveChannels(state, driver) {
2361
4478
  }
2362
4479
  }
2363
4480
  }
2364
- async function cleanup(state) {
4481
+ var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
4482
+ async function runSweep(state, driver, config2) {
4483
+ const mode = `age=${config2.maxAgeMs ?? "\u2014"} count=${config2.maxCount ?? "\u2014"}`;
4484
+ try {
4485
+ const sessions = await listSessions(state.port);
4486
+ if (sessions === null) {
4487
+ logActivity(state, {
4488
+ type: "info",
4489
+ message: `Session cleanup: could not list sessions (opencode unreachable); skipping this sweep (${mode})`
4490
+ });
4491
+ return;
4492
+ }
4493
+ const toDelete = selectSessionsToDelete(
4494
+ sessions.map((s) => ({ id: s.id, lastActivityMs: sessionLastActivityMs(s) })),
4495
+ {
4496
+ maxAgeMs: config2.maxAgeMs,
4497
+ maxCount: config2.maxCount,
4498
+ nowMs: Date.now(),
4499
+ protectedIds: driver.protectedSessionIds()
4500
+ }
4501
+ );
4502
+ const protectedNow = driver.protectedSessionIds();
4503
+ let deleted = 0;
4504
+ let failed = 0;
4505
+ let skippedNewlyActive = 0;
4506
+ for (const id of toDelete) {
4507
+ if (protectedNow.has(id)) {
4508
+ skippedNewlyActive++;
4509
+ logActivity(state, {
4510
+ type: "info",
4511
+ message: `Session cleanup: skipping ${id} \u2014 became active/bound after selection (${mode})`
4512
+ });
4513
+ continue;
4514
+ }
4515
+ if (await deleteSession(state.port, id)) deleted++;
4516
+ else failed++;
4517
+ }
4518
+ const failedNote = failed > 0 ? `, failed ${failed}` : "";
4519
+ const skippedNote = skippedNewlyActive > 0 ? `, skipped ${skippedNewlyActive} newly-active` : "";
4520
+ logActivity(state, {
4521
+ type: "info",
4522
+ message: `Session cleanup: inspected ${sessions.length}, deleted ${deleted}${failedNote}${skippedNote} (${mode})`
4523
+ });
4524
+ } catch (error2) {
4525
+ const message = error2 instanceof Error ? error2.message : String(error2);
4526
+ logActivity(state, {
4527
+ type: "error",
4528
+ error: `Session cleanup sweep failed (non-fatal, ${mode}): ${message}`
4529
+ });
4530
+ }
4531
+ }
4532
+ function scheduleSessionCleanup(state, driver, options) {
4533
+ const config2 = resolveSessionCleanupConfig(
4534
+ {
4535
+ maxAge: options.sessionCleanupMaxAge,
4536
+ maxCount: options.sessionCleanupMaxCount,
4537
+ interval: options.sessionCleanupInterval
4538
+ },
4539
+ process.env
4540
+ );
4541
+ for (const warning2 of config2.warnings) {
4542
+ logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
4543
+ }
4544
+ if (!config2.enabled) return;
4545
+ logActivity(state, {
4546
+ type: "info",
4547
+ message: `Session cleanup enabled (age=${config2.maxAgeMs ?? "\u2014"}, count=${config2.maxCount ?? "\u2014"}, interval=${config2.intervalMs}ms)`
4548
+ });
4549
+ const interval = setInterval(() => void runSweep(state, driver, config2), config2.intervalMs);
4550
+ const firstSweep = setTimeout(
4551
+ () => void runSweep(state, driver, config2),
4552
+ SESSION_CLEANUP_FIRST_SWEEP_MS
4553
+ );
4554
+ state.sessionCleanupTimers.push(interval, firstSweep);
4555
+ }
4556
+ async function notifyOffline(state) {
4557
+ if (!state.agentId || !state.authHeader) return;
4558
+ if (!state.connected) {
4559
+ log2(state, "Skipping offline signal \u2014 this runner does not hold the live tunnel");
4560
+ return;
4561
+ }
4562
+ const result = await notifyAgentDisconnected(state.agentId, state.authHeader);
4563
+ if (result.ok) {
4564
+ log2(state, "Notified Evident the agent is going offline");
4565
+ } else {
4566
+ logActivity(state, {
4567
+ type: "error",
4568
+ error: `Could not notify Evident of offline status (relay will still report it): ${result.error}`
4569
+ });
4570
+ if (state.interactive) displayStatus(state);
4571
+ }
4572
+ }
4573
+ async function cleanup(state, opts = {}) {
2365
4574
  state.running = false;
4575
+ for (const timer of state.sessionCleanupTimers) {
4576
+ clearInterval(timer);
4577
+ clearTimeout(timer);
4578
+ }
4579
+ state.sessionCleanupTimers = [];
4580
+ if (opts.graceful && state.channelDriver) {
4581
+ state.channelDriver.stop();
4582
+ log2(state, "Draining in-flight channel work before shutdown...");
4583
+ if (state.interactive) {
4584
+ logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
4585
+ displayStatus(state);
4586
+ }
4587
+ const settled = await state.channelDriver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS);
4588
+ if (!settled) {
4589
+ logActivity(state, {
4590
+ type: "info",
4591
+ message: "Shutdown drain timed out with work still in flight \u2014 leaving it for restart recovery"
4592
+ });
4593
+ if (state.interactive) displayStatus(state);
4594
+ }
4595
+ }
4596
+ await notifyOffline(state);
2366
4597
  if (state.connection) {
2367
4598
  state.connection.close();
2368
4599
  state.connection = null;
@@ -2373,13 +4604,27 @@ async function cleanup(state) {
2373
4604
  logActivity(state, { type: "info", message: "Stopped OpenCode process" });
2374
4605
  displayStatus(state);
2375
4606
  } else {
2376
- log(state, "Stopped OpenCode process");
4607
+ log2(state, "Stopped OpenCode process");
2377
4608
  }
2378
4609
  state.opencodeProcess = null;
2379
4610
  }
2380
4611
  }
2381
4612
  async function run(options) {
2382
4613
  const interactive = isInteractive(options.json);
4614
+ let logLevel;
4615
+ try {
4616
+ logLevel = resolveLogLevel(options);
4617
+ } catch (error2) {
4618
+ const message = error2 instanceof Error ? error2.message : String(error2);
4619
+ if (options.json) {
4620
+ console.log(JSON.stringify({ status: "error", error: message }));
4621
+ } else {
4622
+ printError(message);
4623
+ }
4624
+ await shutdownTelemetry();
4625
+ process.exit(1);
4626
+ return;
4627
+ }
2383
4628
  const state = {
2384
4629
  agentId: options.agent || "",
2385
4630
  agentName: null,
@@ -2388,31 +4633,38 @@ async function run(options) {
2388
4633
  idleTimeout: options.idleTimeout ?? null,
2389
4634
  json: options.json ?? false,
2390
4635
  interactive,
4636
+ logLevel,
2391
4637
  connected: false,
2392
4638
  opencodeConnected: false,
2393
4639
  opencodeVersion: null,
2394
4640
  opencodeProcess: null,
2395
4641
  connection: null,
4642
+ channelDriver: null,
2396
4643
  running: true,
4644
+ shuttingDown: false,
2397
4645
  activityLog: [],
2398
4646
  messageCount: 0,
4647
+ lastProxiedActivityAt: null,
4648
+ sessionCleanupTimers: [],
2399
4649
  authHeader: ""
2400
4650
  };
2401
4651
  if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
2402
- log(
4652
+ log2(
2403
4653
  state,
2404
- "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
- false
4654
+ "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.",
4655
+ "warn"
2406
4656
  );
2407
4657
  }
2408
4658
  const handleSignal = async () => {
4659
+ if (state.shuttingDown) return;
4660
+ state.shuttingDown = true;
2409
4661
  if (state.interactive) {
2410
4662
  logActivity(state, { type: "info", message: "Shutting down..." });
2411
4663
  displayStatus(state);
2412
4664
  } else {
2413
- log(state, "Shutting down...");
4665
+ log2(state, "Shutting down...");
2414
4666
  }
2415
- await cleanup(state);
4667
+ await cleanup(state, { graceful: true });
2416
4668
  await shutdownTelemetry();
2417
4669
  process.exit(0);
2418
4670
  };
@@ -2443,7 +4695,7 @@ async function run(options) {
2443
4695
  const resolved = await resolveAgentIdFromKey(state.authHeader);
2444
4696
  if (resolved.agent_id) {
2445
4697
  state.agentId = resolved.agent_id;
2446
- log(state, `Resolved agent ID from key: ${state.agentId}`);
4698
+ log2(state, `Resolved agent ID from key: ${state.agentId}`);
2447
4699
  if (state.interactive && !state.json) {
2448
4700
  logActivity(state, {
2449
4701
  type: "info",
@@ -2506,14 +4758,21 @@ async function run(options) {
2506
4758
  port: state.port,
2507
4759
  interactive: state.interactive,
2508
4760
  agentId: state.agentId,
2509
- log: (message) => log(state, message)
4761
+ log: (message) => log2(state, message)
2510
4762
  });
2511
4763
  state.port = oc.port;
2512
4764
  state.opencodeProcess = oc.process;
2513
4765
  state.opencodeVersion = oc.version;
2514
4766
  state.opencodeConnected = oc.process !== null || oc.version !== null;
2515
- const version = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
2516
- ocSpinner?.succeed(`OpenCode running on port ${state.port}${version}`);
4767
+ const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
4768
+ ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
4769
+ const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
4770
+ if (versionWarning) {
4771
+ log2(state, versionWarning, "warn");
4772
+ if (state.interactive && !state.json) {
4773
+ logActivity(state, { type: "info", level: "warn", message: versionWarning });
4774
+ }
4775
+ }
2517
4776
  } catch (error2) {
2518
4777
  ocSpinner?.fail(error2.message);
2519
4778
  throw error2;
@@ -2525,12 +4784,20 @@ async function run(options) {
2525
4784
  apiUrl: getApiUrlConfig(),
2526
4785
  getAuthHeader: () => state.authHeader,
2527
4786
  conversationFilter: state.conversationFilter,
2528
- log: (entry) => logActivity(state, {
2529
- type: entry.level === "error" ? "error" : "info",
2530
- message: entry.message,
2531
- error: entry.level === "error" ? entry.message : void 0
2532
- })
4787
+ stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
4788
+ log: (entry) => (
4789
+ // Thread the driver's real level straight through so `debug`/`warn`
4790
+ // survive the sink filter (they no longer collapse to info). `type`
4791
+ // stays the coarse error/non-error split the activity log renders with.
4792
+ logActivity(state, {
4793
+ type: entry.level === "error" ? "error" : "info",
4794
+ level: entry.level,
4795
+ message: entry.message,
4796
+ error: entry.level === "error" ? entry.message : void 0
4797
+ })
4798
+ )
2533
4799
  });
4800
+ state.channelDriver = channelDriver;
2534
4801
  const connection = new RunnerConnection({
2535
4802
  agentId: state.agentId,
2536
4803
  getAuthHeader: () => state.authHeader,
@@ -2544,7 +4811,11 @@ async function run(options) {
2544
4811
  type: "info",
2545
4812
  message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (agent: ${agentId})`
2546
4813
  });
2547
- emitAgentConnected(state.agentId, { port: state.port });
4814
+ emitAgentConnected(state.agentId, {
4815
+ port: state.port,
4816
+ cli_version: getCliVersion(),
4817
+ opencode_version: state.opencodeVersion
4818
+ });
2548
4819
  if (!isReconnect) tunnelSpinner?.succeed("Tunnel connected");
2549
4820
  if (state.interactive) displayStatus(state);
2550
4821
  channelDriver.drainPending().then((processed) => {
@@ -2578,9 +4849,14 @@ async function run(options) {
2578
4849
  logActivity(state, { type: "error", error: error2 });
2579
4850
  if (state.interactive) displayStatus(state);
2580
4851
  },
2581
- // Web traffic is proxied transparently; only note opencode is live.
4852
+ // Web traffic is proxied transparently; note opencode is live and stamp
4853
+ // proxied activity so the idle loop treats interactive proxy use as work.
4854
+ // Fires per forwarded response head (incl. every SSE open) and excludes
4855
+ // the internal drain-ping, so an actively-used proxy keeps the timer
4856
+ // fresh while a lone idle SSE with no follow-up requests still ages out.
2582
4857
  onResponse: () => {
2583
4858
  state.opencodeConnected = true;
4859
+ state.lastProxiedActivityAt = Date.now();
2584
4860
  },
2585
4861
  // A channel message was queued and the api-worker pinged us over the
2586
4862
  // tunnel to drain immediately instead of waiting for the next poll tick.
@@ -2618,10 +4894,12 @@ async function run(options) {
2618
4894
  if (error2.message === "Unauthorized") tunnelSpinner?.fail("Unauthorized");
2619
4895
  throw error2;
2620
4896
  }
4897
+ scheduleSessionCleanup(state, channelDriver, options);
2621
4898
  if (!interactive || state.json) {
2622
- log(state, "Driving channel messages...");
4899
+ log2(state, "Driving channel messages...");
2623
4900
  }
2624
4901
  await driveChannels(state, channelDriver);
4902
+ if (state.shuttingDown) return;
2625
4903
  await cleanup(state);
2626
4904
  if (state.json) {
2627
4905
  console.log(
@@ -2631,11 +4909,12 @@ async function run(options) {
2631
4909
  })
2632
4910
  );
2633
4911
  } else if (!interactive) {
2634
- log(state, `Completed. Processed ${state.messageCount} message(s).`);
4912
+ log2(state, `Completed. Processed ${state.messageCount} message(s).`);
2635
4913
  }
2636
4914
  await shutdownTelemetry();
2637
4915
  process.exit(0);
2638
4916
  } catch (error2) {
4917
+ if (state.shuttingDown) return;
2639
4918
  await cleanup(state);
2640
4919
  const message = error2 instanceof Error ? error2.message : String(error2);
2641
4920
  if (state.json) {
@@ -2653,8 +4932,9 @@ async function run(options) {
2653
4932
  }
2654
4933
 
2655
4934
  // src/index.ts
4935
+ var { version } = createRequire(import.meta.url)("../package.json");
2656
4936
  var program = new Command();
2657
- program.name("evident").description("Run OpenCode locally and connect it to Evident").version("0.1.0").option(
4937
+ program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
2658
4938
  "--endpoint <url>",
2659
4939
  "Evident API base URL (default: production; e.g. http://localhost:3001)"
2660
4940
  ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").hook("preAction", (thisCommand) => {
@@ -2669,15 +4949,34 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
2669
4949
  program.command("login").description("Authenticate with Evident").option("--token", "Use token-based authentication (for CI/CD)").option("--no-browser", "Do not open the browser automatically").action(login);
2670
4950
  program.command("logout").description("Remove stored credentials for the current endpoint").option("--all", "Remove stored credentials for all endpoints").action((options) => logout({ all: options.all }));
2671
4951
  program.command("whoami").description("Show the currently logged in user").action(whoami);
2672
- program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Agent ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option("-v, --verbose", "Show detailed request/response information").option("-c, --conversation <id>", "Process only this specific conversation").option("--idle-timeout <seconds>", "Exit after N seconds idle").option("--json", "Output in JSON format").action(
4952
+ program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Agent ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
4953
+ "--log-level <level>",
4954
+ "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
4955
+ ).option("-v, --verbose", "Alias for --log-level debug (ignored if --log-level is set)").option("-c, --conversation <id>", "Process only this specific conversation").option("--idle-timeout <seconds>", "Exit after N seconds idle").option("--json", "Output in JSON format").option(
4956
+ "--session-cleanup-max-age <duration>",
4957
+ "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
4958
+ ).option(
4959
+ "--session-cleanup-max-count <n>",
4960
+ "Keep only the newest N OpenCode sessions. Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_COUNT"
4961
+ ).option(
4962
+ "--session-cleanup-interval <duration>",
4963
+ "How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
4964
+ ).action(
2673
4965
  (options) => {
2674
4966
  run({
2675
4967
  agent: options.agent,
2676
4968
  port: parseInt(options.port, 10),
4969
+ // Raw string — validation/precedence is single-sourced in run.ts's
4970
+ // resolveLogLevel (flag > -v > EVIDENT_LOG_LEVEL > info).
4971
+ logLevel: options.logLevel,
2677
4972
  verbose: options.verbose,
2678
4973
  conversation: options.conversation,
2679
4974
  idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
2680
- json: options.json
4975
+ json: options.json,
4976
+ // Raw strings — the resolver in run.ts single-sources parsing (M1).
4977
+ sessionCleanupMaxAge: options.sessionCleanupMaxAge,
4978
+ sessionCleanupMaxCount: options.sessionCleanupMaxCount,
4979
+ sessionCleanupInterval: options.sessionCleanupInterval
2681
4980
  });
2682
4981
  }
2683
4982
  );