@evident-ai/cli 3.0.1-dev.fffc02d → 3.1.1-dev.14c6359

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
@@ -285,14 +285,14 @@ function blank() {
285
285
  console.log();
286
286
  }
287
287
  function waitForEnter(prompt = "Press Enter to continue...") {
288
- return new Promise((resolve) => {
288
+ return new Promise((resolve2) => {
289
289
  process.stdout.write(chalk.dim(prompt));
290
290
  const handler = () => {
291
291
  process.stdin.removeListener("data", handler);
292
292
  process.stdin.setRawMode?.(false);
293
293
  process.stdin.pause();
294
294
  console.log();
295
- resolve();
295
+ resolve2();
296
296
  };
297
297
  if (process.stdin.isTTY) {
298
298
  process.stdin.setRawMode?.(true);
@@ -302,7 +302,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
302
302
  });
303
303
  }
304
304
  function sleep(ms) {
305
- return new Promise((resolve) => setTimeout(resolve, ms));
305
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
306
306
  }
307
307
 
308
308
  // src/commands/login.ts
@@ -376,19 +376,19 @@ async function tokenLogin() {
376
376
  console.log("Visit your Evident dashboard to generate a CLI token.");
377
377
  blank();
378
378
  process.stdout.write("Paste token: ");
379
- const token = await new Promise((resolve) => {
379
+ const token = await new Promise((resolve2) => {
380
380
  let data = "";
381
381
  process.stdin.setEncoding("utf8");
382
382
  process.stdin.on("data", (chunk) => {
383
383
  data += chunk;
384
384
  });
385
385
  process.stdin.on("end", () => {
386
- resolve(data.trim());
386
+ resolve2(data.trim());
387
387
  });
388
388
  if (process.stdin.isTTY) {
389
389
  process.stdin.once("data", (chunk) => {
390
390
  process.stdin.pause();
391
- resolve(chunk.toString().trim());
391
+ resolve2(chunk.toString().trim());
392
392
  });
393
393
  process.stdin.resume();
394
394
  }
@@ -706,7 +706,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
706
706
  if (health.healthy) {
707
707
  return health;
708
708
  }
709
- await new Promise((resolve) => setTimeout(resolve, 1e3));
709
+ await new Promise((resolve2) => setTimeout(resolve2, 1e3));
710
710
  }
711
711
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
712
712
  }
@@ -1078,6 +1078,84 @@ async function getSessionMessages(port, sessionId) {
1078
1078
  return null;
1079
1079
  }
1080
1080
  }
1081
+ function isSessionActivelyGenerating(messages) {
1082
+ if (!messages || messages.length === 0) return false;
1083
+ const last = messages[messages.length - 1];
1084
+ if (roleOf(last) !== "assistant") return false;
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";
1158
+ }
1081
1159
  async function createOpenCodeSession(port, directory) {
1082
1160
  const url = new URL(`${opencodeBase(port)}/session`);
1083
1161
  if (directory && directory.trim()) {
@@ -1095,17 +1173,113 @@ async function createOpenCodeSession(port, directory) {
1095
1173
  const data = await response.json();
1096
1174
  return data.id;
1097
1175
  }
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
+ }
1098
1260
  function messageText(m) {
1099
1261
  if (!m || !Array.isArray(m.parts)) return "";
1100
1262
  return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
1101
1263
  }
1102
- async function sendPromptAsync(port, sessionId, content, options) {
1264
+ async function sendPromptAsync(port, sessionId, content, options, attachments) {
1103
1265
  const before = await getSessionMessages(port, sessionId);
1104
1266
  const knownUserIds = new Set(
1105
1267
  (before ?? []).filter((m) => roleOf(m) === "user").map((m) => idOf(m)).filter((id) => typeof id === "string")
1106
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
+ }
1107
1281
  const body = {
1108
- parts: [{ type: "text", text: content }]
1282
+ parts
1109
1283
  };
1110
1284
  if (options?.agent) {
1111
1285
  body.agent = options.agent;
@@ -1144,10 +1318,13 @@ async function sendPromptAsync(port, sessionId, content, options) {
1144
1318
  best = { id, created };
1145
1319
  }
1146
1320
  }
1147
- if (best) return best.id;
1321
+ if (best) {
1322
+ if (pendingOutcomes && attachments?.onOutcomes) attachments.onOutcomes(pendingOutcomes);
1323
+ return best.id;
1324
+ }
1148
1325
  }
1149
1326
  if (attempt < READ_BACK_ATTEMPTS - 1) {
1150
- await new Promise((resolve) => setTimeout(resolve, READ_BACK_DELAY_MS));
1327
+ await new Promise((resolve2) => setTimeout(resolve2, READ_BACK_DELAY_MS));
1151
1328
  }
1152
1329
  }
1153
1330
  return null;
@@ -1193,6 +1370,72 @@ function findLastAssistantReplyFor(messages, userMessageId) {
1193
1370
  }
1194
1371
  return lastOk ?? last;
1195
1372
  }
1373
+ function messageUsage(messages, userMessageId) {
1374
+ if (!messages || messages.length === 0) return null;
1375
+ const byParentAll = messages.filter(
1376
+ (m) => roleOf(m) === "assistant" && parentIdOf(m) === userMessageId
1377
+ );
1378
+ const byParentNonErrored = byParentAll.filter((m) => errorOf(m) == null);
1379
+ const byParent = byParentNonErrored.length > 0 ? byParentNonErrored : byParentAll;
1380
+ let correlated;
1381
+ if (byParent.length > 0) {
1382
+ correlated = byParent;
1383
+ } else {
1384
+ const reply = findAssistantReplyAfter(messages, userMessageId);
1385
+ correlated = reply ? [reply] : [];
1386
+ }
1387
+ if (correlated.length === 0) return null;
1388
+ let sawAnyUsage = false;
1389
+ let inputSum = 0;
1390
+ let outputSum = 0;
1391
+ let reasoningSum = 0;
1392
+ let cacheReadSum = 0;
1393
+ let cacheWriteSum = 0;
1394
+ let costSum = 0;
1395
+ let sawCost = false;
1396
+ let modelId = null;
1397
+ let providerId = null;
1398
+ for (const m of correlated) {
1399
+ const info = m.info;
1400
+ if (!info) continue;
1401
+ const tokens = info.tokens;
1402
+ if (tokens) {
1403
+ sawAnyUsage = true;
1404
+ inputSum += tokens.input ?? 0;
1405
+ outputSum += tokens.output ?? 0;
1406
+ reasoningSum += tokens.reasoning ?? 0;
1407
+ cacheReadSum += tokens.cache?.read ?? 0;
1408
+ cacheWriteSum += tokens.cache?.write ?? 0;
1409
+ }
1410
+ if (typeof info.cost === "number") {
1411
+ sawAnyUsage = true;
1412
+ sawCost = true;
1413
+ costSum += info.cost;
1414
+ }
1415
+ if (typeof info.modelID === "string") {
1416
+ sawAnyUsage = true;
1417
+ modelId = info.modelID;
1418
+ }
1419
+ if (typeof info.providerID === "string") {
1420
+ sawAnyUsage = true;
1421
+ providerId = info.providerID;
1422
+ }
1423
+ }
1424
+ if (!sawAnyUsage) return null;
1425
+ return {
1426
+ usage_provider_id: providerId,
1427
+ usage_model_id: modelId,
1428
+ usage_tokens_input: inputSum,
1429
+ usage_tokens_output: outputSum,
1430
+ usage_tokens_reasoning: reasoningSum,
1431
+ usage_tokens_cache_read: cacheReadSum,
1432
+ usage_tokens_cache_write: cacheWriteSum,
1433
+ // NULL means "OpenCode never reported a cost" (never inferred from
1434
+ // tokens) — distinct from a genuine 0-cost turn, which would set
1435
+ // `sawCost` true with `costSum === 0`.
1436
+ usage_cost_usd: sawCost ? costSum : null
1437
+ };
1438
+ }
1196
1439
  function messageRunState(messages, userMessageId) {
1197
1440
  if (!messages || messages.length === 0) return "unknown";
1198
1441
  const hasUser = messages.some((m) => idOf(m) === userMessageId);
@@ -1204,6 +1447,11 @@ function messageRunState(messages, userMessageId) {
1204
1447
  if (isAssistantInFlight(reply)) return "running";
1205
1448
  return errorOf(reply) != null ? "failed" : "done";
1206
1449
  }
1450
+ function isPreamblePinnedRunning(messages, userMessageId) {
1451
+ if (messageRunState(messages, userMessageId) !== "running") return false;
1452
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
1453
+ return completedOf(reply) != null && finishOf(reply) === "tool-calls";
1454
+ }
1207
1455
  function messageError(messages, userMessageId) {
1208
1456
  const reply = findLastAssistantReplyFor(messages, userMessageId);
1209
1457
  const error2 = errorOf(reply);
@@ -1224,6 +1472,110 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1224
1472
  );
1225
1473
  }
1226
1474
 
1475
+ // src/lib/opencode/session-cleanup.ts
1476
+ var DURATION_UNIT_MS = {
1477
+ s: 1e3,
1478
+ m: 60 * 1e3,
1479
+ h: 60 * 60 * 1e3,
1480
+ d: 24 * 60 * 60 * 1e3
1481
+ };
1482
+ function parseDurationMs(input) {
1483
+ const trimmed = input.trim();
1484
+ const match = /^(\d+)([smhd])$/.exec(trimmed);
1485
+ if (!match) {
1486
+ throw new Error(
1487
+ `Invalid duration "${input}": expected <number><unit> where unit is one of s, m, h, d (e.g. "7d", "24h", "30m", "90s").`
1488
+ );
1489
+ }
1490
+ const value = Number(match[1]);
1491
+ if (value <= 0) {
1492
+ throw new Error(`Invalid duration "${input}": must be a positive value.`);
1493
+ }
1494
+ return value * DURATION_UNIT_MS[match[2]];
1495
+ }
1496
+ function selectSessionsToDelete(sessions, opts) {
1497
+ const { maxAgeMs, maxCount, nowMs, protectedIds } = opts;
1498
+ if (maxAgeMs === void 0 && maxCount === void 0) return [];
1499
+ const ageEligible = (s) => {
1500
+ if (maxAgeMs === void 0) return false;
1501
+ if (s.lastActivityMs === null) return true;
1502
+ return nowMs - s.lastActivityMs > maxAgeMs;
1503
+ };
1504
+ const countEligibleIds = /* @__PURE__ */ new Set();
1505
+ if (maxCount !== void 0) {
1506
+ const byActivityDesc = [...sessions].sort(
1507
+ (a, b) => (b.lastActivityMs ?? -Infinity) - (a.lastActivityMs ?? -Infinity)
1508
+ );
1509
+ for (const s of byActivityDesc.slice(maxCount)) {
1510
+ countEligibleIds.add(s.id);
1511
+ }
1512
+ }
1513
+ const toDelete = [];
1514
+ for (const s of sessions) {
1515
+ if (protectedIds.has(s.id)) continue;
1516
+ if (ageEligible(s) || countEligibleIds.has(s.id)) {
1517
+ toDelete.push(s.id);
1518
+ }
1519
+ }
1520
+ return toDelete;
1521
+ }
1522
+ var DEFAULT_INTERVAL = "1h";
1523
+ function resolve(flag, envValue, fallback) {
1524
+ return flag ?? envValue ?? fallback;
1525
+ }
1526
+ function parseMaxCount(input) {
1527
+ const trimmed = input.trim();
1528
+ if (!/^\d+$/.test(trimmed)) {
1529
+ throw new Error(`Invalid max-count "${input}": expected a positive integer.`);
1530
+ }
1531
+ const value = Number(trimmed);
1532
+ if (value <= 0) {
1533
+ throw new Error(`Invalid max-count "${input}": must be greater than 0.`);
1534
+ }
1535
+ return value;
1536
+ }
1537
+ function resolveSessionCleanupConfig(flags, env = process.env) {
1538
+ const warnings = [];
1539
+ const maxAgeRaw = resolve(flags.maxAge, env.EVIDENT_SESSION_CLEANUP_MAX_AGE);
1540
+ const maxCountRaw = resolve(flags.maxCount, env.EVIDENT_SESSION_CLEANUP_MAX_COUNT);
1541
+ const intervalRaw = resolve(
1542
+ flags.interval,
1543
+ env.EVIDENT_SESSION_CLEANUP_INTERVAL,
1544
+ DEFAULT_INTERVAL
1545
+ );
1546
+ let maxAgeMs;
1547
+ if (maxAgeRaw !== void 0) {
1548
+ try {
1549
+ maxAgeMs = parseDurationMs(maxAgeRaw);
1550
+ } catch (err) {
1551
+ warnings.push(
1552
+ `Ignoring invalid --session-cleanup-max-age: ${err instanceof Error ? err.message : String(err)}`
1553
+ );
1554
+ }
1555
+ }
1556
+ let maxCount;
1557
+ if (maxCountRaw !== void 0) {
1558
+ try {
1559
+ maxCount = parseMaxCount(maxCountRaw);
1560
+ } catch (err) {
1561
+ warnings.push(
1562
+ `Ignoring invalid --session-cleanup-max-count: ${err instanceof Error ? err.message : String(err)}`
1563
+ );
1564
+ }
1565
+ }
1566
+ let intervalMs;
1567
+ try {
1568
+ intervalMs = parseDurationMs(intervalRaw ?? DEFAULT_INTERVAL);
1569
+ } catch (err) {
1570
+ warnings.push(
1571
+ `Ignoring invalid --session-cleanup-interval, using default ${DEFAULT_INTERVAL}: ${err instanceof Error ? err.message : String(err)}`
1572
+ );
1573
+ intervalMs = parseDurationMs(DEFAULT_INTERVAL);
1574
+ }
1575
+ const enabled = maxAgeMs !== void 0 || maxCount !== void 0;
1576
+ return { enabled, maxAgeMs, maxCount, intervalMs, warnings };
1577
+ }
1578
+
1227
1579
  // src/lib/tunnel/connection.ts
1228
1580
  import WebSocket2 from "ws";
1229
1581
 
@@ -1314,12 +1666,12 @@ var StreamForwarder = class {
1314
1666
  let endBody;
1315
1667
  if (has_body) {
1316
1668
  const chunks = [];
1317
- bodyPromise = new Promise((resolve) => {
1669
+ bodyPromise = new Promise((resolve2) => {
1318
1670
  pushBody = (buf) => {
1319
1671
  chunks.push(buf);
1320
1672
  };
1321
1673
  endBody = () => {
1322
- resolve(Buffer.concat(chunks));
1674
+ resolve2(Buffer.concat(chunks));
1323
1675
  };
1324
1676
  });
1325
1677
  }
@@ -1437,7 +1789,7 @@ function connectTunnel(options) {
1437
1789
  } = options;
1438
1790
  const tunnelUrl = getTunnelUrlConfig();
1439
1791
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
1440
- return new Promise((resolve, reject) => {
1792
+ return new Promise((resolve2, reject) => {
1441
1793
  const ws = new WebSocket2(url, {
1442
1794
  headers: {
1443
1795
  Authorization: authHeader
@@ -1502,7 +1854,7 @@ function connectTunnel(options) {
1502
1854
  clearTimeout(connectionTimeout);
1503
1855
  const connectedAgentId = message.agent_id ?? agentId;
1504
1856
  onConnected?.(connectedAgentId);
1505
- resolve({
1857
+ resolve2({
1506
1858
  ws,
1507
1859
  close: () => ws.close(1e3, "CLI shutdown")
1508
1860
  });
@@ -1624,6 +1976,17 @@ function messageIdOf(m) {
1624
1976
  const infoId = m.info?.id;
1625
1977
  return typeof infoId === "string" ? infoId : void 0;
1626
1978
  }
1979
+ function cleanImageMime(contentType) {
1980
+ if (!contentType) return null;
1981
+ const media = contentType.split(";")[0].trim().toLowerCase();
1982
+ return /^image\/[a-z0-9.+-]+$/.test(media) ? media : null;
1983
+ }
1984
+ var LOG_LEVELS = {
1985
+ debug: 0,
1986
+ info: 1,
1987
+ warn: 2,
1988
+ error: 3
1989
+ };
1627
1990
  var DEFAULT_RETRY_POLICY = {
1628
1991
  maxAttempts: 6,
1629
1992
  baseDelayMs: 500,
@@ -1632,6 +1995,9 @@ var DEFAULT_RETRY_POLICY = {
1632
1995
  var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
1633
1996
  var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
1634
1997
  var DEFAULT_STUCK_QUEUED_MS = 6e4;
1998
+ var HEARTBEAT_MS = 6e4;
1999
+ var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
2000
+ var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
1635
2001
  var ChannelAuthError = class extends Error {
1636
2002
  constructor(message) {
1637
2003
  super(message);
@@ -1728,6 +2094,15 @@ var ChannelDriver = class {
1728
2094
  * the row leaves the processing list, exactly like `dontRedispatch`.
1729
2095
  */
1730
2096
  doneUndeliverable = /* @__PURE__ */ new Set();
2097
+ /**
2098
+ * "Already emitted `readopt_poll_unresolved` for this row" (#229). The b1 /
2099
+ * unreadable-status re-evaluate leaf leaves the row UN-tracked so it is re-read
2100
+ * every ~2s drain until the status map becomes readable — but the server-visible
2101
+ * signal is an OUTCOME, so it must fire at most ONCE per row, not once per drain
2102
+ * (Bugbot "Re-adopt signals flood every drain"). Cleared when the row leaves the
2103
+ * processing list, exactly like `dontRedispatch`/`doneUndeliverable`.
2104
+ */
2105
+ readoptPollUnresolvedSignalled = /* @__PURE__ */ new Set();
1731
2106
  /**
1732
2107
  * "A null-id re-adopt re-dispatch is in flight, awaiting its read-back" (WI-5
1733
2108
  * Task 5.4, High-2). Since we no longer send a caller-supplied id, a re-dispatch
@@ -1742,6 +2117,15 @@ var ChannelDriver = class {
1742
2117
  * so the NEXT tick may retry exactly once more).
1743
2118
  */
1744
2119
  awaitingReadopt = /* @__PURE__ */ new Set();
2120
+ /**
2121
+ * "Already signalled `attachments_skipped` for this Evident message id" (#376).
2122
+ * The in-thread skip note is an OUTCOME, so it must fire AT MOST ONCE per message
2123
+ * — never re-post on a re-dispatch of the same row (`forceReadoptRun` or the
2124
+ * next-tick null-id retry both re-run `sendPromptAsync`, which re-fires
2125
+ * `onOutcomes`). Mirrors `readoptPollUnresolvedSignalled`: a local dedup on the
2126
+ * outcome, not the dispatch. Not cleared (a message is signalled once for life).
2127
+ */
2128
+ attachmentsSkippedSignalled = /* @__PURE__ */ new Set();
1745
2129
  /**
1746
2130
  * Cache of the opencode root directory (from `GET /path`). Resolved lazily on
1747
2131
  * first session creation so drain-created sessions are rooted at the project
@@ -1759,6 +2143,16 @@ var ChannelDriver = class {
1759
2143
  * entry = not yet resolved; `null` = resolved root (stop walking).
1760
2144
  */
1761
2145
  sessionParents = /* @__PURE__ */ new Map();
2146
+ /**
2147
+ * Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
2148
+ * NON-EMPTY name is stored (terminal — a real session name won't later un-name),
2149
+ * so we do NOT re-GET `/session/:id` every tick. A missing entry = not yet
2150
+ * resolved OR resolved-but-still-empty → re-fetch on next need, since OpenCode
2151
+ * names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
2152
+ * the watcher completion path AND the restart-recovery re-adopt path (which has
2153
+ * no watcher) can resolve the title.
2154
+ */
2155
+ sessionTitles = /* @__PURE__ */ new Map();
1762
2156
  /** Serialises drains so a reconnect during a drain doesn't double-process. */
1763
2157
  draining = false;
1764
2158
  /**
@@ -1796,9 +2190,6 @@ var ChannelDriver = class {
1796
2190
  get opencodeBase() {
1797
2191
  return `http://127.0.0.1:${this.port}`;
1798
2192
  }
1799
- // -------------------------------------------------------------------------
1800
- // Public API
1801
- // -------------------------------------------------------------------------
1802
2193
  /**
1803
2194
  * Drain all pending channel conversations once: poll → dispatch → register.
1804
2195
  * Called on tunnel `connected` (WI-CHAN-4) and on each poll tick by `run.ts`.
@@ -1854,6 +2245,28 @@ var ChannelDriver = class {
1854
2245
  }
1855
2246
  return false;
1856
2247
  }
2248
+ /**
2249
+ * OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
2250
+ * exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
2251
+ * `watchers` entry whose `inFlight` set is non-empty — the same predicate
2252
+ * `hasInFlightWatchers()` uses, lifted to return the ids.
2253
+ *
2254
+ * Deliberately does NOT include `this.sessions` (the permanent, never-pruned
2255
+ * conversation→session cache). Protecting every bound-but-idle session there
2256
+ * would shield nearly every session and defeat cleanup — AND it is unnecessary:
2257
+ * `ensureSession` is self-healing (it recreates a session whose id no longer
2258
+ * exists), so deleting an idle bound session is harmless — the conversation's
2259
+ * next turn transparently rebinds a fresh one. The only thing worth protecting
2260
+ * is a session with a turn ACTIVELY in flight right now: tearing that down
2261
+ * mid-turn would strand the running `prompt_async`. Idle sessions are fair game.
2262
+ */
2263
+ protectedSessionIds() {
2264
+ const ids = /* @__PURE__ */ new Set();
2265
+ for (const [sessionId, watcher] of this.watchers) {
2266
+ if (watcher.inFlight.size > 0) ids.add(sessionId);
2267
+ }
2268
+ return ids;
2269
+ }
1857
2270
  /**
1858
2271
  * Begin a graceful stop: stop accepting NEW channel work. Idempotent. After
1859
2272
  * this, `drainPending()` is a no-op (returns 0), so no new message is dispatched
@@ -1918,9 +2331,7 @@ var ChannelDriver = class {
1918
2331
  if (!stillLive) return;
1919
2332
  }
1920
2333
  }
1921
- // -------------------------------------------------------------------------
1922
2334
  // Conversation processing (WI-3 — async dispatch)
1923
- // -------------------------------------------------------------------------
1924
2335
  /**
1925
2336
  * Dispatch each pending message for a conversation to opencode's native queue
1926
2337
  * via `prompt_async` (Task 3.2) and register it with the conversation's
@@ -1952,13 +2363,24 @@ var ChannelDriver = class {
1952
2363
  conversation_id: conv.id,
1953
2364
  message_id: message.id
1954
2365
  });
2366
+ const sendAttachments = this.buildSendAttachments(conv, message);
1955
2367
  opencodeMessageId = await this.dispatchLocked(
1956
2368
  sessionId,
1957
- () => sendPromptAsync(this.port, sessionId, message.content, options)
2369
+ () => sendPromptAsync(this.port, sessionId, message.content, options, sendAttachments)
1958
2370
  );
1959
2371
  } catch (err) {
1960
2372
  if (err instanceof ChannelAuthError) throw err;
1961
2373
  this.dispatched.delete(message.id);
2374
+ if (await sessionExists(this.port, sessionId) === false) {
2375
+ this.sessions.delete(conv.id);
2376
+ this.log({
2377
+ level: "warn",
2378
+ 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.`,
2379
+ conversation_id: conv.id,
2380
+ message_id: message.id
2381
+ });
2382
+ break;
2383
+ }
1962
2384
  await this.markFailed(conv.id, message.id).catch(() => {
1963
2385
  });
1964
2386
  this.log({
@@ -1971,7 +2393,7 @@ var ChannelDriver = class {
1971
2393
  }
1972
2394
  if (opencodeMessageId === null) {
1973
2395
  this.log({
1974
- level: "error",
2396
+ level: "warn",
1975
2397
  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`,
1976
2398
  conversation_id: conv.id,
1977
2399
  message_id: message.id
@@ -1985,7 +2407,7 @@ var ChannelDriver = class {
1985
2407
  }
1986
2408
  if (messages.length > 0 && dispatched === 0 && skippedAlreadyDispatched === messages.length) {
1987
2409
  this.log({
1988
- level: "error",
2410
+ level: "warn",
1989
2411
  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).`,
1990
2412
  conversation_id: conv.id
1991
2413
  });
@@ -1994,16 +2416,33 @@ var ChannelDriver = class {
1994
2416
  return dispatched;
1995
2417
  }
1996
2418
  async ensureSession(conv) {
1997
- const cached = this.sessions.get(conv.id);
1998
- if (cached) return cached;
1999
- if (conv.opencode_session_id) {
2000
- this.sessions.set(conv.id, conv.opencode_session_id);
2001
- return conv.opencode_session_id;
2419
+ const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
2420
+ if (bound) {
2421
+ const exists = await sessionExists(this.port, bound);
2422
+ if (exists === false) {
2423
+ this.log({
2424
+ level: "debug",
2425
+ 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.`,
2426
+ conversation_id: conv.id
2427
+ });
2428
+ this.sessions.delete(conv.id);
2429
+ return this.createAndBindSession(conv.id);
2430
+ }
2431
+ this.sessions.set(conv.id, bound);
2432
+ return bound;
2002
2433
  }
2434
+ return this.createAndBindSession(conv.id);
2435
+ }
2436
+ /**
2437
+ * Create a fresh OpenCode session for a conversation, cache the binding, and
2438
+ * best-effort persist it server-side. Shared by the first-ever bind and the
2439
+ * self-heal recreate path in `ensureSession`.
2440
+ */
2441
+ async createAndBindSession(conversationId) {
2003
2442
  const directory = await this.resolveOpenCodeDirectory();
2004
2443
  const sessionId = await createOpenCodeSession(this.port, directory);
2005
- this.sessions.set(conv.id, sessionId);
2006
- await this.persistSession(conv.id, sessionId).catch(() => {
2444
+ this.sessions.set(conversationId, sessionId);
2445
+ await this.persistSession(conversationId, sessionId).catch(() => {
2007
2446
  });
2008
2447
  return sessionId;
2009
2448
  }
@@ -2017,15 +2456,13 @@ var ChannelDriver = class {
2017
2456
  this.opencodeDirectory = await getOpenCodeDirectory(this.port);
2018
2457
  if (!this.opencodeDirectory) {
2019
2458
  this.log({
2020
- level: "info",
2459
+ level: "warn",
2021
2460
  message: "Could not determine opencode directory (GET /path) \u2014 new sessions may not appear in opencode web"
2022
2461
  });
2023
2462
  }
2024
2463
  return this.opencodeDirectory;
2025
2464
  }
2026
- // -------------------------------------------------------------------------
2027
2465
  // Per-session watcher (WI-3)
2028
- // -------------------------------------------------------------------------
2029
2466
  /**
2030
2467
  * Run one dispatch (`sendPromptAsync` snapshot→POST→read-back) serialized per
2031
2468
  * opencode session (Task 2.1a), so two dispatches into the SAME session can
@@ -2045,6 +2482,103 @@ var ChannelDriver = class {
2045
2482
  );
2046
2483
  return run2;
2047
2484
  }
2485
+ // Inbound image attachments (#255, WI-8)
2486
+ /**
2487
+ * Build the `SendAttachmentsInput` for a message's inbound images, or
2488
+ * `undefined` when the message has none (so a text-only turn is unchanged).
2489
+ *
2490
+ * The driver OWNS the two channel-facing concerns the session module cannot:
2491
+ * - the AUTHENTICATED byte fetch through Evident's WI-6 endpoint
2492
+ * (`fetchAttachmentDataUrl`), using the SAME `getAuthHeader()` as every
2493
+ * other combinedAuth callback — the CLI NEVER talks to Slack directly;
2494
+ * - the in-thread SKIP NOTE (`signalAttachmentsSkipped`) posted over the
2495
+ * existing callback surface when any image was skipped/failed.
2496
+ * `sendPromptAsync` applies the capability gate + appends the `file` parts and
2497
+ * reports outcomes back via `onOutcomes`.
2498
+ */
2499
+ buildSendAttachments(conv, message) {
2500
+ const refs = message.attachments;
2501
+ if (!refs || refs.length === 0) return void 0;
2502
+ return {
2503
+ inputs: refs.map((a, index) => ({
2504
+ index,
2505
+ mime: a.mime,
2506
+ ...a.filename ? { filename: a.filename } : {}
2507
+ })),
2508
+ fetchDataUrl: (index) => this.fetchAttachmentDataUrl(message.id, index, refs[index].mime),
2509
+ onOutcomes: ({ outcomes, capabilityUnknown }) => this.signalAttachmentsSkipped(conv.id, message.id, outcomes, capabilityUnknown)
2510
+ };
2511
+ }
2512
+ /**
2513
+ * Fetch ONE inbound image's bytes through Evident's WI-6 endpoint
2514
+ * (`GET {apiUrl}/agents/{agentId}/attachments/{messageId}/{index}`) using the
2515
+ * existing authenticated fetch, and base64-encode into a
2516
+ * `data:<mime>;base64,<…>` URL for the opencode `file` part's `url`.
2517
+ *
2518
+ * The endpoint streams the source bytes verbatim (200), or returns 404
2519
+ * (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
2520
+ * (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
2521
+ * OMITS that one image and the text turn still sends — NEVER throws the turn.
2522
+ * Failures are logged with context (no silent swallow).
2523
+ */
2524
+ async fetchAttachmentDataUrl(messageId, index, mime) {
2525
+ try {
2526
+ const res = await this.fetchImpl(
2527
+ `${this.apiUrl}/agents/${this.agentId}/attachments/${messageId}/${index}`,
2528
+ { headers: { Authorization: this.getAuthHeader() } }
2529
+ );
2530
+ if (!res.ok) {
2531
+ this.log({
2532
+ level: "error",
2533
+ message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
2534
+ message_id: messageId
2535
+ });
2536
+ return null;
2537
+ }
2538
+ const buf = await res.arrayBuffer();
2539
+ const base64 = Buffer.from(buf).toString("base64");
2540
+ const dataMime = cleanImageMime(res.headers.get("content-type")) || mime;
2541
+ return `data:${dataMime};base64,${base64}`;
2542
+ } catch (err) {
2543
+ this.log({
2544
+ level: "error",
2545
+ 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)}`,
2546
+ message_id: messageId
2547
+ });
2548
+ return null;
2549
+ }
2550
+ }
2551
+ /**
2552
+ * On any skipped/failed image, post an in-thread note to Evident over the
2553
+ * EXISTING combinedAuth callback surface — the CLI NEVER posts to Slack directly.
2554
+ * Evident routes the note to source via `conversation.deliver`.
2555
+ *
2556
+ * The `POST .../messages/:id/signal` route accepts `attachments_skipped` (in
2557
+ * `messageSignalSchema`) and turns it into an in-thread note delivered through
2558
+ * `conversation.deliver` (e.g. "N image(s) couldn't be forwarded"), so the note
2559
+ * reaches the channel.
2560
+ *
2561
+ * Fire-and-forget: never throws into the send/tick (logs its own failure).
2562
+ */
2563
+ signalAttachmentsSkipped(conversationId, messageId, outcomes, capabilityUnknown) {
2564
+ const skipped = outcomes.filter((o) => o.status === "skipped").length;
2565
+ const failed = outcomes.filter((o) => o.status === "failed").length;
2566
+ if (skipped === 0 && failed === 0) return;
2567
+ if (this.attachmentsSkippedSignalled.has(messageId)) return;
2568
+ this.attachmentsSkippedSignalled.add(messageId);
2569
+ const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
2570
+ this.log({
2571
+ level: "info",
2572
+ 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`,
2573
+ conversation_id: conversationId,
2574
+ message_id: messageId
2575
+ });
2576
+ void this.postSignal(conversationId, messageId, "attachments_skipped", {
2577
+ skipped,
2578
+ failed,
2579
+ ...skipped > 0 ? { skipped_reason: skippedReason } : {}
2580
+ });
2581
+ }
2048
2582
  /** Register a freshly-dispatched message with its session's watcher state. */
2049
2583
  registerInFlight(conv, sessionId, message, opencodeMessageId) {
2050
2584
  let watcher = this.watchers.get(sessionId);
@@ -2054,7 +2588,9 @@ var ChannelDriver = class {
2054
2588
  inFlight: /* @__PURE__ */ new Map(),
2055
2589
  loop: null,
2056
2590
  reportedQuestions: /* @__PURE__ */ new Set(),
2057
- reportedPermissions: /* @__PURE__ */ new Set()
2591
+ reportedPermissions: /* @__PURE__ */ new Set(),
2592
+ lastGoodPollAt: this.now(),
2593
+ hadUsablePoll: false
2058
2594
  };
2059
2595
  this.watchers.set(sessionId, watcher);
2060
2596
  }
@@ -2064,20 +2600,37 @@ var ChannelDriver = class {
2064
2600
  opencodeMessageId,
2065
2601
  message,
2066
2602
  dispatchedAt: now,
2603
+ processingAnchorMs: now,
2067
2604
  deadline: now + this.pausedMaxWaitMs,
2068
2605
  started: false,
2069
2606
  done: false,
2070
- stuckReported: false
2607
+ stuckReported: false,
2608
+ lastAliveAt: 0,
2609
+ aliveInFlight: false,
2610
+ awaitingHumanLatched: false,
2611
+ pausedOnQuestion: false,
2612
+ pausedOnPermission: false,
2613
+ pausedClearConfirmed: false,
2614
+ pausedInFlight: false,
2615
+ deliveryDeadlineAnchored: false
2071
2616
  });
2072
2617
  }
2073
2618
  /**
2074
2619
  * Register a RE-ADOPTED `processing` message with its session watcher
2075
2620
  * (ADR-0046, WI-4). Mirrors `registerInFlight` but anchors the give-up
2076
2621
  * `deadline` to the row's SERVER-SIDE `processed_at` (Invariant 1), NEVER to
2077
- * `now`: a row already `processing` for e.g. 5 min must give up ~5 min from now
2078
- * (10 min after `processed_at`), not 10 min from now — otherwise its deadline
2079
- * lands ~15 min after `processed_at`, coinciding with the cron reset →
2080
- * double-drive race. `dispatchedAt` stays `now` (only the appear-guard uses it).
2622
+ * `now`, so the paused/queued/unreachable cases settle on the same wall-clock a
2623
+ * fresh dispatch would (10 min after `processed_at`, not 10 min from now).
2624
+ *
2625
+ * This re-attaches into the SAME watcher, so the ADR-0047 progressing-vs-paused
2626
+ * give-up (`serviceInFlightMessage`) applies unchanged: a re-adopted turn
2627
+ * opencode reports ACTIVELY `running` is watched to completion (its liveness
2628
+ * heartbeat keeps the cron off its row), while a re-adopted turn that is paused
2629
+ * awaiting a human — or queued/unreachable — is still bounded by `deadline` and
2630
+ * handed to the cron. The old "the `deadline` must settle before the ~15-min
2631
+ * cron or they double-drive" reasoning is superseded: liveness now settles the
2632
+ * actively-running case; `deadline` settles the rest. `dispatchedAt` stays `now`
2633
+ * (only the appear-guard uses it).
2081
2634
  *
2082
2635
  * `evidentMessageId` addresses the SERVER row (for markProcessing/markDone);
2083
2636
  * `opencodeMessageId` is the id the watcher polls for a reply — for the orphan
@@ -2095,7 +2648,9 @@ var ChannelDriver = class {
2095
2648
  inFlight: /* @__PURE__ */ new Map(),
2096
2649
  loop: null,
2097
2650
  reportedQuestions: /* @__PURE__ */ new Set(),
2098
- reportedPermissions: /* @__PURE__ */ new Set()
2651
+ reportedPermissions: /* @__PURE__ */ new Set(),
2652
+ lastGoodPollAt: this.now(),
2653
+ hadUsablePoll: false
2099
2654
  };
2100
2655
  this.watchers.set(sessionId, watcher);
2101
2656
  }
@@ -2104,6 +2659,10 @@ var ChannelDriver = class {
2104
2659
  opencodeMessageId,
2105
2660
  message,
2106
2661
  dispatchedAt: this.now(),
2662
+ // Anchor the absolute-age ceiling to the SERVER-SIDE `processed_at` (the same
2663
+ // value seeding `deadline`), NOT `dispatchedAt` — so a re-adopted zombie's age
2664
+ // reflects the real turn duration and the ceiling fires on the ORIGINAL turn.
2665
+ processingAnchorMs: processedAtMs,
2107
2666
  deadline: processedAtMs + this.pausedMaxWaitMs,
2108
2667
  // The server row is ALREADY `processing`; do not re-fire markProcessing.
2109
2668
  started: true,
@@ -2113,7 +2672,20 @@ var ChannelDriver = class {
2113
2672
  // on `state === 'queued'` (turn produced no reply), not on `started`, so a
2114
2673
  // re-adopted row left wedged in `queued` still emits the signal once
2115
2674
  // (#210/#220 observability).
2116
- stuckReported: false
2675
+ stuckReported: false,
2676
+ // Task 5.2: a re-adopted actively-running row re-attaches into the SAME
2677
+ // watcher and so hits the SAME actively-running heartbeat branch in
2678
+ // `serviceInFlightMessage` as a fresh dispatch — monitoring observes "runner
2679
+ // re-adopted and is confirming this row alive" via that `alive` heartbeat,
2680
+ // with no extra `re_adopted` signal needed (folds old WI-6).
2681
+ lastAliveAt: 0,
2682
+ aliveInFlight: false,
2683
+ awaitingHumanLatched: false,
2684
+ pausedOnQuestion: false,
2685
+ pausedOnPermission: false,
2686
+ pausedClearConfirmed: false,
2687
+ pausedInFlight: false,
2688
+ deliveryDeadlineAnchored: false
2117
2689
  });
2118
2690
  }
2119
2691
  /**
@@ -2164,12 +2736,30 @@ var ChannelDriver = class {
2164
2736
  messages = Array.isArray(body) ? body : null;
2165
2737
  }
2166
2738
  } catch {
2167
- continue;
2168
2739
  }
2740
+ if (messages != null && messages.length > 0) {
2741
+ watcher.lastGoodPollAt = this.now();
2742
+ watcher.hadUsablePoll = true;
2743
+ } else {
2744
+ const emptyButReachable = messages != null;
2745
+ const graceApplies = !emptyButReachable || watcher.hadUsablePoll;
2746
+ if (graceApplies && this.now() - watcher.lastGoodPollAt < POLL_MISS_GRACE_MS) {
2747
+ continue;
2748
+ }
2749
+ }
2750
+ const { openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk } = await this.pollInteractions(sessionId, watcher, messages);
2169
2751
  for (const inFlight of [...watcher.inFlight.values()]) {
2170
- await this.serviceInFlightMessage(sessionId, watcher, inFlight, messages);
2752
+ await this.serviceInFlightMessage(
2753
+ sessionId,
2754
+ watcher,
2755
+ inFlight,
2756
+ messages,
2757
+ openQuestions,
2758
+ openPermissions,
2759
+ questionsPolledOk,
2760
+ permissionsPolledOk
2761
+ );
2171
2762
  }
2172
- await this.pollInteractions(sessionId, watcher, messages);
2173
2763
  }
2174
2764
  } catch (err) {
2175
2765
  if (err instanceof ChannelAuthError) {
@@ -2191,28 +2781,55 @@ var ChannelDriver = class {
2191
2781
  });
2192
2782
  }
2193
2783
  }
2784
+ /**
2785
+ * On FIRST observing a terminal (done/failed) state, ensure the delivery
2786
+ * (markDone/markFailed) transient-retry path has a real window. A long
2787
+ * ACTIVELY-running turn is kept past its original `deadline`, so by completion
2788
+ * `now >= deadline` already holds and the retry bound below would fire on the
2789
+ * first transient PATCH failure — dropping the message before its reply lands
2790
+ * (Bugbot "Stale deadline aborts long-turn delivery"). Re-anchor once (latched)
2791
+ * to a fresh `pausedMaxWaitMs` window; only extend if the current deadline is at
2792
+ * or past now, so a still-ample window is left untouched.
2793
+ */
2794
+ anchorDeliveryDeadline(inFlight) {
2795
+ if (inFlight.deliveryDeadlineAnchored) return;
2796
+ inFlight.deliveryDeadlineAnchored = true;
2797
+ if (this.now() >= inFlight.deadline) {
2798
+ inFlight.deadline = this.now() + this.pausedMaxWaitMs;
2799
+ }
2800
+ }
2194
2801
  /**
2195
2802
  * Drive ONE in-flight message's lifecycle from the tick's message snapshot.
2196
2803
  * Fires markProcessing on queued→running and markDone on done (each once),
2197
2804
  * applies the idle-path re-dispatch guard, and removes the message from the
2198
2805
  * in-flight set on completion or timeout.
2199
2806
  */
2200
- async serviceInFlightMessage(sessionId, watcher, inFlight, messages) {
2807
+ async serviceInFlightMessage(sessionId, watcher, inFlight, messages, openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk) {
2201
2808
  const conv = watcher.conv;
2202
2809
  const state = messageRunState(messages, inFlight.opencodeMessageId);
2810
+ const id = inFlight.evidentMessageId;
2811
+ if (openQuestions.has(id)) inFlight.pausedOnQuestion = true;
2812
+ else if (questionsPolledOk) inFlight.pausedOnQuestion = false;
2813
+ if (openPermissions.has(id)) inFlight.pausedOnPermission = true;
2814
+ else if (permissionsPolledOk) inFlight.pausedOnPermission = false;
2815
+ const observedOpen = openQuestions.has(id) || openPermissions.has(id);
2816
+ const latchedPaused = inFlight.pausedOnQuestion || inFlight.pausedOnPermission;
2817
+ const awaitingHuman = observedOpen || latchedPaused;
2203
2818
  if ((state === "running" || state === "done" || state === "failed") && !inFlight.started) {
2819
+ const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
2204
2820
  let claimed;
2205
2821
  try {
2206
2822
  claimed = await this.markProcessing(
2207
2823
  conv.id,
2208
2824
  inFlight.evidentMessageId,
2209
2825
  sessionId,
2210
- inFlight.opencodeMessageId
2826
+ inFlight.opencodeMessageId,
2827
+ title
2211
2828
  );
2212
2829
  } catch (err) {
2213
2830
  if (err instanceof ChannelAuthError) throw err;
2214
2831
  this.log({
2215
- level: "error",
2832
+ level: "warn",
2216
2833
  message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2217
2834
  conversation_id: conv.id,
2218
2835
  message_id: inFlight.evidentMessageId
@@ -2222,7 +2839,7 @@ var ChannelDriver = class {
2222
2839
  inFlight.started = true;
2223
2840
  if (!claimed) {
2224
2841
  this.log({
2225
- level: "info",
2842
+ level: "debug",
2226
2843
  message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
2227
2844
  conversation_id: conv.id,
2228
2845
  message_id: inFlight.evidentMessageId
@@ -2230,6 +2847,7 @@ var ChannelDriver = class {
2230
2847
  }
2231
2848
  }
2232
2849
  if (state === "done") {
2850
+ this.anchorDeliveryDeadline(inFlight);
2233
2851
  if (!inFlight.done) {
2234
2852
  this.log({
2235
2853
  level: "info",
@@ -2237,18 +2855,22 @@ var ChannelDriver = class {
2237
2855
  conversation_id: conv.id,
2238
2856
  message_id: inFlight.evidentMessageId
2239
2857
  });
2858
+ const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
2859
+ const usage = messageUsage(messages, inFlight.opencodeMessageId);
2240
2860
  try {
2241
2861
  await this.markDone(
2242
2862
  conv.id,
2243
2863
  inFlight.evidentMessageId,
2244
2864
  sessionId,
2245
- inFlight.opencodeMessageId
2865
+ inFlight.opencodeMessageId,
2866
+ title,
2867
+ usage
2246
2868
  );
2247
2869
  } catch (err) {
2248
2870
  if (err instanceof ChannelAuthError) throw err;
2249
2871
  if (err instanceof ChannelTerminalError) {
2250
2872
  this.log({
2251
- level: "error",
2873
+ level: "warn",
2252
2874
  message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
2253
2875
  conversation_id: conv.id,
2254
2876
  message_id: inFlight.evidentMessageId
@@ -2258,7 +2880,7 @@ var ChannelDriver = class {
2258
2880
  }
2259
2881
  if (this.now() >= inFlight.deadline) {
2260
2882
  this.log({
2261
- level: "error",
2883
+ level: "warn",
2262
2884
  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)}`,
2263
2885
  conversation_id: conv.id,
2264
2886
  message_id: inFlight.evidentMessageId
@@ -2267,7 +2889,7 @@ var ChannelDriver = class {
2267
2889
  return;
2268
2890
  }
2269
2891
  this.log({
2270
- level: "error",
2892
+ level: "warn",
2271
2893
  message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2272
2894
  conversation_id: conv.id,
2273
2895
  message_id: inFlight.evidentMessageId
@@ -2280,6 +2902,7 @@ var ChannelDriver = class {
2280
2902
  return;
2281
2903
  }
2282
2904
  if (state === "failed") {
2905
+ this.anchorDeliveryDeadline(inFlight);
2283
2906
  if (!inFlight.done) {
2284
2907
  const error2 = messageError(messages, inFlight.opencodeMessageId) ?? void 0;
2285
2908
  this.log({
@@ -2288,13 +2911,14 @@ var ChannelDriver = class {
2288
2911
  conversation_id: conv.id,
2289
2912
  message_id: inFlight.evidentMessageId
2290
2913
  });
2914
+ const usage = messageUsage(messages, inFlight.opencodeMessageId);
2291
2915
  try {
2292
- await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2);
2916
+ await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2, usage);
2293
2917
  } catch (err) {
2294
2918
  if (err instanceof ChannelAuthError) throw err;
2295
2919
  if (err instanceof ChannelTerminalError) {
2296
2920
  this.log({
2297
- level: "error",
2921
+ level: "warn",
2298
2922
  message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} failed (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
2299
2923
  conversation_id: conv.id,
2300
2924
  message_id: inFlight.evidentMessageId
@@ -2304,7 +2928,7 @@ var ChannelDriver = class {
2304
2928
  }
2305
2929
  if (this.now() >= inFlight.deadline) {
2306
2930
  this.log({
2307
- level: "error",
2931
+ level: "warn",
2308
2932
  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)}`,
2309
2933
  conversation_id: conv.id,
2310
2934
  message_id: inFlight.evidentMessageId
@@ -2313,7 +2937,7 @@ var ChannelDriver = class {
2313
2937
  return;
2314
2938
  }
2315
2939
  this.log({
2316
- level: "error",
2940
+ level: "warn",
2317
2941
  message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} failed (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2318
2942
  conversation_id: conv.id,
2319
2943
  message_id: inFlight.evidentMessageId
@@ -2333,9 +2957,53 @@ var ChannelDriver = class {
2333
2957
  stuck_for_ms: this.now() - inFlight.dispatchedAt
2334
2958
  });
2335
2959
  }
2336
- if (this.now() >= inFlight.deadline) {
2960
+ const activelyRunning = state === "running" && !awaitingHuman;
2961
+ if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
2337
2962
  this.log({
2338
- level: "info",
2963
+ level: "warn",
2964
+ 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`,
2965
+ conversation_id: conv.id,
2966
+ message_id: inFlight.evidentMessageId
2967
+ });
2968
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "gave_up", {
2969
+ watched_for_ms: this.now() - inFlight.processingAnchorMs
2970
+ });
2971
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
2972
+ return;
2973
+ }
2974
+ if (activelyRunning && !inFlight.awaitingHumanLatched && !inFlight.aliveInFlight && this.now() - inFlight.lastAliveAt >= HEARTBEAT_MS) {
2975
+ inFlight.aliveInFlight = true;
2976
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "alive").then((ok) => {
2977
+ inFlight.aliveInFlight = false;
2978
+ if (ok) inFlight.lastAliveAt = this.now();
2979
+ });
2980
+ }
2981
+ if (awaitingHuman) {
2982
+ if (!inFlight.awaitingHumanLatched) {
2983
+ inFlight.deadline = this.now() + this.pausedMaxWaitMs;
2984
+ inFlight.awaitingHumanLatched = true;
2985
+ }
2986
+ if (!inFlight.pausedClearConfirmed && !inFlight.pausedInFlight) {
2987
+ inFlight.pausedInFlight = true;
2988
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "paused").then((ok) => {
2989
+ inFlight.pausedInFlight = false;
2990
+ if (ok && inFlight.awaitingHumanLatched) inFlight.pausedClearConfirmed = true;
2991
+ });
2992
+ }
2993
+ } else if (inFlight.awaitingHumanLatched) {
2994
+ inFlight.awaitingHumanLatched = false;
2995
+ inFlight.pausedOnQuestion = false;
2996
+ inFlight.pausedOnPermission = false;
2997
+ inFlight.pausedClearConfirmed = false;
2998
+ }
2999
+ const siblingPaused = (sib) => openQuestions.has(sib.evidentMessageId) || openPermissions.has(sib.evidentMessageId) || sib.awaitingHumanLatched || sib.pausedOnQuestion || sib.pausedOnPermission;
3000
+ const hasActivelyRunningSibling = [...watcher.inFlight.values()].some(
3001
+ (sib) => sib.evidentMessageId !== inFlight.evidentMessageId && messageRunState(messages, sib.opencodeMessageId) === "running" && !siblingPaused(sib)
3002
+ );
3003
+ const queuedBehindRunningSibling = state === "queued" && hasActivelyRunningSibling;
3004
+ if (!activelyRunning && !queuedBehindRunningSibling && this.now() >= inFlight.deadline) {
3005
+ this.log({
3006
+ level: "debug",
2339
3007
  message: `Message ${inFlight.evidentMessageId.slice(0, 8)} did not complete within the watch window \u2014 leaving for the cron safety net`,
2340
3008
  conversation_id: conv.id,
2341
3009
  message_id: inFlight.evidentMessageId
@@ -2346,9 +3014,7 @@ var ChannelDriver = class {
2346
3014
  this.removeInFlight(watcher, inFlight.evidentMessageId);
2347
3015
  }
2348
3016
  }
2349
- // -------------------------------------------------------------------------
2350
3017
  // Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
2351
- // -------------------------------------------------------------------------
2352
3018
  /**
2353
3019
  * Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
2354
3020
  *
@@ -2365,15 +3031,20 @@ var ChannelDriver = class {
2365
3031
  */
2366
3032
  async readoptProcessing() {
2367
3033
  const rows = await this.getProcessingMessages();
2368
- if (this.dontRedispatch.size > 0 || this.doneUndeliverable.size > 0) {
3034
+ if (this.dontRedispatch.size > 0 || this.doneUndeliverable.size > 0 || this.readoptPollUnresolvedSignalled.size > 0) {
2369
3035
  const stillProcessing = new Set(rows.map((r) => r.id));
2370
- for (const id of [...this.dontRedispatch, ...this.doneUndeliverable]) {
3036
+ for (const id of [
3037
+ ...this.dontRedispatch,
3038
+ ...this.doneUndeliverable,
3039
+ ...this.readoptPollUnresolvedSignalled
3040
+ ]) {
2371
3041
  if (!stillProcessing.has(id)) {
2372
3042
  const cleared = this.dontRedispatch.delete(id);
2373
3043
  const clearedUndeliverable = this.doneUndeliverable.delete(id);
3044
+ this.readoptPollUnresolvedSignalled.delete(id);
2374
3045
  if (cleared || clearedUndeliverable) {
2375
3046
  this.log({
2376
- level: "info",
3047
+ level: "debug",
2377
3048
  message: `Re-adopt: message ${id.slice(0, 8)} left the processing list (cron reset) \u2014 cleared gave-up marker`,
2378
3049
  message_id: id
2379
3050
  });
@@ -2386,7 +3057,7 @@ var ChannelDriver = class {
2386
3057
  for (const row of rows) {
2387
3058
  if (!row.opencode_session_id) {
2388
3059
  this.log({
2389
- level: "error",
3060
+ level: "warn",
2390
3061
  message: `Cannot re-adopt processing message ${row.id.slice(0, 8)} \u2014 no opencode session id; leaving for the cron safety net`,
2391
3062
  conversation_id: row.conversation_id,
2392
3063
  message_id: row.id
@@ -2403,7 +3074,7 @@ var ChannelDriver = class {
2403
3074
  const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
2404
3075
  if (!res.ok) {
2405
3076
  this.log({
2406
- level: "error",
3077
+ level: "warn",
2407
3078
  message: `Re-adopt: polling session ${sessionId.slice(0, 8)} returned HTTP ${res.status} \u2014 skipping this session this tick`
2408
3079
  });
2409
3080
  continue;
@@ -2411,7 +3082,7 @@ var ChannelDriver = class {
2411
3082
  const body = await res.json();
2412
3083
  if (!Array.isArray(body)) {
2413
3084
  this.log({
2414
- level: "error",
3085
+ level: "warn",
2415
3086
  message: `Re-adopt: polling session ${sessionId.slice(0, 8)} returned a non-array message body \u2014 skipping this session this tick`
2416
3087
  });
2417
3088
  continue;
@@ -2419,13 +3090,15 @@ var ChannelDriver = class {
2419
3090
  messages = body;
2420
3091
  } catch (err) {
2421
3092
  this.log({
2422
- level: "error",
3093
+ level: "warn",
2423
3094
  message: `Re-adopt: failed to poll session ${sessionId.slice(0, 8)} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`
2424
3095
  });
2425
3096
  continue;
2426
3097
  }
3098
+ const anyUntracked = sessionRows.some((row) => !this.isTracked(sessionId, row.id));
3099
+ const sessionOngoing = anyUntracked ? await isSessionOngoing(this.port, sessionId) : null;
2427
3100
  for (const row of sessionRows) {
2428
- await this.readoptOne(sessionId, row, messages);
3101
+ await this.readoptOne(sessionId, row, messages, sessionOngoing);
2429
3102
  }
2430
3103
  }
2431
3104
  }
@@ -2447,10 +3120,10 @@ var ChannelDriver = class {
2447
3120
  *
2448
3121
  * Only `ChannelAuthError` propagates.
2449
3122
  */
2450
- async readoptOne(sessionId, row, messages) {
3123
+ async readoptOne(sessionId, row, messages, sessionOngoing) {
2451
3124
  if (this.isTracked(sessionId, row.id)) {
2452
3125
  this.log({
2453
- level: "info",
3126
+ level: "debug",
2454
3127
  message: `Re-adopt: message ${row.id.slice(0, 8)} already tracked in-flight \u2014 skipping (owned by the watcher loop)`,
2455
3128
  conversation_id: row.conversation_id,
2456
3129
  message_id: row.id
@@ -2462,7 +3135,7 @@ var ChannelDriver = class {
2462
3135
  if (state === "done") {
2463
3136
  if (this.doneUndeliverable.has(row.id)) {
2464
3137
  this.log({
2465
- level: "info",
3138
+ level: "debug",
2466
3139
  message: `Re-adopt: message ${row.id.slice(0, 8)} markDone is terminally undeliverable \u2014 left to the cron; skipping until it leaves processing`,
2467
3140
  conversation_id: row.conversation_id,
2468
3141
  message_id: row.id
@@ -2476,21 +3149,24 @@ var ChannelDriver = class {
2476
3149
  message_id: row.id
2477
3150
  });
2478
3151
  try {
2479
- await this.markDone(row.conversation_id, row.id, sessionId, ocId);
3152
+ const title = await this.resolveSessionTitle(sessionId, row.conversation_id);
3153
+ const usage = messageUsage(messages, ocId ?? "");
3154
+ await this.markDone(row.conversation_id, row.id, sessionId, ocId, title, usage);
2480
3155
  } catch (err) {
2481
3156
  if (err instanceof ChannelAuthError) throw err;
2482
3157
  if (err instanceof ChannelTerminalError) {
2483
3158
  this.doneUndeliverable.add(row.id);
2484
3159
  this.log({
2485
- level: "error",
3160
+ level: "warn",
2486
3161
  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}`,
2487
3162
  conversation_id: row.conversation_id,
2488
3163
  message_id: row.id
2489
3164
  });
3165
+ void this.postSignal(row.conversation_id, row.id, "readopt_undeliverable");
2490
3166
  return;
2491
3167
  }
2492
3168
  this.log({
2493
- level: "error",
3169
+ level: "warn",
2494
3170
  message: `Re-adopt: failed to mark message ${row.id.slice(0, 8)} done (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
2495
3171
  conversation_id: row.conversation_id,
2496
3172
  message_id: row.id
@@ -2498,10 +3174,12 @@ var ChannelDriver = class {
2498
3174
  return;
2499
3175
  }
2500
3176
  this.dontRedispatch.delete(row.id);
3177
+ void this.postSignal(row.conversation_id, row.id, "readopt_done");
2501
3178
  return;
2502
3179
  }
2503
3180
  if (state === "failed") {
2504
3181
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
3182
+ const usage = messageUsage(messages, ocId ?? "");
2505
3183
  this.log({
2506
3184
  level: "error",
2507
3185
  message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
@@ -2509,21 +3187,22 @@ var ChannelDriver = class {
2509
3187
  message_id: row.id
2510
3188
  });
2511
3189
  try {
2512
- await this.markFailed(row.conversation_id, row.id, sessionId, error2);
3190
+ await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
2513
3191
  } catch (err) {
2514
3192
  if (err instanceof ChannelAuthError) throw err;
2515
3193
  if (err instanceof ChannelTerminalError) {
2516
3194
  this.doneUndeliverable.add(row.id);
2517
3195
  this.log({
2518
- level: "error",
3196
+ level: "warn",
2519
3197
  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}`,
2520
3198
  conversation_id: row.conversation_id,
2521
3199
  message_id: row.id
2522
3200
  });
3201
+ void this.postSignal(row.conversation_id, row.id, "readopt_undeliverable");
2523
3202
  return;
2524
3203
  }
2525
3204
  this.log({
2526
- level: "error",
3205
+ level: "warn",
2527
3206
  message: `Re-adopt: failed to mark message ${row.id.slice(0, 8)} failed (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
2528
3207
  conversation_id: row.conversation_id,
2529
3208
  message_id: row.id
@@ -2531,17 +3210,83 @@ var ChannelDriver = class {
2531
3210
  return;
2532
3211
  }
2533
3212
  this.dontRedispatch.delete(row.id);
3213
+ void this.postSignal(row.conversation_id, row.id, "readopt_failed");
2534
3214
  return;
2535
3215
  }
2536
3216
  if (this.dontRedispatch.has(row.id)) {
2537
3217
  this.log({
2538
- level: "info",
3218
+ level: "debug",
2539
3219
  message: `Re-adopt: message ${row.id.slice(0, 8)} already gave up \u2014 left to the cron; skipping until it leaves processing`,
2540
3220
  conversation_id: row.conversation_id,
2541
3221
  message_id: row.id
2542
3222
  });
2543
3223
  return;
2544
3224
  }
3225
+ let statusReadableOngoing = null;
3226
+ if (state === "running" && ocId) {
3227
+ const reply = findLastAssistantReplyFor(messages, ocId);
3228
+ const shape = this.replyCompletionShape(reply);
3229
+ const ongoing = sessionOngoing;
3230
+ statusReadableOngoing = ongoing;
3231
+ if (ongoing === false) {
3232
+ this.log({
3233
+ level: "info",
3234
+ 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)`,
3235
+ conversation_id: row.conversation_id,
3236
+ message_id: row.id
3237
+ });
3238
+ await this.forceReadoptRun(sessionId, row);
3239
+ return;
3240
+ }
3241
+ if (ongoing === true) {
3242
+ this.log({
3243
+ level: "debug",
3244
+ 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)`,
3245
+ conversation_id: row.conversation_id,
3246
+ message_id: row.id
3247
+ });
3248
+ } else {
3249
+ if (shape === "b1") {
3250
+ this.log({
3251
+ level: "debug",
3252
+ 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`,
3253
+ conversation_id: row.conversation_id,
3254
+ message_id: row.id
3255
+ });
3256
+ if (!this.readoptPollUnresolvedSignalled.has(row.id)) {
3257
+ this.readoptPollUnresolvedSignalled.add(row.id);
3258
+ void this.postSignal(row.conversation_id, row.id, "readopt_poll_unresolved");
3259
+ }
3260
+ return;
3261
+ }
3262
+ this.log({
3263
+ level: "debug",
3264
+ 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`,
3265
+ conversation_id: row.conversation_id,
3266
+ message_id: row.id
3267
+ });
3268
+ }
3269
+ }
3270
+ if (statusReadableOngoing === null && state === "running" && ocId && isPreamblePinnedRunning(messages, ocId)) {
3271
+ const descendantAlive = await this.isAnyDescendantSessionAlive(sessionId);
3272
+ if (descendantAlive === true) {
3273
+ this.log({
3274
+ level: "debug",
3275
+ 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)`,
3276
+ conversation_id: row.conversation_id,
3277
+ message_id: row.id
3278
+ });
3279
+ } else {
3280
+ this.log({
3281
+ level: "info",
3282
+ 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)" : ""}`,
3283
+ conversation_id: row.conversation_id,
3284
+ message_id: row.id
3285
+ });
3286
+ await this.forceReadoptRun(sessionId, row);
3287
+ return;
3288
+ }
3289
+ }
2545
3290
  if ((state === "running" || state === "queued") && ocId) {
2546
3291
  const conv = this.convForRow(sessionId, row);
2547
3292
  const message = this.queuedMessageForRow(row);
@@ -2550,11 +3295,12 @@ var ChannelDriver = class {
2550
3295
  this.readopted.add(row.id);
2551
3296
  this.ensureWatcherRunning(sessionId);
2552
3297
  this.log({
2553
- level: "info",
3298
+ level: "debug",
2554
3299
  message: `Re-adopt: message ${row.id.slice(0, 8)} ${state} \u2014 re-attached watcher (stored id, no re-dispatch)`,
2555
3300
  conversation_id: row.conversation_id,
2556
3301
  message_id: row.id
2557
3302
  });
3303
+ void this.postSignal(row.conversation_id, row.id, "readopt_reattached");
2558
3304
  return;
2559
3305
  }
2560
3306
  await this.forceReadoptRun(sessionId, row);
@@ -2583,7 +3329,7 @@ var ChannelDriver = class {
2583
3329
  async forceReadoptRun(sessionId, row) {
2584
3330
  if (this.stopped) {
2585
3331
  this.log({
2586
- level: "info",
3332
+ level: "debug",
2587
3333
  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`,
2588
3334
  conversation_id: row.conversation_id,
2589
3335
  message_id: row.id
@@ -2592,7 +3338,7 @@ var ChannelDriver = class {
2592
3338
  }
2593
3339
  if (this.awaitingReadopt.has(row.id)) {
2594
3340
  this.log({
2595
- level: "info",
3341
+ level: "debug",
2596
3342
  message: `Re-adopt: message ${row.id.slice(0, 8)} already has a re-dispatch awaiting read-back \u2014 skipping (at most once)`,
2597
3343
  conversation_id: row.conversation_id,
2598
3344
  message_id: row.id
@@ -2602,11 +3348,12 @@ var ChannelDriver = class {
2602
3348
  if (this.processedAtMs(row) + this.pausedMaxWaitMs <= this.now()) {
2603
3349
  this.dontRedispatch.add(row.id);
2604
3350
  this.log({
2605
- level: "info",
3351
+ level: "debug",
2606
3352
  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)`,
2607
3353
  conversation_id: row.conversation_id,
2608
3354
  message_id: row.id
2609
3355
  });
3356
+ void this.postSignal(row.conversation_id, row.id, "readopt_window_elapsed");
2610
3357
  return;
2611
3358
  }
2612
3359
  const options = {
@@ -2620,40 +3367,44 @@ var ChannelDriver = class {
2620
3367
  message_id: row.id
2621
3368
  });
2622
3369
  this.awaitingReadopt.add(row.id);
3370
+ const readoptConv = this.convForRow(sessionId, row);
3371
+ const readoptMessage = this.queuedMessageForRow(row);
3372
+ const sendAttachments = this.buildSendAttachments(readoptConv, readoptMessage);
2623
3373
  let ocId;
2624
3374
  try {
2625
3375
  ocId = await this.dispatchLocked(
2626
3376
  sessionId,
2627
- () => sendPromptAsync(this.port, sessionId, row.content, options)
3377
+ () => sendPromptAsync(this.port, sessionId, row.content, options, sendAttachments)
2628
3378
  );
2629
3379
  } catch (err) {
2630
3380
  this.awaitingReadopt.delete(row.id);
2631
3381
  if (err instanceof ChannelAuthError) throw err;
2632
3382
  this.log({
2633
- level: "error",
3383
+ level: "warn",
2634
3384
  message: `Re-adopt: re-dispatch failed for message ${row.id.slice(0, 8)} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
2635
3385
  conversation_id: row.conversation_id,
2636
3386
  message_id: row.id
2637
3387
  });
3388
+ void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
2638
3389
  return;
2639
3390
  }
2640
3391
  if (ocId === null) {
2641
3392
  this.awaitingReadopt.delete(row.id);
2642
3393
  this.log({
2643
- level: "error",
3394
+ level: "warn",
2644
3395
  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`,
2645
3396
  conversation_id: row.conversation_id,
2646
3397
  message_id: row.id
2647
3398
  });
3399
+ void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
2648
3400
  return;
2649
3401
  }
2650
- const conv = this.convForRow(sessionId, row);
2651
- const message = this.queuedMessageForRow(row);
2652
- this.registerReadopted(conv, sessionId, message, ocId, this.processedAtMs(row));
3402
+ this.registerReadopted(readoptConv, sessionId, readoptMessage, ocId, this.processedAtMs(row));
2653
3403
  this.dispatched.add(row.id);
2654
3404
  this.readopted.add(row.id);
2655
3405
  this.awaitingReadopt.delete(row.id);
2656
3406
  this.ensureWatcherRunning(sessionId);
3407
+ void this.postSignal(row.conversation_id, row.id, "readopt_redispatched");
2657
3408
  }
2658
3409
  /**
2659
3410
  * True if `evidentMessageId` is already being driven — either in the
@@ -2702,7 +3453,8 @@ var ChannelDriver = class {
2702
3453
  opencode_agent: row.opencode_agent,
2703
3454
  opencode_model: row.opencode_model,
2704
3455
  source_message_id: row.source_message_id,
2705
- slack_user_id: row.slack_user_id
3456
+ slack_user_id: row.slack_user_id,
3457
+ attachments: row.attachments ?? null
2706
3458
  };
2707
3459
  }
2708
3460
  /**
@@ -2723,7 +3475,7 @@ var ChannelDriver = class {
2723
3475
  if (this.readopted.delete(evidentMessageId) && inFlight && !inFlight.done) {
2724
3476
  this.dontRedispatch.add(evidentMessageId);
2725
3477
  this.log({
2726
- level: "info",
3478
+ level: "debug",
2727
3479
  message: `Re-adopt: message ${evidentMessageId.slice(0, 8)} gave up \u2014 parking until it leaves the processing list (cron reset)`,
2728
3480
  conversation_id: watcher.conv.id,
2729
3481
  message_id: evidentMessageId
@@ -2745,21 +3497,41 @@ var ChannelDriver = class {
2745
3497
  * RUNNING (not done) is the one that paused. With one running message that is
2746
3498
  * unambiguous; with several we prefer an explicit messageID match, else the
2747
3499
  * oldest running message.
3500
+ *
3501
+ * Returns the set of in-flight Evident message ids that are paused awaiting a
3502
+ * human — an outstanding (still-open) question/permission is attributed to them.
3503
+ * `serviceInFlightMessage` uses this to keep an actively-running turn watched
3504
+ * forever (ADR-0047) while still bounding a turn merely blocked on a person who
3505
+ * may never answer. Attribution here covers ALL open interactions, not just
3506
+ * NEW (un-deduped) ones — a question stays "awaiting a human" until answered,
3507
+ * even after it was already surfaced to the channel.
2748
3508
  */
2749
3509
  async pollInteractions(sessionId, watcher, messages) {
3510
+ const openQuestions = /* @__PURE__ */ new Set();
3511
+ const openPermissions = /* @__PURE__ */ new Set();
3512
+ let questionsPolledOk = true;
3513
+ let permissionsPolledOk = true;
2750
3514
  let questions = [];
2751
3515
  try {
2752
3516
  const res = await this.fetchImpl(`${this.opencodeBase}/question`);
2753
3517
  if (res.ok) {
2754
3518
  const body = await res.json();
2755
- questions = Array.isArray(body) ? body : [];
3519
+ if (Array.isArray(body)) {
3520
+ questions = body;
3521
+ } else {
3522
+ questionsPolledOk = false;
3523
+ }
3524
+ } else {
3525
+ questionsPolledOk = false;
2756
3526
  }
2757
3527
  } catch {
3528
+ questionsPolledOk = false;
2758
3529
  }
2759
3530
  for (const q of questions) {
2760
- if (watcher.reportedQuestions.has(q.id)) continue;
2761
3531
  if (!await this.sessionBelongsTo(q.sessionID, sessionId)) continue;
2762
3532
  const paused = this.attributeInteraction(watcher, q.tool?.messageID, messages);
3533
+ if (paused) openQuestions.add(paused.evidentMessageId);
3534
+ if (watcher.reportedQuestions.has(q.id)) continue;
2763
3535
  const reported = await this.reportInteraction(
2764
3536
  watcher.conv.id,
2765
3537
  "question",
@@ -2773,14 +3545,22 @@ var ChannelDriver = class {
2773
3545
  const res = await this.fetchImpl(`${this.opencodeBase}/permission`);
2774
3546
  if (res.ok) {
2775
3547
  const body = await res.json();
2776
- permissions = Array.isArray(body) ? body : [];
3548
+ if (Array.isArray(body)) {
3549
+ permissions = body;
3550
+ } else {
3551
+ permissionsPolledOk = false;
3552
+ }
3553
+ } else {
3554
+ permissionsPolledOk = false;
2777
3555
  }
2778
3556
  } catch {
3557
+ permissionsPolledOk = false;
2779
3558
  }
2780
3559
  for (const p of permissions) {
2781
- if (watcher.reportedPermissions.has(p.id)) continue;
2782
3560
  if (!await this.sessionBelongsTo(p.sessionID, sessionId)) continue;
2783
3561
  const paused = this.attributeInteraction(watcher, p.messageID, messages);
3562
+ if (paused) openPermissions.add(paused.evidentMessageId);
3563
+ if (watcher.reportedPermissions.has(p.id)) continue;
2784
3564
  const reported = await this.reportInteraction(
2785
3565
  watcher.conv.id,
2786
3566
  "permission",
@@ -2789,6 +3569,7 @@ var ChannelDriver = class {
2789
3569
  );
2790
3570
  if (reported) watcher.reportedPermissions.add(p.id);
2791
3571
  }
3572
+ return { openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk };
2792
3573
  }
2793
3574
  /**
2794
3575
  * True when `sessionId` is the `rootSessionId` itself OR a descendant of it —
@@ -2834,6 +3615,128 @@ var ChannelDriver = class {
2834
3615
  if (parent !== void 0) this.sessionParents.set(sessionId, parent);
2835
3616
  return parent;
2836
3617
  }
3618
+ /**
3619
+ * Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
3620
+ * status PATCH can carry it into the "Live sessions" list. Driver-level cache so
3621
+ * BOTH the watcher completion path and the restart-recovery re-adopt path (which
3622
+ * has no watcher) can use it. `conversationId` is passed only for log context.
3623
+ * Best-effort:
3624
+ * - a resolved NON-EMPTY title is cached and terminal (a real session name
3625
+ * won't later un-name), so we do NOT re-GET `/session/:id` every tick;
3626
+ * - while the title is still absent/empty we do NOT latch it — OpenCode names
3627
+ * sessions asynchronously mid-turn, so an early call (e.g. at `processing`)
3628
+ * must leave the cache unresolved and re-fetch on the next need so a later
3629
+ * call (e.g. at `done`) picks up the name assigned in the meantime. Such a
3630
+ * call returns `null` (omit the title on THIS PATCH) without caching;
3631
+ * - a failed request likewise leaves the cache unresolved (retry next need)
3632
+ * and returns `null` — it must NEVER throw or block completion.
3633
+ * A failure is logged with agent/session context (no silent catch).
3634
+ */
3635
+ async resolveSessionTitle(sessionId, conversationId) {
3636
+ const cached = this.sessionTitles.get(sessionId);
3637
+ if (cached != null) return cached;
3638
+ try {
3639
+ const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}`);
3640
+ if (res.ok) {
3641
+ const body = await res.json();
3642
+ const title = body && typeof body.title === "string" ? body.title.trim() : "";
3643
+ if (title.length > 0) {
3644
+ this.sessionTitles.set(sessionId, title);
3645
+ return title;
3646
+ }
3647
+ return null;
3648
+ }
3649
+ this.log({
3650
+ level: "debug",
3651
+ message: `Session title fetch for session ${sessionId.slice(0, 8)} (agent ${this.agentId.slice(0, 8)}) returned HTTP ${res.status} \u2014 omitting title`,
3652
+ conversation_id: conversationId
3653
+ });
3654
+ } catch (err) {
3655
+ this.log({
3656
+ level: "debug",
3657
+ 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)}`,
3658
+ conversation_id: conversationId
3659
+ });
3660
+ }
3661
+ return null;
3662
+ }
3663
+ /**
3664
+ * DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
3665
+ * (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
3666
+ *
3667
+ * The PRIMARY recovery trigger is "preamble-pinned on recovery ⇒ idle" — a
3668
+ * runner restart wipes OpenCode's in-memory `SessionStatus`/`Runner`, so a
3669
+ * completed `finish: "tool-calls"` root reply encountered during re-adoption is
3670
+ * idle by OpenCode's own definition and is re-dispatched. This method exists only
3671
+ * so the WI-3 caller can VETO that re-dispatch in the rare case a descendant is
3672
+ * provably in flight at the exact moment of recovery.
3673
+ *
3674
+ * "Alive" criterion (TIGHTENED): a descendant is alive only when it is PROVABLY,
3675
+ * ACTIVELY generating — its LAST message is an assistant still mid-generation
3676
+ * (`completed == null`, via `isSessionActivelyGenerating`). An
3677
+ * INCOMPLETE-BUT-NOT-GENERATING child — last message a user message, or a
3678
+ * completed `finish: "tool-calls"` step — is NOT alive after a restart (nothing
3679
+ * is generating once the runner is gone), so it does NOT veto. (This is
3680
+ * deliberately NOT `!isTurnComplete`, which also matches those dead-but-non-terminal
3681
+ * shapes and would falsely veto — re-hanging the very turn this path recovers.)
3682
+ *
3683
+ * Return contract (encoded so WI-3 need not re-derive it):
3684
+ * - `true` → a descendant is provably, actively generating (veto re-dispatch).
3685
+ * - `false` → descendants exist but none is actively generating (the restart
3686
+ * case), OR no descendant is found at all.
3687
+ * - `null` → liveness is INDETERMINATE (enumeration via `listSessions` failed).
3688
+ *
3689
+ * ⚠️ `null` (UNKNOWN) MUST NOT be treated as "alive": WI-3 treats `null` the same
3690
+ * as `false` and does NOT veto — a restart guarantees no live runner, so an
3691
+ * indeterminate cross-check almost always means "couldn't reach a child that no
3692
+ * longer exists". The inversion lives in the caller; this method just reports
3693
+ * true/false/null faithfully.
3694
+ *
3695
+ * VERIFY-BEFORE-DEPEND: we depend ONLY on (a) `parentID` from `GET /session/:id`
3696
+ * (already proven by the existing child-session interaction tests, via
3697
+ * `resolveSessionParent`/`sessionBelongsTo`) and (b) the child's own message-list
3698
+ * terminal state. We do NOT depend on any session-level `busy`/`idle` field —
3699
+ * there is none on `GET /session/:id`; OpenCode's busy state is in-memory
3700
+ * `SessionStatus` only.
3701
+ */
3702
+ async isAnyDescendantSessionAlive(rootSessionId) {
3703
+ const sessions = await listSessions(this.port);
3704
+ if (!sessions) {
3705
+ this.log({
3706
+ level: "warn",
3707
+ message: `Re-adopt: could not enumerate sessions to cross-check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating child liveness as indeterminate`
3708
+ });
3709
+ return null;
3710
+ }
3711
+ for (const candidate of sessions) {
3712
+ if (!candidate?.id || candidate.id === rootSessionId) continue;
3713
+ if (!await this.sessionBelongsTo(candidate.id, rootSessionId)) continue;
3714
+ const childMsgs = await getSessionMessages(this.port, candidate.id);
3715
+ if (isSessionActivelyGenerating(childMsgs)) {
3716
+ return true;
3717
+ }
3718
+ }
3719
+ return false;
3720
+ }
3721
+ /**
3722
+ * Cheap decision-telemetry label for a running row's LAST correlated reply
3723
+ * (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
3724
+ * - `b1` — the reply itself is still in flight (`time.completed == null`) —
3725
+ * the aborted-in-flight production bug after a restart.
3726
+ * - `b2` — a COMPLETED reply pinned running only by `finish === "tool-calls"`
3727
+ * (the sub-agent preamble — #253's shape).
3728
+ * - `other` — any other shape (defensive; a running row is normally b1 or b2).
3729
+ * Reads `info.time.completed` / `info.finish` (tolerating the legacy top-level
3730
+ * shape) directly rather than re-importing the module-private `completedOf`/
3731
+ * `finishOf` — this is a display label only, not a correctness predicate.
3732
+ */
3733
+ replyCompletionShape(reply) {
3734
+ if (!reply) return "other";
3735
+ const completed = reply.info?.time?.completed ?? reply.time?.completed;
3736
+ if (completed == null) return "b1";
3737
+ const finish = reply.info?.finish ?? reply.finish;
3738
+ return finish === "tool-calls" ? "b2" : "other";
3739
+ }
2837
3740
  /**
2838
3741
  * Attribute a surfaced interaction to the in-flight message it paused on (M-1).
2839
3742
  *
@@ -2884,9 +3787,7 @@ var ChannelDriver = class {
2884
3787
  }
2885
3788
  return inFlight.sort(byOldest)[0];
2886
3789
  }
2887
- // -------------------------------------------------------------------------
2888
3790
  // Evident API calls (combinedAuth thread routes)
2889
- // -------------------------------------------------------------------------
2890
3791
  async getPendingConversations() {
2891
3792
  const res = await this.fetchImpl(
2892
3793
  `${this.apiUrl}/agents/${this.agentId}/conversations/pending`,
@@ -2966,7 +3867,7 @@ var ChannelDriver = class {
2966
3867
  * A single attempt (no internal retry): the watcher's per-tick loop is the
2967
3868
  * retry vehicle for the swap-to-running.
2968
3869
  */
2969
- async markProcessing(conversationId, messageId, sessionId, opencodeMessageId) {
3870
+ async markProcessing(conversationId, messageId, sessionId, opencodeMessageId, title) {
2970
3871
  const res = await this.fetchImpl(
2971
3872
  `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
2972
3873
  {
@@ -2975,7 +3876,8 @@ var ChannelDriver = class {
2975
3876
  body: JSON.stringify({
2976
3877
  status: "processing",
2977
3878
  opencode_session_id: sessionId,
2978
- ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {}
3879
+ ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3880
+ ...title ? { title } : {}
2979
3881
  })
2980
3882
  }
2981
3883
  );
@@ -3014,7 +3916,7 @@ var ChannelDriver = class {
3014
3916
  * watcher retries next tick within the
3015
3917
  * deadline, Finding 4).
3016
3918
  */
3017
- async markDone(conversationId, messageId, sessionId, opencodeMessageId) {
3919
+ async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage) {
3018
3920
  const res = await this.fetchImpl(
3019
3921
  `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
3020
3922
  {
@@ -3023,7 +3925,9 @@ var ChannelDriver = class {
3023
3925
  body: JSON.stringify({
3024
3926
  status: "done",
3025
3927
  opencode_session_id: sessionId,
3026
- ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {}
3928
+ ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3929
+ ...title ? { title } : {},
3930
+ ...usage ? usage : {}
3027
3931
  })
3028
3932
  }
3029
3933
  );
@@ -3041,10 +3945,11 @@ var ChannelDriver = class {
3041
3945
  * OpenCode turn sends `{status:'failed', opencode_session_id, error}` so the
3042
3946
  * failure reason reaches the channel.
3043
3947
  */
3044
- async markFailed(conversationId, messageId, sessionId, error2) {
3948
+ async markFailed(conversationId, messageId, sessionId, error2, usage) {
3045
3949
  const body = { status: "failed" };
3046
3950
  if (sessionId !== void 0) body.opencode_session_id = sessionId;
3047
3951
  if (error2 !== void 0) body.error = error2;
3952
+ if (usage) Object.assign(body, usage);
3048
3953
  await this.callWithRetry(
3049
3954
  "marking message as failed",
3050
3955
  () => this.fetchImpl(
@@ -3065,6 +3970,12 @@ var ChannelDriver = class {
3065
3970
  * MUST NOT use `callWithRetry` (a telemetry ping must not block the sequential
3066
3971
  * watcher tick — one attempt is enough). A failure is SWALLOWED but LOGGED with
3067
3972
  * context (no silent catch, per development-workflow).
3973
+ *
3974
+ * Returns whether the POST SUCCEEDED (2xx). Most callers ignore this (pure
3975
+ * telemetry), but the `paused` liveness-clear uses it to know whether to
3976
+ * RE-ASSERT on a later tick — a single dropped `paused` POST must not leave a
3977
+ * stale `last_seen_alive_at` on a still-paused row (Bugbot "Failed paused signal
3978
+ * leaves liveness").
3068
3979
  */
3069
3980
  async postSignal(conversationId, messageId, signal, extra) {
3070
3981
  try {
@@ -3078,19 +3989,22 @@ var ChannelDriver = class {
3078
3989
  );
3079
3990
  if (!res.ok) {
3080
3991
  this.log({
3081
- level: "error",
3992
+ level: "warn",
3082
3993
  message: `Signal '${signal}' for message ${messageId.slice(0, 8)} returned HTTP ${res.status} (telemetry-only, ignored)`,
3083
3994
  conversation_id: conversationId,
3084
3995
  message_id: messageId
3085
3996
  });
3997
+ return false;
3086
3998
  }
3999
+ return true;
3087
4000
  } catch (err) {
3088
4001
  this.log({
3089
- level: "error",
4002
+ level: "warn",
3090
4003
  message: `Signal '${signal}' for message ${messageId.slice(0, 8)} failed (telemetry-only, ignored): ${err instanceof Error ? err.message : String(err)}`,
3091
4004
  conversation_id: conversationId,
3092
4005
  message_id: messageId
3093
4006
  });
4007
+ return false;
3094
4008
  }
3095
4009
  }
3096
4010
  async persistSession(conversationId, sessionId) {
@@ -3147,9 +4061,7 @@ var ChannelDriver = class {
3147
4061
  return false;
3148
4062
  }
3149
4063
  }
3150
- // -------------------------------------------------------------------------
3151
4064
  // Retry wrapper
3152
- // -------------------------------------------------------------------------
3153
4065
  /**
3154
4066
  * Invoke an Evident API call, retrying on transient failures (5xx / 429 /
3155
4067
  * network errors) with exponential backoff + jitter (capped). Auth failures
@@ -3348,7 +4260,7 @@ async function resolveAgentIdFromKey(authHeader) {
3348
4260
  if (!response.ok) {
3349
4261
  const serverMessage = await readErrorMessage(response);
3350
4262
  return {
3351
- error: `Failed to resolve agent from key (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
4263
+ error: `Failed to resolve runner from key (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
3352
4264
  };
3353
4265
  }
3354
4266
  const data = await response.json();
@@ -3356,11 +4268,11 @@ async function resolveAgentIdFromKey(authHeader) {
3356
4268
  return { agent_id: data.agent_id };
3357
4269
  }
3358
4270
  return {
3359
- error: "Cannot resolve agent ID: auth type is not agent_key. Please provide --agent explicitly."
4271
+ error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --agent explicitly."
3360
4272
  };
3361
4273
  } catch (error2) {
3362
4274
  const message = error2 instanceof Error ? error2.message : "Unknown error";
3363
- return { error: `Failed to resolve agent from key: ${message}` };
4275
+ return { error: `Failed to resolve runner from key: ${message}` };
3364
4276
  }
3365
4277
  }
3366
4278
  async function notifyAgentDisconnected(agentId, authHeader) {
@@ -3396,12 +4308,12 @@ async function getAgentInfo(agentId, authHeader) {
3396
4308
  const serverMessage = await readErrorMessage(response);
3397
4309
  return {
3398
4310
  valid: false,
3399
- error: serverMessage ?? "You do not have access to this agent (it may belong to a different team or organization)."
4311
+ error: serverMessage ?? "You do not have access to this runner (it may belong to a different team or organization)."
3400
4312
  };
3401
4313
  }
3402
4314
  if (response.status === 404) {
3403
4315
  const serverMessage = await readErrorMessage(response);
3404
- return { valid: false, error: serverMessage ?? `Agent ${agentId} not found` };
4316
+ return { valid: false, error: serverMessage ?? `Runner ${agentId} not found` };
3405
4317
  }
3406
4318
  if (!response.ok) {
3407
4319
  const serverMessage = await readErrorMessage(response);
@@ -3414,13 +4326,13 @@ async function getAgentInfo(agentId, authHeader) {
3414
4326
  if (agent.agent_type !== "local") {
3415
4327
  return {
3416
4328
  valid: false,
3417
- error: `Agent is type '${agent.agent_type}', must be 'local' for CLI connection`
4329
+ error: `Runner is type '${agent.agent_type}', must be 'local' for CLI connection`
3418
4330
  };
3419
4331
  }
3420
4332
  return { valid: true, agent };
3421
4333
  } catch (error2) {
3422
4334
  const message = error2 instanceof Error ? error2.message : "Unknown error";
3423
- return { valid: false, error: `Failed to validate agent: ${message}` };
4335
+ return { valid: false, error: `Failed to validate runner: ${message}` };
3424
4336
  }
3425
4337
  }
3426
4338
 
@@ -3429,23 +4341,53 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
3429
4341
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
3430
4342
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
3431
4343
  var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
3432
- function log2(state, message, isError = false) {
4344
+ function resolveLogLevel(options) {
4345
+ const accepted = Object.keys(LOG_LEVELS);
4346
+ const validate = (value, source) => {
4347
+ const normalized = value.trim().toLowerCase();
4348
+ if (!accepted.includes(normalized)) {
4349
+ throw new Error(
4350
+ `Invalid log level "${value}"${source}; expected one of ${accepted.join(", ")}`
4351
+ );
4352
+ }
4353
+ return normalized;
4354
+ };
4355
+ if (options.logLevel !== void 0) {
4356
+ return validate(options.logLevel, " (--log-level)");
4357
+ }
4358
+ if (options.verbose) {
4359
+ return "debug";
4360
+ }
4361
+ const env = process.env.EVIDENT_LOG_LEVEL;
4362
+ if (env !== void 0 && env !== "") {
4363
+ return validate(env, " (EVIDENT_LOG_LEVEL)");
4364
+ }
4365
+ return "info";
4366
+ }
4367
+ function meetsThreshold(state, level) {
4368
+ return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
4369
+ }
4370
+ function log2(state, message, level = "info") {
4371
+ if (!meetsThreshold(state, level)) return;
3433
4372
  if (state.json) {
3434
4373
  console.log(
3435
4374
  JSON.stringify({
3436
4375
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3437
- level: isError ? "error" : "info",
4376
+ level,
3438
4377
  message
3439
4378
  })
3440
4379
  );
3441
4380
  } else if (!state.interactive) {
3442
- const prefix = isError ? chalk6.red("\u2717") : chalk6.green("\u2022");
4381
+ const prefix = level === "error" ? chalk6.red("\u2717") : level === "warn" ? chalk6.yellow("!") : level === "debug" ? chalk6.dim("\xB7") : chalk6.green("\u2022");
3443
4382
  console.log(`${prefix} ${message}`);
3444
4383
  }
3445
4384
  }
3446
4385
  function logActivity(state, entry) {
4386
+ const level = entry.level ?? (entry.type === "error" ? "error" : "info");
4387
+ if (!meetsThreshold(state, level)) return;
3447
4388
  const fullEntry = {
3448
4389
  ...entry,
4390
+ level,
3449
4391
  timestamp: /* @__PURE__ */ new Date()
3450
4392
  };
3451
4393
  state.activityLog.push(fullEntry);
@@ -3454,9 +4396,9 @@ function logActivity(state, entry) {
3454
4396
  }
3455
4397
  if (!state.interactive) {
3456
4398
  if (entry.type === "error") {
3457
- log2(state, entry.error ?? "Unknown error", true);
3458
- } else if (entry.type === "info" && entry.message) {
3459
- log2(state, entry.message);
4399
+ log2(state, entry.error ?? "Unknown error", level);
4400
+ } else if (entry.message) {
4401
+ log2(state, entry.message, level);
3460
4402
  }
3461
4403
  }
3462
4404
  }
@@ -3583,7 +4525,7 @@ async function driveChannels(state, driver) {
3583
4525
  logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
3584
4526
  if (state.interactive) displayStatus(state);
3585
4527
  }
3586
- await new Promise((resolve) => setTimeout(resolve, CHANNEL_POLL_INTERVAL_MS));
4528
+ await new Promise((resolve2) => setTimeout(resolve2, CHANNEL_POLL_INTERVAL_MS));
3587
4529
  if (state.idleTimeout !== null && idlePolls >= 2) {
3588
4530
  const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
3589
4531
  if (idleMs > state.idleTimeout * 1e3) {
@@ -3594,6 +4536,81 @@ async function driveChannels(state, driver) {
3594
4536
  }
3595
4537
  }
3596
4538
  }
4539
+ var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
4540
+ async function runSweep(state, driver, config2) {
4541
+ const mode = `age=${config2.maxAgeMs ?? "\u2014"} count=${config2.maxCount ?? "\u2014"}`;
4542
+ try {
4543
+ const sessions = await listSessions(state.port);
4544
+ if (sessions === null) {
4545
+ logActivity(state, {
4546
+ type: "info",
4547
+ message: `Session cleanup: could not list sessions (opencode unreachable); skipping this sweep (${mode})`
4548
+ });
4549
+ return;
4550
+ }
4551
+ const toDelete = selectSessionsToDelete(
4552
+ sessions.map((s) => ({ id: s.id, lastActivityMs: sessionLastActivityMs(s) })),
4553
+ {
4554
+ maxAgeMs: config2.maxAgeMs,
4555
+ maxCount: config2.maxCount,
4556
+ nowMs: Date.now(),
4557
+ protectedIds: driver.protectedSessionIds()
4558
+ }
4559
+ );
4560
+ const protectedNow = driver.protectedSessionIds();
4561
+ let deleted = 0;
4562
+ let failed = 0;
4563
+ let skippedNewlyActive = 0;
4564
+ for (const id of toDelete) {
4565
+ if (protectedNow.has(id)) {
4566
+ skippedNewlyActive++;
4567
+ logActivity(state, {
4568
+ type: "info",
4569
+ message: `Session cleanup: skipping ${id} \u2014 became active/bound after selection (${mode})`
4570
+ });
4571
+ continue;
4572
+ }
4573
+ if (await deleteSession(state.port, id)) deleted++;
4574
+ else failed++;
4575
+ }
4576
+ const failedNote = failed > 0 ? `, failed ${failed}` : "";
4577
+ const skippedNote = skippedNewlyActive > 0 ? `, skipped ${skippedNewlyActive} newly-active` : "";
4578
+ logActivity(state, {
4579
+ type: "info",
4580
+ message: `Session cleanup: inspected ${sessions.length}, deleted ${deleted}${failedNote}${skippedNote} (${mode})`
4581
+ });
4582
+ } catch (error2) {
4583
+ const message = error2 instanceof Error ? error2.message : String(error2);
4584
+ logActivity(state, {
4585
+ type: "error",
4586
+ error: `Session cleanup sweep failed (non-fatal, ${mode}): ${message}`
4587
+ });
4588
+ }
4589
+ }
4590
+ function scheduleSessionCleanup(state, driver, options) {
4591
+ const config2 = resolveSessionCleanupConfig(
4592
+ {
4593
+ maxAge: options.sessionCleanupMaxAge,
4594
+ maxCount: options.sessionCleanupMaxCount,
4595
+ interval: options.sessionCleanupInterval
4596
+ },
4597
+ process.env
4598
+ );
4599
+ for (const warning2 of config2.warnings) {
4600
+ logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
4601
+ }
4602
+ if (!config2.enabled) return;
4603
+ logActivity(state, {
4604
+ type: "info",
4605
+ message: `Session cleanup enabled (age=${config2.maxAgeMs ?? "\u2014"}, count=${config2.maxCount ?? "\u2014"}, interval=${config2.intervalMs}ms)`
4606
+ });
4607
+ const interval = setInterval(() => void runSweep(state, driver, config2), config2.intervalMs);
4608
+ const firstSweep = setTimeout(
4609
+ () => void runSweep(state, driver, config2),
4610
+ SESSION_CLEANUP_FIRST_SWEEP_MS
4611
+ );
4612
+ state.sessionCleanupTimers.push(interval, firstSweep);
4613
+ }
3597
4614
  async function notifyOffline(state) {
3598
4615
  if (!state.agentId || !state.authHeader) return;
3599
4616
  if (!state.connected) {
@@ -3602,7 +4619,7 @@ async function notifyOffline(state) {
3602
4619
  }
3603
4620
  const result = await notifyAgentDisconnected(state.agentId, state.authHeader);
3604
4621
  if (result.ok) {
3605
- log2(state, "Notified Evident the agent is going offline");
4622
+ log2(state, "Notified Evident the runner is going offline");
3606
4623
  } else {
3607
4624
  logActivity(state, {
3608
4625
  type: "error",
@@ -3613,6 +4630,11 @@ async function notifyOffline(state) {
3613
4630
  }
3614
4631
  async function cleanup(state, opts = {}) {
3615
4632
  state.running = false;
4633
+ for (const timer of state.sessionCleanupTimers) {
4634
+ clearInterval(timer);
4635
+ clearTimeout(timer);
4636
+ }
4637
+ state.sessionCleanupTimers = [];
3616
4638
  if (opts.graceful && state.channelDriver) {
3617
4639
  state.channelDriver.stop();
3618
4640
  log2(state, "Draining in-flight channel work before shutdown...");
@@ -3647,6 +4669,20 @@ async function cleanup(state, opts = {}) {
3647
4669
  }
3648
4670
  async function run(options) {
3649
4671
  const interactive = isInteractive(options.json);
4672
+ let logLevel;
4673
+ try {
4674
+ logLevel = resolveLogLevel(options);
4675
+ } catch (error2) {
4676
+ const message = error2 instanceof Error ? error2.message : String(error2);
4677
+ if (options.json) {
4678
+ console.log(JSON.stringify({ status: "error", error: message }));
4679
+ } else {
4680
+ printError(message);
4681
+ }
4682
+ await shutdownTelemetry();
4683
+ process.exit(1);
4684
+ return;
4685
+ }
3650
4686
  const state = {
3651
4687
  agentId: options.agent || "",
3652
4688
  agentName: null,
@@ -3655,6 +4691,7 @@ async function run(options) {
3655
4691
  idleTimeout: options.idleTimeout ?? null,
3656
4692
  json: options.json ?? false,
3657
4693
  interactive,
4694
+ logLevel,
3658
4695
  connected: false,
3659
4696
  opencodeConnected: false,
3660
4697
  opencodeVersion: null,
@@ -3666,13 +4703,14 @@ async function run(options) {
3666
4703
  activityLog: [],
3667
4704
  messageCount: 0,
3668
4705
  lastProxiedActivityAt: null,
4706
+ sessionCleanupTimers: [],
3669
4707
  authHeader: ""
3670
4708
  };
3671
4709
  if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
3672
4710
  log2(
3673
4711
  state,
3674
- "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.",
3675
- false
4712
+ "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.",
4713
+ "warn"
3676
4714
  );
3677
4715
  }
3678
4716
  const handleSignal = async () => {
@@ -3715,15 +4753,15 @@ async function run(options) {
3715
4753
  const resolved = await resolveAgentIdFromKey(state.authHeader);
3716
4754
  if (resolved.agent_id) {
3717
4755
  state.agentId = resolved.agent_id;
3718
- log2(state, `Resolved agent ID from key: ${state.agentId}`);
4756
+ log2(state, `Resolved runner ID from key: ${state.agentId}`);
3719
4757
  if (state.interactive && !state.json) {
3720
4758
  logActivity(state, {
3721
4759
  type: "info",
3722
- message: `Agent ID resolved from key: ${state.agentId}`
4760
+ message: `Runner ID resolved from key: ${state.agentId}`
3723
4761
  });
3724
4762
  }
3725
4763
  } else {
3726
- printError(resolved.error || "Failed to resolve agent ID from key");
4764
+ printError(resolved.error || "Failed to resolve runner ID from key");
3727
4765
  process.exit(1);
3728
4766
  }
3729
4767
  } else {
@@ -3751,7 +4789,7 @@ async function run(options) {
3751
4789
  console.log(chalk6.bold("Evident Run"));
3752
4790
  console.log(chalk6.dim("-".repeat(40)));
3753
4791
  }
3754
- const spinner = interactive && !state.json ? ora3("Validating agent...").start() : null;
4792
+ const spinner = interactive && !state.json ? ora3("Validating runner...").start() : null;
3755
4793
  let validation = await getAgentInfo(state.agentId, state.authHeader);
3756
4794
  if (!validation.valid && validation.authFailed && interactive) {
3757
4795
  spinner?.fail("Authentication failed");
@@ -3763,14 +4801,14 @@ async function run(options) {
3763
4801
  "Login successful! Retrying..."
3764
4802
  );
3765
4803
  state.authHeader = getAuthHeader(credentials2);
3766
- spinner?.start("Validating agent...");
4804
+ spinner?.start("Validating runner...");
3767
4805
  validation = await getAgentInfo(state.agentId, state.authHeader);
3768
4806
  }
3769
4807
  if (!validation.valid) {
3770
- spinner?.fail(`Agent validation failed: ${validation.error}`);
4808
+ spinner?.fail(`Runner validation failed: ${validation.error}`);
3771
4809
  throw new Error(validation.error);
3772
4810
  }
3773
- spinner?.succeed(`Agent: ${validation.agent.name || state.agentId}`);
4811
+ spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
3774
4812
  state.agentName = validation.agent.name;
3775
4813
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
3776
4814
  try {
@@ -3788,9 +4826,9 @@ async function run(options) {
3788
4826
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
3789
4827
  const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
3790
4828
  if (versionWarning) {
3791
- log2(state, versionWarning, false);
4829
+ log2(state, versionWarning, "warn");
3792
4830
  if (state.interactive && !state.json) {
3793
- logActivity(state, { type: "info", message: versionWarning });
4831
+ logActivity(state, { type: "info", level: "warn", message: versionWarning });
3794
4832
  }
3795
4833
  }
3796
4834
  } catch (error2) {
@@ -3805,11 +4843,17 @@ async function run(options) {
3805
4843
  getAuthHeader: () => state.authHeader,
3806
4844
  conversationFilter: state.conversationFilter,
3807
4845
  stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
3808
- log: (entry) => logActivity(state, {
3809
- type: entry.level === "error" ? "error" : "info",
3810
- message: entry.message,
3811
- error: entry.level === "error" ? entry.message : void 0
3812
- })
4846
+ log: (entry) => (
4847
+ // Thread the driver's real level straight through so `debug`/`warn`
4848
+ // survive the sink filter (they no longer collapse to info). `type`
4849
+ // stays the coarse error/non-error split the activity log renders with.
4850
+ logActivity(state, {
4851
+ type: entry.level === "error" ? "error" : "info",
4852
+ level: entry.level,
4853
+ message: entry.message,
4854
+ error: entry.level === "error" ? entry.message : void 0
4855
+ })
4856
+ )
3813
4857
  });
3814
4858
  state.channelDriver = channelDriver;
3815
4859
  const connection = new RunnerConnection({
@@ -3823,7 +4867,7 @@ async function run(options) {
3823
4867
  state.agentId = agentId;
3824
4868
  logActivity(state, {
3825
4869
  type: "info",
3826
- message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (agent: ${agentId})`
4870
+ message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
3827
4871
  });
3828
4872
  emitAgentConnected(state.agentId, {
3829
4873
  port: state.port,
@@ -3908,6 +4952,7 @@ async function run(options) {
3908
4952
  if (error2.message === "Unauthorized") tunnelSpinner?.fail("Unauthorized");
3909
4953
  throw error2;
3910
4954
  }
4955
+ scheduleSessionCleanup(state, channelDriver, options);
3911
4956
  if (!interactive || state.json) {
3912
4957
  log2(state, "Driving channel messages...");
3913
4958
  }
@@ -3962,15 +5007,34 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
3962
5007
  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);
3963
5008
  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 }));
3964
5009
  program.command("whoami").description("Show the currently logged in user").action(whoami);
3965
- 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(
5010
+ program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Runner ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
5011
+ "--log-level <level>",
5012
+ "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
5013
+ ).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(
5014
+ "--session-cleanup-max-age <duration>",
5015
+ "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
5016
+ ).option(
5017
+ "--session-cleanup-max-count <n>",
5018
+ "Keep only the newest N OpenCode sessions. Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_COUNT"
5019
+ ).option(
5020
+ "--session-cleanup-interval <duration>",
5021
+ "How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
5022
+ ).action(
3966
5023
  (options) => {
3967
5024
  run({
3968
5025
  agent: options.agent,
3969
5026
  port: parseInt(options.port, 10),
5027
+ // Raw string — validation/precedence is single-sourced in run.ts's
5028
+ // resolveLogLevel (flag > -v > EVIDENT_LOG_LEVEL > info).
5029
+ logLevel: options.logLevel,
3970
5030
  verbose: options.verbose,
3971
5031
  conversation: options.conversation,
3972
5032
  idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
3973
- json: options.json
5033
+ json: options.json,
5034
+ // Raw strings — the resolver in run.ts single-sources parsing (M1).
5035
+ sessionCleanupMaxAge: options.sessionCleanupMaxAge,
5036
+ sessionCleanupMaxCount: options.sessionCleanupMaxCount,
5037
+ sessionCleanupInterval: options.sessionCleanupInterval
3974
5038
  });
3975
5039
  }
3976
5040
  );