@evident-ai/cli 3.1.1-dev.dcb2f6d → 3.1.1-dev.dcd86e4

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,25 @@ 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("Create a token under Settings \u2192 CLI tokens in the dashboard, then paste it below.");
421
+ console.log(
422
+ "(Alternatively, run `evident login` on a machine with a browser, or set EVIDENT_TOKEN for CI.)"
423
+ );
377
424
  blank();
378
425
  process.stdout.write("Paste token: ");
379
- const token = await new Promise((resolve2) => {
426
+ const token = await new Promise((resolve3) => {
380
427
  let data = "";
381
428
  process.stdin.setEncoding("utf8");
382
429
  process.stdin.on("data", (chunk) => {
383
430
  data += chunk;
384
431
  });
385
432
  process.stdin.on("end", () => {
386
- resolve2(data.trim());
433
+ resolve3(data.trim());
387
434
  });
388
435
  if (process.stdin.isTTY) {
389
436
  process.stdin.once("data", (chunk) => {
390
437
  process.stdin.pause();
391
- resolve2(chunk.toString().trim());
438
+ resolve3(chunk.toString().trim());
392
439
  });
393
440
  process.stdin.resume();
394
441
  }
@@ -397,13 +444,22 @@ async function tokenLogin() {
397
444
  printError("No token provided.");
398
445
  process.exit(1);
399
446
  }
447
+ await validateAndStoreToken(token);
448
+ }
449
+ async function validateAndStoreToken(token) {
400
450
  const spinner = ora("Validating token...").start();
401
451
  try {
402
- const result = await api.post("/auth/token/validate", { token });
452
+ const result = await api.get("/me", {
453
+ headers: { Authorization: `Bearer ${token}` }
454
+ });
455
+ if (!result.user) {
456
+ throw new Error(
457
+ "This token is not a user login (e.g. a runner key). Paste a CLI token instead."
458
+ );
459
+ }
403
460
  await storeToken({
404
461
  token,
405
- user: result.user,
406
- expiresAt: result.expires_at
462
+ user: { email: result.user.email }
407
463
  });
408
464
  spinner.stop();
409
465
  printSuccess(`Logged in as ${chalk2.bold(result.user.email)}`);
@@ -423,9 +479,22 @@ async function login(options) {
423
479
  }
424
480
 
425
481
  // src/commands/logout.ts
482
+ function describeFailure(failure) {
483
+ if (failure.type === "enumerate") {
484
+ return `could not list stored keychain entries (${failure.error.message})`;
485
+ }
486
+ return `${failure.account} (${failure.error.message})`;
487
+ }
426
488
  async function logout(options = {}) {
427
489
  if (options.all) {
428
- await deleteToken({ all: true });
490
+ const result = await deleteToken({ all: true });
491
+ if (result.failures.length > 0) {
492
+ printError(
493
+ `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.`
494
+ );
495
+ process.exitCode = 1;
496
+ return;
497
+ }
429
498
  printSuccess("Logged out of all endpoints.");
430
499
  return;
431
500
  }
@@ -450,7 +519,9 @@ async function whoami() {
450
519
  blank();
451
520
  console.log(keyValue("Endpoint", apiUrl));
452
521
  console.log(keyValue("User", chalk3.bold(credentials2.user.email)));
453
- console.log(keyValue("User ID", credentials2.user.id));
522
+ if (credentials2.user.id) {
523
+ console.log(keyValue("User ID", credentials2.user.id));
524
+ }
454
525
  if (credentials2.expiresAt) {
455
526
  const expiresAt = new Date(credentials2.expiresAt);
456
527
  const now = /* @__PURE__ */ new Date();
@@ -467,9 +538,9 @@ async function whoami() {
467
538
  }
468
539
 
469
540
  // src/commands/run.ts
541
+ import { homedir as homedir2 } from "os";
542
+ import { isAbsolute as isAbsolute2, join as join2, parse, resolve as resolvePath } from "path";
470
543
  import chalk6 from "chalk";
471
- import ora3 from "ora";
472
- import { select as select3 } from "@inquirer/prompts";
473
544
 
474
545
  // ../../packages/types/src/telemetry/index.ts
475
546
  var TelemetryEventTypes = {
@@ -478,13 +549,20 @@ var TelemetryEventTypes = {
478
549
  AGENT_DISCONNECTED: "agent.disconnected",
479
550
  AGENT_MESSAGE_PROCESSING: "agent.message_processing",
480
551
  AGENT_MESSAGE_DONE: "agent.message_done",
481
- AGENT_MESSAGE_FAILED: "agent.message_failed"
552
+ AGENT_MESSAGE_FAILED: "agent.message_failed",
553
+ // A `warn`/`error` runner-side log line forwarded server-side for
554
+ // observability (issue #916) — see `apps/cli/src/lib/runner-activity-telemetry.ts`.
555
+ RUNNER_ACTIVITY: "runner.activity"
482
556
  };
483
557
 
484
558
  // ../../packages/types/src/tunnel/index.ts
485
559
  var MAX_FRAME_BYTES = 256 * 1024;
486
560
  var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
487
561
 
562
+ // ../../packages/types/src/runner-files.ts
563
+ var MAX_FILE_PUSH_BYTES = 64 * 1024;
564
+ var MAX_FILE_SYNC_DIRECTORIES = 16;
565
+
488
566
  // ../../packages/types/src/logging/index.ts
489
567
  var CORRELATION_ID_HEADER = "x-evident-correlation-id";
490
568
  function log(level, event, fields) {
@@ -499,6 +577,12 @@ function log(level, event, fields) {
499
577
  );
500
578
  }
501
579
  }
580
+ function errorFields(err) {
581
+ if (err instanceof Error) {
582
+ return { error: err.message, error_name: err.name };
583
+ }
584
+ return { error: String(err) };
585
+ }
502
586
  function stripQuery(url) {
503
587
  try {
504
588
  return new URL(url).pathname;
@@ -508,6 +592,10 @@ function stripQuery(url) {
508
592
  }
509
593
  }
510
594
 
595
+ // src/commands/run.ts
596
+ import ora3 from "ora";
597
+ import { select as select3 } from "@inquirer/prompts";
598
+
511
599
  // src/lib/telemetry.ts
512
600
  var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
513
601
  function getCliVersion() {
@@ -519,6 +607,13 @@ var isShuttingDown = false;
519
607
  var FLUSH_INTERVAL_MS = 5e3;
520
608
  var MAX_BUFFER_SIZE = 50;
521
609
  var FLUSH_TIMEOUT_MS = 3e3;
610
+ var authProvider = null;
611
+ function setTelemetryAuthProvider(provider) {
612
+ authProvider = provider;
613
+ }
614
+ var FLUSH_FAILURE_LOG_INTERVAL_MS = 6e4;
615
+ var lastFlushFailureLoggedAt = 0;
616
+ var suppressedFlushFailureCount = 0;
522
617
  function logEvent(eventType, options = {}) {
523
618
  const event = {
524
619
  event_type: eventType,
@@ -553,9 +648,16 @@ async function flushEvents() {
553
648
  flushTimeout = null;
554
649
  }
555
650
  try {
556
- const credentials2 = await getToken();
557
- if (!credentials2) {
558
- return;
651
+ const providerContext = authProvider?.();
652
+ let authHeader;
653
+ if (providerContext?.authHeader) {
654
+ authHeader = providerContext.authHeader;
655
+ } else {
656
+ const credentials2 = await getToken();
657
+ if (!credentials2) {
658
+ return;
659
+ }
660
+ authHeader = `Bearer ${credentials2.token}`;
559
661
  }
560
662
  const apiUrl = getApiUrlConfig();
561
663
  const controller = new AbortController();
@@ -570,7 +672,7 @@ async function flushEvents() {
570
672
  method: "POST",
571
673
  headers: {
572
674
  "Content-Type": "application/json",
573
- Authorization: `Bearer ${credentials2.token}`
675
+ Authorization: authHeader
574
676
  },
575
677
  body: JSON.stringify(request),
576
678
  signal: controller.signal
@@ -582,8 +684,15 @@ async function flushEvents() {
582
684
  clearTimeout(timeout);
583
685
  }
584
686
  } catch (error2) {
585
- if (process.env.DEBUG) {
586
- console.error("Telemetry error:", error2);
687
+ const now = Date.now();
688
+ if (now - lastFlushFailureLoggedAt >= FLUSH_FAILURE_LOG_INTERVAL_MS) {
689
+ const message = error2 instanceof Error ? error2.message : String(error2);
690
+ const suffix = suppressedFlushFailureCount > 0 ? ` (${suppressedFlushFailureCount} more suppressed in the last ${FLUSH_FAILURE_LOG_INTERVAL_MS / 1e3}s)` : "";
691
+ console.error(`Telemetry flush error: ${message}${suffix}`);
692
+ lastFlushFailureLoggedAt = now;
693
+ suppressedFlushFailureCount = 0;
694
+ } else {
695
+ suppressedFlushFailureCount++;
587
696
  }
588
697
  }
589
698
  }
@@ -645,14 +754,90 @@ var EventTypes = {
645
754
  // CLI lifecycle
646
755
  CLI_STARTED: "cli.started",
647
756
  CLI_COMMAND: "cli.command",
648
- CLI_ERROR: "cli.error"
757
+ CLI_ERROR: "cli.error",
758
+ // Deprecation telemetry (#412) — usage of the old `--agent`/`EVIDENT_AGENT_KEY`
759
+ // names instead of the preferred `--runner`/`EVIDENT_RUNNER_KEY` (#409).
760
+ DEPRECATED_AGENT_FLAG_USED: "cli.deprecated_agent_flag_used",
761
+ DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
762
+ };
763
+
764
+ // src/lib/runner-activity-telemetry.ts
765
+ var FORWARDED_LEVELS = /* @__PURE__ */ new Set(["warn", "error"]);
766
+ var SEVERITY_BY_LEVEL = {
767
+ warn: "warning",
768
+ error: "error"
649
769
  };
770
+ var MAX_MESSAGE_LENGTH = 500;
771
+ var TRUNCATION_MARKER = "\u2026";
772
+ function redact(message) {
773
+ return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
774
+ }
775
+ function truncate(message) {
776
+ if (message.length <= MAX_MESSAGE_LENGTH) return message;
777
+ return message.slice(0, MAX_MESSAGE_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
778
+ }
779
+ var RATE_LIMIT_WINDOW_MS = 6e4;
780
+ var RATE_LIMIT_MAX_EVENTS = 30;
781
+ var windowStartedAt = 0;
782
+ var windowCount = 0;
783
+ var windowDroppedCount = 0;
784
+ function admitUnderRateLimit(now) {
785
+ if (now - windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
786
+ if (windowDroppedCount > 0) {
787
+ console.error(
788
+ `[runner-activity-telemetry] rate cap reached: dropped ${windowDroppedCount} ${windowDroppedCount === 1 ? "entry" : "entries"} in the last ${RATE_LIMIT_WINDOW_MS / 1e3}s (cap ${RATE_LIMIT_MAX_EVENTS}/min)`
789
+ );
790
+ }
791
+ windowStartedAt = now;
792
+ windowCount = 0;
793
+ windowDroppedCount = 0;
794
+ }
795
+ if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
796
+ windowDroppedCount++;
797
+ if (windowDroppedCount === 1) {
798
+ console.error(
799
+ `[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
800
+ );
801
+ }
802
+ return false;
803
+ }
804
+ windowCount++;
805
+ return true;
806
+ }
807
+ function forwardRunnerActivity(entry, context) {
808
+ try {
809
+ if (!FORWARDED_LEVELS.has(entry.level)) return;
810
+ if (!context.agentId || !context.authHeader) return;
811
+ if (!admitUnderRateLimit(Date.now())) return;
812
+ const rawMessage = entry.error ?? entry.message ?? "";
813
+ const message = truncate(redact(rawMessage));
814
+ logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
815
+ severity: SEVERITY_BY_LEVEL[entry.level],
816
+ message,
817
+ metadata: { source: "cli.run" },
818
+ agentId: context.agentId
819
+ });
820
+ } catch (err) {
821
+ console.error(
822
+ `[runner-activity-telemetry] failed to forward runner activity: ${err instanceof Error ? err.message : String(err)}`
823
+ );
824
+ }
825
+ }
650
826
 
651
827
  // src/lib/auth.ts
652
828
  async function getAuthCredentials() {
829
+ const runnerKey = process.env.EVIDENT_RUNNER_KEY;
653
830
  const agentKey = process.env.EVIDENT_AGENT_KEY;
831
+ if (runnerKey) {
832
+ return {
833
+ token: runnerKey,
834
+ authType: "agent_key",
835
+ keySource: "runner_key",
836
+ notice: agentKey ? "Both EVIDENT_RUNNER_KEY and EVIDENT_AGENT_KEY are set; using EVIDENT_RUNNER_KEY." : void 0
837
+ };
838
+ }
654
839
  if (agentKey) {
655
- return { token: agentKey, authType: "agent_key" };
840
+ return { token: agentKey, authType: "agent_key", keySource: "agent_key" };
656
841
  }
657
842
  const userToken = process.env.EVIDENT_TOKEN;
658
843
  if (userToken) {
@@ -706,7 +891,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
706
891
  if (health.healthy) {
707
892
  return health;
708
893
  }
709
- await new Promise((resolve2) => setTimeout(resolve2, 1e3));
894
+ await new Promise((resolve3) => setTimeout(resolve3, 1e3));
710
895
  }
711
896
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
712
897
  }
@@ -721,7 +906,7 @@ function buildOpenCodeVersionWarning(version2) {
721
906
  if (isQueueValidatedVersion(version2)) return null;
722
907
  const detected = version2 ? `v${version2}` : "unknown";
723
908
  const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
724
- return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack/WhatsApp) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
909
+ return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
725
910
  }
726
911
 
727
912
  // src/lib/opencode/process.ts
@@ -1013,6 +1198,12 @@ async function promptOpenCodeInstall(interactive) {
1013
1198
  return action;
1014
1199
  }
1015
1200
 
1201
+ // src/lib/opencode/provider-check.ts
1202
+ function buildNoProviderWarning(hasProvider) {
1203
+ if (hasProvider !== false) return null;
1204
+ 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).";
1205
+ }
1206
+
1016
1207
  // src/lib/opencode/session.ts
1017
1208
  function opencodeBase(port) {
1018
1209
  return `http://127.0.0.1:${port}`;
@@ -1215,6 +1406,11 @@ async function getModelAttachmentCapability(port, model) {
1215
1406
  }
1216
1407
  const entry = provider.models[modelId];
1217
1408
  if (!entry || typeof entry !== "object") return null;
1409
+ if (entry.capabilities && typeof entry.capabilities === "object") {
1410
+ if (typeof entry.capabilities.attachment === "boolean") {
1411
+ return entry.capabilities.attachment;
1412
+ }
1413
+ }
1218
1414
  return typeof entry.attachment === "boolean" ? entry.attachment : null;
1219
1415
  } catch (err) {
1220
1416
  console.error(
@@ -1243,6 +1439,16 @@ async function buildFileParts(attachments, capable) {
1243
1439
  );
1244
1440
  dataUrl = null;
1245
1441
  }
1442
+ if (dataUrl !== null && typeof dataUrl === "object") {
1443
+ outcomes.push({
1444
+ index: a.index,
1445
+ mime: a.mime,
1446
+ filename: a.filename,
1447
+ status: "failed",
1448
+ reason: "needs_reauth"
1449
+ });
1450
+ continue;
1451
+ }
1246
1452
  if (dataUrl == null) {
1247
1453
  outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
1248
1454
  continue;
@@ -1324,7 +1530,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
1324
1530
  }
1325
1531
  }
1326
1532
  if (attempt < READ_BACK_ATTEMPTS - 1) {
1327
- await new Promise((resolve2) => setTimeout(resolve2, READ_BACK_DELAY_MS));
1533
+ await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
1328
1534
  }
1329
1535
  }
1330
1536
  return null;
@@ -1370,6 +1576,72 @@ function findLastAssistantReplyFor(messages, userMessageId) {
1370
1576
  }
1371
1577
  return lastOk ?? last;
1372
1578
  }
1579
+ function messageUsage(messages, userMessageId) {
1580
+ if (!messages || messages.length === 0) return null;
1581
+ const byParentAll = messages.filter(
1582
+ (m) => roleOf(m) === "assistant" && parentIdOf(m) === userMessageId
1583
+ );
1584
+ const byParentNonErrored = byParentAll.filter((m) => errorOf(m) == null);
1585
+ const byParent = byParentNonErrored.length > 0 ? byParentNonErrored : byParentAll;
1586
+ let correlated;
1587
+ if (byParent.length > 0) {
1588
+ correlated = byParent;
1589
+ } else {
1590
+ const reply = findAssistantReplyAfter(messages, userMessageId);
1591
+ correlated = reply ? [reply] : [];
1592
+ }
1593
+ if (correlated.length === 0) return null;
1594
+ let sawAnyUsage = false;
1595
+ let inputSum = 0;
1596
+ let outputSum = 0;
1597
+ let reasoningSum = 0;
1598
+ let cacheReadSum = 0;
1599
+ let cacheWriteSum = 0;
1600
+ let costSum = 0;
1601
+ let sawCost = false;
1602
+ let modelId = null;
1603
+ let providerId = null;
1604
+ for (const m of correlated) {
1605
+ const info = m.info;
1606
+ if (!info) continue;
1607
+ const tokens = info.tokens;
1608
+ if (tokens) {
1609
+ sawAnyUsage = true;
1610
+ inputSum += tokens.input ?? 0;
1611
+ outputSum += tokens.output ?? 0;
1612
+ reasoningSum += tokens.reasoning ?? 0;
1613
+ cacheReadSum += tokens.cache?.read ?? 0;
1614
+ cacheWriteSum += tokens.cache?.write ?? 0;
1615
+ }
1616
+ if (typeof info.cost === "number") {
1617
+ sawAnyUsage = true;
1618
+ sawCost = true;
1619
+ costSum += info.cost;
1620
+ }
1621
+ if (typeof info.modelID === "string") {
1622
+ sawAnyUsage = true;
1623
+ modelId = info.modelID;
1624
+ }
1625
+ if (typeof info.providerID === "string") {
1626
+ sawAnyUsage = true;
1627
+ providerId = info.providerID;
1628
+ }
1629
+ }
1630
+ if (!sawAnyUsage) return null;
1631
+ return {
1632
+ usage_provider_id: providerId,
1633
+ usage_model_id: modelId,
1634
+ usage_tokens_input: inputSum,
1635
+ usage_tokens_output: outputSum,
1636
+ usage_tokens_reasoning: reasoningSum,
1637
+ usage_tokens_cache_read: cacheReadSum,
1638
+ usage_tokens_cache_write: cacheWriteSum,
1639
+ // NULL means "OpenCode never reported a cost" (never inferred from
1640
+ // tokens) — distinct from a genuine 0-cost turn, which would set
1641
+ // `sawCost` true with `costSum === 0`.
1642
+ usage_cost_usd: sawCost ? costSum : null
1643
+ };
1644
+ }
1373
1645
  function messageRunState(messages, userMessageId) {
1374
1646
  if (!messages || messages.length === 0) return "unknown";
1375
1647
  const hasUser = messages.some((m) => idOf(m) === userMessageId);
@@ -1386,6 +1658,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
1386
1658
  const reply = findLastAssistantReplyFor(messages, userMessageId);
1387
1659
  return completedOf(reply) != null && finishOf(reply) === "tool-calls";
1388
1660
  }
1661
+ function isB2AbandonmentConfirmed(params) {
1662
+ return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
1663
+ }
1389
1664
  function messageError(messages, userMessageId) {
1390
1665
  const reply = findLastAssistantReplyFor(messages, userMessageId);
1391
1666
  const error2 = errorOf(reply);
@@ -1399,12 +1674,79 @@ function messageError(messages, userMessageId) {
1399
1674
  }
1400
1675
  return "The agent run failed.";
1401
1676
  }
1677
+ function messageFailure(messages, userMessageId) {
1678
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
1679
+ const error2 = errorOf(reply);
1680
+ if (error2 == null || typeof error2 !== "object") return null;
1681
+ const e = error2;
1682
+ const replyProviderId = reply?.info?.providerID ?? null;
1683
+ const replyModelId = reply?.info?.modelID ?? null;
1684
+ if (e.name === "ProviderAuthError") {
1685
+ const data = e.data;
1686
+ const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
1687
+ return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
1688
+ }
1689
+ if (e.name === "APIError") {
1690
+ const data = e.data;
1691
+ const statusCode = data?.statusCode;
1692
+ if (statusCode === 401 || statusCode === 403) {
1693
+ return {
1694
+ kind: "model_auth",
1695
+ providerId: replyProviderId,
1696
+ modelId: replyModelId,
1697
+ reason: "rejected"
1698
+ };
1699
+ }
1700
+ }
1701
+ return null;
1702
+ }
1703
+ function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
1704
+ if (classified != null) return classified;
1705
+ if (hasConfiguredProvider !== false) return null;
1706
+ return {
1707
+ kind: "model_auth",
1708
+ providerId: replyProviderId,
1709
+ modelId: replyModelId,
1710
+ reason: "missing"
1711
+ };
1712
+ }
1402
1713
  function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1403
1714
  if (!messages || messages.length === 0) return false;
1404
1715
  return messages.some(
1405
1716
  (m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
1406
1717
  );
1407
1718
  }
1719
+ async function hasAnyConfiguredProvider(port) {
1720
+ try {
1721
+ const res = await fetch(`${opencodeBase(port)}/config/providers`);
1722
+ if (!res.ok) {
1723
+ console.error(
1724
+ `[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
1725
+ );
1726
+ return null;
1727
+ }
1728
+ const body = await res.json();
1729
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
1730
+ console.error(
1731
+ `[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
1732
+ );
1733
+ return null;
1734
+ }
1735
+ const defaults2 = body.default;
1736
+ if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
1737
+ console.error(
1738
+ `[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
1739
+ );
1740
+ return null;
1741
+ }
1742
+ return Object.keys(defaults2).length > 0;
1743
+ } catch (err) {
1744
+ console.error(
1745
+ `[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
1746
+ );
1747
+ return null;
1748
+ }
1749
+ }
1408
1750
 
1409
1751
  // src/lib/opencode/session-cleanup.ts
1410
1752
  var DURATION_UNIT_MS = {
@@ -1563,10 +1905,11 @@ var StreamForwarder = class {
1563
1905
  * Abort every in-flight stream (e.g. on WebSocket close).
1564
1906
  */
1565
1907
  abortAll() {
1566
- for (const stream of this.inflight.values()) {
1908
+ for (const [sid, stream] of this.inflight.entries()) {
1567
1909
  try {
1568
1910
  stream.abort();
1569
- } catch {
1911
+ } catch (err) {
1912
+ log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
1570
1913
  }
1571
1914
  }
1572
1915
  this.inflight.clear();
@@ -1600,12 +1943,12 @@ var StreamForwarder = class {
1600
1943
  let endBody;
1601
1944
  if (has_body) {
1602
1945
  const chunks = [];
1603
- bodyPromise = new Promise((resolve2) => {
1946
+ bodyPromise = new Promise((resolve3) => {
1604
1947
  pushBody = (buf) => {
1605
1948
  chunks.push(buf);
1606
1949
  };
1607
1950
  endBody = () => {
1608
- resolve2(Buffer.concat(chunks));
1951
+ resolve3(Buffer.concat(chunks));
1609
1952
  };
1610
1953
  });
1611
1954
  }
@@ -1716,31 +2059,20 @@ function connectTunnel(options) {
1716
2059
  onConnected,
1717
2060
  onDisconnected,
1718
2061
  onError,
1719
- onRequest,
1720
2062
  onResponse,
1721
2063
  onInfo,
1722
2064
  onDrainPing
1723
2065
  } = options;
1724
2066
  const tunnelUrl = getTunnelUrlConfig();
1725
2067
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
1726
- return new Promise((resolve2, reject) => {
2068
+ return new Promise((resolve3, reject) => {
1727
2069
  const ws = new WebSocket2(url, {
1728
2070
  headers: {
1729
2071
  Authorization: authHeader
1730
2072
  }
1731
2073
  });
1732
- const streamStartTimes = /* @__PURE__ */ new Map();
1733
2074
  const forwarder = new StreamForwarder(ws, port, {
1734
- onOpen: (sid, method, path) => {
1735
- if (path === TUNNEL_DRAIN_PING_PATH) return;
1736
- streamStartTimes.set(sid, Date.now());
1737
- onRequest?.(method, path, sid);
1738
- },
1739
- onHead: (sid, status) => {
1740
- const startedAt = streamStartTimes.get(sid);
1741
- streamStartTimes.delete(sid);
1742
- onResponse?.(status, startedAt ? Date.now() - startedAt : 0, sid);
1743
- },
2075
+ onHead: () => onResponse?.(),
1744
2076
  onDrainPing: () => onDrainPing?.()
1745
2077
  });
1746
2078
  const connectionTimeout = setTimeout(() => {
@@ -1788,7 +2120,7 @@ function connectTunnel(options) {
1788
2120
  clearTimeout(connectionTimeout);
1789
2121
  const connectedAgentId = message.agent_id ?? agentId;
1790
2122
  onConnected?.(connectedAgentId);
1791
- resolve2({
2123
+ resolve3({
1792
2124
  ws,
1793
2125
  close: () => ws.close(1e3, "CLI shutdown")
1794
2126
  });
@@ -1816,7 +2148,6 @@ function connectTunnel(options) {
1816
2148
  ws.on("close", (code, reason) => {
1817
2149
  const reasonStr = reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
1818
2150
  forwarder.abortAll();
1819
- streamStartTimes.clear();
1820
2151
  onDisconnected?.(code, reasonStr);
1821
2152
  });
1822
2153
  });
@@ -1851,7 +2182,11 @@ var RunnerConnection = class {
1851
2182
  if (this.connection) {
1852
2183
  try {
1853
2184
  this.connection.close();
1854
- } catch {
2185
+ } catch (err) {
2186
+ log("error", "runner_connection_close_failed", {
2187
+ agent_id: this.resolvedAgentId,
2188
+ ...errorFields(err)
2189
+ });
1855
2190
  }
1856
2191
  this.connection = null;
1857
2192
  }
@@ -1903,6 +2238,416 @@ var RunnerConnection = class {
1903
2238
  }
1904
2239
  };
1905
2240
 
2241
+ // src/lib/tunnel/ready-marker.ts
2242
+ import { writeFileSync } from "fs";
2243
+ function writeTunnelReadyMarker(path, agentId) {
2244
+ try {
2245
+ writeFileSync(path, `${agentId}
2246
+ `);
2247
+ return { ok: true };
2248
+ } catch (error2) {
2249
+ return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
2250
+ }
2251
+ }
2252
+
2253
+ // src/lib/channels/driver.ts
2254
+ import { homedir } from "os";
2255
+
2256
+ // src/lib/file-push.ts
2257
+ import { randomUUID } from "crypto";
2258
+ import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
2259
+ import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
2260
+ var FILE_MODE = 384;
2261
+ var DIRECTORY_MODE = 448;
2262
+ async function writePushedFile(request) {
2263
+ const { requestedPath, content, allowedDirectories, homeDir } = request;
2264
+ const bytes = content.byteLength;
2265
+ if (allowedDirectories.length === 0) {
2266
+ return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
2267
+ path: requestedPath,
2268
+ bytes
2269
+ });
2270
+ }
2271
+ if (bytes > MAX_FILE_PUSH_BYTES) {
2272
+ return refuse(
2273
+ "file_too_large",
2274
+ `File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
2275
+ {
2276
+ path: requestedPath,
2277
+ bytes
2278
+ }
2279
+ );
2280
+ }
2281
+ const candidate = expandAndValidate(requestedPath, homeDir);
2282
+ if (candidate === null) {
2283
+ return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
2284
+ path: requestedPath,
2285
+ bytes
2286
+ });
2287
+ }
2288
+ try {
2289
+ const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
2290
+ dirname2(candidate)
2291
+ );
2292
+ const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
2293
+ const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
2294
+ if (allowedDirectory === null) {
2295
+ return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
2296
+ path: realTarget,
2297
+ bytes
2298
+ });
2299
+ }
2300
+ if (missingSegments.length > 0) {
2301
+ await createMissingDirectories(existingAncestor, missingSegments);
2302
+ const realParent = await realpath(dirname2(realTarget));
2303
+ if (realParent !== dirname2(realTarget) || !contains(allowedDirectory, realTarget)) {
2304
+ return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
2305
+ path: realTarget,
2306
+ bytes,
2307
+ reason: "parent_changed_after_create"
2308
+ });
2309
+ }
2310
+ }
2311
+ await writeAtomically(realTarget, content);
2312
+ log("info", "file_push_written", { path: realTarget, bytes });
2313
+ return { ok: true, path: realTarget };
2314
+ } catch (err) {
2315
+ const errno = err.code ?? "UNKNOWN";
2316
+ return refuse("write_failed", `The runner could not write the file (${errno}).`, {
2317
+ path: candidate,
2318
+ bytes,
2319
+ errno,
2320
+ ...errorFields(err)
2321
+ });
2322
+ }
2323
+ }
2324
+ function expandAndValidate(requestedPath, homeDir) {
2325
+ if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
2326
+ return null;
2327
+ }
2328
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join(homeDir, requestedPath.slice(2)) : requestedPath;
2329
+ if (expanded.split(/[/\\]/).includes("..")) {
2330
+ return null;
2331
+ }
2332
+ if (!isAbsolute(expanded)) {
2333
+ return null;
2334
+ }
2335
+ const candidate = resolve2(expanded);
2336
+ const name = basename(candidate);
2337
+ return name === "" || name === "." || name === ".." ? null : candidate;
2338
+ }
2339
+ async function resolveNearestExistingAncestor(directory) {
2340
+ const missingSegments = [];
2341
+ let current = directory;
2342
+ for (; ; ) {
2343
+ try {
2344
+ return { existingAncestor: await realpath(current), missingSegments };
2345
+ } catch (err) {
2346
+ const parent = dirname2(current);
2347
+ if (err.code !== "ENOENT" || parent === current) {
2348
+ throw err;
2349
+ }
2350
+ missingSegments.unshift(basename(current));
2351
+ current = parent;
2352
+ }
2353
+ }
2354
+ }
2355
+ async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
2356
+ for (const directory of allowedDirectories) {
2357
+ if (!isAbsolute(directory)) {
2358
+ log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
2359
+ continue;
2360
+ }
2361
+ const realDirectory = await realpathCreatingIfMissing(directory);
2362
+ if (realDirectory !== null && contains(realDirectory, realTarget)) {
2363
+ return realDirectory;
2364
+ }
2365
+ }
2366
+ return null;
2367
+ }
2368
+ async function realpathCreatingIfMissing(directory) {
2369
+ try {
2370
+ return await realpath(directory);
2371
+ } catch (err) {
2372
+ if (err.code !== "ENOENT") {
2373
+ log("warn", "file_push_allowed_directory_skipped", {
2374
+ directory,
2375
+ reason: "unresolvable",
2376
+ ...errorFields(err)
2377
+ });
2378
+ return null;
2379
+ }
2380
+ }
2381
+ try {
2382
+ await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
2383
+ await chmod(directory, DIRECTORY_MODE);
2384
+ return await realpath(directory);
2385
+ } catch (err) {
2386
+ log("warn", "file_push_allowed_directory_skipped", {
2387
+ directory,
2388
+ reason: "create_failed",
2389
+ ...errorFields(err)
2390
+ });
2391
+ return null;
2392
+ }
2393
+ }
2394
+ function contains(realDirectory, realTarget) {
2395
+ const rel = relative(realDirectory, realTarget);
2396
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
2397
+ }
2398
+ async function createMissingDirectories(existingAncestor, missingSegments) {
2399
+ let current = existingAncestor;
2400
+ for (const segment of missingSegments) {
2401
+ current = join(current, segment);
2402
+ await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
2403
+ await chmod(current, DIRECTORY_MODE);
2404
+ }
2405
+ }
2406
+ async function writeAtomically(realTarget, content) {
2407
+ const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2408
+ let handle;
2409
+ try {
2410
+ handle = await open2(temporaryPath, "wx", FILE_MODE);
2411
+ await handle.writeFile(content);
2412
+ await handle.chmod(FILE_MODE);
2413
+ await handle.close();
2414
+ handle = void 0;
2415
+ await rename(temporaryPath, realTarget);
2416
+ } catch (err) {
2417
+ await discardTemporaryFile(temporaryPath, handle);
2418
+ throw err;
2419
+ }
2420
+ }
2421
+ async function discardTemporaryFile(temporaryPath, handle) {
2422
+ try {
2423
+ await handle?.close();
2424
+ } catch (err) {
2425
+ log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
2426
+ }
2427
+ try {
2428
+ await unlink(temporaryPath);
2429
+ } catch (err) {
2430
+ const errno = err.code;
2431
+ if (errno !== "ENOENT" && errno !== "ENOTDIR") {
2432
+ log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
2433
+ }
2434
+ }
2435
+ }
2436
+ function refuse(code, message, fields) {
2437
+ log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
2438
+ return { ok: false, code, message };
2439
+ }
2440
+
2441
+ // src/lib/runner-file-sync.ts
2442
+ var MAX_ACK_ATTEMPTS = 5;
2443
+ async function syncPendingRunnerFiles(options) {
2444
+ const pending = await listPendingFiles(options);
2445
+ const pendingIds = new Set(pending.map((file) => file.id));
2446
+ for (const id of options.ackFailures.keys()) {
2447
+ if (!pendingIds.has(id)) options.ackFailures.delete(id);
2448
+ }
2449
+ if (pending.length === 0) return 0;
2450
+ options.log({
2451
+ level: "info",
2452
+ message: `Runner file sync: ${pending.length} file(s) queued for this runner`
2453
+ });
2454
+ let applied = 0;
2455
+ for (const file of pending) {
2456
+ if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
2457
+ if (await applyOne(options, file)) applied += 1;
2458
+ }
2459
+ return applied;
2460
+ }
2461
+ async function listPendingFiles(options) {
2462
+ let res;
2463
+ try {
2464
+ res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
2465
+ headers: { Authorization: options.getAuthHeader() }
2466
+ });
2467
+ } catch (err) {
2468
+ options.log({
2469
+ level: "warn",
2470
+ message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
2471
+ });
2472
+ return [];
2473
+ }
2474
+ if (!res.ok) {
2475
+ options.log({
2476
+ level: res.status === 404 ? "debug" : "warn",
2477
+ message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
2478
+ });
2479
+ return [];
2480
+ }
2481
+ let body;
2482
+ try {
2483
+ body = await res.json();
2484
+ } catch (err) {
2485
+ options.log({
2486
+ level: "warn",
2487
+ message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
2488
+ });
2489
+ return [];
2490
+ }
2491
+ if (!Array.isArray(body)) {
2492
+ options.log({
2493
+ level: "warn",
2494
+ message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
2495
+ });
2496
+ return [];
2497
+ }
2498
+ const files = [];
2499
+ for (const entry of body) {
2500
+ const file = asPendingFile(entry);
2501
+ if (file === null) {
2502
+ options.log({
2503
+ level: "warn",
2504
+ message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
2505
+ });
2506
+ continue;
2507
+ }
2508
+ files.push(file);
2509
+ }
2510
+ return files;
2511
+ }
2512
+ function asPendingFile(entry) {
2513
+ if (entry === null || typeof entry !== "object") return null;
2514
+ const { id, path, size } = entry;
2515
+ if (typeof id !== "string" || id === "") return null;
2516
+ if (typeof path !== "string" || path === "") return null;
2517
+ if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
2518
+ return { id, path, size };
2519
+ }
2520
+ async function applyOne(options, file) {
2521
+ const label = `${file.id.slice(0, 8)} (${file.path})`;
2522
+ if (options.allowedDirectories.length === 0) {
2523
+ options.log({
2524
+ level: "warn",
2525
+ message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
2526
+ });
2527
+ await ack(options, file, "rejected", "file_sync_disabled");
2528
+ return false;
2529
+ }
2530
+ if (file.size > MAX_FILE_PUSH_BYTES) {
2531
+ options.log({
2532
+ level: "warn",
2533
+ message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
2534
+ });
2535
+ await ack(options, file, "rejected", "file_too_large");
2536
+ return false;
2537
+ }
2538
+ const download = await downloadContent(options, file, label);
2539
+ if (!download.ok) {
2540
+ if (download.terminal) await ack(options, file, "rejected", download.code);
2541
+ return false;
2542
+ }
2543
+ let outcome;
2544
+ try {
2545
+ outcome = await writePushedFile({
2546
+ requestedPath: file.path,
2547
+ content: download.content,
2548
+ allowedDirectories: options.allowedDirectories,
2549
+ homeDir: options.homeDir
2550
+ });
2551
+ } catch (err) {
2552
+ options.log({
2553
+ level: "error",
2554
+ message: `Runner file ${label} could not be written: ${describe(err)}`
2555
+ });
2556
+ await ack(options, file, "rejected", "write_failed");
2557
+ return false;
2558
+ }
2559
+ if (!outcome.ok) {
2560
+ options.log({
2561
+ level: "warn",
2562
+ message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
2563
+ });
2564
+ await ack(options, file, "rejected", outcome.code);
2565
+ return false;
2566
+ }
2567
+ options.log({
2568
+ level: "info",
2569
+ message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
2570
+ });
2571
+ await ack(options, file, "applied");
2572
+ return true;
2573
+ }
2574
+ function durableDownloadCode(status) {
2575
+ return status === 413 ? "file_too_large" : "write_failed";
2576
+ }
2577
+ async function downloadContent(options, file, label) {
2578
+ try {
2579
+ const res = await options.fetchImpl(
2580
+ `${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
2581
+ { headers: { Authorization: options.getAuthHeader() } }
2582
+ );
2583
+ if (!res.ok) {
2584
+ const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
2585
+ if (!terminal) {
2586
+ options.log({
2587
+ level: "warn",
2588
+ message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
2589
+ });
2590
+ return { ok: false, terminal: false };
2591
+ }
2592
+ const code = durableDownloadCode(res.status);
2593
+ options.log({
2594
+ level: "error",
2595
+ message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
2596
+ });
2597
+ return { ok: false, terminal: true, code };
2598
+ }
2599
+ return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
2600
+ } catch (err) {
2601
+ options.log({
2602
+ level: "warn",
2603
+ message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
2604
+ });
2605
+ return { ok: false, terminal: false };
2606
+ }
2607
+ }
2608
+ async function ack(options, file, status, reason) {
2609
+ const outcome = `${status}${reason ? ` (${reason})` : ""}`;
2610
+ try {
2611
+ const res = await options.fetchImpl(
2612
+ `${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
2613
+ {
2614
+ method: "POST",
2615
+ headers: {
2616
+ Authorization: options.getAuthHeader(),
2617
+ "Content-Type": "application/json"
2618
+ },
2619
+ body: JSON.stringify(reason ? { status, reason } : { status })
2620
+ }
2621
+ );
2622
+ if (!res.ok) {
2623
+ recordAckFailure(
2624
+ options,
2625
+ file,
2626
+ `Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
2627
+ );
2628
+ return;
2629
+ }
2630
+ options.ackFailures.delete(file.id);
2631
+ } catch (err) {
2632
+ recordAckFailure(
2633
+ options,
2634
+ file,
2635
+ `Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
2636
+ );
2637
+ }
2638
+ }
2639
+ function recordAckFailure(options, file, what) {
2640
+ const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
2641
+ options.ackFailures.set(file.id, attempts);
2642
+ options.log({
2643
+ level: "error",
2644
+ 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})`
2645
+ });
2646
+ }
2647
+ function describe(err) {
2648
+ return err instanceof Error ? err.message : String(err);
2649
+ }
2650
+
1906
2651
  // src/lib/channels/driver.ts
1907
2652
  function messageIdOf(m) {
1908
2653
  if (!m || typeof m !== "object") return void 0;
@@ -1931,7 +2676,10 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
1931
2676
  var DEFAULT_STUCK_QUEUED_MS = 6e4;
1932
2677
  var HEARTBEAT_MS = 6e4;
1933
2678
  var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
2679
+ var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
2680
+ var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
1934
2681
  var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
2682
+ var MAX_SUPERSEDED_CONVERSATIONS = 256;
1935
2683
  var ChannelAuthError = class extends Error {
1936
2684
  constructor(message) {
1937
2685
  super(message);
@@ -1954,7 +2702,7 @@ function backoffDelay(attempt, policy) {
1954
2702
  function isRetryableStatus(status) {
1955
2703
  return status === 429 || status >= 500 && status <= 599;
1956
2704
  }
1957
- var ChannelDriver = class {
2705
+ var ChannelDriver = class _ChannelDriver {
1958
2706
  agentId;
1959
2707
  port;
1960
2708
  apiUrl;
@@ -1968,8 +2716,38 @@ var ChannelDriver = class {
1968
2716
  pausedMaxWaitMs;
1969
2717
  stuckQueuedMs;
1970
2718
  now;
2719
+ fileSyncDirectories;
2720
+ homeDir;
1971
2721
  /** Cache of conversationId → opencode sessionId. */
1972
2722
  sessions = /* @__PURE__ */ new Map();
2723
+ /**
2724
+ * conversationId → the opencode session this runner has ABANDONED as that
2725
+ * conversation's binding (#553), after a genuine (`sessionExists === true`)
2726
+ * dispatch failure: the session still exists but is wedged, so #485's self-heal
2727
+ * must bind a fresh one.
2728
+ *
2729
+ * Dropping the local binding + clearing the server row is not enough on its own:
2730
+ * a SIBLING message dispatched earlier in the same drain is still in-flight under
2731
+ * the same session, and its watcher's routine status writes carry
2732
+ * `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
2733
+ * and `ensureSession`'s persisted-id fallback then reuses it, defeating the
2734
+ * self-heal. This map makes the runner authoritative instead of racing those
2735
+ * writes: *`ensureSession` never reuses an abandoned id for that conversation,
2736
+ * whatever the server row says* — which holds even when the resurrecting write
2737
+ * is one we deliberately keep (see `markDone`).
2738
+ *
2739
+ * Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
2740
+ * one conversation hold ONE entry (the newest abandonment replaces the older), and
2741
+ * hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
2742
+ * NEWEST abandoned id per conversation is guarded: after a second abandonment a
2743
+ * late sibling of the FIRST session can write that id back and `ensureSession`
2744
+ * will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
2745
+ * NOT dropped when the session's watcher tears down: `markDone` still writes the
2746
+ * abandoned id back (it must, or the reply is lost), so the guard has to outlive
2747
+ * the turn that resurrects it. In-memory only — a restart forgets it, at the same
2748
+ * bounded cost.
2749
+ */
2750
+ supersededSessions = /* @__PURE__ */ new Map();
1973
2751
  /**
1974
2752
  * Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
1975
2753
  * longer idempotent (no caller-supplied `messageID`), and its read-back picks
@@ -2079,9 +2857,12 @@ var ChannelDriver = class {
2079
2857
  sessionParents = /* @__PURE__ */ new Map();
2080
2858
  /**
2081
2859
  * Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
2082
- * NON-EMPTY name is stored (terminal — a real session name won't later un-name),
2083
- * so we do NOT re-GET `/session/:id` every tick. A missing entry = not yet
2084
- * resolved OR resolved-but-still-empty re-fetch on next need, since OpenCode
2860
+ * NON-EMPTY, non-placeholder name is stored (terminal — a real session name
2861
+ * won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
2862
+ * excludes OpenCode's synchronous default title (see
2863
+ * `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
2864
+ * as an empty title so it never latches. A missing entry = not yet resolved OR
2865
+ * resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
2085
2866
  * names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
2086
2867
  * the watcher completion path AND the restart-recovery re-adopt path (which has
2087
2868
  * no watcher) can resolve the title.
@@ -2089,6 +2870,24 @@ var ChannelDriver = class {
2089
2870
  sessionTitles = /* @__PURE__ */ new Map();
2090
2871
  /** Serialises drains so a reconnect during a drain doesn't double-process. */
2091
2872
  draining = false;
2873
+ /**
2874
+ * Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
2875
+ * drain ping don't download, write and ack the same file twice.
2876
+ */
2877
+ syncingFiles = false;
2878
+ /**
2879
+ * Consecutive failed acks per pending file (#559). Lives on the driver so it
2880
+ * survives across drains — without it, a file whose ack keeps failing is
2881
+ * re-downloaded and re-written every ~2s until the server expires it.
2882
+ */
2883
+ fileAckFailures = /* @__PURE__ */ new Map();
2884
+ /**
2885
+ * Monotonic count of files this runner has pulled and written (#559). Only
2886
+ * ever increases, so `run.ts` detects work by comparing it against the value
2887
+ * it saw on the previous cycle — including work that landed mid-sleep, the
2888
+ * same trick `lastProxiedActivityAt` uses.
2889
+ */
2890
+ appliedFileCount = 0;
2092
2891
  /**
2093
2892
  * The currently-executing `drainPending()` promise, or null when idle. Lets a
2094
2893
  * graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
@@ -2119,6 +2918,8 @@ var ChannelDriver = class {
2119
2918
  this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
2120
2919
  this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
2121
2920
  this.now = config2.now ?? (() => Date.now());
2921
+ this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
2922
+ this.homeDir = config2.homeDir ?? homedir();
2122
2923
  }
2123
2924
  /** The IPv4-loopback base URL for the local `opencode serve`. */
2124
2925
  get opencodeBase() {
@@ -2146,6 +2947,47 @@ var ChannelDriver = class {
2146
2947
  );
2147
2948
  return run2;
2148
2949
  }
2950
+ /**
2951
+ * Pull-and-apply any files Evident has queued for this runner (#559), riding
2952
+ * the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
2953
+ * and drain ping that call `drainPending()`. There is deliberately no channel,
2954
+ * control frame or poll loop of its own: worst-case latency is one poll tick.
2955
+ *
2956
+ * NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
2957
+ * cost a conversation turn. Failures are logged and either acked as a terminal
2958
+ * outcome or left pending for the next drain (see `runner-file-sync.ts`).
2959
+ *
2960
+ * Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
2961
+ *
2962
+ * @returns the number of files written to disk.
2963
+ */
2964
+ async syncPendingFiles() {
2965
+ if (this.stopped) return 0;
2966
+ if (this.syncingFiles) return 0;
2967
+ this.syncingFiles = true;
2968
+ try {
2969
+ const applied = await syncPendingRunnerFiles({
2970
+ agentId: this.agentId,
2971
+ apiUrl: this.apiUrl,
2972
+ getAuthHeader: this.getAuthHeader,
2973
+ fetchImpl: this.fetchImpl,
2974
+ allowedDirectories: this.fileSyncDirectories,
2975
+ homeDir: this.homeDir,
2976
+ ackFailures: this.fileAckFailures,
2977
+ log: this.log
2978
+ });
2979
+ this.appliedFileCount += applied;
2980
+ return applied;
2981
+ } catch (err) {
2982
+ this.log({
2983
+ level: "error",
2984
+ message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
2985
+ });
2986
+ return 0;
2987
+ } finally {
2988
+ this.syncingFiles = false;
2989
+ }
2990
+ }
2149
2991
  async runDrain() {
2150
2992
  let dispatched = 0;
2151
2993
  try {
@@ -2179,6 +3021,28 @@ var ChannelDriver = class {
2179
3021
  }
2180
3022
  return false;
2181
3023
  }
3024
+ /**
3025
+ * File-pull work, for `run.ts`'s idle accounting (#559).
3026
+ *
3027
+ * Pulling a file is real work that `drainPending()` knows nothing about, so
3028
+ * without this a near-idle runner counts a credential pull as an empty tick
3029
+ * and `--idle-timeout` can `process.exit` mid-pull — leaving a
3030
+ * `.evident-push-*.tmp` behind — or immediately after the write, before the
3031
+ * browser has run the authorize/callback that activates it (the user then sees
3032
+ * `saved_not_activated` for a runner that was fine).
3033
+ *
3034
+ * Two signals because one cannot cover both cases: `inFlight` is the pull
3035
+ * happening RIGHT NOW (it may outlive the tick that started it), and
3036
+ * `appliedFiles` is monotonic so a pull that started AND finished between two
3037
+ * idle checks still shows up as an advance.
3038
+ *
3039
+ * CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
3040
+ * the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
3041
+ * samples afterwards reads `true` every single cycle and can never idle out.
3042
+ */
3043
+ fileSyncActivity() {
3044
+ return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
3045
+ }
2182
3046
  /**
2183
3047
  * OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
2184
3048
  * exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
@@ -2240,7 +3104,7 @@ var ChannelDriver = class {
2240
3104
  await this.sleep(step);
2241
3105
  }
2242
3106
  }
2243
- while (this.hasInFlightWatchers()) {
3107
+ while (this.hasInFlightWatchers() || this.syncingFiles) {
2244
3108
  if (this.now() >= deadline) return false;
2245
3109
  await this.sleep(step);
2246
3110
  }
@@ -2275,10 +3139,15 @@ var ChannelDriver = class {
2275
3139
  * @returns the count of messages NEWLY dispatched (not already in-flight).
2276
3140
  */
2277
3141
  async processConversation(conv) {
2278
- const sessionId = await this.ensureSession(conv);
3142
+ const { sessionId, refusedSessionId } = await this.ensureSession(conv);
2279
3143
  const messages = await this.getPendingMessages(conv.id);
2280
3144
  let dispatched = 0;
2281
3145
  let skippedAlreadyDispatched = 0;
3146
+ if (refusedSessionId && messages.length > 0) {
3147
+ void this.postSignal(conv.id, messages[0].id, "session_superseded", {
3148
+ superseded_session_id: refusedSessionId
3149
+ });
3150
+ }
2282
3151
  for (const message of messages) {
2283
3152
  if (this.stopped) break;
2284
3153
  if (this.dispatched.has(message.id)) {
@@ -2305,7 +3174,8 @@ var ChannelDriver = class {
2305
3174
  } catch (err) {
2306
3175
  if (err instanceof ChannelAuthError) throw err;
2307
3176
  this.dispatched.delete(message.id);
2308
- if (await sessionExists(this.port, sessionId) === false) {
3177
+ const exists = await sessionExists(this.port, sessionId);
3178
+ if (exists === false) {
2309
3179
  this.sessions.delete(conv.id);
2310
3180
  this.log({
2311
3181
  level: "warn",
@@ -2315,15 +3185,39 @@ var ChannelDriver = class {
2315
3185
  });
2316
3186
  break;
2317
3187
  }
2318
- await this.markFailed(conv.id, message.id).catch(() => {
3188
+ if (exists === null) {
3189
+ this.log({
3190
+ level: "warn",
3191
+ 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.`,
3192
+ conversation_id: conv.id,
3193
+ message_id: message.id
3194
+ });
3195
+ break;
3196
+ }
3197
+ const errorMessage = err instanceof Error ? err.message : String(err);
3198
+ this.sessions.delete(conv.id);
3199
+ this.supersede(conv.id, sessionId);
3200
+ this.log({
3201
+ level: "warn",
3202
+ 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.`,
3203
+ conversation_id: conv.id,
3204
+ message_id: message.id
3205
+ });
3206
+ await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
3207
+ this.log({
3208
+ level: "warn",
3209
+ 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)}`,
3210
+ conversation_id: conv.id,
3211
+ message_id: message.id
3212
+ });
2319
3213
  });
2320
3214
  this.log({
2321
3215
  level: "error",
2322
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${err instanceof Error ? err.message : String(err)}`,
3216
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
2323
3217
  conversation_id: conv.id,
2324
3218
  message_id: message.id
2325
3219
  });
2326
- continue;
3220
+ break;
2327
3221
  }
2328
3222
  if (opencodeMessageId === null) {
2329
3223
  this.log({
@@ -2349,8 +3243,42 @@ var ChannelDriver = class {
2349
3243
  this.ensureWatcherRunning(sessionId);
2350
3244
  return dispatched;
2351
3245
  }
3246
+ /**
3247
+ * Record that `sessionId` is no longer a valid binding for `conversationId`
3248
+ * (#553). Keyed by conversation and hard-capped, so it cannot grow with the
3249
+ * number of failures — see the `supersededSessions` field doc.
3250
+ */
3251
+ supersede(conversationId, sessionId) {
3252
+ this.supersededSessions.delete(conversationId);
3253
+ this.supersededSessions.set(conversationId, sessionId);
3254
+ while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
3255
+ const oldest = this.supersededSessions.keys().next().value;
3256
+ if (oldest === void 0) return;
3257
+ this.supersededSessions.delete(oldest);
3258
+ }
3259
+ }
3260
+ /** Whether `sessionId` is the session this conversation has abandoned (#553). */
3261
+ isSuperseded(conversationId, sessionId) {
3262
+ return this.supersededSessions.get(conversationId) === sessionId;
3263
+ }
3264
+ /**
3265
+ * Resolve the opencode session to run this conversation's turns in.
3266
+ *
3267
+ * `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
3268
+ * binding was an id this runner had abandoned, so a resurrection genuinely
3269
+ * happened and a fresh session was bound instead. The caller reports it.
3270
+ */
2352
3271
  async ensureSession(conv) {
2353
3272
  const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
3273
+ if (bound && this.isSuperseded(conv.id, bound)) {
3274
+ this.log({
3275
+ level: "warn",
3276
+ 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.`,
3277
+ conversation_id: conv.id
3278
+ });
3279
+ this.sessions.delete(conv.id);
3280
+ return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
3281
+ }
2354
3282
  if (bound) {
2355
3283
  const exists = await sessionExists(this.port, bound);
2356
3284
  if (exists === false) {
@@ -2360,12 +3288,12 @@ var ChannelDriver = class {
2360
3288
  conversation_id: conv.id
2361
3289
  });
2362
3290
  this.sessions.delete(conv.id);
2363
- return this.createAndBindSession(conv.id);
3291
+ return { sessionId: await this.createAndBindSession(conv.id) };
2364
3292
  }
2365
3293
  this.sessions.set(conv.id, bound);
2366
- return bound;
3294
+ return { sessionId: bound };
2367
3295
  }
2368
- return this.createAndBindSession(conv.id);
3296
+ return { sessionId: await this.createAndBindSession(conv.id) };
2369
3297
  }
2370
3298
  /**
2371
3299
  * Create a fresh OpenCode session for a conversation, cache the binding, and
@@ -2445,7 +3373,7 @@ var ChannelDriver = class {
2445
3373
  }
2446
3374
  /**
2447
3375
  * Fetch ONE inbound image's bytes through Evident's WI-6 endpoint
2448
- * (`GET {apiUrl}/agents/{agentId}/attachments/{messageId}/{index}`) using the
3376
+ * (`GET {apiUrl}/runners/{agentId}/attachments/{messageId}/{index}`) using the
2449
3377
  * existing authenticated fetch, and base64-encode into a
2450
3378
  * `data:<mime>;base64,<…>` URL for the opencode `file` part's `url`.
2451
3379
  *
@@ -2453,15 +3381,38 @@ var ChannelDriver = class {
2453
3381
  * (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
2454
3382
  * (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
2455
3383
  * OMITS that one image and the text turn still sends — NEVER throws the turn.
2456
- * Failures are logged with context (no silent swallow).
3384
+ * A 404 body carrying `{ reason: 'needs_reauth' }` (#547 the server CONFIRMED
3385
+ * a Slack `files:read` scope problem via `files.info`) instead resolves the
3386
+ * `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
3387
+ * user to reconnect Slack instead of a generic "unavailable". Failures are
3388
+ * logged with context (no silent swallow).
2457
3389
  */
2458
3390
  async fetchAttachmentDataUrl(messageId, index, mime) {
2459
3391
  try {
2460
3392
  const res = await this.fetchImpl(
2461
- `${this.apiUrl}/agents/${this.agentId}/attachments/${messageId}/${index}`,
3393
+ `${this.apiUrl}/runners/${this.agentId}/attachments/${messageId}/${index}`,
2462
3394
  { headers: { Authorization: this.getAuthHeader() } }
2463
3395
  );
2464
3396
  if (!res.ok) {
3397
+ let reason;
3398
+ try {
3399
+ const body = await res.json();
3400
+ if (body && typeof body.reason === "string") reason = body.reason;
3401
+ } catch (parseErr) {
3402
+ this.log({
3403
+ level: "debug",
3404
+ 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`,
3405
+ message_id: messageId
3406
+ });
3407
+ }
3408
+ if (reason === "needs_reauth") {
3409
+ this.log({
3410
+ level: "error",
3411
+ 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)`,
3412
+ message_id: messageId
3413
+ });
3414
+ return { needsReauth: true };
3415
+ }
2465
3416
  this.log({
2466
3417
  level: "error",
2467
3418
  message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
@@ -2501,6 +3452,9 @@ var ChannelDriver = class {
2501
3452
  if (this.attachmentsSkippedSignalled.has(messageId)) return;
2502
3453
  this.attachmentsSkippedSignalled.add(messageId);
2503
3454
  const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
3455
+ const failedReason = outcomes.some(
3456
+ (o) => o.status === "failed" && o.reason === "needs_reauth"
3457
+ ) ? "needs_reauth" : void 0;
2504
3458
  this.log({
2505
3459
  level: "info",
2506
3460
  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`,
@@ -2510,7 +3464,8 @@ var ChannelDriver = class {
2510
3464
  void this.postSignal(conversationId, messageId, "attachments_skipped", {
2511
3465
  skipped,
2512
3466
  failed,
2513
- ...skipped > 0 ? { skipped_reason: skippedReason } : {}
3467
+ ...skipped > 0 ? { skipped_reason: skippedReason } : {},
3468
+ ...failedReason ? { failed_reason: failedReason } : {}
2514
3469
  });
2515
3470
  }
2516
3471
  /** Register a freshly-dispatched message with its session's watcher state. */
@@ -2541,12 +3496,17 @@ var ChannelDriver = class {
2541
3496
  stuckReported: false,
2542
3497
  lastAliveAt: 0,
2543
3498
  aliveInFlight: false,
3499
+ titleSynced: false,
3500
+ titleSyncInFlight: false,
2544
3501
  awaitingHumanLatched: false,
2545
3502
  pausedOnQuestion: false,
2546
3503
  pausedOnPermission: false,
2547
3504
  pausedClearConfirmed: false,
2548
3505
  pausedInFlight: false,
2549
- deliveryDeadlineAnchored: false
3506
+ deliveryDeadlineAnchored: false,
3507
+ b2PinnedSinceMs: 0,
3508
+ b2LastDescendantCheckMs: 0,
3509
+ b2AbandonedSignalled: false
2550
3510
  });
2551
3511
  }
2552
3512
  /**
@@ -2614,12 +3574,17 @@ var ChannelDriver = class {
2614
3574
  // with no extra `re_adopted` signal needed (folds old WI-6).
2615
3575
  lastAliveAt: 0,
2616
3576
  aliveInFlight: false,
3577
+ titleSynced: false,
3578
+ titleSyncInFlight: false,
2617
3579
  awaitingHumanLatched: false,
2618
3580
  pausedOnQuestion: false,
2619
3581
  pausedOnPermission: false,
2620
3582
  pausedClearConfirmed: false,
2621
3583
  pausedInFlight: false,
2622
- deliveryDeadlineAnchored: false
3584
+ deliveryDeadlineAnchored: false,
3585
+ b2PinnedSinceMs: 0,
3586
+ b2LastDescendantCheckMs: 0,
3587
+ b2AbandonedSignalled: false
2623
3588
  });
2624
3589
  }
2625
3590
  /**
@@ -2757,80 +3722,31 @@ var ChannelDriver = class {
2757
3722
  conv.id,
2758
3723
  inFlight.evidentMessageId,
2759
3724
  sessionId,
2760
- inFlight.opencodeMessageId,
2761
- title
2762
- );
2763
- } catch (err) {
2764
- if (err instanceof ChannelAuthError) throw err;
2765
- this.log({
2766
- level: "warn",
2767
- message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2768
- conversation_id: conv.id,
2769
- message_id: inFlight.evidentMessageId
2770
- });
2771
- return;
2772
- }
2773
- inFlight.started = true;
2774
- if (!claimed) {
2775
- this.log({
2776
- level: "debug",
2777
- message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
2778
- conversation_id: conv.id,
2779
- message_id: inFlight.evidentMessageId
2780
- });
2781
- }
2782
- }
2783
- if (state === "done") {
2784
- this.anchorDeliveryDeadline(inFlight);
2785
- if (!inFlight.done) {
2786
- this.log({
2787
- level: "info",
2788
- message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
2789
- conversation_id: conv.id,
2790
- message_id: inFlight.evidentMessageId
2791
- });
2792
- const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
2793
- try {
2794
- await this.markDone(
2795
- conv.id,
2796
- inFlight.evidentMessageId,
2797
- sessionId,
2798
- inFlight.opencodeMessageId,
2799
- title
2800
- );
2801
- } catch (err) {
2802
- if (err instanceof ChannelAuthError) throw err;
2803
- if (err instanceof ChannelTerminalError) {
2804
- this.log({
2805
- level: "warn",
2806
- message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
2807
- conversation_id: conv.id,
2808
- message_id: inFlight.evidentMessageId
2809
- });
2810
- this.removeInFlight(watcher, inFlight.evidentMessageId);
2811
- return;
2812
- }
2813
- if (this.now() >= inFlight.deadline) {
2814
- this.log({
2815
- level: "warn",
2816
- 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)}`,
2817
- conversation_id: conv.id,
2818
- message_id: inFlight.evidentMessageId
2819
- });
2820
- this.removeInFlight(watcher, inFlight.evidentMessageId);
2821
- return;
2822
- }
2823
- this.log({
2824
- level: "warn",
2825
- message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2826
- conversation_id: conv.id,
2827
- message_id: inFlight.evidentMessageId
2828
- });
2829
- return;
2830
- }
2831
- inFlight.done = true;
3725
+ inFlight.opencodeMessageId,
3726
+ title
3727
+ );
3728
+ } catch (err) {
3729
+ if (err instanceof ChannelAuthError) throw err;
3730
+ this.log({
3731
+ level: "warn",
3732
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
3733
+ conversation_id: conv.id,
3734
+ message_id: inFlight.evidentMessageId
3735
+ });
3736
+ return;
2832
3737
  }
2833
- this.removeInFlight(watcher, inFlight.evidentMessageId);
3738
+ inFlight.started = true;
3739
+ if (!claimed) {
3740
+ this.log({
3741
+ level: "debug",
3742
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
3743
+ conversation_id: conv.id,
3744
+ message_id: inFlight.evidentMessageId
3745
+ });
3746
+ }
3747
+ }
3748
+ if (state === "done") {
3749
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
2834
3750
  return;
2835
3751
  }
2836
3752
  if (state === "failed") {
@@ -2843,8 +3759,17 @@ var ChannelDriver = class {
2843
3759
  conversation_id: conv.id,
2844
3760
  message_id: inFlight.evidentMessageId
2845
3761
  });
3762
+ const usage = messageUsage(messages, inFlight.opencodeMessageId);
3763
+ const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
2846
3764
  try {
2847
- await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2);
3765
+ await this.markFailed(
3766
+ conv.id,
3767
+ inFlight.evidentMessageId,
3768
+ sessionId,
3769
+ error2,
3770
+ usage,
3771
+ failure
3772
+ );
2848
3773
  } catch (err) {
2849
3774
  if (err instanceof ChannelAuthError) throw err;
2850
3775
  if (err instanceof ChannelTerminalError) {
@@ -2889,6 +3814,44 @@ var ChannelDriver = class {
2889
3814
  });
2890
3815
  }
2891
3816
  const activelyRunning = state === "running" && !awaitingHuman;
3817
+ const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
3818
+ const snapshotReadable = messages != null && messages.length > 0;
3819
+ if (!pinnedNow) {
3820
+ if (snapshotReadable) {
3821
+ inFlight.b2PinnedSinceMs = 0;
3822
+ inFlight.b2LastDescendantCheckMs = 0;
3823
+ inFlight.b2AbandonedSignalled = false;
3824
+ }
3825
+ } else {
3826
+ if (inFlight.b2AbandonedSignalled) {
3827
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
3828
+ return;
3829
+ }
3830
+ if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
3831
+ const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
3832
+ if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
3833
+ inFlight.b2LastDescendantCheckMs = this.now();
3834
+ const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
3835
+ if (isB2AbandonmentConfirmed({
3836
+ pinnedForMs,
3837
+ minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
3838
+ descendantOngoing
3839
+ })) {
3840
+ inFlight.b2AbandonedSignalled = true;
3841
+ this.log({
3842
+ level: "warn",
3843
+ 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`,
3844
+ conversation_id: conv.id,
3845
+ message_id: id
3846
+ });
3847
+ void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
3848
+ watched_for_ms: pinnedForMs
3849
+ });
3850
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
3851
+ return;
3852
+ }
3853
+ }
3854
+ }
2892
3855
  if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
2893
3856
  this.log({
2894
3857
  level: "warn",
@@ -2908,6 +3871,18 @@ var ChannelDriver = class {
2908
3871
  inFlight.aliveInFlight = false;
2909
3872
  if (ok) inFlight.lastAliveAt = this.now();
2910
3873
  });
3874
+ if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
3875
+ inFlight.titleSyncInFlight = true;
3876
+ void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
3877
+ if (!title) {
3878
+ inFlight.titleSyncInFlight = false;
3879
+ return;
3880
+ }
3881
+ const ok = await this.patchConversationTitle(conv.id, title);
3882
+ inFlight.titleSyncInFlight = false;
3883
+ if (ok) inFlight.titleSynced = true;
3884
+ });
3885
+ }
2911
3886
  }
2912
3887
  if (awaitingHuman) {
2913
3888
  if (!inFlight.awaitingHumanLatched) {
@@ -2945,6 +3920,70 @@ var ChannelDriver = class {
2945
3920
  this.removeInFlight(watcher, inFlight.evidentMessageId);
2946
3921
  }
2947
3922
  }
3923
+ /**
3924
+ * Settle a message whose run-state has resolved `'done'` — extracted verbatim
3925
+ * (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
3926
+ * inline `state === 'done'` branch body, so a SECOND caller (the #721
3927
+ * b2-abandonment resolution) can reach the exact same completion behavior
3928
+ * (delivery-deadline anchoring, title resolution, usage extraction, and
3929
+ * `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
3930
+ * and risking the two copies silently drifting apart.
3931
+ */
3932
+ async settleMessageDone(sessionId, watcher, inFlight, messages) {
3933
+ const conv = watcher.conv;
3934
+ this.anchorDeliveryDeadline(inFlight);
3935
+ if (!inFlight.done) {
3936
+ this.log({
3937
+ level: "info",
3938
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
3939
+ conversation_id: conv.id,
3940
+ message_id: inFlight.evidentMessageId
3941
+ });
3942
+ const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
3943
+ const usage = messageUsage(messages, inFlight.opencodeMessageId);
3944
+ try {
3945
+ await this.markDone(
3946
+ conv.id,
3947
+ inFlight.evidentMessageId,
3948
+ sessionId,
3949
+ inFlight.opencodeMessageId,
3950
+ title,
3951
+ usage
3952
+ );
3953
+ } catch (err) {
3954
+ if (err instanceof ChannelAuthError) throw err;
3955
+ if (err instanceof ChannelTerminalError) {
3956
+ this.log({
3957
+ level: "warn",
3958
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
3959
+ conversation_id: conv.id,
3960
+ message_id: inFlight.evidentMessageId
3961
+ });
3962
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
3963
+ return;
3964
+ }
3965
+ if (this.now() >= inFlight.deadline) {
3966
+ this.log({
3967
+ level: "warn",
3968
+ 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)}`,
3969
+ conversation_id: conv.id,
3970
+ message_id: inFlight.evidentMessageId
3971
+ });
3972
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
3973
+ return;
3974
+ }
3975
+ this.log({
3976
+ level: "warn",
3977
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
3978
+ conversation_id: conv.id,
3979
+ message_id: inFlight.evidentMessageId
3980
+ });
3981
+ return;
3982
+ }
3983
+ inFlight.done = true;
3984
+ }
3985
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
3986
+ }
2948
3987
  // Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
2949
3988
  /**
2950
3989
  * Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
@@ -3081,7 +4120,8 @@ var ChannelDriver = class {
3081
4120
  });
3082
4121
  try {
3083
4122
  const title = await this.resolveSessionTitle(sessionId, row.conversation_id);
3084
- await this.markDone(row.conversation_id, row.id, sessionId, ocId, title);
4123
+ const usage = messageUsage(messages, ocId ?? "");
4124
+ await this.markDone(row.conversation_id, row.id, sessionId, ocId, title, usage);
3085
4125
  } catch (err) {
3086
4126
  if (err instanceof ChannelAuthError) throw err;
3087
4127
  if (err instanceof ChannelTerminalError) {
@@ -3109,6 +4149,8 @@ var ChannelDriver = class {
3109
4149
  }
3110
4150
  if (state === "failed") {
3111
4151
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
4152
+ const usage = messageUsage(messages, ocId ?? "");
4153
+ const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
3112
4154
  this.log({
3113
4155
  level: "error",
3114
4156
  message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
@@ -3116,7 +4158,7 @@ var ChannelDriver = class {
3116
4158
  message_id: row.id
3117
4159
  });
3118
4160
  try {
3119
- await this.markFailed(row.conversation_id, row.id, sessionId, error2);
4161
+ await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
3120
4162
  } catch (err) {
3121
4163
  if (err instanceof ChannelAuthError) throw err;
3122
4164
  if (err instanceof ChannelTerminalError) {
@@ -3522,6 +4564,47 @@ var ChannelDriver = class {
3522
4564
  }
3523
4565
  return false;
3524
4566
  }
4567
+ /**
4568
+ * Tri-state variant of the upward parentID membership walk (#721), used ONLY
4569
+ * by `isAnyDescendantSessionOngoing`. Walks the SAME cached
4570
+ * `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
4571
+ * `sessionBelongsTo`, which deliberately collapses "confirmed not a
4572
+ * descendant" and "the walk's fetch failed" into the same `false` (safe for
4573
+ * its OTHER callers: interaction attribution and the recovery-path
4574
+ * `isAnyDescendantSessionAlive`, both of which just retry next tick with no
4575
+ * safety consequence either way) — this variant keeps those two outcomes
4576
+ * SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
4577
+ * (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
4578
+ * not ongoing".
4579
+ *
4580
+ * Return contract:
4581
+ * - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
4582
+ * - `false` → the walk reached a definitive, parent-less root session
4583
+ * WITHOUT ever matching `rootSessionId` — `sessionId` is
4584
+ * CONFIRMED NOT a descendant of it.
4585
+ * - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
4586
+ * through the walk (`resolveSessionParent` returned `undefined`),
4587
+ * or the depth cap (32) was hit without a definitive answer (a
4588
+ * pathological/cyclic chain proves nothing either way). NEVER
4589
+ * treat this the same as `false` — see `sessionBelongsTo`'s own
4590
+ * doc comment above for why that collapse is safe THERE but not
4591
+ * here.
4592
+ *
4593
+ * `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
4594
+ * to the live-path descendant check, not a modification of shared code used
4595
+ * by interaction attribution or the recovery path.
4596
+ */
4597
+ async resolveSessionMembership(sessionId, rootSessionId) {
4598
+ let current = sessionId;
4599
+ for (let depth = 0; current && depth < 32; depth++) {
4600
+ if (current === rootSessionId) return true;
4601
+ const parent = await this.resolveSessionParent(current);
4602
+ if (parent === void 0) return null;
4603
+ if (parent === null) return false;
4604
+ current = parent;
4605
+ }
4606
+ return null;
4607
+ }
3525
4608
  /**
3526
4609
  * Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
3527
4610
  * `null` for a root session (no parent) and `undefined` when opencode is
@@ -3544,19 +4627,36 @@ var ChannelDriver = class {
3544
4627
  if (parent !== void 0) this.sessionParents.set(sessionId, parent);
3545
4628
  return parent;
3546
4629
  }
4630
+ /**
4631
+ * OpenCode's synchronous default session title (e.g.
4632
+ * `"New session - 1737800000000"`), assigned immediately when a session is
4633
+ * created — before OpenCode's async LLM-based auto-titling later renames it
4634
+ * mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
4635
+ * timestamp suffix's exact format is deliberately NOT matched, since the prefix
4636
+ * alone is the stable, cheap signal and over-anchoring on the timestamp
4637
+ * representation risks silently breaking if OpenCode ever changes it. Accepted
4638
+ * trade-off: a genuine LLM-assigned title that happens to literally start with
4639
+ * this prefix would also fail to latch (see `resolveSessionTitle`) —
4640
+ * vanishingly unlikely in practice, and deliberately not engineered around.
4641
+ */
4642
+ static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
3547
4643
  /**
3548
4644
  * Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
3549
4645
  * status PATCH can carry it into the "Live sessions" list. Driver-level cache so
3550
4646
  * BOTH the watcher completion path and the restart-recovery re-adopt path (which
3551
4647
  * has no watcher) can use it. `conversationId` is passed only for log context.
3552
4648
  * Best-effort:
3553
- * - a resolved NON-EMPTY title is cached and terminal (a real session name
4649
+ * - a resolved NON-EMPTY title that does NOT match
4650
+ * `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
3554
4651
  * won't later un-name), so we do NOT re-GET `/session/:id` every tick;
3555
- * - while the title is still absent/empty we do NOT latch it — OpenCode names
3556
- * sessions asynchronously mid-turn, so an early call (e.g. at `processing`)
3557
- * must leave the cache unresolved and re-fetch on the next need so a later
3558
- * call (e.g. at `done`) picks up the name assigned in the meantime. Such a
3559
- * call returns `null` (omit the title on THIS PATCH) without caching;
4652
+ * - while the title is still absent, empty, or matches the OpenCode
4653
+ * placeholder prefix (#549) we do NOT latch it OpenCode names sessions
4654
+ * asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
4655
+ * the cache unresolved and re-fetch on the next need so a later call (e.g. at
4656
+ * `done`) picks up the name assigned in the meantime. Such a call returns
4657
+ * `null` (omit the title on THIS PATCH) without caching. If a session is
4658
+ * never renamed, the title is omitted forever rather than ever persisting
4659
+ * the placeholder as a last resort;
3560
4660
  * - a failed request likewise leaves the cache unresolved (retry next need)
3561
4661
  * and returns `null` — it must NEVER throw or block completion.
3562
4662
  * A failure is logged with agent/session context (no silent catch).
@@ -3569,7 +4669,7 @@ var ChannelDriver = class {
3569
4669
  if (res.ok) {
3570
4670
  const body = await res.json();
3571
4671
  const title = body && typeof body.title === "string" ? body.title.trim() : "";
3572
- if (title.length > 0) {
4672
+ if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
3573
4673
  this.sessionTitles.set(sessionId, title);
3574
4674
  return title;
3575
4675
  }
@@ -3589,6 +4689,54 @@ var ChannelDriver = class {
3589
4689
  }
3590
4690
  return null;
3591
4691
  }
4692
+ /**
4693
+ * Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
4694
+ * session title onto the conversation via the PLAIN conversation-update
4695
+ * endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
4696
+ * message-status endpoint `markProcessing`/`markDone` use. Deliberately a
4697
+ * separate, lighter call: it carries no `status`, so it cannot re-trigger the
4698
+ * `processing`/`done` transition side effects (Slack notices, activity-log
4699
+ * rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
4700
+ * ever touches `conversations.title`. That route (`routes/conversations.ts`)
4701
+ * skips a title write matching the stored value, so a redundant call with the
4702
+ * same title is a real no-op — it does not bump `updated_at`, which the
4703
+ * conversation list sorts and paginates on. (Note this is a DIFFERENT guard
4704
+ * from `threads.ts`'s "non-empty AND changed" one, which only covers the
4705
+ * message-status PATCH; the non-empty half is enforced here instead, by
4706
+ * `resolveSessionTitle` never returning an empty/placeholder title.)
4707
+ *
4708
+ * Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
4709
+ * is logged and the title is simply retried on the next heartbeat tick (the
4710
+ * caller only latches `titleSynced` on `true`).
4711
+ */
4712
+ async patchConversationTitle(conversationId, title) {
4713
+ try {
4714
+ const res = await this.fetchImpl(
4715
+ `${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
4716
+ {
4717
+ method: "PATCH",
4718
+ headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
4719
+ body: JSON.stringify({ title })
4720
+ }
4721
+ );
4722
+ if (!res.ok) {
4723
+ this.log({
4724
+ level: "debug",
4725
+ message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
4726
+ conversation_id: conversationId
4727
+ });
4728
+ return false;
4729
+ }
4730
+ return true;
4731
+ } catch (err) {
4732
+ this.log({
4733
+ level: "debug",
4734
+ 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)}`,
4735
+ conversation_id: conversationId
4736
+ });
4737
+ return false;
4738
+ }
4739
+ }
3592
4740
  /**
3593
4741
  * DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
3594
4742
  * (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
@@ -3647,6 +4795,84 @@ var ChannelDriver = class {
3647
4795
  }
3648
4796
  return false;
3649
4797
  }
4798
+ /**
4799
+ * LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
4800
+ * sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
4801
+ * in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
4802
+ *
4803
+ * Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
4804
+ * cross-check above): that method judges liveness from the child's OWN
4805
+ * TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
4806
+ * on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
4807
+ * path the local opencode server IS running, so its in-memory status map is
4808
+ * live and authoritative — and per ADR-0047 §4a ("the child has its own entry
4809
+ * [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
4810
+ * ENTIRE turn (including any tool call it is itself executing), not a
4811
+ * per-message transcript snapshot. This sidesteps the "child's own tool is
4812
+ * executing, between its step's completion and the next generation step"
4813
+ * transcript gap that a transcript-based check would need a second,
4814
+ * sustained-window bound to guard against — it is simply not derived from
4815
+ * message timestamps at all.
4816
+ *
4817
+ * Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
4818
+ * status, as the recovery path does per §4a)? Because on the LIVE path the
4819
+ * root session can be shared: a SECOND, unrelated user message can land on the
4820
+ * SAME session (issue #721's own root cause) and keep the root `busy` for a
4821
+ * reason that has nothing to do with THIS message's delegation. A `task`
4822
+ * descendant session is spawned for exactly one delegated turn and never
4823
+ * reused, so its OWN status-map entry is unambiguous evidence about that one
4824
+ * delegation — which the root's status is not.
4825
+ *
4826
+ * Why membership is checked via `resolveSessionMembership`, NOT
4827
+ * `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
4828
+ * `GET /session/:id` fetch failure into "not a descendant", which would
4829
+ * silently drop a genuinely-live candidate from consideration on the one
4830
+ * unlucky tick its membership-walk fetch hiccups (#721).
4831
+ * `resolveSessionMembership` keeps that failure mode as a distinct `null`
4832
+ * (indeterminate) so it is folded into THIS method's own `indeterminate` flag
4833
+ * instead.
4834
+ *
4835
+ * Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
4836
+ * - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
4837
+ * - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
4838
+ * confirmed either way (`resolveSessionMembership` never
4839
+ * returned `null`), and every CONFIRMED descendant's status read
4840
+ * succeeded and is not ongoing (includes "no descendant session
4841
+ * exists at all" — e.g. a plain, non-`task` tool call).
4842
+ * - `null` → INDETERMINATE: `listSessions` failed, OR at least one
4843
+ * candidate's MEMBERSHIP could not be confirmed
4844
+ * (`resolveSessionMembership` returned `null` — a fetch failure
4845
+ * or pathological chain partway through the parent walk), OR at
4846
+ * least one CONFIRMED descendant's `isSessionOngoing` read
4847
+ * failed — and no OTHER candidate was already confirmed `true`.
4848
+ * The caller MUST NOT treat `null` the same as `false` here
4849
+ * (unlike the recovery cross-check's contract) — see
4850
+ * `isB2AbandonmentConfirmed`.
4851
+ */
4852
+ async isAnyDescendantSessionOngoing(rootSessionId) {
4853
+ const sessions = await listSessions(this.port);
4854
+ if (!sessions) {
4855
+ this.log({
4856
+ level: "warn",
4857
+ message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
4858
+ });
4859
+ return null;
4860
+ }
4861
+ let indeterminate = false;
4862
+ for (const candidate of sessions) {
4863
+ if (!candidate?.id || candidate.id === rootSessionId) continue;
4864
+ const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
4865
+ if (membership === null) {
4866
+ indeterminate = true;
4867
+ continue;
4868
+ }
4869
+ if (membership === false) continue;
4870
+ const ongoing = await isSessionOngoing(this.port, candidate.id);
4871
+ if (ongoing === true) return true;
4872
+ if (ongoing === null) indeterminate = true;
4873
+ }
4874
+ return indeterminate ? null : false;
4875
+ }
3650
4876
  /**
3651
4877
  * Cheap decision-telemetry label for a running row's LAST correlated reply
3652
4878
  * (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
@@ -3719,7 +4945,7 @@ var ChannelDriver = class {
3719
4945
  // Evident API calls (combinedAuth thread routes)
3720
4946
  async getPendingConversations() {
3721
4947
  const res = await this.fetchImpl(
3722
- `${this.apiUrl}/agents/${this.agentId}/conversations/pending`,
4948
+ `${this.apiUrl}/runners/${this.agentId}/conversations/pending`,
3723
4949
  {
3724
4950
  headers: { Authorization: this.getAuthHeader() }
3725
4951
  }
@@ -3737,7 +4963,7 @@ var ChannelDriver = class {
3737
4963
  }
3738
4964
  async getPendingMessages(conversationId) {
3739
4965
  const res = await this.fetchImpl(
3740
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages?status=pending`,
4966
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages?status=pending`,
3741
4967
  { headers: { Authorization: this.getAuthHeader() } }
3742
4968
  );
3743
4969
  this.assertAuth(res, "fetching pending messages");
@@ -3761,7 +4987,7 @@ var ChannelDriver = class {
3761
4987
  */
3762
4988
  async getProcessingMessages() {
3763
4989
  const res = await this.fetchImpl(
3764
- `${this.apiUrl}/agents/${this.agentId}/conversations/processing`,
4990
+ `${this.apiUrl}/runners/${this.agentId}/conversations/processing`,
3765
4991
  { headers: { Authorization: this.getAuthHeader() } }
3766
4992
  );
3767
4993
  this.assertAuth(res, "fetching processing messages");
@@ -3775,6 +5001,32 @@ var ChannelDriver = class {
3775
5001
  }
3776
5002
  return messages;
3777
5003
  }
5004
+ /**
5005
+ * The `opencode_session_id` fragment of a status PATCH body — `{}` when this
5006
+ * conversation has ABANDONED that session (#553). The field is optional
5007
+ * server-side and an absent one leaves the persisted binding untouched, so
5008
+ * omitting it is how a routine status write stops resurrecting it.
5009
+ *
5010
+ * ONLY for writes whose sole cost is a lost deep link. The `processing` notice
5011
+ * degrades to no "View in Evident" link (the reaction swap still fires) and the
5012
+ * turn-failure notice is built from the PATCH's own `error` text with a link off
5013
+ * the persisted row — neither loses content the user came for. `markDone`
5014
+ * deliberately does NOT use this helper: the server fetches the reply text
5015
+ * THROUGH the session id it is given, so suppressing there would replace the
5016
+ * agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
5017
+ * `ensureSession` guard, not this suppression, is what makes the self-heal
5018
+ * stick.
5019
+ */
5020
+ sessionIdBody(sessionId, conversationId, messageId, status) {
5021
+ if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
5022
+ this.log({
5023
+ level: "debug",
5024
+ 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)}`,
5025
+ conversation_id: conversationId,
5026
+ message_id: messageId
5027
+ });
5028
+ return {};
5029
+ }
3778
5030
  /**
3779
5031
  * EXISTING combinedAuth route — now fired by the watcher on queued→running
3780
5032
  * (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
@@ -3798,13 +5050,13 @@ var ChannelDriver = class {
3798
5050
  */
3799
5051
  async markProcessing(conversationId, messageId, sessionId, opencodeMessageId, title) {
3800
5052
  const res = await this.fetchImpl(
3801
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
5053
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
3802
5054
  {
3803
5055
  method: "PATCH",
3804
5056
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3805
5057
  body: JSON.stringify({
3806
5058
  status: "processing",
3807
- opencode_session_id: sessionId,
5059
+ ...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
3808
5060
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3809
5061
  ...title ? { title } : {}
3810
5062
  })
@@ -3845,17 +5097,23 @@ var ChannelDriver = class {
3845
5097
  * watcher retries next tick within the
3846
5098
  * deadline, Finding 4).
3847
5099
  */
3848
- async markDone(conversationId, messageId, sessionId, opencodeMessageId, title) {
5100
+ async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage) {
3849
5101
  const res = await this.fetchImpl(
3850
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
5102
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
3851
5103
  {
3852
5104
  method: "PATCH",
3853
5105
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3854
5106
  body: JSON.stringify({
3855
5107
  status: "done",
5108
+ // ALWAYS sent, even for a session this conversation has abandoned
5109
+ // (#553): the server reads the reply text back out of THIS session id
5110
+ // to deliver it. Omitting it would leave the user with "✅ Done!"
5111
+ // instead of the answer — a worse regression than the resurrection it
5112
+ // would prevent, which `ensureSession`'s guard handles anyway.
3856
5113
  opencode_session_id: sessionId,
3857
5114
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3858
- ...title ? { title } : {}
5115
+ ...title ? { title } : {},
5116
+ ...usage ? usage : {}
3859
5117
  })
3860
5118
  }
3861
5119
  );
@@ -3868,19 +5126,35 @@ var ChannelDriver = class {
3868
5126
  }
3869
5127
  /**
3870
5128
  * Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
3871
- * when provided (issue #182): a bare `markFailed(conv, msg)` sends
3872
- * `{status:'failed'}` unchanged (the dispatch-failure path), while an errored
3873
- * OpenCode turn sends `{status:'failed', opencode_session_id, error}` so the
3874
- * failure reason reaches the channel.
5129
+ * when provided (issue #182). Three states for `sessionId`:
5130
+ * - omitted (`undefined`) → don't send the field, leave the persisted
5131
+ * session untouched (unused today; kept for API symmetry).
5132
+ * - a real id (`string`) → send it, update the persisted session (the
5133
+ * turn-failure call sites: an errored OpenCode turn).
5134
+ * - explicit `null` → send it, CLEAR the persisted session (issue
5135
+ * #485's dispatch-handoff-failure call site: the session id still
5136
+ * exists but is wedged, so the next attempt must get a fresh one
5137
+ * instead of reusing it — see WI-1's server-side null-clearing PATCH).
3875
5138
  */
3876
- async markFailed(conversationId, messageId, sessionId, error2) {
5139
+ async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
3877
5140
  const body = { status: "failed" };
3878
- if (sessionId !== void 0) body.opencode_session_id = sessionId;
5141
+ if (sessionId === null) {
5142
+ body.opencode_session_id = null;
5143
+ } else if (sessionId !== void 0) {
5144
+ Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
5145
+ }
3879
5146
  if (error2 !== void 0) body.error = error2;
5147
+ if (usage) Object.assign(body, usage);
5148
+ if (failure) {
5149
+ body.failure_kind = failure.kind;
5150
+ body.failure_provider_id = failure.providerId;
5151
+ body.failure_model_id = failure.modelId;
5152
+ body.failure_reason = failure.reason;
5153
+ }
3880
5154
  await this.callWithRetry(
3881
5155
  "marking message as failed",
3882
5156
  () => this.fetchImpl(
3883
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
5157
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
3884
5158
  {
3885
5159
  method: "PATCH",
3886
5160
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -3889,6 +5163,29 @@ var ChannelDriver = class {
3889
5163
  )
3890
5164
  );
3891
5165
  }
5166
+ /**
5167
+ * Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
5168
+ *
5169
+ * `messageFailure` alone (structured OpenCode error → `model_auth`) covers
5170
+ * most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
5171
+ * to the P1-2b zero-provider check — one extra loopback call to
5172
+ * `hasAnyConfiguredProvider`, only reached when the structured classifier
5173
+ * couldn't place it. Fails open (never throws): a fallback probe failure
5174
+ * (`null`/indeterminate) leaves the classification `null`, which produces
5175
+ * today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
5176
+ */
5177
+ async classifyModelAuthFailure(messages, userMessageId) {
5178
+ const classified = messageFailure(messages, userMessageId);
5179
+ if (classified != null) return classified;
5180
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
5181
+ const hasProvider = await hasAnyConfiguredProvider(this.port);
5182
+ return applyZeroProviderFallback(
5183
+ classified,
5184
+ hasProvider,
5185
+ reply?.info?.providerID ?? null,
5186
+ reply?.info?.modelID ?? null
5187
+ );
5188
+ }
3892
5189
  /**
3893
5190
  * Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
3894
5191
  * (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
@@ -3907,7 +5204,7 @@ var ChannelDriver = class {
3907
5204
  async postSignal(conversationId, messageId, signal, extra) {
3908
5205
  try {
3909
5206
  const res = await this.fetchImpl(
3910
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
5207
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
3911
5208
  {
3912
5209
  method: "POST",
3913
5210
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -3936,7 +5233,7 @@ var ChannelDriver = class {
3936
5233
  }
3937
5234
  async persistSession(conversationId, sessionId) {
3938
5235
  const res = await this.fetchImpl(
3939
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}`,
5236
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}`,
3940
5237
  {
3941
5238
  method: "PATCH",
3942
5239
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -3962,7 +5259,7 @@ var ChannelDriver = class {
3962
5259
  await this.callWithRetry(
3963
5260
  "reporting interactive event",
3964
5261
  () => this.fetchImpl(
3965
- `${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/interactive-event`,
5262
+ `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/interactive-event`,
3966
5263
  {
3967
5264
  method: "POST",
3968
5265
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
@@ -4041,10 +5338,16 @@ var ChannelDriver = class {
4041
5338
  import chalk5 from "chalk";
4042
5339
  import ora2 from "ora";
4043
5340
  import { select as select2 } from "@inquirer/prompts";
5341
+ var INTERACTIVE_START_TIMEOUT_MS = 3e4;
4044
5342
  async function ensureOpenCodeRunning(ctx) {
4045
5343
  const healthCheck = await checkOpenCodeHealth(ctx.port);
4046
5344
  if (healthCheck.healthy) {
4047
- return { port: ctx.port, process: null, version: healthCheck.version ?? null };
5345
+ return {
5346
+ port: ctx.port,
5347
+ process: null,
5348
+ version: healthCheck.version ?? null,
5349
+ notReadyReason: null
5350
+ };
4048
5351
  }
4049
5352
  const runningInstances = await findHealthyOpenCodeInstances();
4050
5353
  if (runningInstances.length > 0) {
@@ -4065,7 +5368,7 @@ async function ensureOpenCodeRunning(ctx) {
4065
5368
  console.log(chalk5.yellow("Tip: Run with the correct port:"));
4066
5369
  console.log(
4067
5370
  chalk5.dim(
4068
- ` ${getCliName()} run --agent ${ctx.agentId} --port ${runningInstances[0].port}`
5371
+ ` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
4069
5372
  )
4070
5373
  );
4071
5374
  }
@@ -4085,14 +5388,22 @@ async function ensureOpenCodeRunning(ctx) {
4085
5388
  if (!ctx.interactive) {
4086
5389
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
4087
5390
  const proc = await startOpenCode(ctx.port);
4088
- const health = await waitForOpenCodeHealth(ctx.port, 3e4);
5391
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
4089
5392
  if (!health.healthy) {
4090
- throw new Error(
4091
- `OpenCode failed to start on port ${ctx.port}. Install with: npm install -g opencode-ai`
4092
- );
5393
+ return {
5394
+ port: ctx.port,
5395
+ process: proc,
5396
+ version: null,
5397
+ notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
5398
+ };
4093
5399
  }
4094
5400
  ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
4095
- return { port: ctx.port, process: proc, version: health.version ?? null };
5401
+ return {
5402
+ port: ctx.port,
5403
+ process: proc,
5404
+ version: health.version ?? null,
5405
+ notReadyReason: null
5406
+ };
4096
5407
  }
4097
5408
  let port = ctx.port;
4098
5409
  if (isPortInUse(port)) {
@@ -4145,15 +5456,15 @@ Port ${port} is already in use.`));
4145
5456
  if (action === "start") {
4146
5457
  const spinner = ora2("Starting OpenCode...").start();
4147
5458
  const proc = await startOpenCode(port);
4148
- const health = await waitForOpenCodeHealth(port, 3e4);
5459
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
4149
5460
  if (!health.healthy) {
4150
5461
  spinner.fail("Failed to start OpenCode");
4151
5462
  throw new Error("OpenCode failed to start");
4152
5463
  }
4153
5464
  spinner.stop();
4154
- return { port, process: proc, version: health.version ?? null };
5465
+ return { port, process: proc, version: health.version ?? null, notReadyReason: null };
4155
5466
  }
4156
- return { port, process: null, version: null };
5467
+ return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
4157
5468
  }
4158
5469
 
4159
5470
  // src/commands/agent-lookup.ts
@@ -4195,19 +5506,21 @@ async function resolveAgentIdFromKey(authHeader) {
4195
5506
  return { agent_id: data.agent_id };
4196
5507
  }
4197
5508
  return {
4198
- error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --agent explicitly."
5509
+ error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
4199
5510
  };
4200
5511
  } catch (error2) {
4201
5512
  const message = error2 instanceof Error ? error2.message : "Unknown error";
4202
5513
  return { error: `Failed to resolve runner from key: ${message}` };
4203
5514
  }
4204
5515
  }
5516
+ var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
4205
5517
  async function notifyAgentDisconnected(agentId, authHeader) {
4206
5518
  const apiUrl = getApiUrlConfig();
4207
5519
  try {
4208
- const response = await fetch(`${apiUrl}/agents/${agentId}/disconnect`, {
5520
+ const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
4209
5521
  method: "POST",
4210
- headers: { Authorization: authHeader }
5522
+ headers: { Authorization: authHeader },
5523
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
4211
5524
  });
4212
5525
  if (!response.ok) {
4213
5526
  const serverMessage = await readErrorMessage(response);
@@ -4218,13 +5531,41 @@ async function notifyAgentDisconnected(agentId, authHeader) {
4218
5531
  }
4219
5532
  return { ok: true };
4220
5533
  } catch (error2) {
4221
- return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
5534
+ return { ok: false, error: describeBestEffortError(error2) };
5535
+ }
5536
+ }
5537
+ function describeBestEffortError(error2) {
5538
+ const name = error2?.name;
5539
+ if (name === "TimeoutError" || name === "AbortError") {
5540
+ return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
5541
+ }
5542
+ return error2 instanceof Error ? error2.message : String(error2);
5543
+ }
5544
+ async function reportMicrovmId(agentId, authHeader, microvmId) {
5545
+ try {
5546
+ const apiUrl = getApiUrlConfig();
5547
+ const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
5548
+ method: "POST",
5549
+ headers: { Authorization: authHeader, "Content-Type": "application/json" },
5550
+ body: JSON.stringify({ microvm_id: microvmId }),
5551
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
5552
+ });
5553
+ if (!response.ok) {
5554
+ const serverMessage = await readErrorMessage(response);
5555
+ return {
5556
+ ok: false,
5557
+ error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
5558
+ };
5559
+ }
5560
+ return { ok: true };
5561
+ } catch (error2) {
5562
+ return { ok: false, error: describeBestEffortError(error2) };
4222
5563
  }
4223
5564
  }
4224
5565
  async function getAgentInfo(agentId, authHeader) {
4225
5566
  const apiUrl = getApiUrlConfig();
4226
5567
  try {
4227
- const response = await fetch(`${apiUrl}/agents/${agentId}`, {
5568
+ const response = await fetch(`${apiUrl}/runners/${agentId}`, {
4228
5569
  headers: { Authorization: authHeader }
4229
5570
  });
4230
5571
  if (response.status === 401) {
@@ -4268,6 +5609,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
4268
5609
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
4269
5610
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
4270
5611
  var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
5612
+ var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
4271
5613
  function resolveLogLevel(options) {
4272
5614
  const accepted = Object.keys(LOG_LEVELS);
4273
5615
  const validate = (value, source) => {
@@ -4291,6 +5633,63 @@ function resolveLogLevel(options) {
4291
5633
  }
4292
5634
  return "info";
4293
5635
  }
5636
+ function resolveFileSyncDirectories(raw, homeDir) {
5637
+ const directories = [];
5638
+ for (const entry of raw ?? []) {
5639
+ const trimmed = entry.trim();
5640
+ if (trimmed === "") {
5641
+ throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
5642
+ }
5643
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join2(homeDir, trimmed.slice(2)) : trimmed;
5644
+ if (!isAbsolute2(expanded)) {
5645
+ throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
5646
+ }
5647
+ const normalized = resolvePath(expanded);
5648
+ if (parse(normalized).root === normalized) {
5649
+ throw new Error(
5650
+ `--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
5651
+ );
5652
+ }
5653
+ if (!directories.includes(normalized)) {
5654
+ directories.push(normalized);
5655
+ }
5656
+ }
5657
+ if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
5658
+ throw new Error(
5659
+ `--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
5660
+ );
5661
+ }
5662
+ return directories;
5663
+ }
5664
+ var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
5665
+ var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
5666
+ var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
5667
+ function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
5668
+ const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
5669
+ let raw;
5670
+ let source;
5671
+ if (options.opencodeStartTimeout !== void 0) {
5672
+ raw = options.opencodeStartTimeout;
5673
+ source = "--opencode-start-timeout";
5674
+ } else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
5675
+ raw = env[OPENCODE_START_TIMEOUT_ENV];
5676
+ source = OPENCODE_START_TIMEOUT_ENV;
5677
+ } else {
5678
+ return { timeoutMs: defaultMs, warnings: [] };
5679
+ }
5680
+ const trimmed = raw.trim();
5681
+ const seconds = Number(trimmed);
5682
+ const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
5683
+ if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
5684
+ return {
5685
+ timeoutMs: defaultMs,
5686
+ warnings: [
5687
+ `Ignoring invalid ${source} "${raw}": expected a positive integer number of seconds (at most ${MAX_OPENCODE_START_TIMEOUT_SECONDS}); using the default ${DEFAULT_OPENCODE_START_TIMEOUT_SECONDS}s`
5688
+ ]
5689
+ };
5690
+ }
5691
+ return { timeoutMs: seconds * 1e3, warnings: [] };
5692
+ }
4294
5693
  function meetsThreshold(state, level) {
4295
5694
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
4296
5695
  }
@@ -4312,6 +5711,10 @@ function log2(state, message, level = "info") {
4312
5711
  function logActivity(state, entry) {
4313
5712
  const level = entry.level ?? (entry.type === "error" ? "error" : "info");
4314
5713
  if (!meetsThreshold(state, level)) return;
5714
+ forwardRunnerActivity(
5715
+ { level, message: entry.message, error: entry.error },
5716
+ { agentId: state.agentId, authHeader: state.authHeader }
5717
+ );
4315
5718
  const fullEntry = {
4316
5719
  ...entry,
4317
5720
  level,
@@ -4412,18 +5815,29 @@ async function handleAuthError(state, error2) {
4412
5815
  async function driveChannels(state, driver) {
4413
5816
  let idlePolls = 0;
4414
5817
  let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
5818
+ let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
4415
5819
  while (state.running) {
4416
5820
  if (state.connection?.reconnecting && state.connection.reconnectPromise) {
4417
5821
  logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
4418
5822
  if (state.interactive) displayStatus(state);
4419
5823
  await state.connection.reconnectPromise;
4420
5824
  }
5825
+ const carriedOverFileSync = driver.fileSyncActivity().inFlight;
5826
+ void driver.syncPendingFiles().catch(
5827
+ (error2) => logActivity(state, {
5828
+ type: "error",
5829
+ error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
5830
+ })
5831
+ );
4421
5832
  try {
4422
5833
  const processed = await driver.drainPending();
4423
5834
  state.messageCount += processed;
4424
5835
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
4425
5836
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
4426
- if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity) {
5837
+ const appliedFiles = driver.fileSyncActivity().appliedFiles;
5838
+ const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
5839
+ lastSeenAppliedFiles = appliedFiles;
5840
+ if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
4427
5841
  idlePolls = 0;
4428
5842
  if (processed > 0 && state.interactive) displayStatus(state);
4429
5843
  } else if (state.idleTimeout !== null) {
@@ -4452,7 +5866,7 @@ async function driveChannels(state, driver) {
4452
5866
  logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
4453
5867
  if (state.interactive) displayStatus(state);
4454
5868
  }
4455
- await new Promise((resolve2) => setTimeout(resolve2, CHANNEL_POLL_INTERVAL_MS));
5869
+ await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
4456
5870
  if (state.idleTimeout !== null && idlePolls >= 2) {
4457
5871
  const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
4458
5872
  if (idleMs > state.idleTimeout * 1e3) {
@@ -4555,7 +5969,18 @@ async function notifyOffline(state) {
4555
5969
  if (state.interactive) displayStatus(state);
4556
5970
  }
4557
5971
  }
5972
+ async function timeShutdownPhase(state, durations, name, run2) {
5973
+ const startedAt = Date.now();
5974
+ try {
5975
+ return await run2();
5976
+ } finally {
5977
+ const elapsedMs = Date.now() - startedAt;
5978
+ durations[name] = elapsedMs;
5979
+ log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
5980
+ }
5981
+ }
4558
5982
  async function cleanup(state, opts = {}) {
5983
+ const durations = {};
4559
5984
  state.running = false;
4560
5985
  for (const timer of state.sessionCleanupTimers) {
4561
5986
  clearInterval(timer);
@@ -4569,7 +5994,13 @@ async function cleanup(state, opts = {}) {
4569
5994
  logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
4570
5995
  displayStatus(state);
4571
5996
  }
4572
- const settled = await state.channelDriver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS);
5997
+ const driver = state.channelDriver;
5998
+ const settled = await timeShutdownPhase(
5999
+ state,
6000
+ durations,
6001
+ "drain",
6002
+ () => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
6003
+ );
4573
6004
  if (!settled) {
4574
6005
  logActivity(state, {
4575
6006
  type: "info",
@@ -4578,13 +6009,15 @@ async function cleanup(state, opts = {}) {
4578
6009
  if (state.interactive) displayStatus(state);
4579
6010
  }
4580
6011
  }
4581
- await notifyOffline(state);
6012
+ await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
4582
6013
  if (state.connection) {
4583
- state.connection.close();
6014
+ const connection = state.connection;
6015
+ await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
4584
6016
  state.connection = null;
4585
6017
  }
4586
6018
  if (state.opencodeProcess) {
4587
- stopOpenCode(state.opencodeProcess);
6019
+ const opencodeProcess = state.opencodeProcess;
6020
+ await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
4588
6021
  if (state.interactive) {
4589
6022
  logActivity(state, { type: "info", message: "Stopped OpenCode process" });
4590
6023
  displayStatus(state);
@@ -4593,12 +6026,15 @@ async function cleanup(state, opts = {}) {
4593
6026
  }
4594
6027
  state.opencodeProcess = null;
4595
6028
  }
6029
+ return durations;
4596
6030
  }
4597
6031
  async function run(options) {
4598
6032
  const interactive = isInteractive(options.json);
4599
6033
  let logLevel;
6034
+ let fileSyncDirectories;
4600
6035
  try {
4601
6036
  logLevel = resolveLogLevel(options);
6037
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
4602
6038
  } catch (error2) {
4603
6039
  const message = error2 instanceof Error ? error2.message : String(error2);
4604
6040
  if (options.json) {
@@ -4611,7 +6047,7 @@ async function run(options) {
4611
6047
  return;
4612
6048
  }
4613
6049
  const state = {
4614
- agentId: options.agent || "",
6050
+ agentId: options.runner || options.agent || "",
4615
6051
  agentName: null,
4616
6052
  port: options.port ?? 4096,
4617
6053
  conversationFilter: options.conversation ?? null,
@@ -4633,6 +6069,25 @@ async function run(options) {
4633
6069
  sessionCleanupTimers: [],
4634
6070
  authHeader: ""
4635
6071
  };
6072
+ setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
6073
+ if (fileSyncDirectories.length > 0) {
6074
+ log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
6075
+ } else {
6076
+ log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
6077
+ }
6078
+ if (!options.runner && options.agent) {
6079
+ telemetry.info(
6080
+ EventTypes.DEPRECATED_AGENT_FLAG_USED,
6081
+ "Deprecated --agent flag used instead of --runner",
6082
+ { command: "run" },
6083
+ state.agentId
6084
+ );
6085
+ const agentFlagNotice = "--agent is deprecated, use --runner instead; will be removed in a future release.";
6086
+ log2(state, agentFlagNotice, "warn");
6087
+ if (state.interactive && !state.json) {
6088
+ logActivity(state, { type: "info", level: "warn", message: agentFlagNotice });
6089
+ }
6090
+ }
4636
6091
  if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
4637
6092
  log2(
4638
6093
  state,
@@ -4643,14 +6098,38 @@ async function run(options) {
4643
6098
  const handleSignal = async () => {
4644
6099
  if (state.shuttingDown) return;
4645
6100
  state.shuttingDown = true;
6101
+ const shutdownStartedAt = Date.now();
4646
6102
  if (state.interactive) {
4647
6103
  logActivity(state, { type: "info", message: "Shutting down..." });
4648
6104
  displayStatus(state);
4649
6105
  } else {
4650
6106
  log2(state, "Shutting down...");
4651
6107
  }
4652
- await cleanup(state, { graceful: true });
4653
- await shutdownTelemetry();
6108
+ const durations = await cleanup(state, { graceful: true });
6109
+ const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
6110
+ await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
6111
+ let timer;
6112
+ const flushed = shutdownTelemetry().then(
6113
+ () => true,
6114
+ (error2) => {
6115
+ log2(
6116
+ state,
6117
+ `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
6118
+ "warn"
6119
+ );
6120
+ return true;
6121
+ }
6122
+ );
6123
+ const timedOut = new Promise((resolve3) => {
6124
+ timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
6125
+ });
6126
+ if (!await Promise.race([flushed, timedOut])) {
6127
+ log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
6128
+ }
6129
+ clearTimeout(timer);
6130
+ });
6131
+ const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
6132
+ log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
4654
6133
  process.exit(0);
4655
6134
  };
4656
6135
  process.on("SIGINT", handleSignal);
@@ -4661,7 +6140,9 @@ async function run(options) {
4661
6140
  if (!interactive) {
4662
6141
  printError("Authentication required");
4663
6142
  blank();
4664
- console.log(chalk6.dim("Set EVIDENT_AGENT_KEY environment variable for CI"));
6143
+ console.log(
6144
+ chalk6.dim("Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY) environment variable for CI")
6145
+ );
4665
6146
  console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
4666
6147
  blank();
4667
6148
  process.exit(1);
@@ -4675,6 +6156,25 @@ async function run(options) {
4675
6156
  );
4676
6157
  }
4677
6158
  state.authHeader = getAuthHeader(credentials2);
6159
+ if (credentials2.notice) {
6160
+ log2(state, credentials2.notice, "warn");
6161
+ if (state.interactive && !state.json) {
6162
+ logActivity(state, { type: "info", level: "warn", message: credentials2.notice });
6163
+ }
6164
+ }
6165
+ if (credentials2.keySource === "agent_key") {
6166
+ telemetry.info(
6167
+ EventTypes.DEPRECATED_AGENT_KEY_ENV_USED,
6168
+ "Deprecated EVIDENT_AGENT_KEY env var used instead of EVIDENT_RUNNER_KEY",
6169
+ { command: "run" },
6170
+ state.agentId
6171
+ );
6172
+ const agentKeyNotice = "EVIDENT_AGENT_KEY is deprecated, use EVIDENT_RUNNER_KEY instead; will be removed in a future release.";
6173
+ log2(state, agentKeyNotice, "warn");
6174
+ if (state.interactive && !state.json) {
6175
+ logActivity(state, { type: "info", level: "warn", message: agentKeyNotice });
6176
+ }
6177
+ }
4678
6178
  if (!state.agentId) {
4679
6179
  if (credentials2.authType === "agent_key") {
4680
6180
  const resolved = await resolveAgentIdFromKey(state.authHeader);
@@ -4692,9 +6192,15 @@ async function run(options) {
4692
6192
  process.exit(1);
4693
6193
  }
4694
6194
  } else {
4695
- printError("--agent is required when not using EVIDENT_AGENT_KEY");
6195
+ printError(
6196
+ "--runner (or --agent) is required when not using EVIDENT_RUNNER_KEY or EVIDENT_AGENT_KEY"
6197
+ );
4696
6198
  blank();
4697
- console.log(chalk6.dim("Either provide --agent <id> or set EVIDENT_AGENT_KEY"));
6199
+ console.log(
6200
+ chalk6.dim(
6201
+ "Either provide --runner/--agent <id> or set EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY"
6202
+ )
6203
+ );
4698
6204
  blank();
4699
6205
  process.exit(1);
4700
6206
  }
@@ -4737,25 +6243,67 @@ async function run(options) {
4737
6243
  }
4738
6244
  spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
4739
6245
  state.agentName = validation.agent.name;
6246
+ const microvmId = process.env.MICROVM_ID?.trim();
6247
+ if (microvmId) {
6248
+ const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
6249
+ if (reported.ok) {
6250
+ log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
6251
+ } else {
6252
+ const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
6253
+ log2(state, message, "warn");
6254
+ if (state.interactive && !state.json) {
6255
+ logActivity(state, { type: "info", level: "warn", message });
6256
+ }
6257
+ }
6258
+ } else {
6259
+ log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
6260
+ }
6261
+ const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
6262
+ for (const warning2 of opencodeStartTimeoutWarnings) {
6263
+ logActivity(state, { type: "info", level: "warn", message: warning2 });
6264
+ }
4740
6265
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
4741
6266
  try {
4742
6267
  const oc = await ensureOpenCodeRunning({
4743
6268
  port: state.port,
4744
6269
  interactive: state.interactive,
4745
6270
  agentId: state.agentId,
4746
- log: (message) => log2(state, message)
6271
+ log: (message) => log2(state, message),
6272
+ startTimeoutMs: opencodeStartTimeoutMs
4747
6273
  });
4748
6274
  state.port = oc.port;
4749
6275
  state.opencodeProcess = oc.process;
4750
6276
  state.opencodeVersion = oc.version;
4751
- state.opencodeConnected = oc.process !== null || oc.version !== null;
6277
+ state.opencodeConnected = oc.notReadyReason === null;
4752
6278
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
4753
6279
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
4754
- const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
4755
- if (versionWarning) {
4756
- log2(state, versionWarning, "warn");
4757
- if (state.interactive && !state.json) {
4758
- logActivity(state, { type: "info", level: "warn", message: versionWarning });
6280
+ if (!state.interactive && oc.notReadyReason !== null) {
6281
+ const message = `OpenCode is not ready on port ${state.port}: ${oc.notReadyReason}. The runner will still come online, but messages will fail until opencode answers \u2014 raise the wait with --opencode-start-timeout <seconds> (env ${OPENCODE_START_TIMEOUT_ENV}).`;
6282
+ logActivity(state, { type: "info", level: "warn", message });
6283
+ } else {
6284
+ const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
6285
+ if (versionWarning) {
6286
+ log2(state, versionWarning, "warn");
6287
+ if (state.interactive && !state.json) {
6288
+ logActivity(state, { type: "info", level: "warn", message: versionWarning });
6289
+ }
6290
+ }
6291
+ const noProviderWarning = buildNoProviderWarning(
6292
+ await hasAnyConfiguredProvider(state.port)
6293
+ );
6294
+ if (noProviderWarning) {
6295
+ log2(state, noProviderWarning, "warn");
6296
+ if (state.interactive && !state.json) {
6297
+ logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
6298
+ blank();
6299
+ console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
6300
+ console.log(
6301
+ chalk6.dim(
6302
+ `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
6303
+ )
6304
+ );
6305
+ blank();
6306
+ }
4759
6307
  }
4760
6308
  }
4761
6309
  } catch (error2) {
@@ -4770,6 +6318,10 @@ async function run(options) {
4770
6318
  getAuthHeader: () => state.authHeader,
4771
6319
  conversationFilter: state.conversationFilter,
4772
6320
  stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
6321
+ // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
6322
+ // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
6323
+ fileSyncDirectories,
6324
+ homeDir: homedir2(),
4773
6325
  log: (entry) => (
4774
6326
  // Thread the driver's real level straight through so `debug`/`warn`
4775
6327
  // survive the sink filter (they no longer collapse to info). `type`
@@ -4796,6 +6348,18 @@ async function run(options) {
4796
6348
  type: "info",
4797
6349
  message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
4798
6350
  });
6351
+ if (options.tunnelReadyFile) {
6352
+ const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
6353
+ if (marker.ok) {
6354
+ log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
6355
+ } else {
6356
+ log2(
6357
+ state,
6358
+ `Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
6359
+ "error"
6360
+ );
6361
+ }
6362
+ }
4799
6363
  emitAgentConnected(state.agentId, {
4800
6364
  port: state.port,
4801
6365
  cli_version: getCliVersion(),
@@ -4851,6 +6415,12 @@ async function run(options) {
4851
6415
  onDrainPing: () => {
4852
6416
  if (!state.running) return;
4853
6417
  logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
6418
+ void channelDriver.syncPendingFiles().catch(
6419
+ (error2) => logActivity(state, {
6420
+ type: "error",
6421
+ error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
6422
+ })
6423
+ );
4854
6424
  channelDriver.drainPending().then((processed) => {
4855
6425
  if (processed > 0) {
4856
6426
  state.messageCount += processed;
@@ -4909,7 +6479,7 @@ async function run(options) {
4909
6479
  }
4910
6480
  telemetry.error(EventTypes.CLI_ERROR, `Run command failed: ${message}`, {
4911
6481
  command: "run",
4912
- agentId: options.agent
6482
+ agentId: options.runner || options.agent
4913
6483
  });
4914
6484
  await shutdownTelemetry();
4915
6485
  process.exit(1);
@@ -4934,10 +6504,16 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
4934
6504
  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);
4935
6505
  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 }));
4936
6506
  program.command("whoami").description("Show the currently logged in user").action(whoami);
4937
- program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Runner ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
6507
+ 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(
6508
+ "-a, --agent [id]",
6509
+ "Deprecated alias for --runner (still supported; --runner wins if both are given)"
6510
+ ).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
4938
6511
  "--log-level <level>",
4939
6512
  "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
4940
- ).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(
6513
+ ).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(
6514
+ "--opencode-start-timeout <seconds>",
6515
+ "Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
6516
+ ).option("--json", "Output in JSON format").option(
4941
6517
  "--session-cleanup-max-age <duration>",
4942
6518
  "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
4943
6519
  ).option(
@@ -4946,10 +6522,19 @@ program.command("run").description("Connect to Evident and process messages").op
4946
6522
  ).option(
4947
6523
  "--session-cleanup-interval <duration>",
4948
6524
  "How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
6525
+ ).option(
6526
+ "--enable-file-sync-to <dir>",
6527
+ "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
6528
+ (value, previous) => previous.concat([value]),
6529
+ []
6530
+ ).option(
6531
+ "--tunnel-ready-file <path>",
6532
+ "Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
4949
6533
  ).action(
4950
6534
  (options) => {
4951
6535
  run({
4952
6536
  agent: options.agent,
6537
+ runner: options.runner,
4953
6538
  port: parseInt(options.port, 10),
4954
6539
  // Raw string — validation/precedence is single-sourced in run.ts's
4955
6540
  // resolveLogLevel (flag > -v > EVIDENT_LOG_LEVEL > info).
@@ -4957,11 +6542,18 @@ program.command("run").description("Connect to Evident and process messages").op
4957
6542
  verbose: options.verbose,
4958
6543
  conversation: options.conversation,
4959
6544
  idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
6545
+ // Raw string — validation/precedence is single-sourced in run.ts's
6546
+ // resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
6547
+ opencodeStartTimeout: options.opencodeStartTimeout,
4960
6548
  json: options.json,
4961
6549
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
4962
6550
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
4963
6551
  sessionCleanupMaxCount: options.sessionCleanupMaxCount,
4964
- sessionCleanupInterval: options.sessionCleanupInterval
6552
+ sessionCleanupInterval: options.sessionCleanupInterval,
6553
+ // Raw values — expansion/validation is single-sourced in run.ts's
6554
+ // resolveFileSyncDirectories.
6555
+ enableFileSyncTo: options.enableFileSyncTo,
6556
+ tunnelReadyFile: options.tunnelReadyFile
4965
6557
  });
4966
6558
  }
4967
6559
  );