@evident-ai/cli 3.0.1-dev.fffc02d → 3.1.1-dev.0d1732f

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
@@ -11,8 +11,8 @@ import chalk2 from "chalk";
11
11
 
12
12
  // src/lib/config.ts
13
13
  import Conf from "conf";
14
- import { homedir } from "os";
15
- import { join } from "path";
14
+ import { chmodSync, existsSync, statSync } from "fs";
15
+ import { dirname } from "path";
16
16
  var PRODUCTION_API_URL = "https://api.production.evident.run/v1";
17
17
  var PRODUCTION_TUNNEL_URL = "wss://tunnel.production.evident.run";
18
18
  var defaults = {
@@ -47,8 +47,35 @@ var credentials = new Conf({
47
47
  projectName: "evident",
48
48
  projectSuffix: "",
49
49
  configName: "credentials",
50
- defaults: {}
50
+ defaults: {},
51
+ configFileMode: 384
51
52
  });
53
+ var CREDENTIALS_FILE_MODE = 384;
54
+ var CREDENTIALS_DIR_MODE = 448;
55
+ var permissionWarningEmitted = false;
56
+ function hardenCredentialsPermissions() {
57
+ if (process.platform === "win32") {
58
+ return;
59
+ }
60
+ const file = credentials.path;
61
+ for (const [path, mode] of [
62
+ [file, CREDENTIALS_FILE_MODE],
63
+ [dirname(file), CREDENTIALS_DIR_MODE]
64
+ ]) {
65
+ try {
66
+ if (existsSync(path) && (statSync(path).mode & 511) !== mode) {
67
+ chmodSync(path, mode);
68
+ }
69
+ } catch (err) {
70
+ if (!permissionWarningEmitted) {
71
+ permissionWarningEmitted = true;
72
+ console.error(
73
+ `[config] could not restrict permissions on ${path}; the credentials file may be readable by other users on this machine: ${err instanceof Error ? err.message : String(err)}`
74
+ );
75
+ }
76
+ }
77
+ }
78
+ }
52
79
  function getApiUrlConfig() {
53
80
  return getApiUrl();
54
81
  }
@@ -59,6 +86,7 @@ function credentialsKey() {
59
86
  return getApiUrl();
60
87
  }
61
88
  function getCredentials() {
89
+ hardenCredentialsPermissions();
62
90
  const byEndpoint = credentials.get("byEndpoint") ?? {};
63
91
  return byEndpoint[credentialsKey()] ?? {};
64
92
  }
@@ -70,14 +98,17 @@ function setCredentials(creds) {
70
98
  expiresAt: creds.expiresAt
71
99
  };
72
100
  credentials.set("byEndpoint", byEndpoint);
101
+ hardenCredentialsPermissions();
73
102
  }
74
103
  function clearCredentials() {
75
104
  const byEndpoint = credentials.get("byEndpoint") ?? {};
76
105
  delete byEndpoint[credentialsKey()];
77
106
  credentials.set("byEndpoint", byEndpoint);
107
+ hardenCredentialsPermissions();
78
108
  }
79
109
  function clearAllCredentials() {
80
110
  credentials.clear();
111
+ hardenCredentialsPermissions();
81
112
  }
82
113
  function getCliName() {
83
114
  const argv1 = process.argv[1] || "";
@@ -285,14 +316,14 @@ function blank() {
285
316
  console.log();
286
317
  }
287
318
  function waitForEnter(prompt = "Press Enter to continue...") {
288
- return new Promise((resolve) => {
319
+ return new Promise((resolve3) => {
289
320
  process.stdout.write(chalk.dim(prompt));
290
321
  const handler = () => {
291
322
  process.stdin.removeListener("data", handler);
292
323
  process.stdin.setRawMode?.(false);
293
324
  process.stdin.pause();
294
325
  console.log();
295
- resolve();
326
+ resolve3();
296
327
  };
297
328
  if (process.stdin.isTTY) {
298
329
  process.stdin.setRawMode?.(true);
@@ -302,7 +333,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
302
333
  });
303
334
  }
304
335
  function sleep(ms) {
305
- return new Promise((resolve) => setTimeout(resolve, ms));
336
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
306
337
  }
307
338
 
308
339
  // src/commands/login.ts
@@ -373,22 +404,23 @@ async function deviceFlowLogin(options) {
373
404
  }
374
405
  async function tokenLogin() {
375
406
  console.log("Token login mode.");
376
- console.log("Visit your Evident dashboard to generate a CLI token.");
407
+ console.log("Run `evident login` on a machine with a browser to get a token.");
408
+ console.log("Manage or revoke existing tokens under Settings \u2192 CLI tokens.");
377
409
  blank();
378
410
  process.stdout.write("Paste token: ");
379
- const token = await new Promise((resolve) => {
411
+ const token = await new Promise((resolve3) => {
380
412
  let data = "";
381
413
  process.stdin.setEncoding("utf8");
382
414
  process.stdin.on("data", (chunk) => {
383
415
  data += chunk;
384
416
  });
385
417
  process.stdin.on("end", () => {
386
- resolve(data.trim());
418
+ resolve3(data.trim());
387
419
  });
388
420
  if (process.stdin.isTTY) {
389
421
  process.stdin.once("data", (chunk) => {
390
422
  process.stdin.pause();
391
- resolve(chunk.toString().trim());
423
+ resolve3(chunk.toString().trim());
392
424
  });
393
425
  process.stdin.resume();
394
426
  }
@@ -467,9 +499,9 @@ async function whoami() {
467
499
  }
468
500
 
469
501
  // src/commands/run.ts
502
+ import { homedir as homedir2 } from "os";
503
+ import { isAbsolute as isAbsolute2, join as join2, parse, resolve as resolvePath } from "path";
470
504
  import chalk6 from "chalk";
471
- import ora3 from "ora";
472
- import { select as select3 } from "@inquirer/prompts";
473
505
 
474
506
  // ../../packages/types/src/telemetry/index.ts
475
507
  var TelemetryEventTypes = {
@@ -485,6 +517,10 @@ var TelemetryEventTypes = {
485
517
  var MAX_FRAME_BYTES = 256 * 1024;
486
518
  var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
487
519
 
520
+ // ../../packages/types/src/runner-files.ts
521
+ var MAX_FILE_PUSH_BYTES = 64 * 1024;
522
+ var MAX_FILE_SYNC_DIRECTORIES = 16;
523
+
488
524
  // ../../packages/types/src/logging/index.ts
489
525
  var CORRELATION_ID_HEADER = "x-evident-correlation-id";
490
526
  function log(level, event, fields) {
@@ -499,6 +535,12 @@ function log(level, event, fields) {
499
535
  );
500
536
  }
501
537
  }
538
+ function errorFields(err) {
539
+ if (err instanceof Error) {
540
+ return { error: err.message, error_name: err.name };
541
+ }
542
+ return { error: String(err) };
543
+ }
502
544
  function stripQuery(url) {
503
545
  try {
504
546
  return new URL(url).pathname;
@@ -508,6 +550,10 @@ function stripQuery(url) {
508
550
  }
509
551
  }
510
552
 
553
+ // src/commands/run.ts
554
+ import ora3 from "ora";
555
+ import { select as select3 } from "@inquirer/prompts";
556
+
511
557
  // src/lib/telemetry.ts
512
558
  var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
513
559
  function getCliVersion() {
@@ -645,14 +691,27 @@ var EventTypes = {
645
691
  // CLI lifecycle
646
692
  CLI_STARTED: "cli.started",
647
693
  CLI_COMMAND: "cli.command",
648
- CLI_ERROR: "cli.error"
694
+ CLI_ERROR: "cli.error",
695
+ // Deprecation telemetry (#412) — usage of the old `--agent`/`EVIDENT_AGENT_KEY`
696
+ // names instead of the preferred `--runner`/`EVIDENT_RUNNER_KEY` (#409).
697
+ DEPRECATED_AGENT_FLAG_USED: "cli.deprecated_agent_flag_used",
698
+ DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
649
699
  };
650
700
 
651
701
  // src/lib/auth.ts
652
702
  async function getAuthCredentials() {
703
+ const runnerKey = process.env.EVIDENT_RUNNER_KEY;
653
704
  const agentKey = process.env.EVIDENT_AGENT_KEY;
705
+ if (runnerKey) {
706
+ return {
707
+ token: runnerKey,
708
+ authType: "agent_key",
709
+ keySource: "runner_key",
710
+ notice: agentKey ? "Both EVIDENT_RUNNER_KEY and EVIDENT_AGENT_KEY are set; using EVIDENT_RUNNER_KEY." : void 0
711
+ };
712
+ }
654
713
  if (agentKey) {
655
- return { token: agentKey, authType: "agent_key" };
714
+ return { token: agentKey, authType: "agent_key", keySource: "agent_key" };
656
715
  }
657
716
  const userToken = process.env.EVIDENT_TOKEN;
658
717
  if (userToken) {
@@ -706,7 +765,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
706
765
  if (health.healthy) {
707
766
  return health;
708
767
  }
709
- await new Promise((resolve) => setTimeout(resolve, 1e3));
768
+ await new Promise((resolve3) => setTimeout(resolve3, 1e3));
710
769
  }
711
770
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
712
771
  }
@@ -721,7 +780,7 @@ function buildOpenCodeVersionWarning(version2) {
721
780
  if (isQueueValidatedVersion(version2)) return null;
722
781
  const detected = version2 ? `v${version2}` : "unknown";
723
782
  const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
724
- return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack/WhatsApp) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
783
+ return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
725
784
  }
726
785
 
727
786
  // src/lib/opencode/process.ts
@@ -1013,6 +1072,12 @@ async function promptOpenCodeInstall(interactive) {
1013
1072
  return action;
1014
1073
  }
1015
1074
 
1075
+ // src/lib/opencode/provider-check.ts
1076
+ function buildNoProviderWarning(hasProvider) {
1077
+ if (hasProvider !== false) return null;
1078
+ return "Warning: opencode has no authenticated model provider configured, so it won't be able to answer prompts. Run `opencode auth login` to set one up (see https://opencode.ai for details).";
1079
+ }
1080
+
1016
1081
  // src/lib/opencode/session.ts
1017
1082
  function opencodeBase(port) {
1018
1083
  return `http://127.0.0.1:${port}`;
@@ -1078,6 +1143,84 @@ async function getSessionMessages(port, sessionId) {
1078
1143
  return null;
1079
1144
  }
1080
1145
  }
1146
+ function isSessionActivelyGenerating(messages) {
1147
+ if (!messages || messages.length === 0) return false;
1148
+ const last = messages[messages.length - 1];
1149
+ if (roleOf(last) !== "assistant") return false;
1150
+ return completedOf(last) == null;
1151
+ }
1152
+ function sessionLastActivityMs(session) {
1153
+ const candidates = [
1154
+ session.time?.updated,
1155
+ session.time?.created,
1156
+ session.time_updated,
1157
+ session.time_created,
1158
+ session.updated,
1159
+ session.created
1160
+ ];
1161
+ for (const c of candidates) {
1162
+ if (typeof c === "number" && Number.isFinite(c)) return c;
1163
+ }
1164
+ return null;
1165
+ }
1166
+ async function listSessions(port) {
1167
+ try {
1168
+ const res = await fetch(`${opencodeBase(port)}/session`);
1169
+ if (!res.ok) return null;
1170
+ const body = await res.json();
1171
+ return Array.isArray(body) ? body : null;
1172
+ } catch {
1173
+ return null;
1174
+ }
1175
+ }
1176
+ async function deleteSession(port, id) {
1177
+ try {
1178
+ const res = await fetch(`${opencodeBase(port)}/session/${id}`, { method: "DELETE" });
1179
+ return res.status >= 200 && res.status < 300;
1180
+ } catch {
1181
+ return false;
1182
+ }
1183
+ }
1184
+ async function sessionExists(port, id) {
1185
+ try {
1186
+ const res = await fetch(`${opencodeBase(port)}/session/${id}`);
1187
+ if (res.status >= 200 && res.status < 300) return true;
1188
+ if (res.status === 404) return false;
1189
+ return null;
1190
+ } catch {
1191
+ return null;
1192
+ }
1193
+ }
1194
+ async function getSessionStatuses(port) {
1195
+ try {
1196
+ const res = await fetch(`${opencodeBase(port)}/session/status`);
1197
+ if (!res.ok) {
1198
+ console.error(
1199
+ `[getSessionStatuses] GET /session/status returned HTTP ${res.status} (port ${port})`
1200
+ );
1201
+ return null;
1202
+ }
1203
+ const body = await res.json();
1204
+ if (body == null || typeof body !== "object" || Array.isArray(body)) {
1205
+ console.error(
1206
+ `[getSessionStatuses] GET /session/status body was not a plain object (port ${port})`
1207
+ );
1208
+ return null;
1209
+ }
1210
+ return body;
1211
+ } catch (err) {
1212
+ console.error(
1213
+ `[getSessionStatuses] GET /session/status failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
1214
+ );
1215
+ return null;
1216
+ }
1217
+ }
1218
+ async function isSessionOngoing(port, id) {
1219
+ const map = await getSessionStatuses(port);
1220
+ if (map == null) return null;
1221
+ const entry = map[id];
1222
+ return entry != null && entry.type !== "idle";
1223
+ }
1081
1224
  async function createOpenCodeSession(port, directory) {
1082
1225
  const url = new URL(`${opencodeBase(port)}/session`);
1083
1226
  if (directory && directory.trim()) {
@@ -1095,17 +1238,128 @@ async function createOpenCodeSession(port, directory) {
1095
1238
  const data = await response.json();
1096
1239
  return data.id;
1097
1240
  }
1241
+ async function getModelAttachmentCapability(port, model) {
1242
+ try {
1243
+ const res = await fetch(`${opencodeBase(port)}/config/providers`);
1244
+ if (!res.ok) {
1245
+ console.error(
1246
+ `[getModelAttachmentCapability] GET /config/providers returned HTTP ${res.status} (port ${port})`
1247
+ );
1248
+ return null;
1249
+ }
1250
+ const body = await res.json();
1251
+ const providers = Array.isArray(body?.providers) ? body.providers : null;
1252
+ if (!providers) {
1253
+ console.error(
1254
+ `[getModelAttachmentCapability] GET /config/providers body had no providers array (port ${port})`
1255
+ );
1256
+ return null;
1257
+ }
1258
+ const slash = model ? model.indexOf("/") : -1;
1259
+ const providerId = slash > 0 ? model.slice(0, slash) : void 0;
1260
+ let modelId = slash > 0 ? model.slice(slash + 1) : void 0;
1261
+ const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
1262
+ let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
1263
+ if (!provider && !providerId) {
1264
+ const defaultProviderIds = defaults2 ? Object.keys(defaults2) : [];
1265
+ if (defaultProviderIds.length === 1) {
1266
+ provider = providers.find((p) => p?.id === defaultProviderIds[0]);
1267
+ }
1268
+ }
1269
+ if (!provider || !provider.models) return null;
1270
+ if (!modelId && defaults2 && typeof provider.id === "string") {
1271
+ const def = defaults2[provider.id];
1272
+ if (typeof def === "string") modelId = def;
1273
+ }
1274
+ if (!modelId) {
1275
+ if (providerId) {
1276
+ const keys = Object.keys(provider.models);
1277
+ if (keys.length === 1) modelId = keys[0];
1278
+ }
1279
+ if (!modelId) return null;
1280
+ }
1281
+ const entry = provider.models[modelId];
1282
+ if (!entry || typeof entry !== "object") return null;
1283
+ if (entry.capabilities && typeof entry.capabilities === "object") {
1284
+ if (typeof entry.capabilities.attachment === "boolean") {
1285
+ return entry.capabilities.attachment;
1286
+ }
1287
+ }
1288
+ return typeof entry.attachment === "boolean" ? entry.attachment : null;
1289
+ } catch (err) {
1290
+ console.error(
1291
+ `[getModelAttachmentCapability] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
1292
+ );
1293
+ return null;
1294
+ }
1295
+ }
1296
+ async function buildFileParts(attachments, capable) {
1297
+ const outcomes = [];
1298
+ const parts = [];
1299
+ const capabilityUnknown = capable === null;
1300
+ if (capable !== true) {
1301
+ for (const a of attachments.inputs) {
1302
+ outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "skipped" });
1303
+ }
1304
+ return { parts, outcomes, capabilityUnknown };
1305
+ }
1306
+ for (const a of attachments.inputs) {
1307
+ let dataUrl = null;
1308
+ try {
1309
+ dataUrl = await attachments.fetchDataUrl(a.index);
1310
+ } catch (err) {
1311
+ console.error(
1312
+ `[buildFileParts] attachment ${a.index} (${a.mime}) fetch threw \u2014 omitting: ${err instanceof Error ? err.message : String(err)}`
1313
+ );
1314
+ dataUrl = null;
1315
+ }
1316
+ if (dataUrl !== null && typeof dataUrl === "object") {
1317
+ outcomes.push({
1318
+ index: a.index,
1319
+ mime: a.mime,
1320
+ filename: a.filename,
1321
+ status: "failed",
1322
+ reason: "needs_reauth"
1323
+ });
1324
+ continue;
1325
+ }
1326
+ if (dataUrl == null) {
1327
+ outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
1328
+ continue;
1329
+ }
1330
+ parts.push({
1331
+ type: "file",
1332
+ mime: a.mime,
1333
+ url: dataUrl,
1334
+ ...a.filename ? { filename: a.filename } : {}
1335
+ });
1336
+ outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "sent" });
1337
+ }
1338
+ return { parts, outcomes, capabilityUnknown };
1339
+ }
1098
1340
  function messageText(m) {
1099
1341
  if (!m || !Array.isArray(m.parts)) return "";
1100
1342
  return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
1101
1343
  }
1102
- async function sendPromptAsync(port, sessionId, content, options) {
1344
+ async function sendPromptAsync(port, sessionId, content, options, attachments) {
1103
1345
  const before = await getSessionMessages(port, sessionId);
1104
1346
  const knownUserIds = new Set(
1105
1347
  (before ?? []).filter((m) => roleOf(m) === "user").map((m) => idOf(m)).filter((id) => typeof id === "string")
1106
1348
  );
1349
+ const parts = [{ type: "text", text: content }];
1350
+ let pendingOutcomes = null;
1351
+ if (attachments && attachments.inputs.length > 0) {
1352
+ const capable = await getModelAttachmentCapability(port, options?.model);
1353
+ const {
1354
+ parts: fileParts,
1355
+ outcomes,
1356
+ capabilityUnknown
1357
+ } = await buildFileParts(attachments, capable);
1358
+ parts.push(...fileParts);
1359
+ if (attachments.onOutcomes) pendingOutcomes = { outcomes, capabilityUnknown };
1360
+ }
1107
1361
  const body = {
1108
- parts: [{ type: "text", text: content }]
1362
+ parts
1109
1363
  };
1110
1364
  if (options?.agent) {
1111
1365
  body.agent = options.agent;
@@ -1144,10 +1398,13 @@ async function sendPromptAsync(port, sessionId, content, options) {
1144
1398
  best = { id, created };
1145
1399
  }
1146
1400
  }
1147
- if (best) return best.id;
1401
+ if (best) {
1402
+ if (pendingOutcomes && attachments?.onOutcomes) attachments.onOutcomes(pendingOutcomes);
1403
+ return best.id;
1404
+ }
1148
1405
  }
1149
1406
  if (attempt < READ_BACK_ATTEMPTS - 1) {
1150
- await new Promise((resolve) => setTimeout(resolve, READ_BACK_DELAY_MS));
1407
+ await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
1151
1408
  }
1152
1409
  }
1153
1410
  return null;
@@ -1193,6 +1450,72 @@ function findLastAssistantReplyFor(messages, userMessageId) {
1193
1450
  }
1194
1451
  return lastOk ?? last;
1195
1452
  }
1453
+ function messageUsage(messages, userMessageId) {
1454
+ if (!messages || messages.length === 0) return null;
1455
+ const byParentAll = messages.filter(
1456
+ (m) => roleOf(m) === "assistant" && parentIdOf(m) === userMessageId
1457
+ );
1458
+ const byParentNonErrored = byParentAll.filter((m) => errorOf(m) == null);
1459
+ const byParent = byParentNonErrored.length > 0 ? byParentNonErrored : byParentAll;
1460
+ let correlated;
1461
+ if (byParent.length > 0) {
1462
+ correlated = byParent;
1463
+ } else {
1464
+ const reply = findAssistantReplyAfter(messages, userMessageId);
1465
+ correlated = reply ? [reply] : [];
1466
+ }
1467
+ if (correlated.length === 0) return null;
1468
+ let sawAnyUsage = false;
1469
+ let inputSum = 0;
1470
+ let outputSum = 0;
1471
+ let reasoningSum = 0;
1472
+ let cacheReadSum = 0;
1473
+ let cacheWriteSum = 0;
1474
+ let costSum = 0;
1475
+ let sawCost = false;
1476
+ let modelId = null;
1477
+ let providerId = null;
1478
+ for (const m of correlated) {
1479
+ const info = m.info;
1480
+ if (!info) continue;
1481
+ const tokens = info.tokens;
1482
+ if (tokens) {
1483
+ sawAnyUsage = true;
1484
+ inputSum += tokens.input ?? 0;
1485
+ outputSum += tokens.output ?? 0;
1486
+ reasoningSum += tokens.reasoning ?? 0;
1487
+ cacheReadSum += tokens.cache?.read ?? 0;
1488
+ cacheWriteSum += tokens.cache?.write ?? 0;
1489
+ }
1490
+ if (typeof info.cost === "number") {
1491
+ sawAnyUsage = true;
1492
+ sawCost = true;
1493
+ costSum += info.cost;
1494
+ }
1495
+ if (typeof info.modelID === "string") {
1496
+ sawAnyUsage = true;
1497
+ modelId = info.modelID;
1498
+ }
1499
+ if (typeof info.providerID === "string") {
1500
+ sawAnyUsage = true;
1501
+ providerId = info.providerID;
1502
+ }
1503
+ }
1504
+ if (!sawAnyUsage) return null;
1505
+ return {
1506
+ usage_provider_id: providerId,
1507
+ usage_model_id: modelId,
1508
+ usage_tokens_input: inputSum,
1509
+ usage_tokens_output: outputSum,
1510
+ usage_tokens_reasoning: reasoningSum,
1511
+ usage_tokens_cache_read: cacheReadSum,
1512
+ usage_tokens_cache_write: cacheWriteSum,
1513
+ // NULL means "OpenCode never reported a cost" (never inferred from
1514
+ // tokens) — distinct from a genuine 0-cost turn, which would set
1515
+ // `sawCost` true with `costSum === 0`.
1516
+ usage_cost_usd: sawCost ? costSum : null
1517
+ };
1518
+ }
1196
1519
  function messageRunState(messages, userMessageId) {
1197
1520
  if (!messages || messages.length === 0) return "unknown";
1198
1521
  const hasUser = messages.some((m) => idOf(m) === userMessageId);
@@ -1204,6 +1527,11 @@ function messageRunState(messages, userMessageId) {
1204
1527
  if (isAssistantInFlight(reply)) return "running";
1205
1528
  return errorOf(reply) != null ? "failed" : "done";
1206
1529
  }
1530
+ function isPreamblePinnedRunning(messages, userMessageId) {
1531
+ if (messageRunState(messages, userMessageId) !== "running") return false;
1532
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
1533
+ return completedOf(reply) != null && finishOf(reply) === "tool-calls";
1534
+ }
1207
1535
  function messageError(messages, userMessageId) {
1208
1536
  const reply = findLastAssistantReplyFor(messages, userMessageId);
1209
1537
  const error2 = errorOf(reply);
@@ -1223,6 +1551,141 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1223
1551
  (m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
1224
1552
  );
1225
1553
  }
1554
+ async function hasAnyConfiguredProvider(port) {
1555
+ try {
1556
+ const res = await fetch(`${opencodeBase(port)}/config/providers`);
1557
+ if (!res.ok) {
1558
+ console.error(
1559
+ `[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
1560
+ );
1561
+ return null;
1562
+ }
1563
+ const body = await res.json();
1564
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
1565
+ console.error(
1566
+ `[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
1567
+ );
1568
+ return null;
1569
+ }
1570
+ const defaults2 = body.default;
1571
+ if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
1572
+ console.error(
1573
+ `[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
1574
+ );
1575
+ return null;
1576
+ }
1577
+ return Object.keys(defaults2).length > 0;
1578
+ } catch (err) {
1579
+ console.error(
1580
+ `[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
1581
+ );
1582
+ return null;
1583
+ }
1584
+ }
1585
+
1586
+ // src/lib/opencode/session-cleanup.ts
1587
+ var DURATION_UNIT_MS = {
1588
+ s: 1e3,
1589
+ m: 60 * 1e3,
1590
+ h: 60 * 60 * 1e3,
1591
+ d: 24 * 60 * 60 * 1e3
1592
+ };
1593
+ function parseDurationMs(input) {
1594
+ const trimmed = input.trim();
1595
+ const match = /^(\d+)([smhd])$/.exec(trimmed);
1596
+ if (!match) {
1597
+ throw new Error(
1598
+ `Invalid duration "${input}": expected <number><unit> where unit is one of s, m, h, d (e.g. "7d", "24h", "30m", "90s").`
1599
+ );
1600
+ }
1601
+ const value = Number(match[1]);
1602
+ if (value <= 0) {
1603
+ throw new Error(`Invalid duration "${input}": must be a positive value.`);
1604
+ }
1605
+ return value * DURATION_UNIT_MS[match[2]];
1606
+ }
1607
+ function selectSessionsToDelete(sessions, opts) {
1608
+ const { maxAgeMs, maxCount, nowMs, protectedIds } = opts;
1609
+ if (maxAgeMs === void 0 && maxCount === void 0) return [];
1610
+ const ageEligible = (s) => {
1611
+ if (maxAgeMs === void 0) return false;
1612
+ if (s.lastActivityMs === null) return true;
1613
+ return nowMs - s.lastActivityMs > maxAgeMs;
1614
+ };
1615
+ const countEligibleIds = /* @__PURE__ */ new Set();
1616
+ if (maxCount !== void 0) {
1617
+ const byActivityDesc = [...sessions].sort(
1618
+ (a, b) => (b.lastActivityMs ?? -Infinity) - (a.lastActivityMs ?? -Infinity)
1619
+ );
1620
+ for (const s of byActivityDesc.slice(maxCount)) {
1621
+ countEligibleIds.add(s.id);
1622
+ }
1623
+ }
1624
+ const toDelete = [];
1625
+ for (const s of sessions) {
1626
+ if (protectedIds.has(s.id)) continue;
1627
+ if (ageEligible(s) || countEligibleIds.has(s.id)) {
1628
+ toDelete.push(s.id);
1629
+ }
1630
+ }
1631
+ return toDelete;
1632
+ }
1633
+ var DEFAULT_INTERVAL = "1h";
1634
+ function resolve(flag, envValue, fallback) {
1635
+ return flag ?? envValue ?? fallback;
1636
+ }
1637
+ function parseMaxCount(input) {
1638
+ const trimmed = input.trim();
1639
+ if (!/^\d+$/.test(trimmed)) {
1640
+ throw new Error(`Invalid max-count "${input}": expected a positive integer.`);
1641
+ }
1642
+ const value = Number(trimmed);
1643
+ if (value <= 0) {
1644
+ throw new Error(`Invalid max-count "${input}": must be greater than 0.`);
1645
+ }
1646
+ return value;
1647
+ }
1648
+ function resolveSessionCleanupConfig(flags, env = process.env) {
1649
+ const warnings = [];
1650
+ const maxAgeRaw = resolve(flags.maxAge, env.EVIDENT_SESSION_CLEANUP_MAX_AGE);
1651
+ const maxCountRaw = resolve(flags.maxCount, env.EVIDENT_SESSION_CLEANUP_MAX_COUNT);
1652
+ const intervalRaw = resolve(
1653
+ flags.interval,
1654
+ env.EVIDENT_SESSION_CLEANUP_INTERVAL,
1655
+ DEFAULT_INTERVAL
1656
+ );
1657
+ let maxAgeMs;
1658
+ if (maxAgeRaw !== void 0) {
1659
+ try {
1660
+ maxAgeMs = parseDurationMs(maxAgeRaw);
1661
+ } catch (err) {
1662
+ warnings.push(
1663
+ `Ignoring invalid --session-cleanup-max-age: ${err instanceof Error ? err.message : String(err)}`
1664
+ );
1665
+ }
1666
+ }
1667
+ let maxCount;
1668
+ if (maxCountRaw !== void 0) {
1669
+ try {
1670
+ maxCount = parseMaxCount(maxCountRaw);
1671
+ } catch (err) {
1672
+ warnings.push(
1673
+ `Ignoring invalid --session-cleanup-max-count: ${err instanceof Error ? err.message : String(err)}`
1674
+ );
1675
+ }
1676
+ }
1677
+ let intervalMs;
1678
+ try {
1679
+ intervalMs = parseDurationMs(intervalRaw ?? DEFAULT_INTERVAL);
1680
+ } catch (err) {
1681
+ warnings.push(
1682
+ `Ignoring invalid --session-cleanup-interval, using default ${DEFAULT_INTERVAL}: ${err instanceof Error ? err.message : String(err)}`
1683
+ );
1684
+ intervalMs = parseDurationMs(DEFAULT_INTERVAL);
1685
+ }
1686
+ const enabled = maxAgeMs !== void 0 || maxCount !== void 0;
1687
+ return { enabled, maxAgeMs, maxCount, intervalMs, warnings };
1688
+ }
1226
1689
 
1227
1690
  // src/lib/tunnel/connection.ts
1228
1691
  import WebSocket2 from "ws";
@@ -1277,10 +1740,11 @@ var StreamForwarder = class {
1277
1740
  * Abort every in-flight stream (e.g. on WebSocket close).
1278
1741
  */
1279
1742
  abortAll() {
1280
- for (const stream of this.inflight.values()) {
1743
+ for (const [sid, stream] of this.inflight.entries()) {
1281
1744
  try {
1282
1745
  stream.abort();
1283
- } catch {
1746
+ } catch (err) {
1747
+ log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
1284
1748
  }
1285
1749
  }
1286
1750
  this.inflight.clear();
@@ -1314,12 +1778,12 @@ var StreamForwarder = class {
1314
1778
  let endBody;
1315
1779
  if (has_body) {
1316
1780
  const chunks = [];
1317
- bodyPromise = new Promise((resolve) => {
1781
+ bodyPromise = new Promise((resolve3) => {
1318
1782
  pushBody = (buf) => {
1319
1783
  chunks.push(buf);
1320
1784
  };
1321
1785
  endBody = () => {
1322
- resolve(Buffer.concat(chunks));
1786
+ resolve3(Buffer.concat(chunks));
1323
1787
  };
1324
1788
  });
1325
1789
  }
@@ -1430,31 +1894,20 @@ function connectTunnel(options) {
1430
1894
  onConnected,
1431
1895
  onDisconnected,
1432
1896
  onError,
1433
- onRequest,
1434
1897
  onResponse,
1435
1898
  onInfo,
1436
1899
  onDrainPing
1437
1900
  } = options;
1438
1901
  const tunnelUrl = getTunnelUrlConfig();
1439
1902
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
1440
- return new Promise((resolve, reject) => {
1903
+ return new Promise((resolve3, reject) => {
1441
1904
  const ws = new WebSocket2(url, {
1442
1905
  headers: {
1443
1906
  Authorization: authHeader
1444
1907
  }
1445
1908
  });
1446
- const streamStartTimes = /* @__PURE__ */ new Map();
1447
1909
  const forwarder = new StreamForwarder(ws, port, {
1448
- onOpen: (sid, method, path) => {
1449
- if (path === TUNNEL_DRAIN_PING_PATH) return;
1450
- streamStartTimes.set(sid, Date.now());
1451
- onRequest?.(method, path, sid);
1452
- },
1453
- onHead: (sid, status) => {
1454
- const startedAt = streamStartTimes.get(sid);
1455
- streamStartTimes.delete(sid);
1456
- onResponse?.(status, startedAt ? Date.now() - startedAt : 0, sid);
1457
- },
1910
+ onHead: () => onResponse?.(),
1458
1911
  onDrainPing: () => onDrainPing?.()
1459
1912
  });
1460
1913
  const connectionTimeout = setTimeout(() => {
@@ -1502,7 +1955,7 @@ function connectTunnel(options) {
1502
1955
  clearTimeout(connectionTimeout);
1503
1956
  const connectedAgentId = message.agent_id ?? agentId;
1504
1957
  onConnected?.(connectedAgentId);
1505
- resolve({
1958
+ resolve3({
1506
1959
  ws,
1507
1960
  close: () => ws.close(1e3, "CLI shutdown")
1508
1961
  });
@@ -1530,7 +1983,6 @@ function connectTunnel(options) {
1530
1983
  ws.on("close", (code, reason) => {
1531
1984
  const reasonStr = reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
1532
1985
  forwarder.abortAll();
1533
- streamStartTimes.clear();
1534
1986
  onDisconnected?.(code, reasonStr);
1535
1987
  });
1536
1988
  });
@@ -1565,7 +2017,11 @@ var RunnerConnection = class {
1565
2017
  if (this.connection) {
1566
2018
  try {
1567
2019
  this.connection.close();
1568
- } catch {
2020
+ } catch (err) {
2021
+ log("error", "runner_connection_close_failed", {
2022
+ agent_id: this.resolvedAgentId,
2023
+ ...errorFields(err)
2024
+ });
1569
2025
  }
1570
2026
  this.connection = null;
1571
2027
  }
@@ -1618,73 +2074,516 @@ var RunnerConnection = class {
1618
2074
  };
1619
2075
 
1620
2076
  // src/lib/channels/driver.ts
1621
- function messageIdOf(m) {
1622
- if (!m || typeof m !== "object") return void 0;
1623
- if (typeof m.id === "string") return m.id;
1624
- const infoId = m.info?.id;
1625
- return typeof infoId === "string" ? infoId : void 0;
2077
+ import { homedir } from "os";
2078
+
2079
+ // src/lib/file-push.ts
2080
+ import { randomUUID } from "crypto";
2081
+ import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
2082
+ import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
2083
+ var FILE_MODE = 384;
2084
+ var DIRECTORY_MODE = 448;
2085
+ async function writePushedFile(request) {
2086
+ const { requestedPath, content, allowedDirectories, homeDir } = request;
2087
+ const bytes = content.byteLength;
2088
+ if (allowedDirectories.length === 0) {
2089
+ return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
2090
+ path: requestedPath,
2091
+ bytes
2092
+ });
2093
+ }
2094
+ if (bytes > MAX_FILE_PUSH_BYTES) {
2095
+ return refuse(
2096
+ "file_too_large",
2097
+ `File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
2098
+ {
2099
+ path: requestedPath,
2100
+ bytes
2101
+ }
2102
+ );
2103
+ }
2104
+ const candidate = expandAndValidate(requestedPath, homeDir);
2105
+ if (candidate === null) {
2106
+ return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
2107
+ path: requestedPath,
2108
+ bytes
2109
+ });
2110
+ }
2111
+ try {
2112
+ const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
2113
+ dirname2(candidate)
2114
+ );
2115
+ const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
2116
+ const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
2117
+ if (allowedDirectory === null) {
2118
+ return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
2119
+ path: realTarget,
2120
+ bytes
2121
+ });
2122
+ }
2123
+ if (missingSegments.length > 0) {
2124
+ await createMissingDirectories(existingAncestor, missingSegments);
2125
+ const realParent = await realpath(dirname2(realTarget));
2126
+ if (realParent !== dirname2(realTarget) || !contains(allowedDirectory, realTarget)) {
2127
+ return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
2128
+ path: realTarget,
2129
+ bytes,
2130
+ reason: "parent_changed_after_create"
2131
+ });
2132
+ }
2133
+ }
2134
+ await writeAtomically(realTarget, content);
2135
+ log("info", "file_push_written", { path: realTarget, bytes });
2136
+ return { ok: true, path: realTarget };
2137
+ } catch (err) {
2138
+ const errno = err.code ?? "UNKNOWN";
2139
+ return refuse("write_failed", `The runner could not write the file (${errno}).`, {
2140
+ path: candidate,
2141
+ bytes,
2142
+ errno,
2143
+ ...errorFields(err)
2144
+ });
2145
+ }
1626
2146
  }
1627
- var DEFAULT_RETRY_POLICY = {
1628
- maxAttempts: 6,
1629
- baseDelayMs: 500,
1630
- maxDelayMs: 3e4
1631
- };
1632
- var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
1633
- var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
1634
- var DEFAULT_STUCK_QUEUED_MS = 6e4;
1635
- var ChannelAuthError = class extends Error {
1636
- constructor(message) {
1637
- super(message);
1638
- this.name = "ChannelAuthError";
2147
+ function expandAndValidate(requestedPath, homeDir) {
2148
+ if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
2149
+ return null;
1639
2150
  }
1640
- };
1641
- var ChannelTerminalError = class extends Error {
1642
- status;
1643
- constructor(message, status) {
1644
- super(message);
1645
- this.name = "ChannelTerminalError";
1646
- this.status = status;
2151
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join(homeDir, requestedPath.slice(2)) : requestedPath;
2152
+ if (expanded.split(/[/\\]/).includes("..")) {
2153
+ return null;
1647
2154
  }
1648
- };
1649
- function backoffDelay(attempt, policy) {
1650
- const exp = policy.baseDelayMs * Math.pow(2, attempt);
1651
- const capped = Math.min(policy.maxDelayMs, exp);
1652
- return Math.floor(Math.random() * capped);
2155
+ if (!isAbsolute(expanded)) {
2156
+ return null;
2157
+ }
2158
+ const candidate = resolve2(expanded);
2159
+ const name = basename(candidate);
2160
+ return name === "" || name === "." || name === ".." ? null : candidate;
1653
2161
  }
1654
- function isRetryableStatus(status) {
1655
- return status === 429 || status >= 500 && status <= 599;
2162
+ async function resolveNearestExistingAncestor(directory) {
2163
+ const missingSegments = [];
2164
+ let current = directory;
2165
+ for (; ; ) {
2166
+ try {
2167
+ return { existingAncestor: await realpath(current), missingSegments };
2168
+ } catch (err) {
2169
+ const parent = dirname2(current);
2170
+ if (err.code !== "ENOENT" || parent === current) {
2171
+ throw err;
2172
+ }
2173
+ missingSegments.unshift(basename(current));
2174
+ current = parent;
2175
+ }
2176
+ }
1656
2177
  }
1657
- var ChannelDriver = class {
1658
- agentId;
1659
- port;
1660
- apiUrl;
1661
- getAuthHeader;
1662
- conversationFilter;
1663
- retry;
1664
- log;
1665
- fetchImpl;
1666
- sleep;
1667
- pausedPollIntervalMs;
1668
- pausedMaxWaitMs;
1669
- stuckQueuedMs;
1670
- now;
1671
- /** Cache of conversationId → opencode sessionId. */
1672
- sessions = /* @__PURE__ */ new Map();
1673
- /**
1674
- * Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
1675
- * longer idempotent (no caller-supplied `messageID`), and its read-back picks
1676
- * "the one new user row" — which is only unambiguous if no OTHER dispatch into
1677
- * the SAME session interleaves its snapshot→POST→read-back. This map chains each
1678
- * session's dispatches so they run serially; distinct sessions stay concurrent.
1679
- */
1680
- sessionDispatchLocks = /* @__PURE__ */ new Map();
1681
- /**
1682
- * Per-SESSION watchers (WI-3), keyed by opencode sessionId. Single-flight per
1683
- * session: one polling loop services all of that session's in-flight messages.
1684
- * A session entry exists while it has any in-flight (dispatched-but-not-done)
1685
- * message; it is removed once its in-flight set empties.
1686
- */
1687
- watchers = /* @__PURE__ */ new Map();
2178
+ async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
2179
+ for (const directory of allowedDirectories) {
2180
+ if (!isAbsolute(directory)) {
2181
+ log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
2182
+ continue;
2183
+ }
2184
+ const realDirectory = await realpathCreatingIfMissing(directory);
2185
+ if (realDirectory !== null && contains(realDirectory, realTarget)) {
2186
+ return realDirectory;
2187
+ }
2188
+ }
2189
+ return null;
2190
+ }
2191
+ async function realpathCreatingIfMissing(directory) {
2192
+ try {
2193
+ return await realpath(directory);
2194
+ } catch (err) {
2195
+ if (err.code !== "ENOENT") {
2196
+ log("warn", "file_push_allowed_directory_skipped", {
2197
+ directory,
2198
+ reason: "unresolvable",
2199
+ ...errorFields(err)
2200
+ });
2201
+ return null;
2202
+ }
2203
+ }
2204
+ try {
2205
+ await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
2206
+ await chmod(directory, DIRECTORY_MODE);
2207
+ return await realpath(directory);
2208
+ } catch (err) {
2209
+ log("warn", "file_push_allowed_directory_skipped", {
2210
+ directory,
2211
+ reason: "create_failed",
2212
+ ...errorFields(err)
2213
+ });
2214
+ return null;
2215
+ }
2216
+ }
2217
+ function contains(realDirectory, realTarget) {
2218
+ const rel = relative(realDirectory, realTarget);
2219
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
2220
+ }
2221
+ async function createMissingDirectories(existingAncestor, missingSegments) {
2222
+ let current = existingAncestor;
2223
+ for (const segment of missingSegments) {
2224
+ current = join(current, segment);
2225
+ await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
2226
+ await chmod(current, DIRECTORY_MODE);
2227
+ }
2228
+ }
2229
+ async function writeAtomically(realTarget, content) {
2230
+ const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2231
+ let handle;
2232
+ try {
2233
+ handle = await open2(temporaryPath, "wx", FILE_MODE);
2234
+ await handle.writeFile(content);
2235
+ await handle.chmod(FILE_MODE);
2236
+ await handle.close();
2237
+ handle = void 0;
2238
+ await rename(temporaryPath, realTarget);
2239
+ } catch (err) {
2240
+ await discardTemporaryFile(temporaryPath, handle);
2241
+ throw err;
2242
+ }
2243
+ }
2244
+ async function discardTemporaryFile(temporaryPath, handle) {
2245
+ try {
2246
+ await handle?.close();
2247
+ } catch (err) {
2248
+ log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
2249
+ }
2250
+ try {
2251
+ await unlink(temporaryPath);
2252
+ } catch (err) {
2253
+ const errno = err.code;
2254
+ if (errno !== "ENOENT" && errno !== "ENOTDIR") {
2255
+ log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
2256
+ }
2257
+ }
2258
+ }
2259
+ function refuse(code, message, fields) {
2260
+ log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
2261
+ return { ok: false, code, message };
2262
+ }
2263
+
2264
+ // src/lib/runner-file-sync.ts
2265
+ var MAX_ACK_ATTEMPTS = 5;
2266
+ async function syncPendingRunnerFiles(options) {
2267
+ const pending = await listPendingFiles(options);
2268
+ const pendingIds = new Set(pending.map((file) => file.id));
2269
+ for (const id of options.ackFailures.keys()) {
2270
+ if (!pendingIds.has(id)) options.ackFailures.delete(id);
2271
+ }
2272
+ if (pending.length === 0) return 0;
2273
+ options.log({
2274
+ level: "info",
2275
+ message: `Runner file sync: ${pending.length} file(s) queued for this runner`
2276
+ });
2277
+ let applied = 0;
2278
+ for (const file of pending) {
2279
+ if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
2280
+ if (await applyOne(options, file)) applied += 1;
2281
+ }
2282
+ return applied;
2283
+ }
2284
+ async function listPendingFiles(options) {
2285
+ let res;
2286
+ try {
2287
+ res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
2288
+ headers: { Authorization: options.getAuthHeader() }
2289
+ });
2290
+ } catch (err) {
2291
+ options.log({
2292
+ level: "warn",
2293
+ message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
2294
+ });
2295
+ return [];
2296
+ }
2297
+ if (!res.ok) {
2298
+ options.log({
2299
+ level: res.status === 404 ? "debug" : "warn",
2300
+ message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
2301
+ });
2302
+ return [];
2303
+ }
2304
+ let body;
2305
+ try {
2306
+ body = await res.json();
2307
+ } catch (err) {
2308
+ options.log({
2309
+ level: "warn",
2310
+ message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
2311
+ });
2312
+ return [];
2313
+ }
2314
+ if (!Array.isArray(body)) {
2315
+ options.log({
2316
+ level: "warn",
2317
+ message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
2318
+ });
2319
+ return [];
2320
+ }
2321
+ const files = [];
2322
+ for (const entry of body) {
2323
+ const file = asPendingFile(entry);
2324
+ if (file === null) {
2325
+ options.log({
2326
+ level: "warn",
2327
+ message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
2328
+ });
2329
+ continue;
2330
+ }
2331
+ files.push(file);
2332
+ }
2333
+ return files;
2334
+ }
2335
+ function asPendingFile(entry) {
2336
+ if (entry === null || typeof entry !== "object") return null;
2337
+ const { id, path, size } = entry;
2338
+ if (typeof id !== "string" || id === "") return null;
2339
+ if (typeof path !== "string" || path === "") return null;
2340
+ if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
2341
+ return { id, path, size };
2342
+ }
2343
+ async function applyOne(options, file) {
2344
+ const label = `${file.id.slice(0, 8)} (${file.path})`;
2345
+ if (options.allowedDirectories.length === 0) {
2346
+ options.log({
2347
+ level: "warn",
2348
+ message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
2349
+ });
2350
+ await ack(options, file, "rejected", "file_sync_disabled");
2351
+ return false;
2352
+ }
2353
+ if (file.size > MAX_FILE_PUSH_BYTES) {
2354
+ options.log({
2355
+ level: "warn",
2356
+ message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
2357
+ });
2358
+ await ack(options, file, "rejected", "file_too_large");
2359
+ return false;
2360
+ }
2361
+ const download = await downloadContent(options, file, label);
2362
+ if (!download.ok) {
2363
+ if (download.terminal) await ack(options, file, "rejected", download.code);
2364
+ return false;
2365
+ }
2366
+ let outcome;
2367
+ try {
2368
+ outcome = await writePushedFile({
2369
+ requestedPath: file.path,
2370
+ content: download.content,
2371
+ allowedDirectories: options.allowedDirectories,
2372
+ homeDir: options.homeDir
2373
+ });
2374
+ } catch (err) {
2375
+ options.log({
2376
+ level: "error",
2377
+ message: `Runner file ${label} could not be written: ${describe(err)}`
2378
+ });
2379
+ await ack(options, file, "rejected", "write_failed");
2380
+ return false;
2381
+ }
2382
+ if (!outcome.ok) {
2383
+ options.log({
2384
+ level: "warn",
2385
+ message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
2386
+ });
2387
+ await ack(options, file, "rejected", outcome.code);
2388
+ return false;
2389
+ }
2390
+ options.log({
2391
+ level: "info",
2392
+ message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
2393
+ });
2394
+ await ack(options, file, "applied");
2395
+ return true;
2396
+ }
2397
+ function durableDownloadCode(status) {
2398
+ return status === 413 ? "file_too_large" : "write_failed";
2399
+ }
2400
+ async function downloadContent(options, file, label) {
2401
+ try {
2402
+ const res = await options.fetchImpl(
2403
+ `${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
2404
+ { headers: { Authorization: options.getAuthHeader() } }
2405
+ );
2406
+ if (!res.ok) {
2407
+ const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
2408
+ if (!terminal) {
2409
+ options.log({
2410
+ level: "warn",
2411
+ message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
2412
+ });
2413
+ return { ok: false, terminal: false };
2414
+ }
2415
+ const code = durableDownloadCode(res.status);
2416
+ options.log({
2417
+ level: "error",
2418
+ message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
2419
+ });
2420
+ return { ok: false, terminal: true, code };
2421
+ }
2422
+ return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
2423
+ } catch (err) {
2424
+ options.log({
2425
+ level: "warn",
2426
+ message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
2427
+ });
2428
+ return { ok: false, terminal: false };
2429
+ }
2430
+ }
2431
+ async function ack(options, file, status, reason) {
2432
+ const outcome = `${status}${reason ? ` (${reason})` : ""}`;
2433
+ try {
2434
+ const res = await options.fetchImpl(
2435
+ `${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
2436
+ {
2437
+ method: "POST",
2438
+ headers: {
2439
+ Authorization: options.getAuthHeader(),
2440
+ "Content-Type": "application/json"
2441
+ },
2442
+ body: JSON.stringify(reason ? { status, reason } : { status })
2443
+ }
2444
+ );
2445
+ if (!res.ok) {
2446
+ recordAckFailure(
2447
+ options,
2448
+ file,
2449
+ `Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
2450
+ );
2451
+ return;
2452
+ }
2453
+ options.ackFailures.delete(file.id);
2454
+ } catch (err) {
2455
+ recordAckFailure(
2456
+ options,
2457
+ file,
2458
+ `Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
2459
+ );
2460
+ }
2461
+ }
2462
+ function recordAckFailure(options, file, what) {
2463
+ const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
2464
+ options.ackFailures.set(file.id, attempts);
2465
+ options.log({
2466
+ level: "error",
2467
+ message: attempts >= MAX_ACK_ATTEMPTS ? `${what} \u2014 giving up after ${attempts} attempts. It stays pending until the server expires it; restart the runner to retry.` : `${what} \u2014 it stays pending until a later drain re-acks it (attempt ${attempts} of ${MAX_ACK_ATTEMPTS})`
2468
+ });
2469
+ }
2470
+ function describe(err) {
2471
+ return err instanceof Error ? err.message : String(err);
2472
+ }
2473
+
2474
+ // src/lib/channels/driver.ts
2475
+ function messageIdOf(m) {
2476
+ if (!m || typeof m !== "object") return void 0;
2477
+ if (typeof m.id === "string") return m.id;
2478
+ const infoId = m.info?.id;
2479
+ return typeof infoId === "string" ? infoId : void 0;
2480
+ }
2481
+ function cleanImageMime(contentType) {
2482
+ if (!contentType) return null;
2483
+ const media = contentType.split(";")[0].trim().toLowerCase();
2484
+ return /^image\/[a-z0-9.+-]+$/.test(media) ? media : null;
2485
+ }
2486
+ var LOG_LEVELS = {
2487
+ debug: 0,
2488
+ info: 1,
2489
+ warn: 2,
2490
+ error: 3
2491
+ };
2492
+ var DEFAULT_RETRY_POLICY = {
2493
+ maxAttempts: 6,
2494
+ baseDelayMs: 500,
2495
+ maxDelayMs: 3e4
2496
+ };
2497
+ var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
2498
+ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
2499
+ var DEFAULT_STUCK_QUEUED_MS = 6e4;
2500
+ var HEARTBEAT_MS = 6e4;
2501
+ var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
2502
+ var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
2503
+ var MAX_SUPERSEDED_CONVERSATIONS = 256;
2504
+ var ChannelAuthError = class extends Error {
2505
+ constructor(message) {
2506
+ super(message);
2507
+ this.name = "ChannelAuthError";
2508
+ }
2509
+ };
2510
+ var ChannelTerminalError = class extends Error {
2511
+ status;
2512
+ constructor(message, status) {
2513
+ super(message);
2514
+ this.name = "ChannelTerminalError";
2515
+ this.status = status;
2516
+ }
2517
+ };
2518
+ function backoffDelay(attempt, policy) {
2519
+ const exp = policy.baseDelayMs * Math.pow(2, attempt);
2520
+ const capped = Math.min(policy.maxDelayMs, exp);
2521
+ return Math.floor(Math.random() * capped);
2522
+ }
2523
+ function isRetryableStatus(status) {
2524
+ return status === 429 || status >= 500 && status <= 599;
2525
+ }
2526
+ var ChannelDriver = class _ChannelDriver {
2527
+ agentId;
2528
+ port;
2529
+ apiUrl;
2530
+ getAuthHeader;
2531
+ conversationFilter;
2532
+ retry;
2533
+ log;
2534
+ fetchImpl;
2535
+ sleep;
2536
+ pausedPollIntervalMs;
2537
+ pausedMaxWaitMs;
2538
+ stuckQueuedMs;
2539
+ now;
2540
+ fileSyncDirectories;
2541
+ homeDir;
2542
+ /** Cache of conversationId → opencode sessionId. */
2543
+ sessions = /* @__PURE__ */ new Map();
2544
+ /**
2545
+ * conversationId → the opencode session this runner has ABANDONED as that
2546
+ * conversation's binding (#553), after a genuine (`sessionExists === true`)
2547
+ * dispatch failure: the session still exists but is wedged, so #485's self-heal
2548
+ * must bind a fresh one.
2549
+ *
2550
+ * Dropping the local binding + clearing the server row is not enough on its own:
2551
+ * a SIBLING message dispatched earlier in the same drain is still in-flight under
2552
+ * the same session, and its watcher's routine status writes carry
2553
+ * `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
2554
+ * and `ensureSession`'s persisted-id fallback then reuses it, defeating the
2555
+ * self-heal. This map makes the runner authoritative instead of racing those
2556
+ * writes: *`ensureSession` never reuses an abandoned id for that conversation,
2557
+ * whatever the server row says* — which holds even when the resurrecting write
2558
+ * is one we deliberately keep (see `markDone`).
2559
+ *
2560
+ * Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
2561
+ * one conversation hold ONE entry (the newest abandonment replaces the older), and
2562
+ * hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
2563
+ * NEWEST abandoned id per conversation is guarded: after a second abandonment a
2564
+ * late sibling of the FIRST session can write that id back and `ensureSession`
2565
+ * will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
2566
+ * NOT dropped when the session's watcher tears down: `markDone` still writes the
2567
+ * abandoned id back (it must, or the reply is lost), so the guard has to outlive
2568
+ * the turn that resurrects it. In-memory only — a restart forgets it, at the same
2569
+ * bounded cost.
2570
+ */
2571
+ supersededSessions = /* @__PURE__ */ new Map();
2572
+ /**
2573
+ * Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
2574
+ * longer idempotent (no caller-supplied `messageID`), and its read-back picks
2575
+ * "the one new user row" — which is only unambiguous if no OTHER dispatch into
2576
+ * the SAME session interleaves its snapshot→POST→read-back. This map chains each
2577
+ * session's dispatches so they run serially; distinct sessions stay concurrent.
2578
+ */
2579
+ sessionDispatchLocks = /* @__PURE__ */ new Map();
2580
+ /**
2581
+ * Per-SESSION watchers (WI-3), keyed by opencode sessionId. Single-flight per
2582
+ * session: one polling loop services all of that session's in-flight messages.
2583
+ * A session entry exists while it has any in-flight (dispatched-but-not-done)
2584
+ * message; it is removed once its in-flight set empties.
2585
+ */
2586
+ watchers = /* @__PURE__ */ new Map();
1688
2587
  /**
1689
2588
  * AUTHORITATIVE local dedup (WI-3): Evident message ids that have been
1690
2589
  * dispatched and are still in-flight. A message in this set is never
@@ -1728,6 +2627,15 @@ var ChannelDriver = class {
1728
2627
  * the row leaves the processing list, exactly like `dontRedispatch`.
1729
2628
  */
1730
2629
  doneUndeliverable = /* @__PURE__ */ new Set();
2630
+ /**
2631
+ * "Already emitted `readopt_poll_unresolved` for this row" (#229). The b1 /
2632
+ * unreadable-status re-evaluate leaf leaves the row UN-tracked so it is re-read
2633
+ * every ~2s drain until the status map becomes readable — but the server-visible
2634
+ * signal is an OUTCOME, so it must fire at most ONCE per row, not once per drain
2635
+ * (Bugbot "Re-adopt signals flood every drain"). Cleared when the row leaves the
2636
+ * processing list, exactly like `dontRedispatch`/`doneUndeliverable`.
2637
+ */
2638
+ readoptPollUnresolvedSignalled = /* @__PURE__ */ new Set();
1731
2639
  /**
1732
2640
  * "A null-id re-adopt re-dispatch is in flight, awaiting its read-back" (WI-5
1733
2641
  * Task 5.4, High-2). Since we no longer send a caller-supplied id, a re-dispatch
@@ -1742,6 +2650,15 @@ var ChannelDriver = class {
1742
2650
  * so the NEXT tick may retry exactly once more).
1743
2651
  */
1744
2652
  awaitingReadopt = /* @__PURE__ */ new Set();
2653
+ /**
2654
+ * "Already signalled `attachments_skipped` for this Evident message id" (#376).
2655
+ * The in-thread skip note is an OUTCOME, so it must fire AT MOST ONCE per message
2656
+ * — never re-post on a re-dispatch of the same row (`forceReadoptRun` or the
2657
+ * next-tick null-id retry both re-run `sendPromptAsync`, which re-fires
2658
+ * `onOutcomes`). Mirrors `readoptPollUnresolvedSignalled`: a local dedup on the
2659
+ * outcome, not the dispatch. Not cleared (a message is signalled once for life).
2660
+ */
2661
+ attachmentsSkippedSignalled = /* @__PURE__ */ new Set();
1745
2662
  /**
1746
2663
  * Cache of the opencode root directory (from `GET /path`). Resolved lazily on
1747
2664
  * first session creation so drain-created sessions are rooted at the project
@@ -1759,8 +2676,39 @@ var ChannelDriver = class {
1759
2676
  * entry = not yet resolved; `null` = resolved root (stop walking).
1760
2677
  */
1761
2678
  sessionParents = /* @__PURE__ */ new Map();
2679
+ /**
2680
+ * Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
2681
+ * NON-EMPTY, non-placeholder name is stored (terminal — a real session name
2682
+ * won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
2683
+ * excludes OpenCode's synchronous default title (see
2684
+ * `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
2685
+ * as an empty title so it never latches. A missing entry = not yet resolved OR
2686
+ * resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
2687
+ * names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
2688
+ * the watcher completion path AND the restart-recovery re-adopt path (which has
2689
+ * no watcher) can resolve the title.
2690
+ */
2691
+ sessionTitles = /* @__PURE__ */ new Map();
1762
2692
  /** Serialises drains so a reconnect during a drain doesn't double-process. */
1763
2693
  draining = false;
2694
+ /**
2695
+ * Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
2696
+ * drain ping don't download, write and ack the same file twice.
2697
+ */
2698
+ syncingFiles = false;
2699
+ /**
2700
+ * Consecutive failed acks per pending file (#559). Lives on the driver so it
2701
+ * survives across drains — without it, a file whose ack keeps failing is
2702
+ * re-downloaded and re-written every ~2s until the server expires it.
2703
+ */
2704
+ fileAckFailures = /* @__PURE__ */ new Map();
2705
+ /**
2706
+ * Monotonic count of files this runner has pulled and written (#559). Only
2707
+ * ever increases, so `run.ts` detects work by comparing it against the value
2708
+ * it saw on the previous cycle — including work that landed mid-sleep, the
2709
+ * same trick `lastProxiedActivityAt` uses.
2710
+ */
2711
+ appliedFileCount = 0;
1764
2712
  /**
1765
2713
  * The currently-executing `drainPending()` promise, or null when idle. Lets a
1766
2714
  * graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
@@ -1791,14 +2739,13 @@ var ChannelDriver = class {
1791
2739
  this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
1792
2740
  this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
1793
2741
  this.now = config2.now ?? (() => Date.now());
2742
+ this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
2743
+ this.homeDir = config2.homeDir ?? homedir();
1794
2744
  }
1795
2745
  /** The IPv4-loopback base URL for the local `opencode serve`. */
1796
2746
  get opencodeBase() {
1797
2747
  return `http://127.0.0.1:${this.port}`;
1798
2748
  }
1799
- // -------------------------------------------------------------------------
1800
- // Public API
1801
- // -------------------------------------------------------------------------
1802
2749
  /**
1803
2750
  * Drain all pending channel conversations once: poll → dispatch → register.
1804
2751
  * Called on tunnel `connected` (WI-CHAN-4) and on each poll tick by `run.ts`.
@@ -1821,6 +2768,47 @@ var ChannelDriver = class {
1821
2768
  );
1822
2769
  return run2;
1823
2770
  }
2771
+ /**
2772
+ * Pull-and-apply any files Evident has queued for this runner (#559), riding
2773
+ * the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
2774
+ * and drain ping that call `drainPending()`. There is deliberately no channel,
2775
+ * control frame or poll loop of its own: worst-case latency is one poll tick.
2776
+ *
2777
+ * NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
2778
+ * cost a conversation turn. Failures are logged and either acked as a terminal
2779
+ * outcome or left pending for the next drain (see `runner-file-sync.ts`).
2780
+ *
2781
+ * Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
2782
+ *
2783
+ * @returns the number of files written to disk.
2784
+ */
2785
+ async syncPendingFiles() {
2786
+ if (this.stopped) return 0;
2787
+ if (this.syncingFiles) return 0;
2788
+ this.syncingFiles = true;
2789
+ try {
2790
+ const applied = await syncPendingRunnerFiles({
2791
+ agentId: this.agentId,
2792
+ apiUrl: this.apiUrl,
2793
+ getAuthHeader: this.getAuthHeader,
2794
+ fetchImpl: this.fetchImpl,
2795
+ allowedDirectories: this.fileSyncDirectories,
2796
+ homeDir: this.homeDir,
2797
+ ackFailures: this.fileAckFailures,
2798
+ log: this.log
2799
+ });
2800
+ this.appliedFileCount += applied;
2801
+ return applied;
2802
+ } catch (err) {
2803
+ this.log({
2804
+ level: "error",
2805
+ message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
2806
+ });
2807
+ return 0;
2808
+ } finally {
2809
+ this.syncingFiles = false;
2810
+ }
2811
+ }
1824
2812
  async runDrain() {
1825
2813
  let dispatched = 0;
1826
2814
  try {
@@ -1854,6 +2842,50 @@ var ChannelDriver = class {
1854
2842
  }
1855
2843
  return false;
1856
2844
  }
2845
+ /**
2846
+ * File-pull work, for `run.ts`'s idle accounting (#559).
2847
+ *
2848
+ * Pulling a file is real work that `drainPending()` knows nothing about, so
2849
+ * without this a near-idle runner counts a credential pull as an empty tick
2850
+ * and `--idle-timeout` can `process.exit` mid-pull — leaving a
2851
+ * `.evident-push-*.tmp` behind — or immediately after the write, before the
2852
+ * browser has run the authorize/callback that activates it (the user then sees
2853
+ * `saved_not_activated` for a runner that was fine).
2854
+ *
2855
+ * Two signals because one cannot cover both cases: `inFlight` is the pull
2856
+ * happening RIGHT NOW (it may outlive the tick that started it), and
2857
+ * `appliedFiles` is monotonic so a pull that started AND finished between two
2858
+ * idle checks still shows up as an advance.
2859
+ *
2860
+ * CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
2861
+ * the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
2862
+ * samples afterwards reads `true` every single cycle and can never idle out.
2863
+ */
2864
+ fileSyncActivity() {
2865
+ return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
2866
+ }
2867
+ /**
2868
+ * OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
2869
+ * exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
2870
+ * `watchers` entry whose `inFlight` set is non-empty — the same predicate
2871
+ * `hasInFlightWatchers()` uses, lifted to return the ids.
2872
+ *
2873
+ * Deliberately does NOT include `this.sessions` (the permanent, never-pruned
2874
+ * conversation→session cache). Protecting every bound-but-idle session there
2875
+ * would shield nearly every session and defeat cleanup — AND it is unnecessary:
2876
+ * `ensureSession` is self-healing (it recreates a session whose id no longer
2877
+ * exists), so deleting an idle bound session is harmless — the conversation's
2878
+ * next turn transparently rebinds a fresh one. The only thing worth protecting
2879
+ * is a session with a turn ACTIVELY in flight right now: tearing that down
2880
+ * mid-turn would strand the running `prompt_async`. Idle sessions are fair game.
2881
+ */
2882
+ protectedSessionIds() {
2883
+ const ids = /* @__PURE__ */ new Set();
2884
+ for (const [sessionId, watcher] of this.watchers) {
2885
+ if (watcher.inFlight.size > 0) ids.add(sessionId);
2886
+ }
2887
+ return ids;
2888
+ }
1857
2889
  /**
1858
2890
  * Begin a graceful stop: stop accepting NEW channel work. Idempotent. After
1859
2891
  * this, `drainPending()` is a no-op (returns 0), so no new message is dispatched
@@ -1893,7 +2925,7 @@ var ChannelDriver = class {
1893
2925
  await this.sleep(step);
1894
2926
  }
1895
2927
  }
1896
- while (this.hasInFlightWatchers()) {
2928
+ while (this.hasInFlightWatchers() || this.syncingFiles) {
1897
2929
  if (this.now() >= deadline) return false;
1898
2930
  await this.sleep(step);
1899
2931
  }
@@ -1918,9 +2950,7 @@ var ChannelDriver = class {
1918
2950
  if (!stillLive) return;
1919
2951
  }
1920
2952
  }
1921
- // -------------------------------------------------------------------------
1922
2953
  // Conversation processing (WI-3 — async dispatch)
1923
- // -------------------------------------------------------------------------
1924
2954
  /**
1925
2955
  * Dispatch each pending message for a conversation to opencode's native queue
1926
2956
  * via `prompt_async` (Task 3.2) and register it with the conversation's
@@ -1930,10 +2960,15 @@ var ChannelDriver = class {
1930
2960
  * @returns the count of messages NEWLY dispatched (not already in-flight).
1931
2961
  */
1932
2962
  async processConversation(conv) {
1933
- const sessionId = await this.ensureSession(conv);
2963
+ const { sessionId, refusedSessionId } = await this.ensureSession(conv);
1934
2964
  const messages = await this.getPendingMessages(conv.id);
1935
2965
  let dispatched = 0;
1936
2966
  let skippedAlreadyDispatched = 0;
2967
+ if (refusedSessionId && messages.length > 0) {
2968
+ void this.postSignal(conv.id, messages[0].id, "session_superseded", {
2969
+ superseded_session_id: refusedSessionId
2970
+ });
2971
+ }
1937
2972
  for (const message of messages) {
1938
2973
  if (this.stopped) break;
1939
2974
  if (this.dispatched.has(message.id)) {
@@ -1952,26 +2987,62 @@ var ChannelDriver = class {
1952
2987
  conversation_id: conv.id,
1953
2988
  message_id: message.id
1954
2989
  });
2990
+ const sendAttachments = this.buildSendAttachments(conv, message);
1955
2991
  opencodeMessageId = await this.dispatchLocked(
1956
2992
  sessionId,
1957
- () => sendPromptAsync(this.port, sessionId, message.content, options)
2993
+ () => sendPromptAsync(this.port, sessionId, message.content, options, sendAttachments)
1958
2994
  );
1959
2995
  } catch (err) {
1960
2996
  if (err instanceof ChannelAuthError) throw err;
1961
2997
  this.dispatched.delete(message.id);
1962
- await this.markFailed(conv.id, message.id).catch(() => {
2998
+ const exists = await sessionExists(this.port, sessionId);
2999
+ if (exists === false) {
3000
+ this.sessions.delete(conv.id);
3001
+ this.log({
3002
+ level: "warn",
3003
+ 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.`,
3004
+ conversation_id: conv.id,
3005
+ message_id: message.id
3006
+ });
3007
+ break;
3008
+ }
3009
+ if (exists === null) {
3010
+ this.log({
3011
+ level: "warn",
3012
+ message: `Message ${message.id.slice(0, 8)} dispatch failed and session (${sessionId.slice(0, 8)}) existence could not be confirmed (opencode momentarily unreachable) \u2014 deferring this and later messages for conversation ${conv.id.slice(0, 8)} to the next tick rather than treating it as a genuine failure.`,
3013
+ conversation_id: conv.id,
3014
+ message_id: message.id
3015
+ });
3016
+ break;
3017
+ }
3018
+ const errorMessage = err instanceof Error ? err.message : String(err);
3019
+ this.sessions.delete(conv.id);
3020
+ this.supersede(conv.id, sessionId);
3021
+ this.log({
3022
+ level: "warn",
3023
+ message: `Abandoning OpenCode session ${sessionId.slice(0, 8)} as the binding for conversation ${conv.id.slice(0, 8)} (it exists but failed to run a turn) \u2014 a fresh session is created on the next tick, whatever the persisted binding says by then.`,
3024
+ conversation_id: conv.id,
3025
+ message_id: message.id
3026
+ });
3027
+ await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
3028
+ this.log({
3029
+ level: "warn",
3030
+ message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
3031
+ conversation_id: conv.id,
3032
+ message_id: message.id
3033
+ });
1963
3034
  });
1964
3035
  this.log({
1965
3036
  level: "error",
1966
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${err instanceof Error ? err.message : String(err)}`,
3037
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
1967
3038
  conversation_id: conv.id,
1968
3039
  message_id: message.id
1969
3040
  });
1970
- continue;
3041
+ break;
1971
3042
  }
1972
3043
  if (opencodeMessageId === null) {
1973
3044
  this.log({
1974
- level: "error",
3045
+ level: "warn",
1975
3046
  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
3047
  conversation_id: conv.id,
1977
3048
  message_id: message.id
@@ -1985,7 +3056,7 @@ var ChannelDriver = class {
1985
3056
  }
1986
3057
  if (messages.length > 0 && dispatched === 0 && skippedAlreadyDispatched === messages.length) {
1987
3058
  this.log({
1988
- level: "error",
3059
+ level: "warn",
1989
3060
  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
3061
  conversation_id: conv.id
1991
3062
  });
@@ -1993,17 +3064,68 @@ var ChannelDriver = class {
1993
3064
  this.ensureWatcherRunning(sessionId);
1994
3065
  return dispatched;
1995
3066
  }
3067
+ /**
3068
+ * Record that `sessionId` is no longer a valid binding for `conversationId`
3069
+ * (#553). Keyed by conversation and hard-capped, so it cannot grow with the
3070
+ * number of failures — see the `supersededSessions` field doc.
3071
+ */
3072
+ supersede(conversationId, sessionId) {
3073
+ this.supersededSessions.delete(conversationId);
3074
+ this.supersededSessions.set(conversationId, sessionId);
3075
+ while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
3076
+ const oldest = this.supersededSessions.keys().next().value;
3077
+ if (oldest === void 0) return;
3078
+ this.supersededSessions.delete(oldest);
3079
+ }
3080
+ }
3081
+ /** Whether `sessionId` is the session this conversation has abandoned (#553). */
3082
+ isSuperseded(conversationId, sessionId) {
3083
+ return this.supersededSessions.get(conversationId) === sessionId;
3084
+ }
3085
+ /**
3086
+ * Resolve the opencode session to run this conversation's turns in.
3087
+ *
3088
+ * `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
3089
+ * binding was an id this runner had abandoned, so a resurrection genuinely
3090
+ * happened and a fresh session was bound instead. The caller reports it.
3091
+ */
1996
3092
  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;
3093
+ const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
3094
+ if (bound && this.isSuperseded(conv.id, bound)) {
3095
+ this.log({
3096
+ level: "warn",
3097
+ message: `OpenCode session ${bound.slice(0, 8)} was abandoned for conversation ${conv.id.slice(0, 8)} after a failed dispatch but is still bound to it (the persisted id was written back by a turn already in flight) \u2014 ignoring it and binding a fresh session.`,
3098
+ conversation_id: conv.id
3099
+ });
3100
+ this.sessions.delete(conv.id);
3101
+ return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
3102
+ }
3103
+ if (bound) {
3104
+ const exists = await sessionExists(this.port, bound);
3105
+ if (exists === false) {
3106
+ this.log({
3107
+ level: "debug",
3108
+ 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.`,
3109
+ conversation_id: conv.id
3110
+ });
3111
+ this.sessions.delete(conv.id);
3112
+ return { sessionId: await this.createAndBindSession(conv.id) };
3113
+ }
3114
+ this.sessions.set(conv.id, bound);
3115
+ return { sessionId: bound };
2002
3116
  }
3117
+ return { sessionId: await this.createAndBindSession(conv.id) };
3118
+ }
3119
+ /**
3120
+ * Create a fresh OpenCode session for a conversation, cache the binding, and
3121
+ * best-effort persist it server-side. Shared by the first-ever bind and the
3122
+ * self-heal recreate path in `ensureSession`.
3123
+ */
3124
+ async createAndBindSession(conversationId) {
2003
3125
  const directory = await this.resolveOpenCodeDirectory();
2004
3126
  const sessionId = await createOpenCodeSession(this.port, directory);
2005
- this.sessions.set(conv.id, sessionId);
2006
- await this.persistSession(conv.id, sessionId).catch(() => {
3127
+ this.sessions.set(conversationId, sessionId);
3128
+ await this.persistSession(conversationId, sessionId).catch(() => {
2007
3129
  });
2008
3130
  return sessionId;
2009
3131
  }
@@ -2017,15 +3139,13 @@ var ChannelDriver = class {
2017
3139
  this.opencodeDirectory = await getOpenCodeDirectory(this.port);
2018
3140
  if (!this.opencodeDirectory) {
2019
3141
  this.log({
2020
- level: "info",
3142
+ level: "warn",
2021
3143
  message: "Could not determine opencode directory (GET /path) \u2014 new sessions may not appear in opencode web"
2022
3144
  });
2023
3145
  }
2024
3146
  return this.opencodeDirectory;
2025
3147
  }
2026
- // -------------------------------------------------------------------------
2027
3148
  // Per-session watcher (WI-3)
2028
- // -------------------------------------------------------------------------
2029
3149
  /**
2030
3150
  * Run one dispatch (`sendPromptAsync` snapshot→POST→read-back) serialized per
2031
3151
  * opencode session (Task 2.1a), so two dispatches into the SAME session can
@@ -2045,6 +3165,130 @@ var ChannelDriver = class {
2045
3165
  );
2046
3166
  return run2;
2047
3167
  }
3168
+ // Inbound image attachments (#255, WI-8)
3169
+ /**
3170
+ * Build the `SendAttachmentsInput` for a message's inbound images, or
3171
+ * `undefined` when the message has none (so a text-only turn is unchanged).
3172
+ *
3173
+ * The driver OWNS the two channel-facing concerns the session module cannot:
3174
+ * - the AUTHENTICATED byte fetch through Evident's WI-6 endpoint
3175
+ * (`fetchAttachmentDataUrl`), using the SAME `getAuthHeader()` as every
3176
+ * other combinedAuth callback — the CLI NEVER talks to Slack directly;
3177
+ * - the in-thread SKIP NOTE (`signalAttachmentsSkipped`) posted over the
3178
+ * existing callback surface when any image was skipped/failed.
3179
+ * `sendPromptAsync` applies the capability gate + appends the `file` parts and
3180
+ * reports outcomes back via `onOutcomes`.
3181
+ */
3182
+ buildSendAttachments(conv, message) {
3183
+ const refs = message.attachments;
3184
+ if (!refs || refs.length === 0) return void 0;
3185
+ return {
3186
+ inputs: refs.map((a, index) => ({
3187
+ index,
3188
+ mime: a.mime,
3189
+ ...a.filename ? { filename: a.filename } : {}
3190
+ })),
3191
+ fetchDataUrl: (index) => this.fetchAttachmentDataUrl(message.id, index, refs[index].mime),
3192
+ onOutcomes: ({ outcomes, capabilityUnknown }) => this.signalAttachmentsSkipped(conv.id, message.id, outcomes, capabilityUnknown)
3193
+ };
3194
+ }
3195
+ /**
3196
+ * Fetch ONE inbound image's bytes through Evident's WI-6 endpoint
3197
+ * (`GET {apiUrl}/runners/{agentId}/attachments/{messageId}/{index}`) using the
3198
+ * existing authenticated fetch, and base64-encode into a
3199
+ * `data:<mime>;base64,<…>` URL for the opencode `file` part's `url`.
3200
+ *
3201
+ * The endpoint streams the source bytes verbatim (200), or returns 404
3202
+ * (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
3203
+ * (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
3204
+ * OMITS that one image and the text turn still sends — NEVER throws the turn.
3205
+ * A 404 body carrying `{ reason: 'needs_reauth' }` (#547 — the server CONFIRMED
3206
+ * a Slack `files:read` scope problem via `files.info`) instead resolves the
3207
+ * `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
3208
+ * user to reconnect Slack instead of a generic "unavailable". Failures are
3209
+ * logged with context (no silent swallow).
3210
+ */
3211
+ async fetchAttachmentDataUrl(messageId, index, mime) {
3212
+ try {
3213
+ const res = await this.fetchImpl(
3214
+ `${this.apiUrl}/runners/${this.agentId}/attachments/${messageId}/${index}`,
3215
+ { headers: { Authorization: this.getAuthHeader() } }
3216
+ );
3217
+ if (!res.ok) {
3218
+ let reason;
3219
+ try {
3220
+ const body = await res.json();
3221
+ if (body && typeof body.reason === "string") reason = body.reason;
3222
+ } catch (parseErr) {
3223
+ this.log({
3224
+ level: "debug",
3225
+ message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index}: error body was not JSON (${parseErr instanceof Error ? parseErr.message : String(parseErr)}) \u2014 treating as a plain failure`,
3226
+ message_id: messageId
3227
+ });
3228
+ }
3229
+ if (reason === "needs_reauth") {
3230
+ this.log({
3231
+ level: "error",
3232
+ message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 server confirmed a Slack reauth/scope problem \u2014 omitting this image (text turn proceeds)`,
3233
+ message_id: messageId
3234
+ });
3235
+ return { needsReauth: true };
3236
+ }
3237
+ this.log({
3238
+ level: "error",
3239
+ message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
3240
+ message_id: messageId
3241
+ });
3242
+ return null;
3243
+ }
3244
+ const buf = await res.arrayBuffer();
3245
+ const base64 = Buffer.from(buf).toString("base64");
3246
+ const dataMime = cleanImageMime(res.headers.get("content-type")) || mime;
3247
+ return `data:${dataMime};base64,${base64}`;
3248
+ } catch (err) {
3249
+ this.log({
3250
+ level: "error",
3251
+ 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)}`,
3252
+ message_id: messageId
3253
+ });
3254
+ return null;
3255
+ }
3256
+ }
3257
+ /**
3258
+ * On any skipped/failed image, post an in-thread note to Evident over the
3259
+ * EXISTING combinedAuth callback surface — the CLI NEVER posts to Slack directly.
3260
+ * Evident routes the note to source via `conversation.deliver`.
3261
+ *
3262
+ * The `POST .../messages/:id/signal` route accepts `attachments_skipped` (in
3263
+ * `messageSignalSchema`) and turns it into an in-thread note delivered through
3264
+ * `conversation.deliver` (e.g. "N image(s) couldn't be forwarded"), so the note
3265
+ * reaches the channel.
3266
+ *
3267
+ * Fire-and-forget: never throws into the send/tick (logs its own failure).
3268
+ */
3269
+ signalAttachmentsSkipped(conversationId, messageId, outcomes, capabilityUnknown) {
3270
+ const skipped = outcomes.filter((o) => o.status === "skipped").length;
3271
+ const failed = outcomes.filter((o) => o.status === "failed").length;
3272
+ if (skipped === 0 && failed === 0) return;
3273
+ if (this.attachmentsSkippedSignalled.has(messageId)) return;
3274
+ this.attachmentsSkippedSignalled.add(messageId);
3275
+ const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
3276
+ const failedReason = outcomes.some(
3277
+ (o) => o.status === "failed" && o.reason === "needs_reauth"
3278
+ ) ? "needs_reauth" : void 0;
3279
+ this.log({
3280
+ level: "info",
3281
+ 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`,
3282
+ conversation_id: conversationId,
3283
+ message_id: messageId
3284
+ });
3285
+ void this.postSignal(conversationId, messageId, "attachments_skipped", {
3286
+ skipped,
3287
+ failed,
3288
+ ...skipped > 0 ? { skipped_reason: skippedReason } : {},
3289
+ ...failedReason ? { failed_reason: failedReason } : {}
3290
+ });
3291
+ }
2048
3292
  /** Register a freshly-dispatched message with its session's watcher state. */
2049
3293
  registerInFlight(conv, sessionId, message, opencodeMessageId) {
2050
3294
  let watcher = this.watchers.get(sessionId);
@@ -2054,7 +3298,9 @@ var ChannelDriver = class {
2054
3298
  inFlight: /* @__PURE__ */ new Map(),
2055
3299
  loop: null,
2056
3300
  reportedQuestions: /* @__PURE__ */ new Set(),
2057
- reportedPermissions: /* @__PURE__ */ new Set()
3301
+ reportedPermissions: /* @__PURE__ */ new Set(),
3302
+ lastGoodPollAt: this.now(),
3303
+ hadUsablePoll: false
2058
3304
  };
2059
3305
  this.watchers.set(sessionId, watcher);
2060
3306
  }
@@ -2064,20 +3310,39 @@ var ChannelDriver = class {
2064
3310
  opencodeMessageId,
2065
3311
  message,
2066
3312
  dispatchedAt: now,
3313
+ processingAnchorMs: now,
2067
3314
  deadline: now + this.pausedMaxWaitMs,
2068
3315
  started: false,
2069
3316
  done: false,
2070
- stuckReported: false
3317
+ stuckReported: false,
3318
+ lastAliveAt: 0,
3319
+ aliveInFlight: false,
3320
+ titleSynced: false,
3321
+ titleSyncInFlight: false,
3322
+ awaitingHumanLatched: false,
3323
+ pausedOnQuestion: false,
3324
+ pausedOnPermission: false,
3325
+ pausedClearConfirmed: false,
3326
+ pausedInFlight: false,
3327
+ deliveryDeadlineAnchored: false
2071
3328
  });
2072
3329
  }
2073
3330
  /**
2074
3331
  * Register a RE-ADOPTED `processing` message with its session watcher
2075
3332
  * (ADR-0046, WI-4). Mirrors `registerInFlight` but anchors the give-up
2076
3333
  * `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).
3334
+ * `now`, so the paused/queued/unreachable cases settle on the same wall-clock a
3335
+ * fresh dispatch would (10 min after `processed_at`, not 10 min from now).
3336
+ *
3337
+ * This re-attaches into the SAME watcher, so the ADR-0047 progressing-vs-paused
3338
+ * give-up (`serviceInFlightMessage`) applies unchanged: a re-adopted turn
3339
+ * opencode reports ACTIVELY `running` is watched to completion (its liveness
3340
+ * heartbeat keeps the cron off its row), while a re-adopted turn that is paused
3341
+ * awaiting a human — or queued/unreachable — is still bounded by `deadline` and
3342
+ * handed to the cron. The old "the `deadline` must settle before the ~15-min
3343
+ * cron or they double-drive" reasoning is superseded: liveness now settles the
3344
+ * actively-running case; `deadline` settles the rest. `dispatchedAt` stays `now`
3345
+ * (only the appear-guard uses it).
2081
3346
  *
2082
3347
  * `evidentMessageId` addresses the SERVER row (for markProcessing/markDone);
2083
3348
  * `opencodeMessageId` is the id the watcher polls for a reply — for the orphan
@@ -2095,7 +3360,9 @@ var ChannelDriver = class {
2095
3360
  inFlight: /* @__PURE__ */ new Map(),
2096
3361
  loop: null,
2097
3362
  reportedQuestions: /* @__PURE__ */ new Set(),
2098
- reportedPermissions: /* @__PURE__ */ new Set()
3363
+ reportedPermissions: /* @__PURE__ */ new Set(),
3364
+ lastGoodPollAt: this.now(),
3365
+ hadUsablePoll: false
2099
3366
  };
2100
3367
  this.watchers.set(sessionId, watcher);
2101
3368
  }
@@ -2104,6 +3371,10 @@ var ChannelDriver = class {
2104
3371
  opencodeMessageId,
2105
3372
  message,
2106
3373
  dispatchedAt: this.now(),
3374
+ // Anchor the absolute-age ceiling to the SERVER-SIDE `processed_at` (the same
3375
+ // value seeding `deadline`), NOT `dispatchedAt` — so a re-adopted zombie's age
3376
+ // reflects the real turn duration and the ceiling fires on the ORIGINAL turn.
3377
+ processingAnchorMs: processedAtMs,
2107
3378
  deadline: processedAtMs + this.pausedMaxWaitMs,
2108
3379
  // The server row is ALREADY `processing`; do not re-fire markProcessing.
2109
3380
  started: true,
@@ -2113,7 +3384,22 @@ var ChannelDriver = class {
2113
3384
  // on `state === 'queued'` (turn produced no reply), not on `started`, so a
2114
3385
  // re-adopted row left wedged in `queued` still emits the signal once
2115
3386
  // (#210/#220 observability).
2116
- stuckReported: false
3387
+ stuckReported: false,
3388
+ // Task 5.2: a re-adopted actively-running row re-attaches into the SAME
3389
+ // watcher and so hits the SAME actively-running heartbeat branch in
3390
+ // `serviceInFlightMessage` as a fresh dispatch — monitoring observes "runner
3391
+ // re-adopted and is confirming this row alive" via that `alive` heartbeat,
3392
+ // with no extra `re_adopted` signal needed (folds old WI-6).
3393
+ lastAliveAt: 0,
3394
+ aliveInFlight: false,
3395
+ titleSynced: false,
3396
+ titleSyncInFlight: false,
3397
+ awaitingHumanLatched: false,
3398
+ pausedOnQuestion: false,
3399
+ pausedOnPermission: false,
3400
+ pausedClearConfirmed: false,
3401
+ pausedInFlight: false,
3402
+ deliveryDeadlineAnchored: false
2117
3403
  });
2118
3404
  }
2119
3405
  /**
@@ -2164,12 +3450,30 @@ var ChannelDriver = class {
2164
3450
  messages = Array.isArray(body) ? body : null;
2165
3451
  }
2166
3452
  } catch {
2167
- continue;
2168
3453
  }
3454
+ if (messages != null && messages.length > 0) {
3455
+ watcher.lastGoodPollAt = this.now();
3456
+ watcher.hadUsablePoll = true;
3457
+ } else {
3458
+ const emptyButReachable = messages != null;
3459
+ const graceApplies = !emptyButReachable || watcher.hadUsablePoll;
3460
+ if (graceApplies && this.now() - watcher.lastGoodPollAt < POLL_MISS_GRACE_MS) {
3461
+ continue;
3462
+ }
3463
+ }
3464
+ const { openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk } = await this.pollInteractions(sessionId, watcher, messages);
2169
3465
  for (const inFlight of [...watcher.inFlight.values()]) {
2170
- await this.serviceInFlightMessage(sessionId, watcher, inFlight, messages);
3466
+ await this.serviceInFlightMessage(
3467
+ sessionId,
3468
+ watcher,
3469
+ inFlight,
3470
+ messages,
3471
+ openQuestions,
3472
+ openPermissions,
3473
+ questionsPolledOk,
3474
+ permissionsPolledOk
3475
+ );
2171
3476
  }
2172
- await this.pollInteractions(sessionId, watcher, messages);
2173
3477
  }
2174
3478
  } catch (err) {
2175
3479
  if (err instanceof ChannelAuthError) {
@@ -2191,28 +3495,55 @@ var ChannelDriver = class {
2191
3495
  });
2192
3496
  }
2193
3497
  }
3498
+ /**
3499
+ * On FIRST observing a terminal (done/failed) state, ensure the delivery
3500
+ * (markDone/markFailed) transient-retry path has a real window. A long
3501
+ * ACTIVELY-running turn is kept past its original `deadline`, so by completion
3502
+ * `now >= deadline` already holds and the retry bound below would fire on the
3503
+ * first transient PATCH failure — dropping the message before its reply lands
3504
+ * (Bugbot "Stale deadline aborts long-turn delivery"). Re-anchor once (latched)
3505
+ * to a fresh `pausedMaxWaitMs` window; only extend if the current deadline is at
3506
+ * or past now, so a still-ample window is left untouched.
3507
+ */
3508
+ anchorDeliveryDeadline(inFlight) {
3509
+ if (inFlight.deliveryDeadlineAnchored) return;
3510
+ inFlight.deliveryDeadlineAnchored = true;
3511
+ if (this.now() >= inFlight.deadline) {
3512
+ inFlight.deadline = this.now() + this.pausedMaxWaitMs;
3513
+ }
3514
+ }
2194
3515
  /**
2195
3516
  * Drive ONE in-flight message's lifecycle from the tick's message snapshot.
2196
3517
  * Fires markProcessing on queued→running and markDone on done (each once),
2197
3518
  * applies the idle-path re-dispatch guard, and removes the message from the
2198
3519
  * in-flight set on completion or timeout.
2199
3520
  */
2200
- async serviceInFlightMessage(sessionId, watcher, inFlight, messages) {
3521
+ async serviceInFlightMessage(sessionId, watcher, inFlight, messages, openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk) {
2201
3522
  const conv = watcher.conv;
2202
3523
  const state = messageRunState(messages, inFlight.opencodeMessageId);
3524
+ const id = inFlight.evidentMessageId;
3525
+ if (openQuestions.has(id)) inFlight.pausedOnQuestion = true;
3526
+ else if (questionsPolledOk) inFlight.pausedOnQuestion = false;
3527
+ if (openPermissions.has(id)) inFlight.pausedOnPermission = true;
3528
+ else if (permissionsPolledOk) inFlight.pausedOnPermission = false;
3529
+ const observedOpen = openQuestions.has(id) || openPermissions.has(id);
3530
+ const latchedPaused = inFlight.pausedOnQuestion || inFlight.pausedOnPermission;
3531
+ const awaitingHuman = observedOpen || latchedPaused;
2203
3532
  if ((state === "running" || state === "done" || state === "failed") && !inFlight.started) {
3533
+ const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
2204
3534
  let claimed;
2205
3535
  try {
2206
3536
  claimed = await this.markProcessing(
2207
3537
  conv.id,
2208
3538
  inFlight.evidentMessageId,
2209
3539
  sessionId,
2210
- inFlight.opencodeMessageId
3540
+ inFlight.opencodeMessageId,
3541
+ title
2211
3542
  );
2212
3543
  } catch (err) {
2213
3544
  if (err instanceof ChannelAuthError) throw err;
2214
3545
  this.log({
2215
- level: "error",
3546
+ level: "warn",
2216
3547
  message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2217
3548
  conversation_id: conv.id,
2218
3549
  message_id: inFlight.evidentMessageId
@@ -2222,7 +3553,7 @@ var ChannelDriver = class {
2222
3553
  inFlight.started = true;
2223
3554
  if (!claimed) {
2224
3555
  this.log({
2225
- level: "info",
3556
+ level: "debug",
2226
3557
  message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
2227
3558
  conversation_id: conv.id,
2228
3559
  message_id: inFlight.evidentMessageId
@@ -2230,6 +3561,7 @@ var ChannelDriver = class {
2230
3561
  }
2231
3562
  }
2232
3563
  if (state === "done") {
3564
+ this.anchorDeliveryDeadline(inFlight);
2233
3565
  if (!inFlight.done) {
2234
3566
  this.log({
2235
3567
  level: "info",
@@ -2237,18 +3569,22 @@ var ChannelDriver = class {
2237
3569
  conversation_id: conv.id,
2238
3570
  message_id: inFlight.evidentMessageId
2239
3571
  });
3572
+ const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
3573
+ const usage = messageUsage(messages, inFlight.opencodeMessageId);
2240
3574
  try {
2241
3575
  await this.markDone(
2242
3576
  conv.id,
2243
3577
  inFlight.evidentMessageId,
2244
3578
  sessionId,
2245
- inFlight.opencodeMessageId
3579
+ inFlight.opencodeMessageId,
3580
+ title,
3581
+ usage
2246
3582
  );
2247
3583
  } catch (err) {
2248
3584
  if (err instanceof ChannelAuthError) throw err;
2249
3585
  if (err instanceof ChannelTerminalError) {
2250
3586
  this.log({
2251
- level: "error",
3587
+ level: "warn",
2252
3588
  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
3589
  conversation_id: conv.id,
2254
3590
  message_id: inFlight.evidentMessageId
@@ -2258,7 +3594,7 @@ var ChannelDriver = class {
2258
3594
  }
2259
3595
  if (this.now() >= inFlight.deadline) {
2260
3596
  this.log({
2261
- level: "error",
3597
+ level: "warn",
2262
3598
  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
3599
  conversation_id: conv.id,
2264
3600
  message_id: inFlight.evidentMessageId
@@ -2267,7 +3603,7 @@ var ChannelDriver = class {
2267
3603
  return;
2268
3604
  }
2269
3605
  this.log({
2270
- level: "error",
3606
+ level: "warn",
2271
3607
  message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2272
3608
  conversation_id: conv.id,
2273
3609
  message_id: inFlight.evidentMessageId
@@ -2280,6 +3616,7 @@ var ChannelDriver = class {
2280
3616
  return;
2281
3617
  }
2282
3618
  if (state === "failed") {
3619
+ this.anchorDeliveryDeadline(inFlight);
2283
3620
  if (!inFlight.done) {
2284
3621
  const error2 = messageError(messages, inFlight.opencodeMessageId) ?? void 0;
2285
3622
  this.log({
@@ -2288,13 +3625,14 @@ var ChannelDriver = class {
2288
3625
  conversation_id: conv.id,
2289
3626
  message_id: inFlight.evidentMessageId
2290
3627
  });
3628
+ const usage = messageUsage(messages, inFlight.opencodeMessageId);
2291
3629
  try {
2292
- await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2);
3630
+ await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2, usage);
2293
3631
  } catch (err) {
2294
3632
  if (err instanceof ChannelAuthError) throw err;
2295
3633
  if (err instanceof ChannelTerminalError) {
2296
3634
  this.log({
2297
- level: "error",
3635
+ level: "warn",
2298
3636
  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
3637
  conversation_id: conv.id,
2300
3638
  message_id: inFlight.evidentMessageId
@@ -2304,7 +3642,7 @@ var ChannelDriver = class {
2304
3642
  }
2305
3643
  if (this.now() >= inFlight.deadline) {
2306
3644
  this.log({
2307
- level: "error",
3645
+ level: "warn",
2308
3646
  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
3647
  conversation_id: conv.id,
2310
3648
  message_id: inFlight.evidentMessageId
@@ -2313,7 +3651,7 @@ var ChannelDriver = class {
2313
3651
  return;
2314
3652
  }
2315
3653
  this.log({
2316
- level: "error",
3654
+ level: "warn",
2317
3655
  message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} failed (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2318
3656
  conversation_id: conv.id,
2319
3657
  message_id: inFlight.evidentMessageId
@@ -2333,9 +3671,65 @@ var ChannelDriver = class {
2333
3671
  stuck_for_ms: this.now() - inFlight.dispatchedAt
2334
3672
  });
2335
3673
  }
2336
- if (this.now() >= inFlight.deadline) {
3674
+ const activelyRunning = state === "running" && !awaitingHuman;
3675
+ if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
2337
3676
  this.log({
2338
- level: "info",
3677
+ level: "warn",
3678
+ 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`,
3679
+ conversation_id: conv.id,
3680
+ message_id: inFlight.evidentMessageId
3681
+ });
3682
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "gave_up", {
3683
+ watched_for_ms: this.now() - inFlight.processingAnchorMs
3684
+ });
3685
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
3686
+ return;
3687
+ }
3688
+ if (activelyRunning && !inFlight.awaitingHumanLatched && !inFlight.aliveInFlight && this.now() - inFlight.lastAliveAt >= HEARTBEAT_MS) {
3689
+ inFlight.aliveInFlight = true;
3690
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "alive").then((ok) => {
3691
+ inFlight.aliveInFlight = false;
3692
+ if (ok) inFlight.lastAliveAt = this.now();
3693
+ });
3694
+ if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
3695
+ inFlight.titleSyncInFlight = true;
3696
+ void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
3697
+ if (!title) {
3698
+ inFlight.titleSyncInFlight = false;
3699
+ return;
3700
+ }
3701
+ const ok = await this.patchConversationTitle(conv.id, title);
3702
+ inFlight.titleSyncInFlight = false;
3703
+ if (ok) inFlight.titleSynced = true;
3704
+ });
3705
+ }
3706
+ }
3707
+ if (awaitingHuman) {
3708
+ if (!inFlight.awaitingHumanLatched) {
3709
+ inFlight.deadline = this.now() + this.pausedMaxWaitMs;
3710
+ inFlight.awaitingHumanLatched = true;
3711
+ }
3712
+ if (!inFlight.pausedClearConfirmed && !inFlight.pausedInFlight) {
3713
+ inFlight.pausedInFlight = true;
3714
+ void this.postSignal(conv.id, inFlight.evidentMessageId, "paused").then((ok) => {
3715
+ inFlight.pausedInFlight = false;
3716
+ if (ok && inFlight.awaitingHumanLatched) inFlight.pausedClearConfirmed = true;
3717
+ });
3718
+ }
3719
+ } else if (inFlight.awaitingHumanLatched) {
3720
+ inFlight.awaitingHumanLatched = false;
3721
+ inFlight.pausedOnQuestion = false;
3722
+ inFlight.pausedOnPermission = false;
3723
+ inFlight.pausedClearConfirmed = false;
3724
+ }
3725
+ const siblingPaused = (sib) => openQuestions.has(sib.evidentMessageId) || openPermissions.has(sib.evidentMessageId) || sib.awaitingHumanLatched || sib.pausedOnQuestion || sib.pausedOnPermission;
3726
+ const hasActivelyRunningSibling = [...watcher.inFlight.values()].some(
3727
+ (sib) => sib.evidentMessageId !== inFlight.evidentMessageId && messageRunState(messages, sib.opencodeMessageId) === "running" && !siblingPaused(sib)
3728
+ );
3729
+ const queuedBehindRunningSibling = state === "queued" && hasActivelyRunningSibling;
3730
+ if (!activelyRunning && !queuedBehindRunningSibling && this.now() >= inFlight.deadline) {
3731
+ this.log({
3732
+ level: "debug",
2339
3733
  message: `Message ${inFlight.evidentMessageId.slice(0, 8)} did not complete within the watch window \u2014 leaving for the cron safety net`,
2340
3734
  conversation_id: conv.id,
2341
3735
  message_id: inFlight.evidentMessageId
@@ -2346,9 +3740,7 @@ var ChannelDriver = class {
2346
3740
  this.removeInFlight(watcher, inFlight.evidentMessageId);
2347
3741
  }
2348
3742
  }
2349
- // -------------------------------------------------------------------------
2350
3743
  // Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
2351
- // -------------------------------------------------------------------------
2352
3744
  /**
2353
3745
  * Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
2354
3746
  *
@@ -2365,15 +3757,20 @@ var ChannelDriver = class {
2365
3757
  */
2366
3758
  async readoptProcessing() {
2367
3759
  const rows = await this.getProcessingMessages();
2368
- if (this.dontRedispatch.size > 0 || this.doneUndeliverable.size > 0) {
3760
+ if (this.dontRedispatch.size > 0 || this.doneUndeliverable.size > 0 || this.readoptPollUnresolvedSignalled.size > 0) {
2369
3761
  const stillProcessing = new Set(rows.map((r) => r.id));
2370
- for (const id of [...this.dontRedispatch, ...this.doneUndeliverable]) {
3762
+ for (const id of [
3763
+ ...this.dontRedispatch,
3764
+ ...this.doneUndeliverable,
3765
+ ...this.readoptPollUnresolvedSignalled
3766
+ ]) {
2371
3767
  if (!stillProcessing.has(id)) {
2372
3768
  const cleared = this.dontRedispatch.delete(id);
2373
3769
  const clearedUndeliverable = this.doneUndeliverable.delete(id);
3770
+ this.readoptPollUnresolvedSignalled.delete(id);
2374
3771
  if (cleared || clearedUndeliverable) {
2375
3772
  this.log({
2376
- level: "info",
3773
+ level: "debug",
2377
3774
  message: `Re-adopt: message ${id.slice(0, 8)} left the processing list (cron reset) \u2014 cleared gave-up marker`,
2378
3775
  message_id: id
2379
3776
  });
@@ -2386,7 +3783,7 @@ var ChannelDriver = class {
2386
3783
  for (const row of rows) {
2387
3784
  if (!row.opencode_session_id) {
2388
3785
  this.log({
2389
- level: "error",
3786
+ level: "warn",
2390
3787
  message: `Cannot re-adopt processing message ${row.id.slice(0, 8)} \u2014 no opencode session id; leaving for the cron safety net`,
2391
3788
  conversation_id: row.conversation_id,
2392
3789
  message_id: row.id
@@ -2403,7 +3800,7 @@ var ChannelDriver = class {
2403
3800
  const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
2404
3801
  if (!res.ok) {
2405
3802
  this.log({
2406
- level: "error",
3803
+ level: "warn",
2407
3804
  message: `Re-adopt: polling session ${sessionId.slice(0, 8)} returned HTTP ${res.status} \u2014 skipping this session this tick`
2408
3805
  });
2409
3806
  continue;
@@ -2411,7 +3808,7 @@ var ChannelDriver = class {
2411
3808
  const body = await res.json();
2412
3809
  if (!Array.isArray(body)) {
2413
3810
  this.log({
2414
- level: "error",
3811
+ level: "warn",
2415
3812
  message: `Re-adopt: polling session ${sessionId.slice(0, 8)} returned a non-array message body \u2014 skipping this session this tick`
2416
3813
  });
2417
3814
  continue;
@@ -2419,13 +3816,15 @@ var ChannelDriver = class {
2419
3816
  messages = body;
2420
3817
  } catch (err) {
2421
3818
  this.log({
2422
- level: "error",
3819
+ level: "warn",
2423
3820
  message: `Re-adopt: failed to poll session ${sessionId.slice(0, 8)} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`
2424
3821
  });
2425
3822
  continue;
2426
3823
  }
3824
+ const anyUntracked = sessionRows.some((row) => !this.isTracked(sessionId, row.id));
3825
+ const sessionOngoing = anyUntracked ? await isSessionOngoing(this.port, sessionId) : null;
2427
3826
  for (const row of sessionRows) {
2428
- await this.readoptOne(sessionId, row, messages);
3827
+ await this.readoptOne(sessionId, row, messages, sessionOngoing);
2429
3828
  }
2430
3829
  }
2431
3830
  }
@@ -2447,10 +3846,10 @@ var ChannelDriver = class {
2447
3846
  *
2448
3847
  * Only `ChannelAuthError` propagates.
2449
3848
  */
2450
- async readoptOne(sessionId, row, messages) {
3849
+ async readoptOne(sessionId, row, messages, sessionOngoing) {
2451
3850
  if (this.isTracked(sessionId, row.id)) {
2452
3851
  this.log({
2453
- level: "info",
3852
+ level: "debug",
2454
3853
  message: `Re-adopt: message ${row.id.slice(0, 8)} already tracked in-flight \u2014 skipping (owned by the watcher loop)`,
2455
3854
  conversation_id: row.conversation_id,
2456
3855
  message_id: row.id
@@ -2462,7 +3861,7 @@ var ChannelDriver = class {
2462
3861
  if (state === "done") {
2463
3862
  if (this.doneUndeliverable.has(row.id)) {
2464
3863
  this.log({
2465
- level: "info",
3864
+ level: "debug",
2466
3865
  message: `Re-adopt: message ${row.id.slice(0, 8)} markDone is terminally undeliverable \u2014 left to the cron; skipping until it leaves processing`,
2467
3866
  conversation_id: row.conversation_id,
2468
3867
  message_id: row.id
@@ -2476,21 +3875,24 @@ var ChannelDriver = class {
2476
3875
  message_id: row.id
2477
3876
  });
2478
3877
  try {
2479
- await this.markDone(row.conversation_id, row.id, sessionId, ocId);
3878
+ const title = await this.resolveSessionTitle(sessionId, row.conversation_id);
3879
+ const usage = messageUsage(messages, ocId ?? "");
3880
+ await this.markDone(row.conversation_id, row.id, sessionId, ocId, title, usage);
2480
3881
  } catch (err) {
2481
3882
  if (err instanceof ChannelAuthError) throw err;
2482
3883
  if (err instanceof ChannelTerminalError) {
2483
3884
  this.doneUndeliverable.add(row.id);
2484
3885
  this.log({
2485
- level: "error",
3886
+ level: "warn",
2486
3887
  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
3888
  conversation_id: row.conversation_id,
2488
3889
  message_id: row.id
2489
3890
  });
3891
+ void this.postSignal(row.conversation_id, row.id, "readopt_undeliverable");
2490
3892
  return;
2491
3893
  }
2492
3894
  this.log({
2493
- level: "error",
3895
+ level: "warn",
2494
3896
  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
3897
  conversation_id: row.conversation_id,
2496
3898
  message_id: row.id
@@ -2498,10 +3900,12 @@ var ChannelDriver = class {
2498
3900
  return;
2499
3901
  }
2500
3902
  this.dontRedispatch.delete(row.id);
3903
+ void this.postSignal(row.conversation_id, row.id, "readopt_done");
2501
3904
  return;
2502
3905
  }
2503
3906
  if (state === "failed") {
2504
3907
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
3908
+ const usage = messageUsage(messages, ocId ?? "");
2505
3909
  this.log({
2506
3910
  level: "error",
2507
3911
  message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
@@ -2509,21 +3913,22 @@ var ChannelDriver = class {
2509
3913
  message_id: row.id
2510
3914
  });
2511
3915
  try {
2512
- await this.markFailed(row.conversation_id, row.id, sessionId, error2);
3916
+ await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
2513
3917
  } catch (err) {
2514
3918
  if (err instanceof ChannelAuthError) throw err;
2515
3919
  if (err instanceof ChannelTerminalError) {
2516
3920
  this.doneUndeliverable.add(row.id);
2517
3921
  this.log({
2518
- level: "error",
3922
+ level: "warn",
2519
3923
  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
3924
  conversation_id: row.conversation_id,
2521
3925
  message_id: row.id
2522
3926
  });
3927
+ void this.postSignal(row.conversation_id, row.id, "readopt_undeliverable");
2523
3928
  return;
2524
3929
  }
2525
3930
  this.log({
2526
- level: "error",
3931
+ level: "warn",
2527
3932
  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
3933
  conversation_id: row.conversation_id,
2529
3934
  message_id: row.id
@@ -2531,17 +3936,83 @@ var ChannelDriver = class {
2531
3936
  return;
2532
3937
  }
2533
3938
  this.dontRedispatch.delete(row.id);
3939
+ void this.postSignal(row.conversation_id, row.id, "readopt_failed");
2534
3940
  return;
2535
3941
  }
2536
3942
  if (this.dontRedispatch.has(row.id)) {
2537
3943
  this.log({
2538
- level: "info",
3944
+ level: "debug",
2539
3945
  message: `Re-adopt: message ${row.id.slice(0, 8)} already gave up \u2014 left to the cron; skipping until it leaves processing`,
2540
3946
  conversation_id: row.conversation_id,
2541
3947
  message_id: row.id
2542
3948
  });
2543
3949
  return;
2544
3950
  }
3951
+ let statusReadableOngoing = null;
3952
+ if (state === "running" && ocId) {
3953
+ const reply = findLastAssistantReplyFor(messages, ocId);
3954
+ const shape = this.replyCompletionShape(reply);
3955
+ const ongoing = sessionOngoing;
3956
+ statusReadableOngoing = ongoing;
3957
+ if (ongoing === false) {
3958
+ this.log({
3959
+ level: "info",
3960
+ 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)`,
3961
+ conversation_id: row.conversation_id,
3962
+ message_id: row.id
3963
+ });
3964
+ await this.forceReadoptRun(sessionId, row);
3965
+ return;
3966
+ }
3967
+ if (ongoing === true) {
3968
+ this.log({
3969
+ level: "debug",
3970
+ 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)`,
3971
+ conversation_id: row.conversation_id,
3972
+ message_id: row.id
3973
+ });
3974
+ } else {
3975
+ if (shape === "b1") {
3976
+ this.log({
3977
+ level: "debug",
3978
+ 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`,
3979
+ conversation_id: row.conversation_id,
3980
+ message_id: row.id
3981
+ });
3982
+ if (!this.readoptPollUnresolvedSignalled.has(row.id)) {
3983
+ this.readoptPollUnresolvedSignalled.add(row.id);
3984
+ void this.postSignal(row.conversation_id, row.id, "readopt_poll_unresolved");
3985
+ }
3986
+ return;
3987
+ }
3988
+ this.log({
3989
+ level: "debug",
3990
+ 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`,
3991
+ conversation_id: row.conversation_id,
3992
+ message_id: row.id
3993
+ });
3994
+ }
3995
+ }
3996
+ if (statusReadableOngoing === null && state === "running" && ocId && isPreamblePinnedRunning(messages, ocId)) {
3997
+ const descendantAlive = await this.isAnyDescendantSessionAlive(sessionId);
3998
+ if (descendantAlive === true) {
3999
+ this.log({
4000
+ level: "debug",
4001
+ 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)`,
4002
+ conversation_id: row.conversation_id,
4003
+ message_id: row.id
4004
+ });
4005
+ } else {
4006
+ this.log({
4007
+ level: "info",
4008
+ 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)" : ""}`,
4009
+ conversation_id: row.conversation_id,
4010
+ message_id: row.id
4011
+ });
4012
+ await this.forceReadoptRun(sessionId, row);
4013
+ return;
4014
+ }
4015
+ }
2545
4016
  if ((state === "running" || state === "queued") && ocId) {
2546
4017
  const conv = this.convForRow(sessionId, row);
2547
4018
  const message = this.queuedMessageForRow(row);
@@ -2550,11 +4021,12 @@ var ChannelDriver = class {
2550
4021
  this.readopted.add(row.id);
2551
4022
  this.ensureWatcherRunning(sessionId);
2552
4023
  this.log({
2553
- level: "info",
4024
+ level: "debug",
2554
4025
  message: `Re-adopt: message ${row.id.slice(0, 8)} ${state} \u2014 re-attached watcher (stored id, no re-dispatch)`,
2555
4026
  conversation_id: row.conversation_id,
2556
4027
  message_id: row.id
2557
4028
  });
4029
+ void this.postSignal(row.conversation_id, row.id, "readopt_reattached");
2558
4030
  return;
2559
4031
  }
2560
4032
  await this.forceReadoptRun(sessionId, row);
@@ -2583,7 +4055,7 @@ var ChannelDriver = class {
2583
4055
  async forceReadoptRun(sessionId, row) {
2584
4056
  if (this.stopped) {
2585
4057
  this.log({
2586
- level: "info",
4058
+ level: "debug",
2587
4059
  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
4060
  conversation_id: row.conversation_id,
2589
4061
  message_id: row.id
@@ -2592,7 +4064,7 @@ var ChannelDriver = class {
2592
4064
  }
2593
4065
  if (this.awaitingReadopt.has(row.id)) {
2594
4066
  this.log({
2595
- level: "info",
4067
+ level: "debug",
2596
4068
  message: `Re-adopt: message ${row.id.slice(0, 8)} already has a re-dispatch awaiting read-back \u2014 skipping (at most once)`,
2597
4069
  conversation_id: row.conversation_id,
2598
4070
  message_id: row.id
@@ -2602,11 +4074,12 @@ var ChannelDriver = class {
2602
4074
  if (this.processedAtMs(row) + this.pausedMaxWaitMs <= this.now()) {
2603
4075
  this.dontRedispatch.add(row.id);
2604
4076
  this.log({
2605
- level: "info",
4077
+ level: "debug",
2606
4078
  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
4079
  conversation_id: row.conversation_id,
2608
4080
  message_id: row.id
2609
4081
  });
4082
+ void this.postSignal(row.conversation_id, row.id, "readopt_window_elapsed");
2610
4083
  return;
2611
4084
  }
2612
4085
  const options = {
@@ -2620,40 +4093,44 @@ var ChannelDriver = class {
2620
4093
  message_id: row.id
2621
4094
  });
2622
4095
  this.awaitingReadopt.add(row.id);
4096
+ const readoptConv = this.convForRow(sessionId, row);
4097
+ const readoptMessage = this.queuedMessageForRow(row);
4098
+ const sendAttachments = this.buildSendAttachments(readoptConv, readoptMessage);
2623
4099
  let ocId;
2624
4100
  try {
2625
4101
  ocId = await this.dispatchLocked(
2626
4102
  sessionId,
2627
- () => sendPromptAsync(this.port, sessionId, row.content, options)
4103
+ () => sendPromptAsync(this.port, sessionId, row.content, options, sendAttachments)
2628
4104
  );
2629
4105
  } catch (err) {
2630
4106
  this.awaitingReadopt.delete(row.id);
2631
4107
  if (err instanceof ChannelAuthError) throw err;
2632
4108
  this.log({
2633
- level: "error",
4109
+ level: "warn",
2634
4110
  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
4111
  conversation_id: row.conversation_id,
2636
4112
  message_id: row.id
2637
4113
  });
4114
+ void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
2638
4115
  return;
2639
4116
  }
2640
4117
  if (ocId === null) {
2641
4118
  this.awaitingReadopt.delete(row.id);
2642
4119
  this.log({
2643
- level: "error",
4120
+ level: "warn",
2644
4121
  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
4122
  conversation_id: row.conversation_id,
2646
4123
  message_id: row.id
2647
4124
  });
4125
+ void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
2648
4126
  return;
2649
4127
  }
2650
- const conv = this.convForRow(sessionId, row);
2651
- const message = this.queuedMessageForRow(row);
2652
- this.registerReadopted(conv, sessionId, message, ocId, this.processedAtMs(row));
4128
+ this.registerReadopted(readoptConv, sessionId, readoptMessage, ocId, this.processedAtMs(row));
2653
4129
  this.dispatched.add(row.id);
2654
4130
  this.readopted.add(row.id);
2655
4131
  this.awaitingReadopt.delete(row.id);
2656
4132
  this.ensureWatcherRunning(sessionId);
4133
+ void this.postSignal(row.conversation_id, row.id, "readopt_redispatched");
2657
4134
  }
2658
4135
  /**
2659
4136
  * True if `evidentMessageId` is already being driven — either in the
@@ -2702,7 +4179,8 @@ var ChannelDriver = class {
2702
4179
  opencode_agent: row.opencode_agent,
2703
4180
  opencode_model: row.opencode_model,
2704
4181
  source_message_id: row.source_message_id,
2705
- slack_user_id: row.slack_user_id
4182
+ slack_user_id: row.slack_user_id,
4183
+ attachments: row.attachments ?? null
2706
4184
  };
2707
4185
  }
2708
4186
  /**
@@ -2723,7 +4201,7 @@ var ChannelDriver = class {
2723
4201
  if (this.readopted.delete(evidentMessageId) && inFlight && !inFlight.done) {
2724
4202
  this.dontRedispatch.add(evidentMessageId);
2725
4203
  this.log({
2726
- level: "info",
4204
+ level: "debug",
2727
4205
  message: `Re-adopt: message ${evidentMessageId.slice(0, 8)} gave up \u2014 parking until it leaves the processing list (cron reset)`,
2728
4206
  conversation_id: watcher.conv.id,
2729
4207
  message_id: evidentMessageId
@@ -2745,21 +4223,41 @@ var ChannelDriver = class {
2745
4223
  * RUNNING (not done) is the one that paused. With one running message that is
2746
4224
  * unambiguous; with several we prefer an explicit messageID match, else the
2747
4225
  * oldest running message.
4226
+ *
4227
+ * Returns the set of in-flight Evident message ids that are paused awaiting a
4228
+ * human — an outstanding (still-open) question/permission is attributed to them.
4229
+ * `serviceInFlightMessage` uses this to keep an actively-running turn watched
4230
+ * forever (ADR-0047) while still bounding a turn merely blocked on a person who
4231
+ * may never answer. Attribution here covers ALL open interactions, not just
4232
+ * NEW (un-deduped) ones — a question stays "awaiting a human" until answered,
4233
+ * even after it was already surfaced to the channel.
2748
4234
  */
2749
4235
  async pollInteractions(sessionId, watcher, messages) {
4236
+ const openQuestions = /* @__PURE__ */ new Set();
4237
+ const openPermissions = /* @__PURE__ */ new Set();
4238
+ let questionsPolledOk = true;
4239
+ let permissionsPolledOk = true;
2750
4240
  let questions = [];
2751
4241
  try {
2752
4242
  const res = await this.fetchImpl(`${this.opencodeBase}/question`);
2753
4243
  if (res.ok) {
2754
4244
  const body = await res.json();
2755
- questions = Array.isArray(body) ? body : [];
4245
+ if (Array.isArray(body)) {
4246
+ questions = body;
4247
+ } else {
4248
+ questionsPolledOk = false;
4249
+ }
4250
+ } else {
4251
+ questionsPolledOk = false;
2756
4252
  }
2757
4253
  } catch {
4254
+ questionsPolledOk = false;
2758
4255
  }
2759
4256
  for (const q of questions) {
2760
- if (watcher.reportedQuestions.has(q.id)) continue;
2761
4257
  if (!await this.sessionBelongsTo(q.sessionID, sessionId)) continue;
2762
4258
  const paused = this.attributeInteraction(watcher, q.tool?.messageID, messages);
4259
+ if (paused) openQuestions.add(paused.evidentMessageId);
4260
+ if (watcher.reportedQuestions.has(q.id)) continue;
2763
4261
  const reported = await this.reportInteraction(
2764
4262
  watcher.conv.id,
2765
4263
  "question",
@@ -2773,14 +4271,22 @@ var ChannelDriver = class {
2773
4271
  const res = await this.fetchImpl(`${this.opencodeBase}/permission`);
2774
4272
  if (res.ok) {
2775
4273
  const body = await res.json();
2776
- permissions = Array.isArray(body) ? body : [];
4274
+ if (Array.isArray(body)) {
4275
+ permissions = body;
4276
+ } else {
4277
+ permissionsPolledOk = false;
4278
+ }
4279
+ } else {
4280
+ permissionsPolledOk = false;
2777
4281
  }
2778
4282
  } catch {
4283
+ permissionsPolledOk = false;
2779
4284
  }
2780
4285
  for (const p of permissions) {
2781
- if (watcher.reportedPermissions.has(p.id)) continue;
2782
4286
  if (!await this.sessionBelongsTo(p.sessionID, sessionId)) continue;
2783
4287
  const paused = this.attributeInteraction(watcher, p.messageID, messages);
4288
+ if (paused) openPermissions.add(paused.evidentMessageId);
4289
+ if (watcher.reportedPermissions.has(p.id)) continue;
2784
4290
  const reported = await this.reportInteraction(
2785
4291
  watcher.conv.id,
2786
4292
  "permission",
@@ -2789,6 +4295,7 @@ var ChannelDriver = class {
2789
4295
  );
2790
4296
  if (reported) watcher.reportedPermissions.add(p.id);
2791
4297
  }
4298
+ return { openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk };
2792
4299
  }
2793
4300
  /**
2794
4301
  * True when `sessionId` is the `rootSessionId` itself OR a descendant of it —
@@ -2834,6 +4341,193 @@ var ChannelDriver = class {
2834
4341
  if (parent !== void 0) this.sessionParents.set(sessionId, parent);
2835
4342
  return parent;
2836
4343
  }
4344
+ /**
4345
+ * OpenCode's synchronous default session title (e.g.
4346
+ * `"New session - 1737800000000"`), assigned immediately when a session is
4347
+ * created — before OpenCode's async LLM-based auto-titling later renames it
4348
+ * mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
4349
+ * timestamp suffix's exact format is deliberately NOT matched, since the prefix
4350
+ * alone is the stable, cheap signal and over-anchoring on the timestamp
4351
+ * representation risks silently breaking if OpenCode ever changes it. Accepted
4352
+ * trade-off: a genuine LLM-assigned title that happens to literally start with
4353
+ * this prefix would also fail to latch (see `resolveSessionTitle`) —
4354
+ * vanishingly unlikely in practice, and deliberately not engineered around.
4355
+ */
4356
+ static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
4357
+ /**
4358
+ * Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
4359
+ * status PATCH can carry it into the "Live sessions" list. Driver-level cache so
4360
+ * BOTH the watcher completion path and the restart-recovery re-adopt path (which
4361
+ * has no watcher) can use it. `conversationId` is passed only for log context.
4362
+ * Best-effort:
4363
+ * - a resolved NON-EMPTY title that does NOT match
4364
+ * `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
4365
+ * won't later un-name), so we do NOT re-GET `/session/:id` every tick;
4366
+ * - while the title is still absent, empty, or matches the OpenCode
4367
+ * placeholder prefix (#549) we do NOT latch it — OpenCode names sessions
4368
+ * asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
4369
+ * the cache unresolved and re-fetch on the next need so a later call (e.g. at
4370
+ * `done`) picks up the name assigned in the meantime. Such a call returns
4371
+ * `null` (omit the title on THIS PATCH) without caching. If a session is
4372
+ * never renamed, the title is omitted forever rather than ever persisting
4373
+ * the placeholder as a last resort;
4374
+ * - a failed request likewise leaves the cache unresolved (retry next need)
4375
+ * and returns `null` — it must NEVER throw or block completion.
4376
+ * A failure is logged with agent/session context (no silent catch).
4377
+ */
4378
+ async resolveSessionTitle(sessionId, conversationId) {
4379
+ const cached = this.sessionTitles.get(sessionId);
4380
+ if (cached != null) return cached;
4381
+ try {
4382
+ const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}`);
4383
+ if (res.ok) {
4384
+ const body = await res.json();
4385
+ const title = body && typeof body.title === "string" ? body.title.trim() : "";
4386
+ if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
4387
+ this.sessionTitles.set(sessionId, title);
4388
+ return title;
4389
+ }
4390
+ return null;
4391
+ }
4392
+ this.log({
4393
+ level: "debug",
4394
+ message: `Session title fetch for session ${sessionId.slice(0, 8)} (agent ${this.agentId.slice(0, 8)}) returned HTTP ${res.status} \u2014 omitting title`,
4395
+ conversation_id: conversationId
4396
+ });
4397
+ } catch (err) {
4398
+ this.log({
4399
+ level: "debug",
4400
+ 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)}`,
4401
+ conversation_id: conversationId
4402
+ });
4403
+ }
4404
+ return null;
4405
+ }
4406
+ /**
4407
+ * Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
4408
+ * session title onto the conversation via the PLAIN conversation-update
4409
+ * endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
4410
+ * message-status endpoint `markProcessing`/`markDone` use. Deliberately a
4411
+ * separate, lighter call: it carries no `status`, so it cannot re-trigger the
4412
+ * `processing`/`done` transition side effects (Slack notices, activity-log
4413
+ * rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
4414
+ * ever touches `conversations.title`. That route (`routes/conversations.ts`)
4415
+ * skips a title write matching the stored value, so a redundant call with the
4416
+ * same title is a real no-op — it does not bump `updated_at`, which the
4417
+ * conversation list sorts and paginates on. (Note this is a DIFFERENT guard
4418
+ * from `threads.ts`'s "non-empty AND changed" one, which only covers the
4419
+ * message-status PATCH; the non-empty half is enforced here instead, by
4420
+ * `resolveSessionTitle` never returning an empty/placeholder title.)
4421
+ *
4422
+ * Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
4423
+ * is logged and the title is simply retried on the next heartbeat tick (the
4424
+ * caller only latches `titleSynced` on `true`).
4425
+ */
4426
+ async patchConversationTitle(conversationId, title) {
4427
+ try {
4428
+ const res = await this.fetchImpl(
4429
+ `${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
4430
+ {
4431
+ method: "PATCH",
4432
+ headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
4433
+ body: JSON.stringify({ title })
4434
+ }
4435
+ );
4436
+ if (!res.ok) {
4437
+ this.log({
4438
+ level: "debug",
4439
+ message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
4440
+ conversation_id: conversationId
4441
+ });
4442
+ return false;
4443
+ }
4444
+ return true;
4445
+ } catch (err) {
4446
+ this.log({
4447
+ level: "debug",
4448
+ message: `Best-effort mid-turn title sync PATCH failed for conversation ${conversationId.slice(0, 8)} (will retry next heartbeat): ${err instanceof Error ? err.message : String(err)}`,
4449
+ conversation_id: conversationId
4450
+ });
4451
+ return false;
4452
+ }
4453
+ }
4454
+ /**
4455
+ * DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
4456
+ * (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
4457
+ *
4458
+ * The PRIMARY recovery trigger is "preamble-pinned on recovery ⇒ idle" — a
4459
+ * runner restart wipes OpenCode's in-memory `SessionStatus`/`Runner`, so a
4460
+ * completed `finish: "tool-calls"` root reply encountered during re-adoption is
4461
+ * idle by OpenCode's own definition and is re-dispatched. This method exists only
4462
+ * so the WI-3 caller can VETO that re-dispatch in the rare case a descendant is
4463
+ * provably in flight at the exact moment of recovery.
4464
+ *
4465
+ * "Alive" criterion (TIGHTENED): a descendant is alive only when it is PROVABLY,
4466
+ * ACTIVELY generating — its LAST message is an assistant still mid-generation
4467
+ * (`completed == null`, via `isSessionActivelyGenerating`). An
4468
+ * INCOMPLETE-BUT-NOT-GENERATING child — last message a user message, or a
4469
+ * completed `finish: "tool-calls"` step — is NOT alive after a restart (nothing
4470
+ * is generating once the runner is gone), so it does NOT veto. (This is
4471
+ * deliberately NOT `!isTurnComplete`, which also matches those dead-but-non-terminal
4472
+ * shapes and would falsely veto — re-hanging the very turn this path recovers.)
4473
+ *
4474
+ * Return contract (encoded so WI-3 need not re-derive it):
4475
+ * - `true` → a descendant is provably, actively generating (veto re-dispatch).
4476
+ * - `false` → descendants exist but none is actively generating (the restart
4477
+ * case), OR no descendant is found at all.
4478
+ * - `null` → liveness is INDETERMINATE (enumeration via `listSessions` failed).
4479
+ *
4480
+ * ⚠️ `null` (UNKNOWN) MUST NOT be treated as "alive": WI-3 treats `null` the same
4481
+ * as `false` and does NOT veto — a restart guarantees no live runner, so an
4482
+ * indeterminate cross-check almost always means "couldn't reach a child that no
4483
+ * longer exists". The inversion lives in the caller; this method just reports
4484
+ * true/false/null faithfully.
4485
+ *
4486
+ * VERIFY-BEFORE-DEPEND: we depend ONLY on (a) `parentID` from `GET /session/:id`
4487
+ * (already proven by the existing child-session interaction tests, via
4488
+ * `resolveSessionParent`/`sessionBelongsTo`) and (b) the child's own message-list
4489
+ * terminal state. We do NOT depend on any session-level `busy`/`idle` field —
4490
+ * there is none on `GET /session/:id`; OpenCode's busy state is in-memory
4491
+ * `SessionStatus` only.
4492
+ */
4493
+ async isAnyDescendantSessionAlive(rootSessionId) {
4494
+ const sessions = await listSessions(this.port);
4495
+ if (!sessions) {
4496
+ this.log({
4497
+ level: "warn",
4498
+ message: `Re-adopt: could not enumerate sessions to cross-check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating child liveness as indeterminate`
4499
+ });
4500
+ return null;
4501
+ }
4502
+ for (const candidate of sessions) {
4503
+ if (!candidate?.id || candidate.id === rootSessionId) continue;
4504
+ if (!await this.sessionBelongsTo(candidate.id, rootSessionId)) continue;
4505
+ const childMsgs = await getSessionMessages(this.port, candidate.id);
4506
+ if (isSessionActivelyGenerating(childMsgs)) {
4507
+ return true;
4508
+ }
4509
+ }
4510
+ return false;
4511
+ }
4512
+ /**
4513
+ * Cheap decision-telemetry label for a running row's LAST correlated reply
4514
+ * (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
4515
+ * - `b1` — the reply itself is still in flight (`time.completed == null`) —
4516
+ * the aborted-in-flight production bug after a restart.
4517
+ * - `b2` — a COMPLETED reply pinned running only by `finish === "tool-calls"`
4518
+ * (the sub-agent preamble — #253's shape).
4519
+ * - `other` — any other shape (defensive; a running row is normally b1 or b2).
4520
+ * Reads `info.time.completed` / `info.finish` (tolerating the legacy top-level
4521
+ * shape) directly rather than re-importing the module-private `completedOf`/
4522
+ * `finishOf` — this is a display label only, not a correctness predicate.
4523
+ */
4524
+ replyCompletionShape(reply) {
4525
+ if (!reply) return "other";
4526
+ const completed = reply.info?.time?.completed ?? reply.time?.completed;
4527
+ if (completed == null) return "b1";
4528
+ const finish = reply.info?.finish ?? reply.finish;
4529
+ return finish === "tool-calls" ? "b2" : "other";
4530
+ }
2837
4531
  /**
2838
4532
  * Attribute a surfaced interaction to the in-flight message it paused on (M-1).
2839
4533
  *
@@ -2884,12 +4578,10 @@ var ChannelDriver = class {
2884
4578
  }
2885
4579
  return inFlight.sort(byOldest)[0];
2886
4580
  }
2887
- // -------------------------------------------------------------------------
2888
4581
  // Evident API calls (combinedAuth thread routes)
2889
- // -------------------------------------------------------------------------
2890
4582
  async getPendingConversations() {
2891
4583
  const res = await this.fetchImpl(
2892
- `${this.apiUrl}/agents/${this.agentId}/conversations/pending`,
4584
+ `${this.apiUrl}/runners/${this.agentId}/conversations/pending`,
2893
4585
  {
2894
4586
  headers: { Authorization: this.getAuthHeader() }
2895
4587
  }
@@ -2907,7 +4599,7 @@ var ChannelDriver = class {
2907
4599
  }
2908
4600
  async getPendingMessages(conversationId) {
2909
4601
  const res = await this.fetchImpl(
2910
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages?status=pending`,
4602
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages?status=pending`,
2911
4603
  { headers: { Authorization: this.getAuthHeader() } }
2912
4604
  );
2913
4605
  this.assertAuth(res, "fetching pending messages");
@@ -2931,7 +4623,7 @@ var ChannelDriver = class {
2931
4623
  */
2932
4624
  async getProcessingMessages() {
2933
4625
  const res = await this.fetchImpl(
2934
- `${this.apiUrl}/agents/${this.agentId}/conversations/processing`,
4626
+ `${this.apiUrl}/runners/${this.agentId}/conversations/processing`,
2935
4627
  { headers: { Authorization: this.getAuthHeader() } }
2936
4628
  );
2937
4629
  this.assertAuth(res, "fetching processing messages");
@@ -2945,6 +4637,32 @@ var ChannelDriver = class {
2945
4637
  }
2946
4638
  return messages;
2947
4639
  }
4640
+ /**
4641
+ * The `opencode_session_id` fragment of a status PATCH body — `{}` when this
4642
+ * conversation has ABANDONED that session (#553). The field is optional
4643
+ * server-side and an absent one leaves the persisted binding untouched, so
4644
+ * omitting it is how a routine status write stops resurrecting it.
4645
+ *
4646
+ * ONLY for writes whose sole cost is a lost deep link. The `processing` notice
4647
+ * degrades to no "View in Evident" link (the reaction swap still fires) and the
4648
+ * turn-failure notice is built from the PATCH's own `error` text with a link off
4649
+ * the persisted row — neither loses content the user came for. `markDone`
4650
+ * deliberately does NOT use this helper: the server fetches the reply text
4651
+ * THROUGH the session id it is given, so suppressing there would replace the
4652
+ * agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
4653
+ * `ensureSession` guard, not this suppression, is what makes the self-heal
4654
+ * stick.
4655
+ */
4656
+ sessionIdBody(sessionId, conversationId, messageId, status) {
4657
+ if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
4658
+ this.log({
4659
+ level: "debug",
4660
+ message: `Omitting the abandoned OpenCode session ${sessionId.slice(0, 8)} from the '${status}' update for message ${messageId.slice(0, 8)} so it is not re-bound to conversation ${conversationId.slice(0, 8)}`,
4661
+ conversation_id: conversationId,
4662
+ message_id: messageId
4663
+ });
4664
+ return {};
4665
+ }
2948
4666
  /**
2949
4667
  * EXISTING combinedAuth route — now fired by the watcher on queued→running
2950
4668
  * (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
@@ -2966,16 +4684,17 @@ var ChannelDriver = class {
2966
4684
  * A single attempt (no internal retry): the watcher's per-tick loop is the
2967
4685
  * retry vehicle for the swap-to-running.
2968
4686
  */
2969
- async markProcessing(conversationId, messageId, sessionId, opencodeMessageId) {
4687
+ async markProcessing(conversationId, messageId, sessionId, opencodeMessageId, title) {
2970
4688
  const res = await this.fetchImpl(
2971
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
4689
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
2972
4690
  {
2973
4691
  method: "PATCH",
2974
4692
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
2975
4693
  body: JSON.stringify({
2976
4694
  status: "processing",
2977
- opencode_session_id: sessionId,
2978
- ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {}
4695
+ ...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
4696
+ ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
4697
+ ...title ? { title } : {}
2979
4698
  })
2980
4699
  }
2981
4700
  );
@@ -3014,16 +4733,23 @@ var ChannelDriver = class {
3014
4733
  * watcher retries next tick within the
3015
4734
  * deadline, Finding 4).
3016
4735
  */
3017
- async markDone(conversationId, messageId, sessionId, opencodeMessageId) {
4736
+ async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage) {
3018
4737
  const res = await this.fetchImpl(
3019
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
4738
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
3020
4739
  {
3021
4740
  method: "PATCH",
3022
4741
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3023
4742
  body: JSON.stringify({
3024
4743
  status: "done",
4744
+ // ALWAYS sent, even for a session this conversation has abandoned
4745
+ // (#553): the server reads the reply text back out of THIS session id
4746
+ // to deliver it. Omitting it would leave the user with "✅ Done!"
4747
+ // instead of the answer — a worse regression than the resurrection it
4748
+ // would prevent, which `ensureSession`'s guard handles anyway.
3025
4749
  opencode_session_id: sessionId,
3026
- ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {}
4750
+ ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
4751
+ ...title ? { title } : {},
4752
+ ...usage ? usage : {}
3027
4753
  })
3028
4754
  }
3029
4755
  );
@@ -3036,19 +4762,29 @@ var ChannelDriver = class {
3036
4762
  }
3037
4763
  /**
3038
4764
  * Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
3039
- * when provided (issue #182): a bare `markFailed(conv, msg)` sends
3040
- * `{status:'failed'}` unchanged (the dispatch-failure path), while an errored
3041
- * OpenCode turn sends `{status:'failed', opencode_session_id, error}` so the
3042
- * failure reason reaches the channel.
4765
+ * when provided (issue #182). Three states for `sessionId`:
4766
+ * - omitted (`undefined`) → don't send the field, leave the persisted
4767
+ * session untouched (unused today; kept for API symmetry).
4768
+ * - a real id (`string`) → send it, update the persisted session (the
4769
+ * turn-failure call sites: an errored OpenCode turn).
4770
+ * - explicit `null` → send it, CLEAR the persisted session (issue
4771
+ * #485's dispatch-handoff-failure call site: the session id still
4772
+ * exists but is wedged, so the next attempt must get a fresh one
4773
+ * instead of reusing it — see WI-1's server-side null-clearing PATCH).
3043
4774
  */
3044
- async markFailed(conversationId, messageId, sessionId, error2) {
4775
+ async markFailed(conversationId, messageId, sessionId, error2, usage) {
3045
4776
  const body = { status: "failed" };
3046
- if (sessionId !== void 0) body.opencode_session_id = sessionId;
4777
+ if (sessionId === null) {
4778
+ body.opencode_session_id = null;
4779
+ } else if (sessionId !== void 0) {
4780
+ Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
4781
+ }
3047
4782
  if (error2 !== void 0) body.error = error2;
4783
+ if (usage) Object.assign(body, usage);
3048
4784
  await this.callWithRetry(
3049
4785
  "marking message as failed",
3050
4786
  () => this.fetchImpl(
3051
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
4787
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
3052
4788
  {
3053
4789
  method: "PATCH",
3054
4790
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -3065,11 +4801,17 @@ var ChannelDriver = class {
3065
4801
  * MUST NOT use `callWithRetry` (a telemetry ping must not block the sequential
3066
4802
  * watcher tick — one attempt is enough). A failure is SWALLOWED but LOGGED with
3067
4803
  * context (no silent catch, per development-workflow).
4804
+ *
4805
+ * Returns whether the POST SUCCEEDED (2xx). Most callers ignore this (pure
4806
+ * telemetry), but the `paused` liveness-clear uses it to know whether to
4807
+ * RE-ASSERT on a later tick — a single dropped `paused` POST must not leave a
4808
+ * stale `last_seen_alive_at` on a still-paused row (Bugbot "Failed paused signal
4809
+ * leaves liveness").
3068
4810
  */
3069
4811
  async postSignal(conversationId, messageId, signal, extra) {
3070
4812
  try {
3071
4813
  const res = await this.fetchImpl(
3072
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
4814
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
3073
4815
  {
3074
4816
  method: "POST",
3075
4817
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -3078,24 +4820,27 @@ var ChannelDriver = class {
3078
4820
  );
3079
4821
  if (!res.ok) {
3080
4822
  this.log({
3081
- level: "error",
4823
+ level: "warn",
3082
4824
  message: `Signal '${signal}' for message ${messageId.slice(0, 8)} returned HTTP ${res.status} (telemetry-only, ignored)`,
3083
4825
  conversation_id: conversationId,
3084
4826
  message_id: messageId
3085
4827
  });
4828
+ return false;
3086
4829
  }
4830
+ return true;
3087
4831
  } catch (err) {
3088
4832
  this.log({
3089
- level: "error",
4833
+ level: "warn",
3090
4834
  message: `Signal '${signal}' for message ${messageId.slice(0, 8)} failed (telemetry-only, ignored): ${err instanceof Error ? err.message : String(err)}`,
3091
4835
  conversation_id: conversationId,
3092
4836
  message_id: messageId
3093
4837
  });
4838
+ return false;
3094
4839
  }
3095
4840
  }
3096
4841
  async persistSession(conversationId, sessionId) {
3097
4842
  const res = await this.fetchImpl(
3098
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}`,
4843
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}`,
3099
4844
  {
3100
4845
  method: "PATCH",
3101
4846
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -3121,7 +4866,7 @@ var ChannelDriver = class {
3121
4866
  await this.callWithRetry(
3122
4867
  "reporting interactive event",
3123
4868
  () => this.fetchImpl(
3124
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/interactive-event`,
4869
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/interactive-event`,
3125
4870
  {
3126
4871
  method: "POST",
3127
4872
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -3147,9 +4892,7 @@ var ChannelDriver = class {
3147
4892
  return false;
3148
4893
  }
3149
4894
  }
3150
- // -------------------------------------------------------------------------
3151
4895
  // Retry wrapper
3152
- // -------------------------------------------------------------------------
3153
4896
  /**
3154
4897
  * Invoke an Evident API call, retrying on transient failures (5xx / 429 /
3155
4898
  * network errors) with exponential backoff + jitter (capped). Auth failures
@@ -3348,7 +5091,7 @@ async function resolveAgentIdFromKey(authHeader) {
3348
5091
  if (!response.ok) {
3349
5092
  const serverMessage = await readErrorMessage(response);
3350
5093
  return {
3351
- error: `Failed to resolve agent from key (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
5094
+ error: `Failed to resolve runner from key (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
3352
5095
  };
3353
5096
  }
3354
5097
  const data = await response.json();
@@ -3356,19 +5099,49 @@ async function resolveAgentIdFromKey(authHeader) {
3356
5099
  return { agent_id: data.agent_id };
3357
5100
  }
3358
5101
  return {
3359
- error: "Cannot resolve agent ID: auth type is not agent_key. Please provide --agent explicitly."
5102
+ error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --agent explicitly."
3360
5103
  };
3361
5104
  } catch (error2) {
3362
5105
  const message = error2 instanceof Error ? error2.message : "Unknown error";
3363
- return { error: `Failed to resolve agent from key: ${message}` };
5106
+ return { error: `Failed to resolve runner from key: ${message}` };
3364
5107
  }
3365
5108
  }
5109
+ var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
3366
5110
  async function notifyAgentDisconnected(agentId, authHeader) {
3367
5111
  const apiUrl = getApiUrlConfig();
3368
5112
  try {
3369
- const response = await fetch(`${apiUrl}/agents/${agentId}/disconnect`, {
5113
+ const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
3370
5114
  method: "POST",
3371
- headers: { Authorization: authHeader }
5115
+ headers: { Authorization: authHeader },
5116
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
5117
+ });
5118
+ if (!response.ok) {
5119
+ const serverMessage = await readErrorMessage(response);
5120
+ return {
5121
+ ok: false,
5122
+ error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
5123
+ };
5124
+ }
5125
+ return { ok: true };
5126
+ } catch (error2) {
5127
+ return { ok: false, error: describeBestEffortError(error2) };
5128
+ }
5129
+ }
5130
+ function describeBestEffortError(error2) {
5131
+ const name = error2?.name;
5132
+ if (name === "TimeoutError" || name === "AbortError") {
5133
+ return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
5134
+ }
5135
+ return error2 instanceof Error ? error2.message : String(error2);
5136
+ }
5137
+ async function reportMicrovmId(agentId, authHeader, microvmId) {
5138
+ try {
5139
+ const apiUrl = getApiUrlConfig();
5140
+ const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
5141
+ method: "POST",
5142
+ headers: { Authorization: authHeader, "Content-Type": "application/json" },
5143
+ body: JSON.stringify({ microvm_id: microvmId }),
5144
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
3372
5145
  });
3373
5146
  if (!response.ok) {
3374
5147
  const serverMessage = await readErrorMessage(response);
@@ -3379,13 +5152,13 @@ async function notifyAgentDisconnected(agentId, authHeader) {
3379
5152
  }
3380
5153
  return { ok: true };
3381
5154
  } catch (error2) {
3382
- return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
5155
+ return { ok: false, error: describeBestEffortError(error2) };
3383
5156
  }
3384
5157
  }
3385
5158
  async function getAgentInfo(agentId, authHeader) {
3386
5159
  const apiUrl = getApiUrlConfig();
3387
5160
  try {
3388
- const response = await fetch(`${apiUrl}/agents/${agentId}`, {
5161
+ const response = await fetch(`${apiUrl}/runners/${agentId}`, {
3389
5162
  headers: { Authorization: authHeader }
3390
5163
  });
3391
5164
  if (response.status === 401) {
@@ -3396,12 +5169,12 @@ async function getAgentInfo(agentId, authHeader) {
3396
5169
  const serverMessage = await readErrorMessage(response);
3397
5170
  return {
3398
5171
  valid: false,
3399
- error: serverMessage ?? "You do not have access to this agent (it may belong to a different team or organization)."
5172
+ error: serverMessage ?? "You do not have access to this runner (it may belong to a different team or organization)."
3400
5173
  };
3401
5174
  }
3402
5175
  if (response.status === 404) {
3403
5176
  const serverMessage = await readErrorMessage(response);
3404
- return { valid: false, error: serverMessage ?? `Agent ${agentId} not found` };
5177
+ return { valid: false, error: serverMessage ?? `Runner ${agentId} not found` };
3405
5178
  }
3406
5179
  if (!response.ok) {
3407
5180
  const serverMessage = await readErrorMessage(response);
@@ -3414,13 +5187,13 @@ async function getAgentInfo(agentId, authHeader) {
3414
5187
  if (agent.agent_type !== "local") {
3415
5188
  return {
3416
5189
  valid: false,
3417
- error: `Agent is type '${agent.agent_type}', must be 'local' for CLI connection`
5190
+ error: `Runner is type '${agent.agent_type}', must be 'local' for CLI connection`
3418
5191
  };
3419
5192
  }
3420
5193
  return { valid: true, agent };
3421
5194
  } catch (error2) {
3422
5195
  const message = error2 instanceof Error ? error2.message : "Unknown error";
3423
- return { valid: false, error: `Failed to validate agent: ${message}` };
5196
+ return { valid: false, error: `Failed to validate runner: ${message}` };
3424
5197
  }
3425
5198
  }
3426
5199
 
@@ -3429,23 +5202,82 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
3429
5202
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
3430
5203
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
3431
5204
  var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
3432
- function log2(state, message, isError = false) {
5205
+ var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
5206
+ function resolveLogLevel(options) {
5207
+ const accepted = Object.keys(LOG_LEVELS);
5208
+ const validate = (value, source) => {
5209
+ const normalized = value.trim().toLowerCase();
5210
+ if (!accepted.includes(normalized)) {
5211
+ throw new Error(
5212
+ `Invalid log level "${value}"${source}; expected one of ${accepted.join(", ")}`
5213
+ );
5214
+ }
5215
+ return normalized;
5216
+ };
5217
+ if (options.logLevel !== void 0) {
5218
+ return validate(options.logLevel, " (--log-level)");
5219
+ }
5220
+ if (options.verbose) {
5221
+ return "debug";
5222
+ }
5223
+ const env = process.env.EVIDENT_LOG_LEVEL;
5224
+ if (env !== void 0 && env !== "") {
5225
+ return validate(env, " (EVIDENT_LOG_LEVEL)");
5226
+ }
5227
+ return "info";
5228
+ }
5229
+ function resolveFileSyncDirectories(raw, homeDir) {
5230
+ const directories = [];
5231
+ for (const entry of raw ?? []) {
5232
+ const trimmed = entry.trim();
5233
+ if (trimmed === "") {
5234
+ throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
5235
+ }
5236
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join2(homeDir, trimmed.slice(2)) : trimmed;
5237
+ if (!isAbsolute2(expanded)) {
5238
+ throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
5239
+ }
5240
+ const normalized = resolvePath(expanded);
5241
+ if (parse(normalized).root === normalized) {
5242
+ throw new Error(
5243
+ `--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
5244
+ );
5245
+ }
5246
+ if (!directories.includes(normalized)) {
5247
+ directories.push(normalized);
5248
+ }
5249
+ }
5250
+ if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
5251
+ throw new Error(
5252
+ `--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
5253
+ );
5254
+ }
5255
+ return directories;
5256
+ }
5257
+ function meetsThreshold(state, level) {
5258
+ return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
5259
+ }
5260
+ function log2(state, message, level = "info") {
5261
+ if (!meetsThreshold(state, level)) return;
3433
5262
  if (state.json) {
3434
5263
  console.log(
3435
5264
  JSON.stringify({
3436
5265
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3437
- level: isError ? "error" : "info",
5266
+ level,
3438
5267
  message
3439
5268
  })
3440
5269
  );
3441
5270
  } else if (!state.interactive) {
3442
- const prefix = isError ? chalk6.red("\u2717") : chalk6.green("\u2022");
5271
+ const prefix = level === "error" ? chalk6.red("\u2717") : level === "warn" ? chalk6.yellow("!") : level === "debug" ? chalk6.dim("\xB7") : chalk6.green("\u2022");
3443
5272
  console.log(`${prefix} ${message}`);
3444
5273
  }
3445
5274
  }
3446
5275
  function logActivity(state, entry) {
5276
+ const level = entry.level ?? (entry.type === "error" ? "error" : "info");
5277
+ if (!meetsThreshold(state, level)) return;
3447
5278
  const fullEntry = {
3448
5279
  ...entry,
5280
+ level,
3449
5281
  timestamp: /* @__PURE__ */ new Date()
3450
5282
  };
3451
5283
  state.activityLog.push(fullEntry);
@@ -3454,9 +5286,9 @@ function logActivity(state, entry) {
3454
5286
  }
3455
5287
  if (!state.interactive) {
3456
5288
  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);
5289
+ log2(state, entry.error ?? "Unknown error", level);
5290
+ } else if (entry.message) {
5291
+ log2(state, entry.message, level);
3460
5292
  }
3461
5293
  }
3462
5294
  }
@@ -3543,18 +5375,29 @@ async function handleAuthError(state, error2) {
3543
5375
  async function driveChannels(state, driver) {
3544
5376
  let idlePolls = 0;
3545
5377
  let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
5378
+ let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
3546
5379
  while (state.running) {
3547
5380
  if (state.connection?.reconnecting && state.connection.reconnectPromise) {
3548
5381
  logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
3549
5382
  if (state.interactive) displayStatus(state);
3550
5383
  await state.connection.reconnectPromise;
3551
5384
  }
5385
+ const carriedOverFileSync = driver.fileSyncActivity().inFlight;
5386
+ void driver.syncPendingFiles().catch(
5387
+ (error2) => logActivity(state, {
5388
+ type: "error",
5389
+ error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
5390
+ })
5391
+ );
3552
5392
  try {
3553
5393
  const processed = await driver.drainPending();
3554
5394
  state.messageCount += processed;
3555
5395
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
3556
5396
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
3557
- if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity) {
5397
+ const appliedFiles = driver.fileSyncActivity().appliedFiles;
5398
+ const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
5399
+ lastSeenAppliedFiles = appliedFiles;
5400
+ if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
3558
5401
  idlePolls = 0;
3559
5402
  if (processed > 0 && state.interactive) displayStatus(state);
3560
5403
  } else if (state.idleTimeout !== null) {
@@ -3583,7 +5426,7 @@ async function driveChannels(state, driver) {
3583
5426
  logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
3584
5427
  if (state.interactive) displayStatus(state);
3585
5428
  }
3586
- await new Promise((resolve) => setTimeout(resolve, CHANNEL_POLL_INTERVAL_MS));
5429
+ await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
3587
5430
  if (state.idleTimeout !== null && idlePolls >= 2) {
3588
5431
  const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
3589
5432
  if (idleMs > state.idleTimeout * 1e3) {
@@ -3594,6 +5437,81 @@ async function driveChannels(state, driver) {
3594
5437
  }
3595
5438
  }
3596
5439
  }
5440
+ var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
5441
+ async function runSweep(state, driver, config2) {
5442
+ const mode = `age=${config2.maxAgeMs ?? "\u2014"} count=${config2.maxCount ?? "\u2014"}`;
5443
+ try {
5444
+ const sessions = await listSessions(state.port);
5445
+ if (sessions === null) {
5446
+ logActivity(state, {
5447
+ type: "info",
5448
+ message: `Session cleanup: could not list sessions (opencode unreachable); skipping this sweep (${mode})`
5449
+ });
5450
+ return;
5451
+ }
5452
+ const toDelete = selectSessionsToDelete(
5453
+ sessions.map((s) => ({ id: s.id, lastActivityMs: sessionLastActivityMs(s) })),
5454
+ {
5455
+ maxAgeMs: config2.maxAgeMs,
5456
+ maxCount: config2.maxCount,
5457
+ nowMs: Date.now(),
5458
+ protectedIds: driver.protectedSessionIds()
5459
+ }
5460
+ );
5461
+ const protectedNow = driver.protectedSessionIds();
5462
+ let deleted = 0;
5463
+ let failed = 0;
5464
+ let skippedNewlyActive = 0;
5465
+ for (const id of toDelete) {
5466
+ if (protectedNow.has(id)) {
5467
+ skippedNewlyActive++;
5468
+ logActivity(state, {
5469
+ type: "info",
5470
+ message: `Session cleanup: skipping ${id} \u2014 became active/bound after selection (${mode})`
5471
+ });
5472
+ continue;
5473
+ }
5474
+ if (await deleteSession(state.port, id)) deleted++;
5475
+ else failed++;
5476
+ }
5477
+ const failedNote = failed > 0 ? `, failed ${failed}` : "";
5478
+ const skippedNote = skippedNewlyActive > 0 ? `, skipped ${skippedNewlyActive} newly-active` : "";
5479
+ logActivity(state, {
5480
+ type: "info",
5481
+ message: `Session cleanup: inspected ${sessions.length}, deleted ${deleted}${failedNote}${skippedNote} (${mode})`
5482
+ });
5483
+ } catch (error2) {
5484
+ const message = error2 instanceof Error ? error2.message : String(error2);
5485
+ logActivity(state, {
5486
+ type: "error",
5487
+ error: `Session cleanup sweep failed (non-fatal, ${mode}): ${message}`
5488
+ });
5489
+ }
5490
+ }
5491
+ function scheduleSessionCleanup(state, driver, options) {
5492
+ const config2 = resolveSessionCleanupConfig(
5493
+ {
5494
+ maxAge: options.sessionCleanupMaxAge,
5495
+ maxCount: options.sessionCleanupMaxCount,
5496
+ interval: options.sessionCleanupInterval
5497
+ },
5498
+ process.env
5499
+ );
5500
+ for (const warning2 of config2.warnings) {
5501
+ logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
5502
+ }
5503
+ if (!config2.enabled) return;
5504
+ logActivity(state, {
5505
+ type: "info",
5506
+ message: `Session cleanup enabled (age=${config2.maxAgeMs ?? "\u2014"}, count=${config2.maxCount ?? "\u2014"}, interval=${config2.intervalMs}ms)`
5507
+ });
5508
+ const interval = setInterval(() => void runSweep(state, driver, config2), config2.intervalMs);
5509
+ const firstSweep = setTimeout(
5510
+ () => void runSweep(state, driver, config2),
5511
+ SESSION_CLEANUP_FIRST_SWEEP_MS
5512
+ );
5513
+ state.sessionCleanupTimers.push(interval, firstSweep);
5514
+ }
3597
5515
  async function notifyOffline(state) {
3598
5516
  if (!state.agentId || !state.authHeader) return;
3599
5517
  if (!state.connected) {
@@ -3602,7 +5520,7 @@ async function notifyOffline(state) {
3602
5520
  }
3603
5521
  const result = await notifyAgentDisconnected(state.agentId, state.authHeader);
3604
5522
  if (result.ok) {
3605
- log2(state, "Notified Evident the agent is going offline");
5523
+ log2(state, "Notified Evident the runner is going offline");
3606
5524
  } else {
3607
5525
  logActivity(state, {
3608
5526
  type: "error",
@@ -3611,8 +5529,24 @@ async function notifyOffline(state) {
3611
5529
  if (state.interactive) displayStatus(state);
3612
5530
  }
3613
5531
  }
5532
+ async function timeShutdownPhase(state, durations, name, run2) {
5533
+ const startedAt = Date.now();
5534
+ try {
5535
+ return await run2();
5536
+ } finally {
5537
+ const elapsedMs = Date.now() - startedAt;
5538
+ durations[name] = elapsedMs;
5539
+ log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
5540
+ }
5541
+ }
3614
5542
  async function cleanup(state, opts = {}) {
5543
+ const durations = {};
3615
5544
  state.running = false;
5545
+ for (const timer of state.sessionCleanupTimers) {
5546
+ clearInterval(timer);
5547
+ clearTimeout(timer);
5548
+ }
5549
+ state.sessionCleanupTimers = [];
3616
5550
  if (opts.graceful && state.channelDriver) {
3617
5551
  state.channelDriver.stop();
3618
5552
  log2(state, "Draining in-flight channel work before shutdown...");
@@ -3620,7 +5554,13 @@ async function cleanup(state, opts = {}) {
3620
5554
  logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
3621
5555
  displayStatus(state);
3622
5556
  }
3623
- const settled = await state.channelDriver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS);
5557
+ const driver = state.channelDriver;
5558
+ const settled = await timeShutdownPhase(
5559
+ state,
5560
+ durations,
5561
+ "drain",
5562
+ () => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
5563
+ );
3624
5564
  if (!settled) {
3625
5565
  logActivity(state, {
3626
5566
  type: "info",
@@ -3629,13 +5569,15 @@ async function cleanup(state, opts = {}) {
3629
5569
  if (state.interactive) displayStatus(state);
3630
5570
  }
3631
5571
  }
3632
- await notifyOffline(state);
5572
+ await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
3633
5573
  if (state.connection) {
3634
- state.connection.close();
5574
+ const connection = state.connection;
5575
+ await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
3635
5576
  state.connection = null;
3636
5577
  }
3637
5578
  if (state.opencodeProcess) {
3638
- stopOpenCode(state.opencodeProcess);
5579
+ const opencodeProcess = state.opencodeProcess;
5580
+ await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
3639
5581
  if (state.interactive) {
3640
5582
  logActivity(state, { type: "info", message: "Stopped OpenCode process" });
3641
5583
  displayStatus(state);
@@ -3644,17 +5586,35 @@ async function cleanup(state, opts = {}) {
3644
5586
  }
3645
5587
  state.opencodeProcess = null;
3646
5588
  }
5589
+ return durations;
3647
5590
  }
3648
5591
  async function run(options) {
3649
5592
  const interactive = isInteractive(options.json);
5593
+ let logLevel;
5594
+ let fileSyncDirectories;
5595
+ try {
5596
+ logLevel = resolveLogLevel(options);
5597
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
5598
+ } catch (error2) {
5599
+ const message = error2 instanceof Error ? error2.message : String(error2);
5600
+ if (options.json) {
5601
+ console.log(JSON.stringify({ status: "error", error: message }));
5602
+ } else {
5603
+ printError(message);
5604
+ }
5605
+ await shutdownTelemetry();
5606
+ process.exit(1);
5607
+ return;
5608
+ }
3650
5609
  const state = {
3651
- agentId: options.agent || "",
5610
+ agentId: options.runner || options.agent || "",
3652
5611
  agentName: null,
3653
5612
  port: options.port ?? 4096,
3654
5613
  conversationFilter: options.conversation ?? null,
3655
5614
  idleTimeout: options.idleTimeout ?? null,
3656
5615
  json: options.json ?? false,
3657
5616
  interactive,
5617
+ logLevel,
3658
5618
  connected: false,
3659
5619
  opencodeConnected: false,
3660
5620
  opencodeVersion: null,
@@ -3666,26 +5626,69 @@ async function run(options) {
3666
5626
  activityLog: [],
3667
5627
  messageCount: 0,
3668
5628
  lastProxiedActivityAt: null,
5629
+ sessionCleanupTimers: [],
3669
5630
  authHeader: ""
3670
5631
  };
5632
+ if (fileSyncDirectories.length > 0) {
5633
+ log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
5634
+ } else {
5635
+ log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
5636
+ }
5637
+ if (!options.runner && options.agent) {
5638
+ telemetry.info(
5639
+ EventTypes.DEPRECATED_AGENT_FLAG_USED,
5640
+ "Deprecated --agent flag used instead of --runner",
5641
+ { command: "run" },
5642
+ state.agentId
5643
+ );
5644
+ const agentFlagNotice = "--agent is deprecated, use --runner instead; will be removed in a future release.";
5645
+ log2(state, agentFlagNotice, "warn");
5646
+ if (state.interactive && !state.json) {
5647
+ logActivity(state, { type: "info", level: "warn", message: agentFlagNotice });
5648
+ }
5649
+ }
3671
5650
  if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
3672
5651
  log2(
3673
5652
  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
5653
+ "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.",
5654
+ "warn"
3676
5655
  );
3677
5656
  }
3678
5657
  const handleSignal = async () => {
3679
5658
  if (state.shuttingDown) return;
3680
5659
  state.shuttingDown = true;
5660
+ const shutdownStartedAt = Date.now();
3681
5661
  if (state.interactive) {
3682
5662
  logActivity(state, { type: "info", message: "Shutting down..." });
3683
5663
  displayStatus(state);
3684
5664
  } else {
3685
5665
  log2(state, "Shutting down...");
3686
5666
  }
3687
- await cleanup(state, { graceful: true });
3688
- await shutdownTelemetry();
5667
+ const durations = await cleanup(state, { graceful: true });
5668
+ const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
5669
+ await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
5670
+ let timer;
5671
+ const flushed = shutdownTelemetry().then(
5672
+ () => true,
5673
+ (error2) => {
5674
+ log2(
5675
+ state,
5676
+ `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
5677
+ "warn"
5678
+ );
5679
+ return true;
5680
+ }
5681
+ );
5682
+ const timedOut = new Promise((resolve3) => {
5683
+ timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
5684
+ });
5685
+ if (!await Promise.race([flushed, timedOut])) {
5686
+ log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
5687
+ }
5688
+ clearTimeout(timer);
5689
+ });
5690
+ const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
5691
+ log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
3689
5692
  process.exit(0);
3690
5693
  };
3691
5694
  process.on("SIGINT", handleSignal);
@@ -3696,7 +5699,9 @@ async function run(options) {
3696
5699
  if (!interactive) {
3697
5700
  printError("Authentication required");
3698
5701
  blank();
3699
- console.log(chalk6.dim("Set EVIDENT_AGENT_KEY environment variable for CI"));
5702
+ console.log(
5703
+ chalk6.dim("Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY) environment variable for CI")
5704
+ );
3700
5705
  console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
3701
5706
  blank();
3702
5707
  process.exit(1);
@@ -3710,26 +5715,51 @@ async function run(options) {
3710
5715
  );
3711
5716
  }
3712
5717
  state.authHeader = getAuthHeader(credentials2);
5718
+ if (credentials2.notice) {
5719
+ log2(state, credentials2.notice, "warn");
5720
+ if (state.interactive && !state.json) {
5721
+ logActivity(state, { type: "info", level: "warn", message: credentials2.notice });
5722
+ }
5723
+ }
5724
+ if (credentials2.keySource === "agent_key") {
5725
+ telemetry.info(
5726
+ EventTypes.DEPRECATED_AGENT_KEY_ENV_USED,
5727
+ "Deprecated EVIDENT_AGENT_KEY env var used instead of EVIDENT_RUNNER_KEY",
5728
+ { command: "run" },
5729
+ state.agentId
5730
+ );
5731
+ const agentKeyNotice = "EVIDENT_AGENT_KEY is deprecated, use EVIDENT_RUNNER_KEY instead; will be removed in a future release.";
5732
+ log2(state, agentKeyNotice, "warn");
5733
+ if (state.interactive && !state.json) {
5734
+ logActivity(state, { type: "info", level: "warn", message: agentKeyNotice });
5735
+ }
5736
+ }
3713
5737
  if (!state.agentId) {
3714
5738
  if (credentials2.authType === "agent_key") {
3715
5739
  const resolved = await resolveAgentIdFromKey(state.authHeader);
3716
5740
  if (resolved.agent_id) {
3717
5741
  state.agentId = resolved.agent_id;
3718
- log2(state, `Resolved agent ID from key: ${state.agentId}`);
5742
+ log2(state, `Resolved runner ID from key: ${state.agentId}`);
3719
5743
  if (state.interactive && !state.json) {
3720
5744
  logActivity(state, {
3721
5745
  type: "info",
3722
- message: `Agent ID resolved from key: ${state.agentId}`
5746
+ message: `Runner ID resolved from key: ${state.agentId}`
3723
5747
  });
3724
5748
  }
3725
5749
  } else {
3726
- printError(resolved.error || "Failed to resolve agent ID from key");
5750
+ printError(resolved.error || "Failed to resolve runner ID from key");
3727
5751
  process.exit(1);
3728
5752
  }
3729
5753
  } else {
3730
- printError("--agent is required when not using EVIDENT_AGENT_KEY");
5754
+ printError(
5755
+ "--runner (or --agent) is required when not using EVIDENT_RUNNER_KEY or EVIDENT_AGENT_KEY"
5756
+ );
3731
5757
  blank();
3732
- console.log(chalk6.dim("Either provide --agent <id> or set EVIDENT_AGENT_KEY"));
5758
+ console.log(
5759
+ chalk6.dim(
5760
+ "Either provide --runner/--agent <id> or set EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY"
5761
+ )
5762
+ );
3733
5763
  blank();
3734
5764
  process.exit(1);
3735
5765
  }
@@ -3751,7 +5781,7 @@ async function run(options) {
3751
5781
  console.log(chalk6.bold("Evident Run"));
3752
5782
  console.log(chalk6.dim("-".repeat(40)));
3753
5783
  }
3754
- const spinner = interactive && !state.json ? ora3("Validating agent...").start() : null;
5784
+ const spinner = interactive && !state.json ? ora3("Validating runner...").start() : null;
3755
5785
  let validation = await getAgentInfo(state.agentId, state.authHeader);
3756
5786
  if (!validation.valid && validation.authFailed && interactive) {
3757
5787
  spinner?.fail("Authentication failed");
@@ -3763,15 +5793,30 @@ async function run(options) {
3763
5793
  "Login successful! Retrying..."
3764
5794
  );
3765
5795
  state.authHeader = getAuthHeader(credentials2);
3766
- spinner?.start("Validating agent...");
5796
+ spinner?.start("Validating runner...");
3767
5797
  validation = await getAgentInfo(state.agentId, state.authHeader);
3768
5798
  }
3769
5799
  if (!validation.valid) {
3770
- spinner?.fail(`Agent validation failed: ${validation.error}`);
5800
+ spinner?.fail(`Runner validation failed: ${validation.error}`);
3771
5801
  throw new Error(validation.error);
3772
5802
  }
3773
- spinner?.succeed(`Agent: ${validation.agent.name || state.agentId}`);
5803
+ spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
3774
5804
  state.agentName = validation.agent.name;
5805
+ const microvmId = process.env.MICROVM_ID?.trim();
5806
+ if (microvmId) {
5807
+ const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
5808
+ if (reported.ok) {
5809
+ log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
5810
+ } else {
5811
+ const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
5812
+ log2(state, message, "warn");
5813
+ if (state.interactive && !state.json) {
5814
+ logActivity(state, { type: "info", level: "warn", message });
5815
+ }
5816
+ }
5817
+ } else {
5818
+ log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
5819
+ }
3775
5820
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
3776
5821
  try {
3777
5822
  const oc = await ensureOpenCodeRunning({
@@ -3788,9 +5833,24 @@ async function run(options) {
3788
5833
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
3789
5834
  const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
3790
5835
  if (versionWarning) {
3791
- log2(state, versionWarning, false);
5836
+ log2(state, versionWarning, "warn");
5837
+ if (state.interactive && !state.json) {
5838
+ logActivity(state, { type: "info", level: "warn", message: versionWarning });
5839
+ }
5840
+ }
5841
+ const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
5842
+ if (noProviderWarning) {
5843
+ log2(state, noProviderWarning, "warn");
3792
5844
  if (state.interactive && !state.json) {
3793
- logActivity(state, { type: "info", message: versionWarning });
5845
+ logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
5846
+ blank();
5847
+ console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
5848
+ console.log(
5849
+ chalk6.dim(
5850
+ `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
5851
+ )
5852
+ );
5853
+ blank();
3794
5854
  }
3795
5855
  }
3796
5856
  } catch (error2) {
@@ -3805,11 +5865,21 @@ async function run(options) {
3805
5865
  getAuthHeader: () => state.authHeader,
3806
5866
  conversationFilter: state.conversationFilter,
3807
5867
  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
- })
5868
+ // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
5869
+ // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
5870
+ fileSyncDirectories,
5871
+ homeDir: homedir2(),
5872
+ log: (entry) => (
5873
+ // Thread the driver's real level straight through so `debug`/`warn`
5874
+ // survive the sink filter (they no longer collapse to info). `type`
5875
+ // stays the coarse error/non-error split the activity log renders with.
5876
+ logActivity(state, {
5877
+ type: entry.level === "error" ? "error" : "info",
5878
+ level: entry.level,
5879
+ message: entry.message,
5880
+ error: entry.level === "error" ? entry.message : void 0
5881
+ })
5882
+ )
3813
5883
  });
3814
5884
  state.channelDriver = channelDriver;
3815
5885
  const connection = new RunnerConnection({
@@ -3823,7 +5893,7 @@ async function run(options) {
3823
5893
  state.agentId = agentId;
3824
5894
  logActivity(state, {
3825
5895
  type: "info",
3826
- message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (agent: ${agentId})`
5896
+ message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
3827
5897
  });
3828
5898
  emitAgentConnected(state.agentId, {
3829
5899
  port: state.port,
@@ -3880,6 +5950,12 @@ async function run(options) {
3880
5950
  onDrainPing: () => {
3881
5951
  if (!state.running) return;
3882
5952
  logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
5953
+ void channelDriver.syncPendingFiles().catch(
5954
+ (error2) => logActivity(state, {
5955
+ type: "error",
5956
+ error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
5957
+ })
5958
+ );
3883
5959
  channelDriver.drainPending().then((processed) => {
3884
5960
  if (processed > 0) {
3885
5961
  state.messageCount += processed;
@@ -3908,6 +5984,7 @@ async function run(options) {
3908
5984
  if (error2.message === "Unauthorized") tunnelSpinner?.fail("Unauthorized");
3909
5985
  throw error2;
3910
5986
  }
5987
+ scheduleSessionCleanup(state, channelDriver, options);
3911
5988
  if (!interactive || state.json) {
3912
5989
  log2(state, "Driving channel messages...");
3913
5990
  }
@@ -3937,7 +6014,7 @@ async function run(options) {
3937
6014
  }
3938
6015
  telemetry.error(EventTypes.CLI_ERROR, `Run command failed: ${message}`, {
3939
6016
  command: "run",
3940
- agentId: options.agent
6017
+ agentId: options.runner || options.agent
3941
6018
  });
3942
6019
  await shutdownTelemetry();
3943
6020
  process.exit(1);
@@ -3962,15 +6039,46 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
3962
6039
  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
6040
  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
6041
  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(
6042
+ program.command("run").description("Connect to Evident and process messages").option("--runner [id]", "Runner ID to connect to (optional when EVIDENT_RUNNER_KEY is set)").option(
6043
+ "-a, --agent [id]",
6044
+ "Deprecated alias for --runner (still supported; --runner wins if both are given)"
6045
+ ).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
6046
+ "--log-level <level>",
6047
+ "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
6048
+ ).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(
6049
+ "--session-cleanup-max-age <duration>",
6050
+ "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
6051
+ ).option(
6052
+ "--session-cleanup-max-count <n>",
6053
+ "Keep only the newest N OpenCode sessions. Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_COUNT"
6054
+ ).option(
6055
+ "--session-cleanup-interval <duration>",
6056
+ "How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
6057
+ ).option(
6058
+ "--enable-file-sync-to <dir>",
6059
+ "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
6060
+ (value, previous) => previous.concat([value]),
6061
+ []
6062
+ ).action(
3966
6063
  (options) => {
3967
6064
  run({
3968
6065
  agent: options.agent,
6066
+ runner: options.runner,
3969
6067
  port: parseInt(options.port, 10),
6068
+ // Raw string — validation/precedence is single-sourced in run.ts's
6069
+ // resolveLogLevel (flag > -v > EVIDENT_LOG_LEVEL > info).
6070
+ logLevel: options.logLevel,
3970
6071
  verbose: options.verbose,
3971
6072
  conversation: options.conversation,
3972
6073
  idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
3973
- json: options.json
6074
+ json: options.json,
6075
+ // Raw strings — the resolver in run.ts single-sources parsing (M1).
6076
+ sessionCleanupMaxAge: options.sessionCleanupMaxAge,
6077
+ sessionCleanupMaxCount: options.sessionCleanupMaxCount,
6078
+ sessionCleanupInterval: options.sessionCleanupInterval,
6079
+ // Raw values — expansion/validation is single-sourced in run.ts's
6080
+ // resolveFileSyncDirectories.
6081
+ enableFileSyncTo: options.enableFileSyncTo
3974
6082
  });
3975
6083
  }
3976
6084
  );