@evident-ai/cli 3.1.1-dev.5376764 → 3.1.1-dev.561700

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] || "";
@@ -236,16 +267,28 @@ async function getToken() {
236
267
  }
237
268
  return null;
238
269
  }
270
+ function toError(err) {
271
+ return err instanceof Error ? err : new Error(String(err));
272
+ }
239
273
  async function deleteToken(options = {}) {
240
274
  const keytar = await getKeytar();
275
+ const failures = [];
241
276
  if (keytar) {
242
277
  if (options.all) {
243
- const all = await keytar.findCredentials(SERVICE_NAME).catch(() => []);
278
+ let accounts = [];
279
+ try {
280
+ accounts = await keytar.findCredentials(SERVICE_NAME);
281
+ } catch (err) {
282
+ failures.push({ type: "enumerate", error: toError(err) });
283
+ }
244
284
  await Promise.all(
245
- all.map(
246
- (entry) => keytar.deletePassword(SERVICE_NAME, entry.account).catch(() => {
247
- })
248
- )
285
+ accounts.map(async (entry) => {
286
+ try {
287
+ await keytar.deletePassword(SERVICE_NAME, entry.account);
288
+ } catch (err) {
289
+ failures.push({ type: "delete", account: entry.account, error: toError(err) });
290
+ }
291
+ })
249
292
  );
250
293
  } else {
251
294
  await keytar.deletePassword(SERVICE_NAME, keychainAccount());
@@ -256,6 +299,7 @@ async function deleteToken(options = {}) {
256
299
  } else {
257
300
  clearCredentials();
258
301
  }
302
+ return { failures };
259
303
  }
260
304
 
261
305
  // src/utils/ui.ts
@@ -285,14 +329,14 @@ function blank() {
285
329
  console.log();
286
330
  }
287
331
  function waitForEnter(prompt = "Press Enter to continue...") {
288
- return new Promise((resolve2) => {
332
+ return new Promise((resolve3) => {
289
333
  process.stdout.write(chalk.dim(prompt));
290
334
  const handler = () => {
291
335
  process.stdin.removeListener("data", handler);
292
336
  process.stdin.setRawMode?.(false);
293
337
  process.stdin.pause();
294
338
  console.log();
295
- resolve2();
339
+ resolve3();
296
340
  };
297
341
  if (process.stdin.isTTY) {
298
342
  process.stdin.setRawMode?.(true);
@@ -302,7 +346,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
302
346
  });
303
347
  }
304
348
  function sleep(ms) {
305
- return new Promise((resolve2) => setTimeout(resolve2, ms));
349
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
306
350
  }
307
351
 
308
352
  // src/commands/login.ts
@@ -373,22 +417,23 @@ async function deviceFlowLogin(options) {
373
417
  }
374
418
  async function tokenLogin() {
375
419
  console.log("Token login mode.");
376
- console.log("Visit your Evident dashboard to generate a CLI token.");
420
+ console.log("Run `evident login` on a machine with a browser to get a token.");
421
+ console.log("Manage or revoke existing tokens under Settings \u2192 CLI tokens.");
377
422
  blank();
378
423
  process.stdout.write("Paste token: ");
379
- const token = await new Promise((resolve2) => {
424
+ const token = await new Promise((resolve3) => {
380
425
  let data = "";
381
426
  process.stdin.setEncoding("utf8");
382
427
  process.stdin.on("data", (chunk) => {
383
428
  data += chunk;
384
429
  });
385
430
  process.stdin.on("end", () => {
386
- resolve2(data.trim());
431
+ resolve3(data.trim());
387
432
  });
388
433
  if (process.stdin.isTTY) {
389
434
  process.stdin.once("data", (chunk) => {
390
435
  process.stdin.pause();
391
- resolve2(chunk.toString().trim());
436
+ resolve3(chunk.toString().trim());
392
437
  });
393
438
  process.stdin.resume();
394
439
  }
@@ -423,9 +468,22 @@ async function login(options) {
423
468
  }
424
469
 
425
470
  // src/commands/logout.ts
471
+ function describeFailure(failure) {
472
+ if (failure.type === "enumerate") {
473
+ return `could not list stored keychain entries (${failure.error.message})`;
474
+ }
475
+ return `${failure.account} (${failure.error.message})`;
476
+ }
426
477
  async function logout(options = {}) {
427
478
  if (options.all) {
428
- await deleteToken({ all: true });
479
+ const result = await deleteToken({ all: true });
480
+ if (result.failures.length > 0) {
481
+ printError(
482
+ `Failed to fully clear your keychain: ${result.failures.map(describeFailure).join("; ")}. Your local credentials file was cleared, but stale keychain entries may remain \u2014 run \`evident logout --all\` again, or remove them manually from your OS keychain / credential manager.`
483
+ );
484
+ process.exitCode = 1;
485
+ return;
486
+ }
429
487
  printSuccess("Logged out of all endpoints.");
430
488
  return;
431
489
  }
@@ -467,9 +525,9 @@ async function whoami() {
467
525
  }
468
526
 
469
527
  // src/commands/run.ts
528
+ import { homedir as homedir2 } from "os";
529
+ import { isAbsolute as isAbsolute2, join as join2, parse, resolve as resolvePath } from "path";
470
530
  import chalk6 from "chalk";
471
- import ora3 from "ora";
472
- import { select as select3 } from "@inquirer/prompts";
473
531
 
474
532
  // ../../packages/types/src/telemetry/index.ts
475
533
  var TelemetryEventTypes = {
@@ -485,6 +543,10 @@ var TelemetryEventTypes = {
485
543
  var MAX_FRAME_BYTES = 256 * 1024;
486
544
  var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
487
545
 
546
+ // ../../packages/types/src/runner-files.ts
547
+ var MAX_FILE_PUSH_BYTES = 64 * 1024;
548
+ var MAX_FILE_SYNC_DIRECTORIES = 16;
549
+
488
550
  // ../../packages/types/src/logging/index.ts
489
551
  var CORRELATION_ID_HEADER = "x-evident-correlation-id";
490
552
  function log(level, event, fields) {
@@ -499,6 +561,12 @@ function log(level, event, fields) {
499
561
  );
500
562
  }
501
563
  }
564
+ function errorFields(err) {
565
+ if (err instanceof Error) {
566
+ return { error: err.message, error_name: err.name };
567
+ }
568
+ return { error: String(err) };
569
+ }
502
570
  function stripQuery(url) {
503
571
  try {
504
572
  return new URL(url).pathname;
@@ -508,6 +576,10 @@ function stripQuery(url) {
508
576
  }
509
577
  }
510
578
 
579
+ // src/commands/run.ts
580
+ import ora3 from "ora";
581
+ import { select as select3 } from "@inquirer/prompts";
582
+
511
583
  // src/lib/telemetry.ts
512
584
  var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
513
585
  function getCliVersion() {
@@ -719,7 +791,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
719
791
  if (health.healthy) {
720
792
  return health;
721
793
  }
722
- await new Promise((resolve2) => setTimeout(resolve2, 1e3));
794
+ await new Promise((resolve3) => setTimeout(resolve3, 1e3));
723
795
  }
724
796
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
725
797
  }
@@ -734,7 +806,7 @@ function buildOpenCodeVersionWarning(version2) {
734
806
  if (isQueueValidatedVersion(version2)) return null;
735
807
  const detected = version2 ? `v${version2}` : "unknown";
736
808
  const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
737
- 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.`;
809
+ 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.`;
738
810
  }
739
811
 
740
812
  // src/lib/opencode/process.ts
@@ -1026,6 +1098,12 @@ async function promptOpenCodeInstall(interactive) {
1026
1098
  return action;
1027
1099
  }
1028
1100
 
1101
+ // src/lib/opencode/provider-check.ts
1102
+ function buildNoProviderWarning(hasProvider) {
1103
+ if (hasProvider !== false) return null;
1104
+ 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).";
1105
+ }
1106
+
1029
1107
  // src/lib/opencode/session.ts
1030
1108
  function opencodeBase(port) {
1031
1109
  return `http://127.0.0.1:${port}`;
@@ -1228,6 +1306,11 @@ async function getModelAttachmentCapability(port, model) {
1228
1306
  }
1229
1307
  const entry = provider.models[modelId];
1230
1308
  if (!entry || typeof entry !== "object") return null;
1309
+ if (entry.capabilities && typeof entry.capabilities === "object") {
1310
+ if (typeof entry.capabilities.attachment === "boolean") {
1311
+ return entry.capabilities.attachment;
1312
+ }
1313
+ }
1231
1314
  return typeof entry.attachment === "boolean" ? entry.attachment : null;
1232
1315
  } catch (err) {
1233
1316
  console.error(
@@ -1256,6 +1339,16 @@ async function buildFileParts(attachments, capable) {
1256
1339
  );
1257
1340
  dataUrl = null;
1258
1341
  }
1342
+ if (dataUrl !== null && typeof dataUrl === "object") {
1343
+ outcomes.push({
1344
+ index: a.index,
1345
+ mime: a.mime,
1346
+ filename: a.filename,
1347
+ status: "failed",
1348
+ reason: "needs_reauth"
1349
+ });
1350
+ continue;
1351
+ }
1259
1352
  if (dataUrl == null) {
1260
1353
  outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
1261
1354
  continue;
@@ -1337,7 +1430,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
1337
1430
  }
1338
1431
  }
1339
1432
  if (attempt < READ_BACK_ATTEMPTS - 1) {
1340
- await new Promise((resolve2) => setTimeout(resolve2, READ_BACK_DELAY_MS));
1433
+ await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
1341
1434
  }
1342
1435
  }
1343
1436
  return null;
@@ -1465,6 +1558,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
1465
1558
  const reply = findLastAssistantReplyFor(messages, userMessageId);
1466
1559
  return completedOf(reply) != null && finishOf(reply) === "tool-calls";
1467
1560
  }
1561
+ function isB2AbandonmentConfirmed(params) {
1562
+ return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
1563
+ }
1468
1564
  function messageError(messages, userMessageId) {
1469
1565
  const reply = findLastAssistantReplyFor(messages, userMessageId);
1470
1566
  const error2 = errorOf(reply);
@@ -1478,12 +1574,79 @@ function messageError(messages, userMessageId) {
1478
1574
  }
1479
1575
  return "The agent run failed.";
1480
1576
  }
1577
+ function messageFailure(messages, userMessageId) {
1578
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
1579
+ const error2 = errorOf(reply);
1580
+ if (error2 == null || typeof error2 !== "object") return null;
1581
+ const e = error2;
1582
+ const replyProviderId = reply?.info?.providerID ?? null;
1583
+ const replyModelId = reply?.info?.modelID ?? null;
1584
+ if (e.name === "ProviderAuthError") {
1585
+ const data = e.data;
1586
+ const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
1587
+ return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
1588
+ }
1589
+ if (e.name === "APIError") {
1590
+ const data = e.data;
1591
+ const statusCode = data?.statusCode;
1592
+ if (statusCode === 401 || statusCode === 403) {
1593
+ return {
1594
+ kind: "model_auth",
1595
+ providerId: replyProviderId,
1596
+ modelId: replyModelId,
1597
+ reason: "rejected"
1598
+ };
1599
+ }
1600
+ }
1601
+ return null;
1602
+ }
1603
+ function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
1604
+ if (classified != null) return classified;
1605
+ if (hasConfiguredProvider !== false) return null;
1606
+ return {
1607
+ kind: "model_auth",
1608
+ providerId: replyProviderId,
1609
+ modelId: replyModelId,
1610
+ reason: "missing"
1611
+ };
1612
+ }
1481
1613
  function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1482
1614
  if (!messages || messages.length === 0) return false;
1483
1615
  return messages.some(
1484
1616
  (m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
1485
1617
  );
1486
1618
  }
1619
+ async function hasAnyConfiguredProvider(port) {
1620
+ try {
1621
+ const res = await fetch(`${opencodeBase(port)}/config/providers`);
1622
+ if (!res.ok) {
1623
+ console.error(
1624
+ `[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
1625
+ );
1626
+ return null;
1627
+ }
1628
+ const body = await res.json();
1629
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
1630
+ console.error(
1631
+ `[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
1632
+ );
1633
+ return null;
1634
+ }
1635
+ const defaults2 = body.default;
1636
+ if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
1637
+ console.error(
1638
+ `[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
1639
+ );
1640
+ return null;
1641
+ }
1642
+ return Object.keys(defaults2).length > 0;
1643
+ } catch (err) {
1644
+ console.error(
1645
+ `[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
1646
+ );
1647
+ return null;
1648
+ }
1649
+ }
1487
1650
 
1488
1651
  // src/lib/opencode/session-cleanup.ts
1489
1652
  var DURATION_UNIT_MS = {
@@ -1642,10 +1805,11 @@ var StreamForwarder = class {
1642
1805
  * Abort every in-flight stream (e.g. on WebSocket close).
1643
1806
  */
1644
1807
  abortAll() {
1645
- for (const stream of this.inflight.values()) {
1808
+ for (const [sid, stream] of this.inflight.entries()) {
1646
1809
  try {
1647
1810
  stream.abort();
1648
- } catch {
1811
+ } catch (err) {
1812
+ log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
1649
1813
  }
1650
1814
  }
1651
1815
  this.inflight.clear();
@@ -1679,12 +1843,12 @@ var StreamForwarder = class {
1679
1843
  let endBody;
1680
1844
  if (has_body) {
1681
1845
  const chunks = [];
1682
- bodyPromise = new Promise((resolve2) => {
1846
+ bodyPromise = new Promise((resolve3) => {
1683
1847
  pushBody = (buf) => {
1684
1848
  chunks.push(buf);
1685
1849
  };
1686
1850
  endBody = () => {
1687
- resolve2(Buffer.concat(chunks));
1851
+ resolve3(Buffer.concat(chunks));
1688
1852
  };
1689
1853
  });
1690
1854
  }
@@ -1801,7 +1965,7 @@ function connectTunnel(options) {
1801
1965
  } = options;
1802
1966
  const tunnelUrl = getTunnelUrlConfig();
1803
1967
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
1804
- return new Promise((resolve2, reject) => {
1968
+ return new Promise((resolve3, reject) => {
1805
1969
  const ws = new WebSocket2(url, {
1806
1970
  headers: {
1807
1971
  Authorization: authHeader
@@ -1856,7 +2020,7 @@ function connectTunnel(options) {
1856
2020
  clearTimeout(connectionTimeout);
1857
2021
  const connectedAgentId = message.agent_id ?? agentId;
1858
2022
  onConnected?.(connectedAgentId);
1859
- resolve2({
2023
+ resolve3({
1860
2024
  ws,
1861
2025
  close: () => ws.close(1e3, "CLI shutdown")
1862
2026
  });
@@ -1918,7 +2082,11 @@ var RunnerConnection = class {
1918
2082
  if (this.connection) {
1919
2083
  try {
1920
2084
  this.connection.close();
1921
- } catch {
2085
+ } catch (err) {
2086
+ log("error", "runner_connection_close_failed", {
2087
+ agent_id: this.resolvedAgentId,
2088
+ ...errorFields(err)
2089
+ });
1922
2090
  }
1923
2091
  this.connection = null;
1924
2092
  }
@@ -1970,6 +2138,416 @@ var RunnerConnection = class {
1970
2138
  }
1971
2139
  };
1972
2140
 
2141
+ // src/lib/tunnel/ready-marker.ts
2142
+ import { writeFileSync } from "fs";
2143
+ function writeTunnelReadyMarker(path, agentId) {
2144
+ try {
2145
+ writeFileSync(path, `${agentId}
2146
+ `);
2147
+ return { ok: true };
2148
+ } catch (error2) {
2149
+ return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
2150
+ }
2151
+ }
2152
+
2153
+ // src/lib/channels/driver.ts
2154
+ import { homedir } from "os";
2155
+
2156
+ // src/lib/file-push.ts
2157
+ import { randomUUID } from "crypto";
2158
+ import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
2159
+ import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
2160
+ var FILE_MODE = 384;
2161
+ var DIRECTORY_MODE = 448;
2162
+ async function writePushedFile(request) {
2163
+ const { requestedPath, content, allowedDirectories, homeDir } = request;
2164
+ const bytes = content.byteLength;
2165
+ if (allowedDirectories.length === 0) {
2166
+ return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
2167
+ path: requestedPath,
2168
+ bytes
2169
+ });
2170
+ }
2171
+ if (bytes > MAX_FILE_PUSH_BYTES) {
2172
+ return refuse(
2173
+ "file_too_large",
2174
+ `File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
2175
+ {
2176
+ path: requestedPath,
2177
+ bytes
2178
+ }
2179
+ );
2180
+ }
2181
+ const candidate = expandAndValidate(requestedPath, homeDir);
2182
+ if (candidate === null) {
2183
+ return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
2184
+ path: requestedPath,
2185
+ bytes
2186
+ });
2187
+ }
2188
+ try {
2189
+ const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
2190
+ dirname2(candidate)
2191
+ );
2192
+ const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
2193
+ const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
2194
+ if (allowedDirectory === null) {
2195
+ return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
2196
+ path: realTarget,
2197
+ bytes
2198
+ });
2199
+ }
2200
+ if (missingSegments.length > 0) {
2201
+ await createMissingDirectories(existingAncestor, missingSegments);
2202
+ const realParent = await realpath(dirname2(realTarget));
2203
+ if (realParent !== dirname2(realTarget) || !contains(allowedDirectory, realTarget)) {
2204
+ return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
2205
+ path: realTarget,
2206
+ bytes,
2207
+ reason: "parent_changed_after_create"
2208
+ });
2209
+ }
2210
+ }
2211
+ await writeAtomically(realTarget, content);
2212
+ log("info", "file_push_written", { path: realTarget, bytes });
2213
+ return { ok: true, path: realTarget };
2214
+ } catch (err) {
2215
+ const errno = err.code ?? "UNKNOWN";
2216
+ return refuse("write_failed", `The runner could not write the file (${errno}).`, {
2217
+ path: candidate,
2218
+ bytes,
2219
+ errno,
2220
+ ...errorFields(err)
2221
+ });
2222
+ }
2223
+ }
2224
+ function expandAndValidate(requestedPath, homeDir) {
2225
+ if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
2226
+ return null;
2227
+ }
2228
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join(homeDir, requestedPath.slice(2)) : requestedPath;
2229
+ if (expanded.split(/[/\\]/).includes("..")) {
2230
+ return null;
2231
+ }
2232
+ if (!isAbsolute(expanded)) {
2233
+ return null;
2234
+ }
2235
+ const candidate = resolve2(expanded);
2236
+ const name = basename(candidate);
2237
+ return name === "" || name === "." || name === ".." ? null : candidate;
2238
+ }
2239
+ async function resolveNearestExistingAncestor(directory) {
2240
+ const missingSegments = [];
2241
+ let current = directory;
2242
+ for (; ; ) {
2243
+ try {
2244
+ return { existingAncestor: await realpath(current), missingSegments };
2245
+ } catch (err) {
2246
+ const parent = dirname2(current);
2247
+ if (err.code !== "ENOENT" || parent === current) {
2248
+ throw err;
2249
+ }
2250
+ missingSegments.unshift(basename(current));
2251
+ current = parent;
2252
+ }
2253
+ }
2254
+ }
2255
+ async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
2256
+ for (const directory of allowedDirectories) {
2257
+ if (!isAbsolute(directory)) {
2258
+ log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
2259
+ continue;
2260
+ }
2261
+ const realDirectory = await realpathCreatingIfMissing(directory);
2262
+ if (realDirectory !== null && contains(realDirectory, realTarget)) {
2263
+ return realDirectory;
2264
+ }
2265
+ }
2266
+ return null;
2267
+ }
2268
+ async function realpathCreatingIfMissing(directory) {
2269
+ try {
2270
+ return await realpath(directory);
2271
+ } catch (err) {
2272
+ if (err.code !== "ENOENT") {
2273
+ log("warn", "file_push_allowed_directory_skipped", {
2274
+ directory,
2275
+ reason: "unresolvable",
2276
+ ...errorFields(err)
2277
+ });
2278
+ return null;
2279
+ }
2280
+ }
2281
+ try {
2282
+ await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
2283
+ await chmod(directory, DIRECTORY_MODE);
2284
+ return await realpath(directory);
2285
+ } catch (err) {
2286
+ log("warn", "file_push_allowed_directory_skipped", {
2287
+ directory,
2288
+ reason: "create_failed",
2289
+ ...errorFields(err)
2290
+ });
2291
+ return null;
2292
+ }
2293
+ }
2294
+ function contains(realDirectory, realTarget) {
2295
+ const rel = relative(realDirectory, realTarget);
2296
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
2297
+ }
2298
+ async function createMissingDirectories(existingAncestor, missingSegments) {
2299
+ let current = existingAncestor;
2300
+ for (const segment of missingSegments) {
2301
+ current = join(current, segment);
2302
+ await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
2303
+ await chmod(current, DIRECTORY_MODE);
2304
+ }
2305
+ }
2306
+ async function writeAtomically(realTarget, content) {
2307
+ const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2308
+ let handle;
2309
+ try {
2310
+ handle = await open2(temporaryPath, "wx", FILE_MODE);
2311
+ await handle.writeFile(content);
2312
+ await handle.chmod(FILE_MODE);
2313
+ await handle.close();
2314
+ handle = void 0;
2315
+ await rename(temporaryPath, realTarget);
2316
+ } catch (err) {
2317
+ await discardTemporaryFile(temporaryPath, handle);
2318
+ throw err;
2319
+ }
2320
+ }
2321
+ async function discardTemporaryFile(temporaryPath, handle) {
2322
+ try {
2323
+ await handle?.close();
2324
+ } catch (err) {
2325
+ log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
2326
+ }
2327
+ try {
2328
+ await unlink(temporaryPath);
2329
+ } catch (err) {
2330
+ const errno = err.code;
2331
+ if (errno !== "ENOENT" && errno !== "ENOTDIR") {
2332
+ log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
2333
+ }
2334
+ }
2335
+ }
2336
+ function refuse(code, message, fields) {
2337
+ log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
2338
+ return { ok: false, code, message };
2339
+ }
2340
+
2341
+ // src/lib/runner-file-sync.ts
2342
+ var MAX_ACK_ATTEMPTS = 5;
2343
+ async function syncPendingRunnerFiles(options) {
2344
+ const pending = await listPendingFiles(options);
2345
+ const pendingIds = new Set(pending.map((file) => file.id));
2346
+ for (const id of options.ackFailures.keys()) {
2347
+ if (!pendingIds.has(id)) options.ackFailures.delete(id);
2348
+ }
2349
+ if (pending.length === 0) return 0;
2350
+ options.log({
2351
+ level: "info",
2352
+ message: `Runner file sync: ${pending.length} file(s) queued for this runner`
2353
+ });
2354
+ let applied = 0;
2355
+ for (const file of pending) {
2356
+ if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
2357
+ if (await applyOne(options, file)) applied += 1;
2358
+ }
2359
+ return applied;
2360
+ }
2361
+ async function listPendingFiles(options) {
2362
+ let res;
2363
+ try {
2364
+ res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
2365
+ headers: { Authorization: options.getAuthHeader() }
2366
+ });
2367
+ } catch (err) {
2368
+ options.log({
2369
+ level: "warn",
2370
+ message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
2371
+ });
2372
+ return [];
2373
+ }
2374
+ if (!res.ok) {
2375
+ options.log({
2376
+ level: res.status === 404 ? "debug" : "warn",
2377
+ message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
2378
+ });
2379
+ return [];
2380
+ }
2381
+ let body;
2382
+ try {
2383
+ body = await res.json();
2384
+ } catch (err) {
2385
+ options.log({
2386
+ level: "warn",
2387
+ message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
2388
+ });
2389
+ return [];
2390
+ }
2391
+ if (!Array.isArray(body)) {
2392
+ options.log({
2393
+ level: "warn",
2394
+ message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
2395
+ });
2396
+ return [];
2397
+ }
2398
+ const files = [];
2399
+ for (const entry of body) {
2400
+ const file = asPendingFile(entry);
2401
+ if (file === null) {
2402
+ options.log({
2403
+ level: "warn",
2404
+ message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
2405
+ });
2406
+ continue;
2407
+ }
2408
+ files.push(file);
2409
+ }
2410
+ return files;
2411
+ }
2412
+ function asPendingFile(entry) {
2413
+ if (entry === null || typeof entry !== "object") return null;
2414
+ const { id, path, size } = entry;
2415
+ if (typeof id !== "string" || id === "") return null;
2416
+ if (typeof path !== "string" || path === "") return null;
2417
+ if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
2418
+ return { id, path, size };
2419
+ }
2420
+ async function applyOne(options, file) {
2421
+ const label = `${file.id.slice(0, 8)} (${file.path})`;
2422
+ if (options.allowedDirectories.length === 0) {
2423
+ options.log({
2424
+ level: "warn",
2425
+ message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
2426
+ });
2427
+ await ack(options, file, "rejected", "file_sync_disabled");
2428
+ return false;
2429
+ }
2430
+ if (file.size > MAX_FILE_PUSH_BYTES) {
2431
+ options.log({
2432
+ level: "warn",
2433
+ message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
2434
+ });
2435
+ await ack(options, file, "rejected", "file_too_large");
2436
+ return false;
2437
+ }
2438
+ const download = await downloadContent(options, file, label);
2439
+ if (!download.ok) {
2440
+ if (download.terminal) await ack(options, file, "rejected", download.code);
2441
+ return false;
2442
+ }
2443
+ let outcome;
2444
+ try {
2445
+ outcome = await writePushedFile({
2446
+ requestedPath: file.path,
2447
+ content: download.content,
2448
+ allowedDirectories: options.allowedDirectories,
2449
+ homeDir: options.homeDir
2450
+ });
2451
+ } catch (err) {
2452
+ options.log({
2453
+ level: "error",
2454
+ message: `Runner file ${label} could not be written: ${describe(err)}`
2455
+ });
2456
+ await ack(options, file, "rejected", "write_failed");
2457
+ return false;
2458
+ }
2459
+ if (!outcome.ok) {
2460
+ options.log({
2461
+ level: "warn",
2462
+ message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
2463
+ });
2464
+ await ack(options, file, "rejected", outcome.code);
2465
+ return false;
2466
+ }
2467
+ options.log({
2468
+ level: "info",
2469
+ message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
2470
+ });
2471
+ await ack(options, file, "applied");
2472
+ return true;
2473
+ }
2474
+ function durableDownloadCode(status) {
2475
+ return status === 413 ? "file_too_large" : "write_failed";
2476
+ }
2477
+ async function downloadContent(options, file, label) {
2478
+ try {
2479
+ const res = await options.fetchImpl(
2480
+ `${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
2481
+ { headers: { Authorization: options.getAuthHeader() } }
2482
+ );
2483
+ if (!res.ok) {
2484
+ const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
2485
+ if (!terminal) {
2486
+ options.log({
2487
+ level: "warn",
2488
+ message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
2489
+ });
2490
+ return { ok: false, terminal: false };
2491
+ }
2492
+ const code = durableDownloadCode(res.status);
2493
+ options.log({
2494
+ level: "error",
2495
+ message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
2496
+ });
2497
+ return { ok: false, terminal: true, code };
2498
+ }
2499
+ return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
2500
+ } catch (err) {
2501
+ options.log({
2502
+ level: "warn",
2503
+ message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
2504
+ });
2505
+ return { ok: false, terminal: false };
2506
+ }
2507
+ }
2508
+ async function ack(options, file, status, reason) {
2509
+ const outcome = `${status}${reason ? ` (${reason})` : ""}`;
2510
+ try {
2511
+ const res = await options.fetchImpl(
2512
+ `${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
2513
+ {
2514
+ method: "POST",
2515
+ headers: {
2516
+ Authorization: options.getAuthHeader(),
2517
+ "Content-Type": "application/json"
2518
+ },
2519
+ body: JSON.stringify(reason ? { status, reason } : { status })
2520
+ }
2521
+ );
2522
+ if (!res.ok) {
2523
+ recordAckFailure(
2524
+ options,
2525
+ file,
2526
+ `Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
2527
+ );
2528
+ return;
2529
+ }
2530
+ options.ackFailures.delete(file.id);
2531
+ } catch (err) {
2532
+ recordAckFailure(
2533
+ options,
2534
+ file,
2535
+ `Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
2536
+ );
2537
+ }
2538
+ }
2539
+ function recordAckFailure(options, file, what) {
2540
+ const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
2541
+ options.ackFailures.set(file.id, attempts);
2542
+ options.log({
2543
+ level: "error",
2544
+ 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})`
2545
+ });
2546
+ }
2547
+ function describe(err) {
2548
+ return err instanceof Error ? err.message : String(err);
2549
+ }
2550
+
1973
2551
  // src/lib/channels/driver.ts
1974
2552
  function messageIdOf(m) {
1975
2553
  if (!m || typeof m !== "object") return void 0;
@@ -1998,7 +2576,10 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
1998
2576
  var DEFAULT_STUCK_QUEUED_MS = 6e4;
1999
2577
  var HEARTBEAT_MS = 6e4;
2000
2578
  var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
2579
+ var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
2580
+ var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
2001
2581
  var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
2582
+ var MAX_SUPERSEDED_CONVERSATIONS = 256;
2002
2583
  var ChannelAuthError = class extends Error {
2003
2584
  constructor(message) {
2004
2585
  super(message);
@@ -2021,7 +2602,7 @@ function backoffDelay(attempt, policy) {
2021
2602
  function isRetryableStatus(status) {
2022
2603
  return status === 429 || status >= 500 && status <= 599;
2023
2604
  }
2024
- var ChannelDriver = class {
2605
+ var ChannelDriver = class _ChannelDriver {
2025
2606
  agentId;
2026
2607
  port;
2027
2608
  apiUrl;
@@ -2035,8 +2616,38 @@ var ChannelDriver = class {
2035
2616
  pausedMaxWaitMs;
2036
2617
  stuckQueuedMs;
2037
2618
  now;
2619
+ fileSyncDirectories;
2620
+ homeDir;
2038
2621
  /** Cache of conversationId → opencode sessionId. */
2039
2622
  sessions = /* @__PURE__ */ new Map();
2623
+ /**
2624
+ * conversationId → the opencode session this runner has ABANDONED as that
2625
+ * conversation's binding (#553), after a genuine (`sessionExists === true`)
2626
+ * dispatch failure: the session still exists but is wedged, so #485's self-heal
2627
+ * must bind a fresh one.
2628
+ *
2629
+ * Dropping the local binding + clearing the server row is not enough on its own:
2630
+ * a SIBLING message dispatched earlier in the same drain is still in-flight under
2631
+ * the same session, and its watcher's routine status writes carry
2632
+ * `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
2633
+ * and `ensureSession`'s persisted-id fallback then reuses it, defeating the
2634
+ * self-heal. This map makes the runner authoritative instead of racing those
2635
+ * writes: *`ensureSession` never reuses an abandoned id for that conversation,
2636
+ * whatever the server row says* — which holds even when the resurrecting write
2637
+ * is one we deliberately keep (see `markDone`).
2638
+ *
2639
+ * Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
2640
+ * one conversation hold ONE entry (the newest abandonment replaces the older), and
2641
+ * hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
2642
+ * NEWEST abandoned id per conversation is guarded: after a second abandonment a
2643
+ * late sibling of the FIRST session can write that id back and `ensureSession`
2644
+ * will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
2645
+ * NOT dropped when the session's watcher tears down: `markDone` still writes the
2646
+ * abandoned id back (it must, or the reply is lost), so the guard has to outlive
2647
+ * the turn that resurrects it. In-memory only — a restart forgets it, at the same
2648
+ * bounded cost.
2649
+ */
2650
+ supersededSessions = /* @__PURE__ */ new Map();
2040
2651
  /**
2041
2652
  * Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
2042
2653
  * longer idempotent (no caller-supplied `messageID`), and its read-back picks
@@ -2146,9 +2757,12 @@ var ChannelDriver = class {
2146
2757
  sessionParents = /* @__PURE__ */ new Map();
2147
2758
  /**
2148
2759
  * Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
2149
- * NON-EMPTY name is stored (terminal — a real session name won't later un-name),
2150
- * so we do NOT re-GET `/session/:id` every tick. A missing entry = not yet
2151
- * resolved OR resolved-but-still-empty re-fetch on next need, since OpenCode
2760
+ * NON-EMPTY, non-placeholder name is stored (terminal — a real session name
2761
+ * won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
2762
+ * excludes OpenCode's synchronous default title (see
2763
+ * `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
2764
+ * as an empty title so it never latches. A missing entry = not yet resolved OR
2765
+ * resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
2152
2766
  * names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
2153
2767
  * the watcher completion path AND the restart-recovery re-adopt path (which has
2154
2768
  * no watcher) can resolve the title.
@@ -2156,6 +2770,24 @@ var ChannelDriver = class {
2156
2770
  sessionTitles = /* @__PURE__ */ new Map();
2157
2771
  /** Serialises drains so a reconnect during a drain doesn't double-process. */
2158
2772
  draining = false;
2773
+ /**
2774
+ * Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
2775
+ * drain ping don't download, write and ack the same file twice.
2776
+ */
2777
+ syncingFiles = false;
2778
+ /**
2779
+ * Consecutive failed acks per pending file (#559). Lives on the driver so it
2780
+ * survives across drains — without it, a file whose ack keeps failing is
2781
+ * re-downloaded and re-written every ~2s until the server expires it.
2782
+ */
2783
+ fileAckFailures = /* @__PURE__ */ new Map();
2784
+ /**
2785
+ * Monotonic count of files this runner has pulled and written (#559). Only
2786
+ * ever increases, so `run.ts` detects work by comparing it against the value
2787
+ * it saw on the previous cycle — including work that landed mid-sleep, the
2788
+ * same trick `lastProxiedActivityAt` uses.
2789
+ */
2790
+ appliedFileCount = 0;
2159
2791
  /**
2160
2792
  * The currently-executing `drainPending()` promise, or null when idle. Lets a
2161
2793
  * graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
@@ -2186,6 +2818,8 @@ var ChannelDriver = class {
2186
2818
  this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
2187
2819
  this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
2188
2820
  this.now = config2.now ?? (() => Date.now());
2821
+ this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
2822
+ this.homeDir = config2.homeDir ?? homedir();
2189
2823
  }
2190
2824
  /** The IPv4-loopback base URL for the local `opencode serve`. */
2191
2825
  get opencodeBase() {
@@ -2213,6 +2847,47 @@ var ChannelDriver = class {
2213
2847
  );
2214
2848
  return run2;
2215
2849
  }
2850
+ /**
2851
+ * Pull-and-apply any files Evident has queued for this runner (#559), riding
2852
+ * the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
2853
+ * and drain ping that call `drainPending()`. There is deliberately no channel,
2854
+ * control frame or poll loop of its own: worst-case latency is one poll tick.
2855
+ *
2856
+ * NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
2857
+ * cost a conversation turn. Failures are logged and either acked as a terminal
2858
+ * outcome or left pending for the next drain (see `runner-file-sync.ts`).
2859
+ *
2860
+ * Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
2861
+ *
2862
+ * @returns the number of files written to disk.
2863
+ */
2864
+ async syncPendingFiles() {
2865
+ if (this.stopped) return 0;
2866
+ if (this.syncingFiles) return 0;
2867
+ this.syncingFiles = true;
2868
+ try {
2869
+ const applied = await syncPendingRunnerFiles({
2870
+ agentId: this.agentId,
2871
+ apiUrl: this.apiUrl,
2872
+ getAuthHeader: this.getAuthHeader,
2873
+ fetchImpl: this.fetchImpl,
2874
+ allowedDirectories: this.fileSyncDirectories,
2875
+ homeDir: this.homeDir,
2876
+ ackFailures: this.fileAckFailures,
2877
+ log: this.log
2878
+ });
2879
+ this.appliedFileCount += applied;
2880
+ return applied;
2881
+ } catch (err) {
2882
+ this.log({
2883
+ level: "error",
2884
+ message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
2885
+ });
2886
+ return 0;
2887
+ } finally {
2888
+ this.syncingFiles = false;
2889
+ }
2890
+ }
2216
2891
  async runDrain() {
2217
2892
  let dispatched = 0;
2218
2893
  try {
@@ -2246,6 +2921,28 @@ var ChannelDriver = class {
2246
2921
  }
2247
2922
  return false;
2248
2923
  }
2924
+ /**
2925
+ * File-pull work, for `run.ts`'s idle accounting (#559).
2926
+ *
2927
+ * Pulling a file is real work that `drainPending()` knows nothing about, so
2928
+ * without this a near-idle runner counts a credential pull as an empty tick
2929
+ * and `--idle-timeout` can `process.exit` mid-pull — leaving a
2930
+ * `.evident-push-*.tmp` behind — or immediately after the write, before the
2931
+ * browser has run the authorize/callback that activates it (the user then sees
2932
+ * `saved_not_activated` for a runner that was fine).
2933
+ *
2934
+ * Two signals because one cannot cover both cases: `inFlight` is the pull
2935
+ * happening RIGHT NOW (it may outlive the tick that started it), and
2936
+ * `appliedFiles` is monotonic so a pull that started AND finished between two
2937
+ * idle checks still shows up as an advance.
2938
+ *
2939
+ * CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
2940
+ * the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
2941
+ * samples afterwards reads `true` every single cycle and can never idle out.
2942
+ */
2943
+ fileSyncActivity() {
2944
+ return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
2945
+ }
2249
2946
  /**
2250
2947
  * OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
2251
2948
  * exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
@@ -2307,7 +3004,7 @@ var ChannelDriver = class {
2307
3004
  await this.sleep(step);
2308
3005
  }
2309
3006
  }
2310
- while (this.hasInFlightWatchers()) {
3007
+ while (this.hasInFlightWatchers() || this.syncingFiles) {
2311
3008
  if (this.now() >= deadline) return false;
2312
3009
  await this.sleep(step);
2313
3010
  }
@@ -2342,10 +3039,15 @@ var ChannelDriver = class {
2342
3039
  * @returns the count of messages NEWLY dispatched (not already in-flight).
2343
3040
  */
2344
3041
  async processConversation(conv) {
2345
- const sessionId = await this.ensureSession(conv);
3042
+ const { sessionId, refusedSessionId } = await this.ensureSession(conv);
2346
3043
  const messages = await this.getPendingMessages(conv.id);
2347
3044
  let dispatched = 0;
2348
3045
  let skippedAlreadyDispatched = 0;
3046
+ if (refusedSessionId && messages.length > 0) {
3047
+ void this.postSignal(conv.id, messages[0].id, "session_superseded", {
3048
+ superseded_session_id: refusedSessionId
3049
+ });
3050
+ }
2349
3051
  for (const message of messages) {
2350
3052
  if (this.stopped) break;
2351
3053
  if (this.dispatched.has(message.id)) {
@@ -2372,7 +3074,8 @@ var ChannelDriver = class {
2372
3074
  } catch (err) {
2373
3075
  if (err instanceof ChannelAuthError) throw err;
2374
3076
  this.dispatched.delete(message.id);
2375
- if (await sessionExists(this.port, sessionId) === false) {
3077
+ const exists = await sessionExists(this.port, sessionId);
3078
+ if (exists === false) {
2376
3079
  this.sessions.delete(conv.id);
2377
3080
  this.log({
2378
3081
  level: "warn",
@@ -2382,15 +3085,39 @@ var ChannelDriver = class {
2382
3085
  });
2383
3086
  break;
2384
3087
  }
2385
- await this.markFailed(conv.id, message.id).catch(() => {
3088
+ if (exists === null) {
3089
+ this.log({
3090
+ level: "warn",
3091
+ 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.`,
3092
+ conversation_id: conv.id,
3093
+ message_id: message.id
3094
+ });
3095
+ break;
3096
+ }
3097
+ const errorMessage = err instanceof Error ? err.message : String(err);
3098
+ this.sessions.delete(conv.id);
3099
+ this.supersede(conv.id, sessionId);
3100
+ this.log({
3101
+ level: "warn",
3102
+ 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.`,
3103
+ conversation_id: conv.id,
3104
+ message_id: message.id
3105
+ });
3106
+ await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
3107
+ this.log({
3108
+ level: "warn",
3109
+ 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)}`,
3110
+ conversation_id: conv.id,
3111
+ message_id: message.id
3112
+ });
2386
3113
  });
2387
3114
  this.log({
2388
3115
  level: "error",
2389
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${err instanceof Error ? err.message : String(err)}`,
3116
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
2390
3117
  conversation_id: conv.id,
2391
3118
  message_id: message.id
2392
3119
  });
2393
- continue;
3120
+ break;
2394
3121
  }
2395
3122
  if (opencodeMessageId === null) {
2396
3123
  this.log({
@@ -2409,15 +3136,49 @@ var ChannelDriver = class {
2409
3136
  if (messages.length > 0 && dispatched === 0 && skippedAlreadyDispatched === messages.length) {
2410
3137
  this.log({
2411
3138
  level: "warn",
2412
- 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).`,
3139
+ 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).`,
3140
+ conversation_id: conv.id
3141
+ });
3142
+ }
3143
+ this.ensureWatcherRunning(sessionId);
3144
+ return dispatched;
3145
+ }
3146
+ /**
3147
+ * Record that `sessionId` is no longer a valid binding for `conversationId`
3148
+ * (#553). Keyed by conversation and hard-capped, so it cannot grow with the
3149
+ * number of failures — see the `supersededSessions` field doc.
3150
+ */
3151
+ supersede(conversationId, sessionId) {
3152
+ this.supersededSessions.delete(conversationId);
3153
+ this.supersededSessions.set(conversationId, sessionId);
3154
+ while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
3155
+ const oldest = this.supersededSessions.keys().next().value;
3156
+ if (oldest === void 0) return;
3157
+ this.supersededSessions.delete(oldest);
3158
+ }
3159
+ }
3160
+ /** Whether `sessionId` is the session this conversation has abandoned (#553). */
3161
+ isSuperseded(conversationId, sessionId) {
3162
+ return this.supersededSessions.get(conversationId) === sessionId;
3163
+ }
3164
+ /**
3165
+ * Resolve the opencode session to run this conversation's turns in.
3166
+ *
3167
+ * `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
3168
+ * binding was an id this runner had abandoned, so a resurrection genuinely
3169
+ * happened and a fresh session was bound instead. The caller reports it.
3170
+ */
3171
+ async ensureSession(conv) {
3172
+ const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
3173
+ if (bound && this.isSuperseded(conv.id, bound)) {
3174
+ this.log({
3175
+ level: "warn",
3176
+ 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.`,
2413
3177
  conversation_id: conv.id
2414
3178
  });
3179
+ this.sessions.delete(conv.id);
3180
+ return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
2415
3181
  }
2416
- this.ensureWatcherRunning(sessionId);
2417
- return dispatched;
2418
- }
2419
- async ensureSession(conv) {
2420
- const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
2421
3182
  if (bound) {
2422
3183
  const exists = await sessionExists(this.port, bound);
2423
3184
  if (exists === false) {
@@ -2427,12 +3188,12 @@ var ChannelDriver = class {
2427
3188
  conversation_id: conv.id
2428
3189
  });
2429
3190
  this.sessions.delete(conv.id);
2430
- return this.createAndBindSession(conv.id);
3191
+ return { sessionId: await this.createAndBindSession(conv.id) };
2431
3192
  }
2432
3193
  this.sessions.set(conv.id, bound);
2433
- return bound;
3194
+ return { sessionId: bound };
2434
3195
  }
2435
- return this.createAndBindSession(conv.id);
3196
+ return { sessionId: await this.createAndBindSession(conv.id) };
2436
3197
  }
2437
3198
  /**
2438
3199
  * Create a fresh OpenCode session for a conversation, cache the binding, and
@@ -2520,7 +3281,11 @@ var ChannelDriver = class {
2520
3281
  * (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
2521
3282
  * (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
2522
3283
  * OMITS that one image and the text turn still sends — NEVER throws the turn.
2523
- * Failures are logged with context (no silent swallow).
3284
+ * A 404 body carrying `{ reason: 'needs_reauth' }` (#547 the server CONFIRMED
3285
+ * a Slack `files:read` scope problem via `files.info`) instead resolves the
3286
+ * `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
3287
+ * user to reconnect Slack instead of a generic "unavailable". Failures are
3288
+ * logged with context (no silent swallow).
2524
3289
  */
2525
3290
  async fetchAttachmentDataUrl(messageId, index, mime) {
2526
3291
  try {
@@ -2529,6 +3294,25 @@ var ChannelDriver = class {
2529
3294
  { headers: { Authorization: this.getAuthHeader() } }
2530
3295
  );
2531
3296
  if (!res.ok) {
3297
+ let reason;
3298
+ try {
3299
+ const body = await res.json();
3300
+ if (body && typeof body.reason === "string") reason = body.reason;
3301
+ } catch (parseErr) {
3302
+ this.log({
3303
+ level: "debug",
3304
+ 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`,
3305
+ message_id: messageId
3306
+ });
3307
+ }
3308
+ if (reason === "needs_reauth") {
3309
+ this.log({
3310
+ level: "error",
3311
+ 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)`,
3312
+ message_id: messageId
3313
+ });
3314
+ return { needsReauth: true };
3315
+ }
2532
3316
  this.log({
2533
3317
  level: "error",
2534
3318
  message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
@@ -2568,6 +3352,9 @@ var ChannelDriver = class {
2568
3352
  if (this.attachmentsSkippedSignalled.has(messageId)) return;
2569
3353
  this.attachmentsSkippedSignalled.add(messageId);
2570
3354
  const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
3355
+ const failedReason = outcomes.some(
3356
+ (o) => o.status === "failed" && o.reason === "needs_reauth"
3357
+ ) ? "needs_reauth" : void 0;
2571
3358
  this.log({
2572
3359
  level: "info",
2573
3360
  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`,
@@ -2577,7 +3364,8 @@ var ChannelDriver = class {
2577
3364
  void this.postSignal(conversationId, messageId, "attachments_skipped", {
2578
3365
  skipped,
2579
3366
  failed,
2580
- ...skipped > 0 ? { skipped_reason: skippedReason } : {}
3367
+ ...skipped > 0 ? { skipped_reason: skippedReason } : {},
3368
+ ...failedReason ? { failed_reason: failedReason } : {}
2581
3369
  });
2582
3370
  }
2583
3371
  /** Register a freshly-dispatched message with its session's watcher state. */
@@ -2608,12 +3396,17 @@ var ChannelDriver = class {
2608
3396
  stuckReported: false,
2609
3397
  lastAliveAt: 0,
2610
3398
  aliveInFlight: false,
3399
+ titleSynced: false,
3400
+ titleSyncInFlight: false,
2611
3401
  awaitingHumanLatched: false,
2612
3402
  pausedOnQuestion: false,
2613
3403
  pausedOnPermission: false,
2614
3404
  pausedClearConfirmed: false,
2615
3405
  pausedInFlight: false,
2616
- deliveryDeadlineAnchored: false
3406
+ deliveryDeadlineAnchored: false,
3407
+ b2PinnedSinceMs: 0,
3408
+ b2LastDescendantCheckMs: 0,
3409
+ b2AbandonedSignalled: false
2617
3410
  });
2618
3411
  }
2619
3412
  /**
@@ -2681,12 +3474,17 @@ var ChannelDriver = class {
2681
3474
  // with no extra `re_adopted` signal needed (folds old WI-6).
2682
3475
  lastAliveAt: 0,
2683
3476
  aliveInFlight: false,
3477
+ titleSynced: false,
3478
+ titleSyncInFlight: false,
2684
3479
  awaitingHumanLatched: false,
2685
3480
  pausedOnQuestion: false,
2686
3481
  pausedOnPermission: false,
2687
3482
  pausedClearConfirmed: false,
2688
3483
  pausedInFlight: false,
2689
- deliveryDeadlineAnchored: false
3484
+ deliveryDeadlineAnchored: false,
3485
+ b2PinnedSinceMs: 0,
3486
+ b2LastDescendantCheckMs: 0,
3487
+ b2AbandonedSignalled: false
2690
3488
  });
2691
3489
  }
2692
3490
  /**
@@ -2848,58 +3646,7 @@ var ChannelDriver = class {
2848
3646
  }
2849
3647
  }
2850
3648
  if (state === "done") {
2851
- this.anchorDeliveryDeadline(inFlight);
2852
- if (!inFlight.done) {
2853
- this.log({
2854
- level: "info",
2855
- message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
2856
- conversation_id: conv.id,
2857
- message_id: inFlight.evidentMessageId
2858
- });
2859
- const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
2860
- const usage = messageUsage(messages, inFlight.opencodeMessageId);
2861
- try {
2862
- await this.markDone(
2863
- conv.id,
2864
- inFlight.evidentMessageId,
2865
- sessionId,
2866
- inFlight.opencodeMessageId,
2867
- title,
2868
- usage
2869
- );
2870
- } catch (err) {
2871
- if (err instanceof ChannelAuthError) throw err;
2872
- if (err instanceof ChannelTerminalError) {
2873
- this.log({
2874
- level: "warn",
2875
- message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
2876
- conversation_id: conv.id,
2877
- message_id: inFlight.evidentMessageId
2878
- });
2879
- this.removeInFlight(watcher, inFlight.evidentMessageId);
2880
- return;
2881
- }
2882
- if (this.now() >= inFlight.deadline) {
2883
- this.log({
2884
- level: "warn",
2885
- 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)}`,
2886
- conversation_id: conv.id,
2887
- message_id: inFlight.evidentMessageId
2888
- });
2889
- this.removeInFlight(watcher, inFlight.evidentMessageId);
2890
- return;
2891
- }
2892
- this.log({
2893
- level: "warn",
2894
- message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2895
- conversation_id: conv.id,
2896
- message_id: inFlight.evidentMessageId
2897
- });
2898
- return;
2899
- }
2900
- inFlight.done = true;
2901
- }
2902
- this.removeInFlight(watcher, inFlight.evidentMessageId);
3649
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
2903
3650
  return;
2904
3651
  }
2905
3652
  if (state === "failed") {
@@ -2913,8 +3660,16 @@ var ChannelDriver = class {
2913
3660
  message_id: inFlight.evidentMessageId
2914
3661
  });
2915
3662
  const usage = messageUsage(messages, inFlight.opencodeMessageId);
3663
+ const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
2916
3664
  try {
2917
- await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2, usage);
3665
+ await this.markFailed(
3666
+ conv.id,
3667
+ inFlight.evidentMessageId,
3668
+ sessionId,
3669
+ error2,
3670
+ usage,
3671
+ failure
3672
+ );
2918
3673
  } catch (err) {
2919
3674
  if (err instanceof ChannelAuthError) throw err;
2920
3675
  if (err instanceof ChannelTerminalError) {
@@ -2959,6 +3714,44 @@ var ChannelDriver = class {
2959
3714
  });
2960
3715
  }
2961
3716
  const activelyRunning = state === "running" && !awaitingHuman;
3717
+ const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
3718
+ const snapshotReadable = messages != null && messages.length > 0;
3719
+ if (!pinnedNow) {
3720
+ if (snapshotReadable) {
3721
+ inFlight.b2PinnedSinceMs = 0;
3722
+ inFlight.b2LastDescendantCheckMs = 0;
3723
+ inFlight.b2AbandonedSignalled = false;
3724
+ }
3725
+ } else {
3726
+ if (inFlight.b2AbandonedSignalled) {
3727
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
3728
+ return;
3729
+ }
3730
+ if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
3731
+ const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
3732
+ if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
3733
+ inFlight.b2LastDescendantCheckMs = this.now();
3734
+ const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
3735
+ if (isB2AbandonmentConfirmed({
3736
+ pinnedForMs,
3737
+ minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
3738
+ descendantOngoing
3739
+ })) {
3740
+ inFlight.b2AbandonedSignalled = true;
3741
+ this.log({
3742
+ level: "warn",
3743
+ message: `Message ${id.slice(0, 8)} b2-pinned for ${Math.round(pinnedForMs / 1e3)}s with no ongoing descendant sub-agent session (status-map confirmed) \u2014 treating the delegated/tool turn as abandoned, resolving done`,
3744
+ conversation_id: conv.id,
3745
+ message_id: id
3746
+ });
3747
+ void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
3748
+ watched_for_ms: pinnedForMs
3749
+ });
3750
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
3751
+ return;
3752
+ }
3753
+ }
3754
+ }
2962
3755
  if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
2963
3756
  this.log({
2964
3757
  level: "warn",
@@ -2978,6 +3771,18 @@ var ChannelDriver = class {
2978
3771
  inFlight.aliveInFlight = false;
2979
3772
  if (ok) inFlight.lastAliveAt = this.now();
2980
3773
  });
3774
+ if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
3775
+ inFlight.titleSyncInFlight = true;
3776
+ void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
3777
+ if (!title) {
3778
+ inFlight.titleSyncInFlight = false;
3779
+ return;
3780
+ }
3781
+ const ok = await this.patchConversationTitle(conv.id, title);
3782
+ inFlight.titleSyncInFlight = false;
3783
+ if (ok) inFlight.titleSynced = true;
3784
+ });
3785
+ }
2981
3786
  }
2982
3787
  if (awaitingHuman) {
2983
3788
  if (!inFlight.awaitingHumanLatched) {
@@ -3015,6 +3820,70 @@ var ChannelDriver = class {
3015
3820
  this.removeInFlight(watcher, inFlight.evidentMessageId);
3016
3821
  }
3017
3822
  }
3823
+ /**
3824
+ * Settle a message whose run-state has resolved `'done'` — extracted verbatim
3825
+ * (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
3826
+ * inline `state === 'done'` branch body, so a SECOND caller (the #721
3827
+ * b2-abandonment resolution) can reach the exact same completion behavior
3828
+ * (delivery-deadline anchoring, title resolution, usage extraction, and
3829
+ * `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
3830
+ * and risking the two copies silently drifting apart.
3831
+ */
3832
+ async settleMessageDone(sessionId, watcher, inFlight, messages) {
3833
+ const conv = watcher.conv;
3834
+ this.anchorDeliveryDeadline(inFlight);
3835
+ if (!inFlight.done) {
3836
+ this.log({
3837
+ level: "info",
3838
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
3839
+ conversation_id: conv.id,
3840
+ message_id: inFlight.evidentMessageId
3841
+ });
3842
+ const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
3843
+ const usage = messageUsage(messages, inFlight.opencodeMessageId);
3844
+ try {
3845
+ await this.markDone(
3846
+ conv.id,
3847
+ inFlight.evidentMessageId,
3848
+ sessionId,
3849
+ inFlight.opencodeMessageId,
3850
+ title,
3851
+ usage
3852
+ );
3853
+ } catch (err) {
3854
+ if (err instanceof ChannelAuthError) throw err;
3855
+ if (err instanceof ChannelTerminalError) {
3856
+ this.log({
3857
+ level: "warn",
3858
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
3859
+ conversation_id: conv.id,
3860
+ message_id: inFlight.evidentMessageId
3861
+ });
3862
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
3863
+ return;
3864
+ }
3865
+ if (this.now() >= inFlight.deadline) {
3866
+ this.log({
3867
+ level: "warn",
3868
+ 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)}`,
3869
+ conversation_id: conv.id,
3870
+ message_id: inFlight.evidentMessageId
3871
+ });
3872
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
3873
+ return;
3874
+ }
3875
+ this.log({
3876
+ level: "warn",
3877
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
3878
+ conversation_id: conv.id,
3879
+ message_id: inFlight.evidentMessageId
3880
+ });
3881
+ return;
3882
+ }
3883
+ inFlight.done = true;
3884
+ }
3885
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
3886
+ }
3018
3887
  // Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
3019
3888
  /**
3020
3889
  * Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
@@ -3181,6 +4050,7 @@ var ChannelDriver = class {
3181
4050
  if (state === "failed") {
3182
4051
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
3183
4052
  const usage = messageUsage(messages, ocId ?? "");
4053
+ const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
3184
4054
  this.log({
3185
4055
  level: "error",
3186
4056
  message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
@@ -3188,7 +4058,7 @@ var ChannelDriver = class {
3188
4058
  message_id: row.id
3189
4059
  });
3190
4060
  try {
3191
- await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
4061
+ await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
3192
4062
  } catch (err) {
3193
4063
  if (err instanceof ChannelAuthError) throw err;
3194
4064
  if (err instanceof ChannelTerminalError) {
@@ -3594,6 +4464,47 @@ var ChannelDriver = class {
3594
4464
  }
3595
4465
  return false;
3596
4466
  }
4467
+ /**
4468
+ * Tri-state variant of the upward parentID membership walk (#721), used ONLY
4469
+ * by `isAnyDescendantSessionOngoing`. Walks the SAME cached
4470
+ * `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
4471
+ * `sessionBelongsTo`, which deliberately collapses "confirmed not a
4472
+ * descendant" and "the walk's fetch failed" into the same `false` (safe for
4473
+ * its OTHER callers: interaction attribution and the recovery-path
4474
+ * `isAnyDescendantSessionAlive`, both of which just retry next tick with no
4475
+ * safety consequence either way) — this variant keeps those two outcomes
4476
+ * SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
4477
+ * (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
4478
+ * not ongoing".
4479
+ *
4480
+ * Return contract:
4481
+ * - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
4482
+ * - `false` → the walk reached a definitive, parent-less root session
4483
+ * WITHOUT ever matching `rootSessionId` — `sessionId` is
4484
+ * CONFIRMED NOT a descendant of it.
4485
+ * - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
4486
+ * through the walk (`resolveSessionParent` returned `undefined`),
4487
+ * or the depth cap (32) was hit without a definitive answer (a
4488
+ * pathological/cyclic chain proves nothing either way). NEVER
4489
+ * treat this the same as `false` — see `sessionBelongsTo`'s own
4490
+ * doc comment above for why that collapse is safe THERE but not
4491
+ * here.
4492
+ *
4493
+ * `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
4494
+ * to the live-path descendant check, not a modification of shared code used
4495
+ * by interaction attribution or the recovery path.
4496
+ */
4497
+ async resolveSessionMembership(sessionId, rootSessionId) {
4498
+ let current = sessionId;
4499
+ for (let depth = 0; current && depth < 32; depth++) {
4500
+ if (current === rootSessionId) return true;
4501
+ const parent = await this.resolveSessionParent(current);
4502
+ if (parent === void 0) return null;
4503
+ if (parent === null) return false;
4504
+ current = parent;
4505
+ }
4506
+ return null;
4507
+ }
3597
4508
  /**
3598
4509
  * Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
3599
4510
  * `null` for a root session (no parent) and `undefined` when opencode is
@@ -3616,19 +4527,36 @@ var ChannelDriver = class {
3616
4527
  if (parent !== void 0) this.sessionParents.set(sessionId, parent);
3617
4528
  return parent;
3618
4529
  }
4530
+ /**
4531
+ * OpenCode's synchronous default session title (e.g.
4532
+ * `"New session - 1737800000000"`), assigned immediately when a session is
4533
+ * created — before OpenCode's async LLM-based auto-titling later renames it
4534
+ * mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
4535
+ * timestamp suffix's exact format is deliberately NOT matched, since the prefix
4536
+ * alone is the stable, cheap signal and over-anchoring on the timestamp
4537
+ * representation risks silently breaking if OpenCode ever changes it. Accepted
4538
+ * trade-off: a genuine LLM-assigned title that happens to literally start with
4539
+ * this prefix would also fail to latch (see `resolveSessionTitle`) —
4540
+ * vanishingly unlikely in practice, and deliberately not engineered around.
4541
+ */
4542
+ static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
3619
4543
  /**
3620
4544
  * Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
3621
4545
  * status PATCH can carry it into the "Live sessions" list. Driver-level cache so
3622
4546
  * BOTH the watcher completion path and the restart-recovery re-adopt path (which
3623
4547
  * has no watcher) can use it. `conversationId` is passed only for log context.
3624
4548
  * Best-effort:
3625
- * - a resolved NON-EMPTY title is cached and terminal (a real session name
4549
+ * - a resolved NON-EMPTY title that does NOT match
4550
+ * `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
3626
4551
  * won't later un-name), so we do NOT re-GET `/session/:id` every tick;
3627
- * - while the title is still absent/empty we do NOT latch it — OpenCode names
3628
- * sessions asynchronously mid-turn, so an early call (e.g. at `processing`)
3629
- * must leave the cache unresolved and re-fetch on the next need so a later
3630
- * call (e.g. at `done`) picks up the name assigned in the meantime. Such a
3631
- * call returns `null` (omit the title on THIS PATCH) without caching;
4552
+ * - while the title is still absent, empty, or matches the OpenCode
4553
+ * placeholder prefix (#549) we do NOT latch it OpenCode names sessions
4554
+ * asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
4555
+ * the cache unresolved and re-fetch on the next need so a later call (e.g. at
4556
+ * `done`) picks up the name assigned in the meantime. Such a call returns
4557
+ * `null` (omit the title on THIS PATCH) without caching. If a session is
4558
+ * never renamed, the title is omitted forever rather than ever persisting
4559
+ * the placeholder as a last resort;
3632
4560
  * - a failed request likewise leaves the cache unresolved (retry next need)
3633
4561
  * and returns `null` — it must NEVER throw or block completion.
3634
4562
  * A failure is logged with agent/session context (no silent catch).
@@ -3641,7 +4569,7 @@ var ChannelDriver = class {
3641
4569
  if (res.ok) {
3642
4570
  const body = await res.json();
3643
4571
  const title = body && typeof body.title === "string" ? body.title.trim() : "";
3644
- if (title.length > 0) {
4572
+ if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
3645
4573
  this.sessionTitles.set(sessionId, title);
3646
4574
  return title;
3647
4575
  }
@@ -3661,6 +4589,54 @@ var ChannelDriver = class {
3661
4589
  }
3662
4590
  return null;
3663
4591
  }
4592
+ /**
4593
+ * Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
4594
+ * session title onto the conversation via the PLAIN conversation-update
4595
+ * endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
4596
+ * message-status endpoint `markProcessing`/`markDone` use. Deliberately a
4597
+ * separate, lighter call: it carries no `status`, so it cannot re-trigger the
4598
+ * `processing`/`done` transition side effects (Slack notices, activity-log
4599
+ * rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
4600
+ * ever touches `conversations.title`. That route (`routes/conversations.ts`)
4601
+ * skips a title write matching the stored value, so a redundant call with the
4602
+ * same title is a real no-op — it does not bump `updated_at`, which the
4603
+ * conversation list sorts and paginates on. (Note this is a DIFFERENT guard
4604
+ * from `threads.ts`'s "non-empty AND changed" one, which only covers the
4605
+ * message-status PATCH; the non-empty half is enforced here instead, by
4606
+ * `resolveSessionTitle` never returning an empty/placeholder title.)
4607
+ *
4608
+ * Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
4609
+ * is logged and the title is simply retried on the next heartbeat tick (the
4610
+ * caller only latches `titleSynced` on `true`).
4611
+ */
4612
+ async patchConversationTitle(conversationId, title) {
4613
+ try {
4614
+ const res = await this.fetchImpl(
4615
+ `${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
4616
+ {
4617
+ method: "PATCH",
4618
+ headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
4619
+ body: JSON.stringify({ title })
4620
+ }
4621
+ );
4622
+ if (!res.ok) {
4623
+ this.log({
4624
+ level: "debug",
4625
+ message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
4626
+ conversation_id: conversationId
4627
+ });
4628
+ return false;
4629
+ }
4630
+ return true;
4631
+ } catch (err) {
4632
+ this.log({
4633
+ level: "debug",
4634
+ 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)}`,
4635
+ conversation_id: conversationId
4636
+ });
4637
+ return false;
4638
+ }
4639
+ }
3664
4640
  /**
3665
4641
  * DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
3666
4642
  * (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
@@ -3719,6 +4695,84 @@ var ChannelDriver = class {
3719
4695
  }
3720
4696
  return false;
3721
4697
  }
4698
+ /**
4699
+ * LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
4700
+ * sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
4701
+ * in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
4702
+ *
4703
+ * Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
4704
+ * cross-check above): that method judges liveness from the child's OWN
4705
+ * TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
4706
+ * on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
4707
+ * path the local opencode server IS running, so its in-memory status map is
4708
+ * live and authoritative — and per ADR-0047 §4a ("the child has its own entry
4709
+ * [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
4710
+ * ENTIRE turn (including any tool call it is itself executing), not a
4711
+ * per-message transcript snapshot. This sidesteps the "child's own tool is
4712
+ * executing, between its step's completion and the next generation step"
4713
+ * transcript gap that a transcript-based check would need a second,
4714
+ * sustained-window bound to guard against — it is simply not derived from
4715
+ * message timestamps at all.
4716
+ *
4717
+ * Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
4718
+ * status, as the recovery path does per §4a)? Because on the LIVE path the
4719
+ * root session can be shared: a SECOND, unrelated user message can land on the
4720
+ * SAME session (issue #721's own root cause) and keep the root `busy` for a
4721
+ * reason that has nothing to do with THIS message's delegation. A `task`
4722
+ * descendant session is spawned for exactly one delegated turn and never
4723
+ * reused, so its OWN status-map entry is unambiguous evidence about that one
4724
+ * delegation — which the root's status is not.
4725
+ *
4726
+ * Why membership is checked via `resolveSessionMembership`, NOT
4727
+ * `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
4728
+ * `GET /session/:id` fetch failure into "not a descendant", which would
4729
+ * silently drop a genuinely-live candidate from consideration on the one
4730
+ * unlucky tick its membership-walk fetch hiccups (#721).
4731
+ * `resolveSessionMembership` keeps that failure mode as a distinct `null`
4732
+ * (indeterminate) so it is folded into THIS method's own `indeterminate` flag
4733
+ * instead.
4734
+ *
4735
+ * Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
4736
+ * - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
4737
+ * - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
4738
+ * confirmed either way (`resolveSessionMembership` never
4739
+ * returned `null`), and every CONFIRMED descendant's status read
4740
+ * succeeded and is not ongoing (includes "no descendant session
4741
+ * exists at all" — e.g. a plain, non-`task` tool call).
4742
+ * - `null` → INDETERMINATE: `listSessions` failed, OR at least one
4743
+ * candidate's MEMBERSHIP could not be confirmed
4744
+ * (`resolveSessionMembership` returned `null` — a fetch failure
4745
+ * or pathological chain partway through the parent walk), OR at
4746
+ * least one CONFIRMED descendant's `isSessionOngoing` read
4747
+ * failed — and no OTHER candidate was already confirmed `true`.
4748
+ * The caller MUST NOT treat `null` the same as `false` here
4749
+ * (unlike the recovery cross-check's contract) — see
4750
+ * `isB2AbandonmentConfirmed`.
4751
+ */
4752
+ async isAnyDescendantSessionOngoing(rootSessionId) {
4753
+ const sessions = await listSessions(this.port);
4754
+ if (!sessions) {
4755
+ this.log({
4756
+ level: "warn",
4757
+ message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
4758
+ });
4759
+ return null;
4760
+ }
4761
+ let indeterminate = false;
4762
+ for (const candidate of sessions) {
4763
+ if (!candidate?.id || candidate.id === rootSessionId) continue;
4764
+ const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
4765
+ if (membership === null) {
4766
+ indeterminate = true;
4767
+ continue;
4768
+ }
4769
+ if (membership === false) continue;
4770
+ const ongoing = await isSessionOngoing(this.port, candidate.id);
4771
+ if (ongoing === true) return true;
4772
+ if (ongoing === null) indeterminate = true;
4773
+ }
4774
+ return indeterminate ? null : false;
4775
+ }
3722
4776
  /**
3723
4777
  * Cheap decision-telemetry label for a running row's LAST correlated reply
3724
4778
  * (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
@@ -3847,6 +4901,32 @@ var ChannelDriver = class {
3847
4901
  }
3848
4902
  return messages;
3849
4903
  }
4904
+ /**
4905
+ * The `opencode_session_id` fragment of a status PATCH body — `{}` when this
4906
+ * conversation has ABANDONED that session (#553). The field is optional
4907
+ * server-side and an absent one leaves the persisted binding untouched, so
4908
+ * omitting it is how a routine status write stops resurrecting it.
4909
+ *
4910
+ * ONLY for writes whose sole cost is a lost deep link. The `processing` notice
4911
+ * degrades to no "View in Evident" link (the reaction swap still fires) and the
4912
+ * turn-failure notice is built from the PATCH's own `error` text with a link off
4913
+ * the persisted row — neither loses content the user came for. `markDone`
4914
+ * deliberately does NOT use this helper: the server fetches the reply text
4915
+ * THROUGH the session id it is given, so suppressing there would replace the
4916
+ * agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
4917
+ * `ensureSession` guard, not this suppression, is what makes the self-heal
4918
+ * stick.
4919
+ */
4920
+ sessionIdBody(sessionId, conversationId, messageId, status) {
4921
+ if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
4922
+ this.log({
4923
+ level: "debug",
4924
+ 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)}`,
4925
+ conversation_id: conversationId,
4926
+ message_id: messageId
4927
+ });
4928
+ return {};
4929
+ }
3850
4930
  /**
3851
4931
  * EXISTING combinedAuth route — now fired by the watcher on queued→running
3852
4932
  * (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
@@ -3876,7 +4956,7 @@ var ChannelDriver = class {
3876
4956
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3877
4957
  body: JSON.stringify({
3878
4958
  status: "processing",
3879
- opencode_session_id: sessionId,
4959
+ ...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
3880
4960
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3881
4961
  ...title ? { title } : {}
3882
4962
  })
@@ -3925,6 +5005,11 @@ var ChannelDriver = class {
3925
5005
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3926
5006
  body: JSON.stringify({
3927
5007
  status: "done",
5008
+ // ALWAYS sent, even for a session this conversation has abandoned
5009
+ // (#553): the server reads the reply text back out of THIS session id
5010
+ // to deliver it. Omitting it would leave the user with "✅ Done!"
5011
+ // instead of the answer — a worse regression than the resurrection it
5012
+ // would prevent, which `ensureSession`'s guard handles anyway.
3928
5013
  opencode_session_id: sessionId,
3929
5014
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3930
5015
  ...title ? { title } : {},
@@ -3941,16 +5026,31 @@ var ChannelDriver = class {
3941
5026
  }
3942
5027
  /**
3943
5028
  * Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
3944
- * when provided (issue #182): a bare `markFailed(conv, msg)` sends
3945
- * `{status:'failed'}` unchanged (the dispatch-failure path), while an errored
3946
- * OpenCode turn sends `{status:'failed', opencode_session_id, error}` so the
3947
- * failure reason reaches the channel.
5029
+ * when provided (issue #182). Three states for `sessionId`:
5030
+ * - omitted (`undefined`) → don't send the field, leave the persisted
5031
+ * session untouched (unused today; kept for API symmetry).
5032
+ * - a real id (`string`) → send it, update the persisted session (the
5033
+ * turn-failure call sites: an errored OpenCode turn).
5034
+ * - explicit `null` → send it, CLEAR the persisted session (issue
5035
+ * #485's dispatch-handoff-failure call site: the session id still
5036
+ * exists but is wedged, so the next attempt must get a fresh one
5037
+ * instead of reusing it — see WI-1's server-side null-clearing PATCH).
3948
5038
  */
3949
- async markFailed(conversationId, messageId, sessionId, error2, usage) {
5039
+ async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
3950
5040
  const body = { status: "failed" };
3951
- if (sessionId !== void 0) body.opencode_session_id = sessionId;
5041
+ if (sessionId === null) {
5042
+ body.opencode_session_id = null;
5043
+ } else if (sessionId !== void 0) {
5044
+ Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
5045
+ }
3952
5046
  if (error2 !== void 0) body.error = error2;
3953
5047
  if (usage) Object.assign(body, usage);
5048
+ if (failure) {
5049
+ body.failure_kind = failure.kind;
5050
+ body.failure_provider_id = failure.providerId;
5051
+ body.failure_model_id = failure.modelId;
5052
+ body.failure_reason = failure.reason;
5053
+ }
3954
5054
  await this.callWithRetry(
3955
5055
  "marking message as failed",
3956
5056
  () => this.fetchImpl(
@@ -3963,6 +5063,29 @@ var ChannelDriver = class {
3963
5063
  )
3964
5064
  );
3965
5065
  }
5066
+ /**
5067
+ * Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
5068
+ *
5069
+ * `messageFailure` alone (structured OpenCode error → `model_auth`) covers
5070
+ * most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
5071
+ * to the P1-2b zero-provider check — one extra loopback call to
5072
+ * `hasAnyConfiguredProvider`, only reached when the structured classifier
5073
+ * couldn't place it. Fails open (never throws): a fallback probe failure
5074
+ * (`null`/indeterminate) leaves the classification `null`, which produces
5075
+ * today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
5076
+ */
5077
+ async classifyModelAuthFailure(messages, userMessageId) {
5078
+ const classified = messageFailure(messages, userMessageId);
5079
+ if (classified != null) return classified;
5080
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
5081
+ const hasProvider = await hasAnyConfiguredProvider(this.port);
5082
+ return applyZeroProviderFallback(
5083
+ classified,
5084
+ hasProvider,
5085
+ reply?.info?.providerID ?? null,
5086
+ reply?.info?.modelID ?? null
5087
+ );
5088
+ }
3966
5089
  /**
3967
5090
  * Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
3968
5091
  * (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
@@ -4139,7 +5262,7 @@ async function ensureOpenCodeRunning(ctx) {
4139
5262
  console.log(chalk5.yellow("Tip: Run with the correct port:"));
4140
5263
  console.log(
4141
5264
  chalk5.dim(
4142
- ` ${getCliName()} run --agent ${ctx.agentId} --port ${runningInstances[0].port}`
5265
+ ` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
4143
5266
  )
4144
5267
  );
4145
5268
  }
@@ -4269,19 +5392,21 @@ async function resolveAgentIdFromKey(authHeader) {
4269
5392
  return { agent_id: data.agent_id };
4270
5393
  }
4271
5394
  return {
4272
- error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --agent explicitly."
5395
+ error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
4273
5396
  };
4274
5397
  } catch (error2) {
4275
5398
  const message = error2 instanceof Error ? error2.message : "Unknown error";
4276
5399
  return { error: `Failed to resolve runner from key: ${message}` };
4277
5400
  }
4278
5401
  }
5402
+ var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
4279
5403
  async function notifyAgentDisconnected(agentId, authHeader) {
4280
5404
  const apiUrl = getApiUrlConfig();
4281
5405
  try {
4282
5406
  const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
4283
5407
  method: "POST",
4284
- headers: { Authorization: authHeader }
5408
+ headers: { Authorization: authHeader },
5409
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
4285
5410
  });
4286
5411
  if (!response.ok) {
4287
5412
  const serverMessage = await readErrorMessage(response);
@@ -4292,7 +5417,35 @@ async function notifyAgentDisconnected(agentId, authHeader) {
4292
5417
  }
4293
5418
  return { ok: true };
4294
5419
  } catch (error2) {
4295
- return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
5420
+ return { ok: false, error: describeBestEffortError(error2) };
5421
+ }
5422
+ }
5423
+ function describeBestEffortError(error2) {
5424
+ const name = error2?.name;
5425
+ if (name === "TimeoutError" || name === "AbortError") {
5426
+ return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
5427
+ }
5428
+ return error2 instanceof Error ? error2.message : String(error2);
5429
+ }
5430
+ async function reportMicrovmId(agentId, authHeader, microvmId) {
5431
+ try {
5432
+ const apiUrl = getApiUrlConfig();
5433
+ const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
5434
+ method: "POST",
5435
+ headers: { Authorization: authHeader, "Content-Type": "application/json" },
5436
+ body: JSON.stringify({ microvm_id: microvmId }),
5437
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
5438
+ });
5439
+ if (!response.ok) {
5440
+ const serverMessage = await readErrorMessage(response);
5441
+ return {
5442
+ ok: false,
5443
+ error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
5444
+ };
5445
+ }
5446
+ return { ok: true };
5447
+ } catch (error2) {
5448
+ return { ok: false, error: describeBestEffortError(error2) };
4296
5449
  }
4297
5450
  }
4298
5451
  async function getAgentInfo(agentId, authHeader) {
@@ -4342,6 +5495,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
4342
5495
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
4343
5496
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
4344
5497
  var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
5498
+ var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
4345
5499
  function resolveLogLevel(options) {
4346
5500
  const accepted = Object.keys(LOG_LEVELS);
4347
5501
  const validate = (value, source) => {
@@ -4365,6 +5519,34 @@ function resolveLogLevel(options) {
4365
5519
  }
4366
5520
  return "info";
4367
5521
  }
5522
+ function resolveFileSyncDirectories(raw, homeDir) {
5523
+ const directories = [];
5524
+ for (const entry of raw ?? []) {
5525
+ const trimmed = entry.trim();
5526
+ if (trimmed === "") {
5527
+ throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
5528
+ }
5529
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join2(homeDir, trimmed.slice(2)) : trimmed;
5530
+ if (!isAbsolute2(expanded)) {
5531
+ throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
5532
+ }
5533
+ const normalized = resolvePath(expanded);
5534
+ if (parse(normalized).root === normalized) {
5535
+ throw new Error(
5536
+ `--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
5537
+ );
5538
+ }
5539
+ if (!directories.includes(normalized)) {
5540
+ directories.push(normalized);
5541
+ }
5542
+ }
5543
+ if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
5544
+ throw new Error(
5545
+ `--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
5546
+ );
5547
+ }
5548
+ return directories;
5549
+ }
4368
5550
  function meetsThreshold(state, level) {
4369
5551
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
4370
5552
  }
@@ -4486,18 +5668,29 @@ async function handleAuthError(state, error2) {
4486
5668
  async function driveChannels(state, driver) {
4487
5669
  let idlePolls = 0;
4488
5670
  let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
5671
+ let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
4489
5672
  while (state.running) {
4490
5673
  if (state.connection?.reconnecting && state.connection.reconnectPromise) {
4491
5674
  logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
4492
5675
  if (state.interactive) displayStatus(state);
4493
5676
  await state.connection.reconnectPromise;
4494
5677
  }
5678
+ const carriedOverFileSync = driver.fileSyncActivity().inFlight;
5679
+ void driver.syncPendingFiles().catch(
5680
+ (error2) => logActivity(state, {
5681
+ type: "error",
5682
+ error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
5683
+ })
5684
+ );
4495
5685
  try {
4496
5686
  const processed = await driver.drainPending();
4497
5687
  state.messageCount += processed;
4498
5688
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
4499
5689
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
4500
- if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity) {
5690
+ const appliedFiles = driver.fileSyncActivity().appliedFiles;
5691
+ const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
5692
+ lastSeenAppliedFiles = appliedFiles;
5693
+ if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
4501
5694
  idlePolls = 0;
4502
5695
  if (processed > 0 && state.interactive) displayStatus(state);
4503
5696
  } else if (state.idleTimeout !== null) {
@@ -4526,7 +5719,7 @@ async function driveChannels(state, driver) {
4526
5719
  logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
4527
5720
  if (state.interactive) displayStatus(state);
4528
5721
  }
4529
- await new Promise((resolve2) => setTimeout(resolve2, CHANNEL_POLL_INTERVAL_MS));
5722
+ await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
4530
5723
  if (state.idleTimeout !== null && idlePolls >= 2) {
4531
5724
  const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
4532
5725
  if (idleMs > state.idleTimeout * 1e3) {
@@ -4629,7 +5822,18 @@ async function notifyOffline(state) {
4629
5822
  if (state.interactive) displayStatus(state);
4630
5823
  }
4631
5824
  }
5825
+ async function timeShutdownPhase(state, durations, name, run2) {
5826
+ const startedAt = Date.now();
5827
+ try {
5828
+ return await run2();
5829
+ } finally {
5830
+ const elapsedMs = Date.now() - startedAt;
5831
+ durations[name] = elapsedMs;
5832
+ log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
5833
+ }
5834
+ }
4632
5835
  async function cleanup(state, opts = {}) {
5836
+ const durations = {};
4633
5837
  state.running = false;
4634
5838
  for (const timer of state.sessionCleanupTimers) {
4635
5839
  clearInterval(timer);
@@ -4643,7 +5847,13 @@ async function cleanup(state, opts = {}) {
4643
5847
  logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
4644
5848
  displayStatus(state);
4645
5849
  }
4646
- const settled = await state.channelDriver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS);
5850
+ const driver = state.channelDriver;
5851
+ const settled = await timeShutdownPhase(
5852
+ state,
5853
+ durations,
5854
+ "drain",
5855
+ () => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
5856
+ );
4647
5857
  if (!settled) {
4648
5858
  logActivity(state, {
4649
5859
  type: "info",
@@ -4652,13 +5862,15 @@ async function cleanup(state, opts = {}) {
4652
5862
  if (state.interactive) displayStatus(state);
4653
5863
  }
4654
5864
  }
4655
- await notifyOffline(state);
5865
+ await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
4656
5866
  if (state.connection) {
4657
- state.connection.close();
5867
+ const connection = state.connection;
5868
+ await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
4658
5869
  state.connection = null;
4659
5870
  }
4660
5871
  if (state.opencodeProcess) {
4661
- stopOpenCode(state.opencodeProcess);
5872
+ const opencodeProcess = state.opencodeProcess;
5873
+ await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
4662
5874
  if (state.interactive) {
4663
5875
  logActivity(state, { type: "info", message: "Stopped OpenCode process" });
4664
5876
  displayStatus(state);
@@ -4667,12 +5879,15 @@ async function cleanup(state, opts = {}) {
4667
5879
  }
4668
5880
  state.opencodeProcess = null;
4669
5881
  }
5882
+ return durations;
4670
5883
  }
4671
5884
  async function run(options) {
4672
5885
  const interactive = isInteractive(options.json);
4673
5886
  let logLevel;
5887
+ let fileSyncDirectories;
4674
5888
  try {
4675
5889
  logLevel = resolveLogLevel(options);
5890
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
4676
5891
  } catch (error2) {
4677
5892
  const message = error2 instanceof Error ? error2.message : String(error2);
4678
5893
  if (options.json) {
@@ -4707,6 +5922,11 @@ async function run(options) {
4707
5922
  sessionCleanupTimers: [],
4708
5923
  authHeader: ""
4709
5924
  };
5925
+ if (fileSyncDirectories.length > 0) {
5926
+ log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
5927
+ } else {
5928
+ log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
5929
+ }
4710
5930
  if (!options.runner && options.agent) {
4711
5931
  telemetry.info(
4712
5932
  EventTypes.DEPRECATED_AGENT_FLAG_USED,
@@ -4730,14 +5950,38 @@ async function run(options) {
4730
5950
  const handleSignal = async () => {
4731
5951
  if (state.shuttingDown) return;
4732
5952
  state.shuttingDown = true;
5953
+ const shutdownStartedAt = Date.now();
4733
5954
  if (state.interactive) {
4734
5955
  logActivity(state, { type: "info", message: "Shutting down..." });
4735
5956
  displayStatus(state);
4736
5957
  } else {
4737
5958
  log2(state, "Shutting down...");
4738
5959
  }
4739
- await cleanup(state, { graceful: true });
4740
- await shutdownTelemetry();
5960
+ const durations = await cleanup(state, { graceful: true });
5961
+ const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
5962
+ await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
5963
+ let timer;
5964
+ const flushed = shutdownTelemetry().then(
5965
+ () => true,
5966
+ (error2) => {
5967
+ log2(
5968
+ state,
5969
+ `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
5970
+ "warn"
5971
+ );
5972
+ return true;
5973
+ }
5974
+ );
5975
+ const timedOut = new Promise((resolve3) => {
5976
+ timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
5977
+ });
5978
+ if (!await Promise.race([flushed, timedOut])) {
5979
+ log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
5980
+ }
5981
+ clearTimeout(timer);
5982
+ });
5983
+ const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
5984
+ log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
4741
5985
  process.exit(0);
4742
5986
  };
4743
5987
  process.on("SIGINT", handleSignal);
@@ -4851,6 +6095,21 @@ async function run(options) {
4851
6095
  }
4852
6096
  spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
4853
6097
  state.agentName = validation.agent.name;
6098
+ const microvmId = process.env.MICROVM_ID?.trim();
6099
+ if (microvmId) {
6100
+ const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
6101
+ if (reported.ok) {
6102
+ log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
6103
+ } else {
6104
+ const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
6105
+ log2(state, message, "warn");
6106
+ if (state.interactive && !state.json) {
6107
+ logActivity(state, { type: "info", level: "warn", message });
6108
+ }
6109
+ }
6110
+ } else {
6111
+ log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
6112
+ }
4854
6113
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
4855
6114
  try {
4856
6115
  const oc = await ensureOpenCodeRunning({
@@ -4872,6 +6131,21 @@ async function run(options) {
4872
6131
  logActivity(state, { type: "info", level: "warn", message: versionWarning });
4873
6132
  }
4874
6133
  }
6134
+ const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
6135
+ if (noProviderWarning) {
6136
+ log2(state, noProviderWarning, "warn");
6137
+ if (state.interactive && !state.json) {
6138
+ logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
6139
+ blank();
6140
+ console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
6141
+ console.log(
6142
+ chalk6.dim(
6143
+ `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
6144
+ )
6145
+ );
6146
+ blank();
6147
+ }
6148
+ }
4875
6149
  } catch (error2) {
4876
6150
  ocSpinner?.fail(error2.message);
4877
6151
  throw error2;
@@ -4884,6 +6158,10 @@ async function run(options) {
4884
6158
  getAuthHeader: () => state.authHeader,
4885
6159
  conversationFilter: state.conversationFilter,
4886
6160
  stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
6161
+ // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
6162
+ // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
6163
+ fileSyncDirectories,
6164
+ homeDir: homedir2(),
4887
6165
  log: (entry) => (
4888
6166
  // Thread the driver's real level straight through so `debug`/`warn`
4889
6167
  // survive the sink filter (they no longer collapse to info). `type`
@@ -4910,6 +6188,18 @@ async function run(options) {
4910
6188
  type: "info",
4911
6189
  message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
4912
6190
  });
6191
+ if (options.tunnelReadyFile) {
6192
+ const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
6193
+ if (marker.ok) {
6194
+ log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
6195
+ } else {
6196
+ log2(
6197
+ state,
6198
+ `Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
6199
+ "error"
6200
+ );
6201
+ }
6202
+ }
4913
6203
  emitAgentConnected(state.agentId, {
4914
6204
  port: state.port,
4915
6205
  cli_version: getCliVersion(),
@@ -4965,6 +6255,12 @@ async function run(options) {
4965
6255
  onDrainPing: () => {
4966
6256
  if (!state.running) return;
4967
6257
  logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
6258
+ void channelDriver.syncPendingFiles().catch(
6259
+ (error2) => logActivity(state, {
6260
+ type: "error",
6261
+ error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
6262
+ })
6263
+ );
4968
6264
  channelDriver.drainPending().then((processed) => {
4969
6265
  if (processed > 0) {
4970
6266
  state.messageCount += processed;
@@ -5048,7 +6344,10 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
5048
6344
  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);
5049
6345
  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 }));
5050
6346
  program.command("whoami").description("Show the currently logged in user").action(whoami);
5051
- program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Runner ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("--runner [id]", "Alias for --agent (preferred name; wins if both are given)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
6347
+ 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(
6348
+ "-a, --agent [id]",
6349
+ "Deprecated alias for --runner (still supported; --runner wins if both are given)"
6350
+ ).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
5052
6351
  "--log-level <level>",
5053
6352
  "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
5054
6353
  ).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(
@@ -5060,6 +6359,14 @@ program.command("run").description("Connect to Evident and process messages").op
5060
6359
  ).option(
5061
6360
  "--session-cleanup-interval <duration>",
5062
6361
  "How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
6362
+ ).option(
6363
+ "--enable-file-sync-to <dir>",
6364
+ "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
6365
+ (value, previous) => previous.concat([value]),
6366
+ []
6367
+ ).option(
6368
+ "--tunnel-ready-file <path>",
6369
+ "Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
5063
6370
  ).action(
5064
6371
  (options) => {
5065
6372
  run({
@@ -5076,7 +6383,11 @@ program.command("run").description("Connect to Evident and process messages").op
5076
6383
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
5077
6384
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
5078
6385
  sessionCleanupMaxCount: options.sessionCleanupMaxCount,
5079
- sessionCleanupInterval: options.sessionCleanupInterval
6386
+ sessionCleanupInterval: options.sessionCleanupInterval,
6387
+ // Raw values — expansion/validation is single-sourced in run.ts's
6388
+ // resolveFileSyncDirectories.
6389
+ enableFileSyncTo: options.enableFileSyncTo,
6390
+ tunnelReadyFile: options.tunnelReadyFile
5080
6391
  });
5081
6392
  }
5082
6393
  );