@evident-ai/cli 3.0.1-dev.043168c → 3.0.1-dev.07ee447

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((resolve2) => {
288
+ return new Promise((resolve) => {
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
- resolve2();
295
+ resolve();
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((resolve2) => setTimeout(resolve2, ms));
305
+ return new Promise((resolve) => setTimeout(resolve, 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((resolve2) => {
379
+ const token = await new Promise((resolve) => {
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
- resolve2(data.trim());
386
+ resolve(data.trim());
387
387
  });
388
388
  if (process.stdin.isTTY) {
389
389
  process.stdin.once("data", (chunk) => {
390
390
  process.stdin.pause();
391
- resolve2(chunk.toString().trim());
391
+ resolve(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((resolve2) => setTimeout(resolve2, 1e3));
709
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
710
710
  }
711
711
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
712
712
  }
@@ -1078,48 +1078,6 @@ async function getSessionMessages(port, sessionId) {
1078
1078
  return null;
1079
1079
  }
1080
1080
  }
1081
- function sessionLastActivityMs(session) {
1082
- const candidates = [
1083
- session.time?.updated,
1084
- session.time?.created,
1085
- session.time_updated,
1086
- session.time_created,
1087
- session.updated,
1088
- session.created
1089
- ];
1090
- for (const c of candidates) {
1091
- if (typeof c === "number" && Number.isFinite(c)) return c;
1092
- }
1093
- return null;
1094
- }
1095
- async function listSessions(port) {
1096
- try {
1097
- const res = await fetch(`${opencodeBase(port)}/session`);
1098
- if (!res.ok) return null;
1099
- const body = await res.json();
1100
- return Array.isArray(body) ? body : null;
1101
- } catch {
1102
- return null;
1103
- }
1104
- }
1105
- async function deleteSession(port, id) {
1106
- try {
1107
- const res = await fetch(`${opencodeBase(port)}/session/${id}`, { method: "DELETE" });
1108
- return res.status >= 200 && res.status < 300;
1109
- } catch {
1110
- return false;
1111
- }
1112
- }
1113
- async function sessionExists(port, id) {
1114
- try {
1115
- const res = await fetch(`${opencodeBase(port)}/session/${id}`);
1116
- if (res.status >= 200 && res.status < 300) return true;
1117
- if (res.status === 404) return false;
1118
- return null;
1119
- } catch {
1120
- return null;
1121
- }
1122
- }
1123
1081
  async function createOpenCodeSession(port, directory) {
1124
1082
  const url = new URL(`${opencodeBase(port)}/session`);
1125
1083
  if (directory && directory.trim()) {
@@ -1189,7 +1147,7 @@ async function sendPromptAsync(port, sessionId, content, options) {
1189
1147
  if (best) return best.id;
1190
1148
  }
1191
1149
  if (attempt < READ_BACK_ATTEMPTS - 1) {
1192
- await new Promise((resolve2) => setTimeout(resolve2, READ_BACK_DELAY_MS));
1150
+ await new Promise((resolve) => setTimeout(resolve, READ_BACK_DELAY_MS));
1193
1151
  }
1194
1152
  }
1195
1153
  return null;
@@ -1266,110 +1224,6 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1266
1224
  );
1267
1225
  }
1268
1226
 
1269
- // src/lib/opencode/session-cleanup.ts
1270
- var DURATION_UNIT_MS = {
1271
- s: 1e3,
1272
- m: 60 * 1e3,
1273
- h: 60 * 60 * 1e3,
1274
- d: 24 * 60 * 60 * 1e3
1275
- };
1276
- function parseDurationMs(input) {
1277
- const trimmed = input.trim();
1278
- const match = /^(\d+)([smhd])$/.exec(trimmed);
1279
- if (!match) {
1280
- throw new Error(
1281
- `Invalid duration "${input}": expected <number><unit> where unit is one of s, m, h, d (e.g. "7d", "24h", "30m", "90s").`
1282
- );
1283
- }
1284
- const value = Number(match[1]);
1285
- if (value <= 0) {
1286
- throw new Error(`Invalid duration "${input}": must be a positive value.`);
1287
- }
1288
- return value * DURATION_UNIT_MS[match[2]];
1289
- }
1290
- function selectSessionsToDelete(sessions, opts) {
1291
- const { maxAgeMs, maxCount, nowMs, protectedIds } = opts;
1292
- if (maxAgeMs === void 0 && maxCount === void 0) return [];
1293
- const ageEligible = (s) => {
1294
- if (maxAgeMs === void 0) return false;
1295
- if (s.lastActivityMs === null) return true;
1296
- return nowMs - s.lastActivityMs > maxAgeMs;
1297
- };
1298
- const countEligibleIds = /* @__PURE__ */ new Set();
1299
- if (maxCount !== void 0) {
1300
- const byActivityDesc = [...sessions].sort(
1301
- (a, b) => (b.lastActivityMs ?? -Infinity) - (a.lastActivityMs ?? -Infinity)
1302
- );
1303
- for (const s of byActivityDesc.slice(maxCount)) {
1304
- countEligibleIds.add(s.id);
1305
- }
1306
- }
1307
- const toDelete = [];
1308
- for (const s of sessions) {
1309
- if (protectedIds.has(s.id)) continue;
1310
- if (ageEligible(s) || countEligibleIds.has(s.id)) {
1311
- toDelete.push(s.id);
1312
- }
1313
- }
1314
- return toDelete;
1315
- }
1316
- var DEFAULT_INTERVAL = "1h";
1317
- function resolve(flag, envValue, fallback) {
1318
- return flag ?? envValue ?? fallback;
1319
- }
1320
- function parseMaxCount(input) {
1321
- const trimmed = input.trim();
1322
- if (!/^\d+$/.test(trimmed)) {
1323
- throw new Error(`Invalid max-count "${input}": expected a positive integer.`);
1324
- }
1325
- const value = Number(trimmed);
1326
- if (value <= 0) {
1327
- throw new Error(`Invalid max-count "${input}": must be greater than 0.`);
1328
- }
1329
- return value;
1330
- }
1331
- function resolveSessionCleanupConfig(flags, env = process.env) {
1332
- const warnings = [];
1333
- const maxAgeRaw = resolve(flags.maxAge, env.EVIDENT_SESSION_CLEANUP_MAX_AGE);
1334
- const maxCountRaw = resolve(flags.maxCount, env.EVIDENT_SESSION_CLEANUP_MAX_COUNT);
1335
- const intervalRaw = resolve(
1336
- flags.interval,
1337
- env.EVIDENT_SESSION_CLEANUP_INTERVAL,
1338
- DEFAULT_INTERVAL
1339
- );
1340
- let maxAgeMs;
1341
- if (maxAgeRaw !== void 0) {
1342
- try {
1343
- maxAgeMs = parseDurationMs(maxAgeRaw);
1344
- } catch (err) {
1345
- warnings.push(
1346
- `Ignoring invalid --session-cleanup-max-age: ${err instanceof Error ? err.message : String(err)}`
1347
- );
1348
- }
1349
- }
1350
- let maxCount;
1351
- if (maxCountRaw !== void 0) {
1352
- try {
1353
- maxCount = parseMaxCount(maxCountRaw);
1354
- } catch (err) {
1355
- warnings.push(
1356
- `Ignoring invalid --session-cleanup-max-count: ${err instanceof Error ? err.message : String(err)}`
1357
- );
1358
- }
1359
- }
1360
- let intervalMs;
1361
- try {
1362
- intervalMs = parseDurationMs(intervalRaw ?? DEFAULT_INTERVAL);
1363
- } catch (err) {
1364
- warnings.push(
1365
- `Ignoring invalid --session-cleanup-interval, using default ${DEFAULT_INTERVAL}: ${err instanceof Error ? err.message : String(err)}`
1366
- );
1367
- intervalMs = parseDurationMs(DEFAULT_INTERVAL);
1368
- }
1369
- const enabled = maxAgeMs !== void 0 || maxCount !== void 0;
1370
- return { enabled, maxAgeMs, maxCount, intervalMs, warnings };
1371
- }
1372
-
1373
1227
  // src/lib/tunnel/connection.ts
1374
1228
  import WebSocket2 from "ws";
1375
1229
 
@@ -1446,26 +1300,24 @@ var StreamForwarder = class {
1446
1300
  this.send({ type: "res_end", sid });
1447
1301
  return;
1448
1302
  }
1449
- if (process.env.DEBUG) {
1450
- log("debug", "agent_request", {
1451
- correlation_id: correlationId,
1452
- sid,
1453
- method,
1454
- path: stripQuery(path)
1455
- });
1456
- }
1303
+ log("info", "agent_request", {
1304
+ correlation_id: correlationId,
1305
+ sid,
1306
+ method,
1307
+ path: stripQuery(path)
1308
+ });
1457
1309
  const ac = new AbortController();
1458
1310
  let bodyPromise;
1459
1311
  let pushBody;
1460
1312
  let endBody;
1461
1313
  if (has_body) {
1462
1314
  const chunks = [];
1463
- bodyPromise = new Promise((resolve2) => {
1315
+ bodyPromise = new Promise((resolve) => {
1464
1316
  pushBody = (buf) => {
1465
1317
  chunks.push(buf);
1466
1318
  };
1467
1319
  endBody = () => {
1468
- resolve2(Buffer.concat(chunks));
1320
+ resolve(Buffer.concat(chunks));
1469
1321
  };
1470
1322
  });
1471
1323
  }
@@ -1500,14 +1352,12 @@ var StreamForwarder = class {
1500
1352
  if (!STRIP_RES.has(key.toLowerCase())) resHeaders[key] = value;
1501
1353
  });
1502
1354
  this.send({ type: "head", sid, status: upstream.status, headers: resHeaders });
1503
- if (process.env.DEBUG) {
1504
- log("debug", "agent_response", {
1505
- correlation_id: correlationId,
1506
- sid,
1507
- status: upstream.status,
1508
- duration_ms: Date.now() - startedAt
1509
- });
1510
- }
1355
+ log("info", "agent_response", {
1356
+ correlation_id: correlationId,
1357
+ sid,
1358
+ status: upstream.status,
1359
+ duration_ms: Date.now() - startedAt
1360
+ });
1511
1361
  this.callbacks.onHead?.(sid, upstream.status);
1512
1362
  try {
1513
1363
  if (upstream.body) {
@@ -1583,7 +1433,7 @@ function connectTunnel(options) {
1583
1433
  } = options;
1584
1434
  const tunnelUrl = getTunnelUrlConfig();
1585
1435
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
1586
- return new Promise((resolve2, reject) => {
1436
+ return new Promise((resolve, reject) => {
1587
1437
  const ws = new WebSocket2(url, {
1588
1438
  headers: {
1589
1439
  Authorization: authHeader
@@ -1648,7 +1498,7 @@ function connectTunnel(options) {
1648
1498
  clearTimeout(connectionTimeout);
1649
1499
  const connectedAgentId = message.agent_id ?? agentId;
1650
1500
  onConnected?.(connectedAgentId);
1651
- resolve2({
1501
+ resolve({
1652
1502
  ws,
1653
1503
  close: () => ws.close(1e3, "CLI shutdown")
1654
1504
  });
@@ -1895,33 +1745,8 @@ var ChannelDriver = class {
1895
1745
  * not yet resolved; `null` = resolved-but-unavailable (don't keep retrying).
1896
1746
  */
1897
1747
  opencodeDirectory = void 0;
1898
- /**
1899
- * Cache of opencode `sessionId → parentID` (its parent session, or `null` when
1900
- * the session is a root with no parent). Sub-agents spawned via the `task` tool
1901
- * run in CHILD sessions whose `parentID` chains up to the Evident-created
1902
- * (watched) session; we resolve this once per session so a child-session
1903
- * question/permission can be attributed to the watched session's subtree
1904
- * (`sessionBelongsTo`) instead of being dropped by an exact-id filter. A missing
1905
- * entry = not yet resolved; `null` = resolved root (stop walking).
1906
- */
1907
- sessionParents = /* @__PURE__ */ new Map();
1908
1748
  /** Serialises drains so a reconnect during a drain doesn't double-process. */
1909
1749
  draining = false;
1910
- /**
1911
- * The currently-executing `drainPending()` promise, or null when idle. Lets a
1912
- * graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
1913
- * is about to dispatch is not missed by the `hasInFlightWatchers()` check (a
1914
- * drain that entered before `stop()` still registers its watcher).
1915
- */
1916
- activeDrain = null;
1917
- /**
1918
- * Set by `stop()` on graceful shutdown. Once stopped, `drainPending` no longer
1919
- * dispatches NEW work (it returns 0 immediately) — but the per-session watcher
1920
- * loops already running keep going so in-flight turns can finish and deliver
1921
- * their reply. `run.ts` awaits `waitForInFlight()` before it closes the tunnel
1922
- * and stops opencode.
1923
- */
1924
- stopped = false;
1925
1750
  constructor(config2) {
1926
1751
  this.agentId = config2.agentId;
1927
1752
  this.port = config2.port;
@@ -1953,21 +1778,8 @@ var ChannelDriver = class {
1953
1778
  * @returns the number of messages NEWLY dispatched to opencode's native queue.
1954
1779
  */
1955
1780
  async drainPending() {
1956
- if (this.stopped) return 0;
1957
1781
  if (this.draining) return 0;
1958
1782
  this.draining = true;
1959
- const run2 = this.runDrain();
1960
- this.activeDrain = run2.then(
1961
- () => {
1962
- this.activeDrain = null;
1963
- },
1964
- () => {
1965
- this.activeDrain = null;
1966
- }
1967
- );
1968
- return run2;
1969
- }
1970
- async runDrain() {
1971
1783
  let dispatched = 0;
1972
1784
  try {
1973
1785
  const conversations = await this.getPendingConversations();
@@ -1979,7 +1791,6 @@ var ChannelDriver = class {
1979
1791
  });
1980
1792
  }
1981
1793
  for (const conv of conversations) {
1982
- if (this.stopped) break;
1983
1794
  dispatched += await this.processConversation(conv);
1984
1795
  }
1985
1796
  await this.readoptProcessing();
@@ -2000,73 +1811,6 @@ var ChannelDriver = class {
2000
1811
  }
2001
1812
  return false;
2002
1813
  }
2003
- /**
2004
- * OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
2005
- * exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
2006
- * `watchers` entry whose `inFlight` set is non-empty — the same predicate
2007
- * `hasInFlightWatchers()` uses, lifted to return the ids.
2008
- *
2009
- * Deliberately does NOT include `this.sessions` (the permanent, never-pruned
2010
- * conversation→session cache). Protecting every bound-but-idle session there
2011
- * would shield nearly every session and defeat cleanup — AND it is unnecessary:
2012
- * `ensureSession` is self-healing (it recreates a session whose id no longer
2013
- * exists), so deleting an idle bound session is harmless — the conversation's
2014
- * next turn transparently rebinds a fresh one. The only thing worth protecting
2015
- * is a session with a turn ACTIVELY in flight right now: tearing that down
2016
- * mid-turn would strand the running `prompt_async`. Idle sessions are fair game.
2017
- */
2018
- protectedSessionIds() {
2019
- const ids = /* @__PURE__ */ new Set();
2020
- for (const [sessionId, watcher] of this.watchers) {
2021
- if (watcher.inFlight.size > 0) ids.add(sessionId);
2022
- }
2023
- return ids;
2024
- }
2025
- /**
2026
- * Begin a graceful stop: stop accepting NEW channel work. Idempotent. After
2027
- * this, `drainPending()` is a no-op (returns 0), so no new message is dispatched
2028
- * — but the watcher loops already tracking in-flight turns keep running, so a
2029
- * turn that has finished (or is about to) still fires `markDone` and delivers
2030
- * its reply. Pair with `waitForInFlight()` to bound how long shutdown waits.
2031
- */
2032
- stop() {
2033
- this.stopped = true;
2034
- }
2035
- /**
2036
- * Wait (up to `timeoutMs`) for in-flight watcher work to settle during a
2037
- * graceful shutdown, so a turn whose reply is ready — or completes within the
2038
- * window — is delivered before the process exits, instead of being cut off and
2039
- * left for the ADR-0046 restart-recovery path.
2040
- *
2041
- * Bounded on purpose: the watcher's own give-up deadline is up to 10 minutes,
2042
- * far longer than a shutdown grace period (e.g. Fargate's SIGTERM→SIGKILL
2043
- * window). We poll `hasInFlightWatchers()` and return as soon as the in-flight
2044
- * set empties OR the timeout elapses. Anything still in flight at the timeout is
2045
- * safe to abandon — it stays `processing` server-side and is re-adopted on the
2046
- * next runner start (ADR-0046).
2047
- *
2048
- * @returns true if all in-flight work settled within the window; false if the
2049
- * timeout elapsed with work still in flight.
2050
- */
2051
- async waitForInFlight(timeoutMs) {
2052
- const deadline = this.now() + timeoutMs;
2053
- const step = Math.min(this.pausedPollIntervalMs, 250);
2054
- if (this.activeDrain) {
2055
- let drainSettled = false;
2056
- void this.activeDrain.then(() => {
2057
- drainSettled = true;
2058
- });
2059
- while (!drainSettled) {
2060
- if (this.now() >= deadline) return false;
2061
- await this.sleep(step);
2062
- }
2063
- }
2064
- while (this.hasInFlightWatchers()) {
2065
- if (this.now() >= deadline) return false;
2066
- await this.sleep(step);
2067
- }
2068
- return true;
2069
- }
2070
1814
  /**
2071
1815
  * Await all outstanding per-session watchers (WI-3).
2072
1816
  *
@@ -2103,7 +1847,6 @@ var ChannelDriver = class {
2103
1847
  let dispatched = 0;
2104
1848
  let skippedAlreadyDispatched = 0;
2105
1849
  for (const message of messages) {
2106
- if (this.stopped) break;
2107
1850
  if (this.dispatched.has(message.id)) {
2108
1851
  skippedAlreadyDispatched += 1;
2109
1852
  continue;
@@ -2127,16 +1870,6 @@ var ChannelDriver = class {
2127
1870
  } catch (err) {
2128
1871
  if (err instanceof ChannelAuthError) throw err;
2129
1872
  this.dispatched.delete(message.id);
2130
- if (await sessionExists(this.port, sessionId) === false) {
2131
- this.sessions.delete(conv.id);
2132
- this.log({
2133
- level: "info",
2134
- 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.`,
2135
- conversation_id: conv.id,
2136
- message_id: message.id
2137
- });
2138
- break;
2139
- }
2140
1873
  await this.markFailed(conv.id, message.id).catch(() => {
2141
1874
  });
2142
1875
  this.log({
@@ -2172,33 +1905,16 @@ var ChannelDriver = class {
2172
1905
  return dispatched;
2173
1906
  }
2174
1907
  async ensureSession(conv) {
2175
- const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
2176
- if (bound) {
2177
- const exists = await sessionExists(this.port, bound);
2178
- if (exists === false) {
2179
- this.log({
2180
- level: "info",
2181
- 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.`,
2182
- conversation_id: conv.id
2183
- });
2184
- this.sessions.delete(conv.id);
2185
- return this.createAndBindSession(conv.id);
2186
- }
2187
- this.sessions.set(conv.id, bound);
2188
- return bound;
1908
+ const cached = this.sessions.get(conv.id);
1909
+ if (cached) return cached;
1910
+ if (conv.opencode_session_id) {
1911
+ this.sessions.set(conv.id, conv.opencode_session_id);
1912
+ return conv.opencode_session_id;
2189
1913
  }
2190
- return this.createAndBindSession(conv.id);
2191
- }
2192
- /**
2193
- * Create a fresh OpenCode session for a conversation, cache the binding, and
2194
- * best-effort persist it server-side. Shared by the first-ever bind and the
2195
- * self-heal recreate path in `ensureSession`.
2196
- */
2197
- async createAndBindSession(conversationId) {
2198
1914
  const directory = await this.resolveOpenCodeDirectory();
2199
1915
  const sessionId = await createOpenCodeSession(this.port, directory);
2200
- this.sessions.set(conversationId, sessionId);
2201
- await this.persistSession(conversationId, sessionId).catch(() => {
1916
+ this.sessions.set(conv.id, sessionId);
1917
+ await this.persistSession(conv.id, sessionId).catch(() => {
2202
1918
  });
2203
1919
  return sessionId;
2204
1920
  }
@@ -2776,15 +2492,6 @@ var ChannelDriver = class {
2776
2492
  * `processed_at` (Invariant 1).
2777
2493
  */
2778
2494
  async forceReadoptRun(sessionId, row) {
2779
- if (this.stopped) {
2780
- this.log({
2781
- level: "info",
2782
- 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`,
2783
- conversation_id: row.conversation_id,
2784
- message_id: row.id
2785
- });
2786
- return;
2787
- }
2788
2495
  if (this.awaitingReadopt.has(row.id)) {
2789
2496
  this.log({
2790
2497
  level: "info",
@@ -2952,8 +2659,8 @@ var ChannelDriver = class {
2952
2659
  } catch {
2953
2660
  }
2954
2661
  for (const q of questions) {
2662
+ if (q.sessionID !== sessionId) continue;
2955
2663
  if (watcher.reportedQuestions.has(q.id)) continue;
2956
- if (!await this.sessionBelongsTo(q.sessionID, sessionId)) continue;
2957
2664
  const paused = this.attributeInteraction(watcher, q.tool?.messageID, messages);
2958
2665
  const reported = await this.reportInteraction(
2959
2666
  watcher.conv.id,
@@ -2973,8 +2680,8 @@ var ChannelDriver = class {
2973
2680
  } catch {
2974
2681
  }
2975
2682
  for (const p of permissions) {
2683
+ if (p.sessionID !== sessionId) continue;
2976
2684
  if (watcher.reportedPermissions.has(p.id)) continue;
2977
- if (!await this.sessionBelongsTo(p.sessionID, sessionId)) continue;
2978
2685
  const paused = this.attributeInteraction(watcher, p.messageID, messages);
2979
2686
  const reported = await this.reportInteraction(
2980
2687
  watcher.conv.id,
@@ -2985,50 +2692,6 @@ var ChannelDriver = class {
2985
2692
  if (reported) watcher.reportedPermissions.add(p.id);
2986
2693
  }
2987
2694
  }
2988
- /**
2989
- * True when `sessionId` is the `rootSessionId` itself OR a descendant of it —
2990
- * i.e. its `parentID` chain (resolved via `GET /session/:id`) reaches the
2991
- * watched root. Sub-agents spawned via the `task` tool run in child sessions,
2992
- * so their questions/permissions live under a different `sessionID` that must
2993
- * still be attributed to the root conversation the watcher owns.
2994
- *
2995
- * Parents are cached in `sessionParents` so we walk each session at most once;
2996
- * a bounded depth cap guards against a cycle or a pathological chain, and any
2997
- * fetch failure is treated as "not a descendant" (best-effort — the interaction
2998
- * simply isn't surfaced this tick and is retried next tick once resolvable).
2999
- */
3000
- async sessionBelongsTo(sessionId, rootSessionId) {
3001
- let current = sessionId;
3002
- for (let depth = 0; current && depth < 32; depth++) {
3003
- if (current === rootSessionId) return true;
3004
- const parent = await this.resolveSessionParent(current);
3005
- if (parent === null || parent === void 0) return false;
3006
- current = parent;
3007
- }
3008
- return false;
3009
- }
3010
- /**
3011
- * Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
3012
- * `null` for a root session (no parent) and `undefined` when opencode is
3013
- * unreachable / the session can't be read (so the caller stops walking without
3014
- * caching a wrong answer — the next tick retries).
3015
- */
3016
- async resolveSessionParent(sessionId) {
3017
- const cached = this.sessionParents.get(sessionId);
3018
- if (cached !== void 0) return cached;
3019
- let parent = void 0;
3020
- try {
3021
- const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}`);
3022
- if (res.ok) {
3023
- const body = await res.json();
3024
- parent = body && typeof body.parentID === "string" ? body.parentID : null;
3025
- }
3026
- } catch {
3027
- parent = void 0;
3028
- }
3029
- if (parent !== void 0) this.sessionParents.set(sessionId, parent);
3030
- return parent;
3031
- }
3032
2695
  /**
3033
2696
  * Attribute a surfaced interaction to the in-flight message it paused on (M-1).
3034
2697
  *
@@ -3558,25 +3221,6 @@ async function resolveAgentIdFromKey(authHeader) {
3558
3221
  return { error: `Failed to resolve agent from key: ${message}` };
3559
3222
  }
3560
3223
  }
3561
- async function notifyAgentDisconnected(agentId, authHeader) {
3562
- const apiUrl = getApiUrlConfig();
3563
- try {
3564
- const response = await fetch(`${apiUrl}/agents/${agentId}/disconnect`, {
3565
- method: "POST",
3566
- headers: { Authorization: authHeader }
3567
- });
3568
- if (!response.ok) {
3569
- const serverMessage = await readErrorMessage(response);
3570
- return {
3571
- ok: false,
3572
- error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
3573
- };
3574
- }
3575
- return { ok: true };
3576
- } catch (error2) {
3577
- return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
3578
- }
3579
- }
3580
3224
  async function getAgentInfo(agentId, authHeader) {
3581
3225
  const apiUrl = getApiUrlConfig();
3582
3226
  try {
@@ -3623,7 +3267,6 @@ async function getAgentInfo(agentId, authHeader) {
3623
3267
  var MAX_ACTIVITY_LOG_ENTRIES = 10;
3624
3268
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
3625
3269
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
3626
- var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
3627
3270
  function log2(state, message, isError = false) {
3628
3271
  if (state.json) {
3629
3272
  console.log(
@@ -3778,7 +3421,7 @@ async function driveChannels(state, driver) {
3778
3421
  logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
3779
3422
  if (state.interactive) displayStatus(state);
3780
3423
  }
3781
- await new Promise((resolve2) => setTimeout(resolve2, CHANNEL_POLL_INTERVAL_MS));
3424
+ await new Promise((resolve) => setTimeout(resolve, CHANNEL_POLL_INTERVAL_MS));
3782
3425
  if (state.idleTimeout !== null && idlePolls >= 2) {
3783
3426
  const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
3784
3427
  if (idleMs > state.idleTimeout * 1e3) {
@@ -3789,122 +3432,8 @@ async function driveChannels(state, driver) {
3789
3432
  }
3790
3433
  }
3791
3434
  }
3792
- var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
3793
- async function runSweep(state, driver, config2) {
3794
- const mode = `age=${config2.maxAgeMs ?? "\u2014"} count=${config2.maxCount ?? "\u2014"}`;
3795
- try {
3796
- const sessions = await listSessions(state.port);
3797
- if (sessions === null) {
3798
- logActivity(state, {
3799
- type: "info",
3800
- message: `Session cleanup: could not list sessions (opencode unreachable); skipping this sweep (${mode})`
3801
- });
3802
- return;
3803
- }
3804
- const toDelete = selectSessionsToDelete(
3805
- sessions.map((s) => ({ id: s.id, lastActivityMs: sessionLastActivityMs(s) })),
3806
- {
3807
- maxAgeMs: config2.maxAgeMs,
3808
- maxCount: config2.maxCount,
3809
- nowMs: Date.now(),
3810
- protectedIds: driver.protectedSessionIds()
3811
- }
3812
- );
3813
- const protectedNow = driver.protectedSessionIds();
3814
- let deleted = 0;
3815
- let failed = 0;
3816
- let skippedNewlyActive = 0;
3817
- for (const id of toDelete) {
3818
- if (protectedNow.has(id)) {
3819
- skippedNewlyActive++;
3820
- logActivity(state, {
3821
- type: "info",
3822
- message: `Session cleanup: skipping ${id} \u2014 became active/bound after selection (${mode})`
3823
- });
3824
- continue;
3825
- }
3826
- if (await deleteSession(state.port, id)) deleted++;
3827
- else failed++;
3828
- }
3829
- const failedNote = failed > 0 ? `, failed ${failed}` : "";
3830
- const skippedNote = skippedNewlyActive > 0 ? `, skipped ${skippedNewlyActive} newly-active` : "";
3831
- logActivity(state, {
3832
- type: "info",
3833
- message: `Session cleanup: inspected ${sessions.length}, deleted ${deleted}${failedNote}${skippedNote} (${mode})`
3834
- });
3835
- } catch (error2) {
3836
- const message = error2 instanceof Error ? error2.message : String(error2);
3837
- logActivity(state, {
3838
- type: "error",
3839
- error: `Session cleanup sweep failed (non-fatal, ${mode}): ${message}`
3840
- });
3841
- }
3842
- }
3843
- function scheduleSessionCleanup(state, driver, options) {
3844
- const config2 = resolveSessionCleanupConfig(
3845
- {
3846
- maxAge: options.sessionCleanupMaxAge,
3847
- maxCount: options.sessionCleanupMaxCount,
3848
- interval: options.sessionCleanupInterval
3849
- },
3850
- process.env
3851
- );
3852
- for (const warning2 of config2.warnings) {
3853
- logActivity(state, { type: "info", message: `Session cleanup: ${warning2}` });
3854
- }
3855
- if (!config2.enabled) return;
3856
- logActivity(state, {
3857
- type: "info",
3858
- message: `Session cleanup enabled (age=${config2.maxAgeMs ?? "\u2014"}, count=${config2.maxCount ?? "\u2014"}, interval=${config2.intervalMs}ms)`
3859
- });
3860
- const interval = setInterval(() => void runSweep(state, driver, config2), config2.intervalMs);
3861
- const firstSweep = setTimeout(
3862
- () => void runSweep(state, driver, config2),
3863
- SESSION_CLEANUP_FIRST_SWEEP_MS
3864
- );
3865
- state.sessionCleanupTimers.push(interval, firstSweep);
3866
- }
3867
- async function notifyOffline(state) {
3868
- if (!state.agentId || !state.authHeader) return;
3869
- if (!state.connected) {
3870
- log2(state, "Skipping offline signal \u2014 this runner does not hold the live tunnel");
3871
- return;
3872
- }
3873
- const result = await notifyAgentDisconnected(state.agentId, state.authHeader);
3874
- if (result.ok) {
3875
- log2(state, "Notified Evident the agent is going offline");
3876
- } else {
3877
- logActivity(state, {
3878
- type: "error",
3879
- error: `Could not notify Evident of offline status (relay will still report it): ${result.error}`
3880
- });
3881
- if (state.interactive) displayStatus(state);
3882
- }
3883
- }
3884
- async function cleanup(state, opts = {}) {
3435
+ async function cleanup(state) {
3885
3436
  state.running = false;
3886
- for (const timer of state.sessionCleanupTimers) {
3887
- clearInterval(timer);
3888
- clearTimeout(timer);
3889
- }
3890
- state.sessionCleanupTimers = [];
3891
- if (opts.graceful && state.channelDriver) {
3892
- state.channelDriver.stop();
3893
- log2(state, "Draining in-flight channel work before shutdown...");
3894
- if (state.interactive) {
3895
- logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
3896
- displayStatus(state);
3897
- }
3898
- const settled = await state.channelDriver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS);
3899
- if (!settled) {
3900
- logActivity(state, {
3901
- type: "info",
3902
- message: "Shutdown drain timed out with work still in flight \u2014 leaving it for restart recovery"
3903
- });
3904
- if (state.interactive) displayStatus(state);
3905
- }
3906
- }
3907
- await notifyOffline(state);
3908
3437
  if (state.connection) {
3909
3438
  state.connection.close();
3910
3439
  state.connection = null;
@@ -3935,13 +3464,10 @@ async function run(options) {
3935
3464
  opencodeVersion: null,
3936
3465
  opencodeProcess: null,
3937
3466
  connection: null,
3938
- channelDriver: null,
3939
3467
  running: true,
3940
- shuttingDown: false,
3941
3468
  activityLog: [],
3942
3469
  messageCount: 0,
3943
3470
  lastProxiedActivityAt: null,
3944
- sessionCleanupTimers: [],
3945
3471
  authHeader: ""
3946
3472
  };
3947
3473
  if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
@@ -3952,15 +3478,13 @@ async function run(options) {
3952
3478
  );
3953
3479
  }
3954
3480
  const handleSignal = async () => {
3955
- if (state.shuttingDown) return;
3956
- state.shuttingDown = true;
3957
3481
  if (state.interactive) {
3958
3482
  logActivity(state, { type: "info", message: "Shutting down..." });
3959
3483
  displayStatus(state);
3960
3484
  } else {
3961
3485
  log2(state, "Shutting down...");
3962
3486
  }
3963
- await cleanup(state, { graceful: true });
3487
+ await cleanup(state);
3964
3488
  await shutdownTelemetry();
3965
3489
  process.exit(0);
3966
3490
  };
@@ -4087,7 +3611,6 @@ async function run(options) {
4087
3611
  error: entry.level === "error" ? entry.message : void 0
4088
3612
  })
4089
3613
  });
4090
- state.channelDriver = channelDriver;
4091
3614
  const connection = new RunnerConnection({
4092
3615
  agentId: state.agentId,
4093
3616
  getAuthHeader: () => state.authHeader,
@@ -4184,12 +3707,10 @@ async function run(options) {
4184
3707
  if (error2.message === "Unauthorized") tunnelSpinner?.fail("Unauthorized");
4185
3708
  throw error2;
4186
3709
  }
4187
- scheduleSessionCleanup(state, channelDriver, options);
4188
3710
  if (!interactive || state.json) {
4189
3711
  log2(state, "Driving channel messages...");
4190
3712
  }
4191
3713
  await driveChannels(state, channelDriver);
4192
- if (state.shuttingDown) return;
4193
3714
  await cleanup(state);
4194
3715
  if (state.json) {
4195
3716
  console.log(
@@ -4204,7 +3725,6 @@ async function run(options) {
4204
3725
  await shutdownTelemetry();
4205
3726
  process.exit(0);
4206
3727
  } catch (error2) {
4207
- if (state.shuttingDown) return;
4208
3728
  await cleanup(state);
4209
3729
  const message = error2 instanceof Error ? error2.message : String(error2);
4210
3730
  if (state.json) {
@@ -4239,16 +3759,7 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
4239
3759
  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);
4240
3760
  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 }));
4241
3761
  program.command("whoami").description("Show the currently logged in user").action(whoami);
4242
- 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").option(
4243
- "--session-cleanup-max-age <duration>",
4244
- "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
4245
- ).option(
4246
- "--session-cleanup-max-count <n>",
4247
- "Keep only the newest N OpenCode sessions. Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_COUNT"
4248
- ).option(
4249
- "--session-cleanup-interval <duration>",
4250
- "How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
4251
- ).action(
3762
+ 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(
4252
3763
  (options) => {
4253
3764
  run({
4254
3765
  agent: options.agent,
@@ -4256,11 +3767,7 @@ program.command("run").description("Connect to Evident and process messages").op
4256
3767
  verbose: options.verbose,
4257
3768
  conversation: options.conversation,
4258
3769
  idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
4259
- json: options.json,
4260
- // Raw strings — the resolver in run.ts single-sources parsing (M1).
4261
- sessionCleanupMaxAge: options.sessionCleanupMaxAge,
4262
- sessionCleanupMaxCount: options.sessionCleanupMaxCount,
4263
- sessionCleanupInterval: options.sessionCleanupInterval
3770
+ json: options.json
4264
3771
  });
4265
3772
  }
4266
3773
  );