@evident-ai/cli 3.1.1-dev.4159d3a → 3.1.1-dev.45e3647

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 = {
@@ -38,17 +38,39 @@ function getApiUrl() {
38
38
  function getTunnelUrl() {
39
39
  return tunnelOverride ?? process.env.EVIDENT_TUNNEL_URL ?? defaults.tunnelUrl;
40
40
  }
41
- var config = new Conf({
42
- projectName: "evident",
43
- projectSuffix: "",
44
- defaults
45
- });
46
41
  var credentials = new Conf({
47
42
  projectName: "evident",
48
43
  projectSuffix: "",
49
44
  configName: "credentials",
50
- defaults: {}
45
+ defaults: {},
46
+ configFileMode: 384
51
47
  });
48
+ var CREDENTIALS_FILE_MODE = 384;
49
+ var CREDENTIALS_DIR_MODE = 448;
50
+ var permissionWarningEmitted = false;
51
+ function hardenCredentialsPermissions() {
52
+ if (process.platform === "win32") {
53
+ return;
54
+ }
55
+ const file = credentials.path;
56
+ for (const [path, mode] of [
57
+ [file, CREDENTIALS_FILE_MODE],
58
+ [dirname(file), CREDENTIALS_DIR_MODE]
59
+ ]) {
60
+ try {
61
+ if (existsSync(path) && (statSync(path).mode & 511) !== mode) {
62
+ chmodSync(path, mode);
63
+ }
64
+ } catch (err) {
65
+ if (!permissionWarningEmitted) {
66
+ permissionWarningEmitted = true;
67
+ console.error(
68
+ `[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)}`
69
+ );
70
+ }
71
+ }
72
+ }
73
+ }
52
74
  function getApiUrlConfig() {
53
75
  return getApiUrl();
54
76
  }
@@ -59,6 +81,7 @@ function credentialsKey() {
59
81
  return getApiUrl();
60
82
  }
61
83
  function getCredentials() {
84
+ hardenCredentialsPermissions();
62
85
  const byEndpoint = credentials.get("byEndpoint") ?? {};
63
86
  return byEndpoint[credentialsKey()] ?? {};
64
87
  }
@@ -70,14 +93,17 @@ function setCredentials(creds) {
70
93
  expiresAt: creds.expiresAt
71
94
  };
72
95
  credentials.set("byEndpoint", byEndpoint);
96
+ hardenCredentialsPermissions();
73
97
  }
74
98
  function clearCredentials() {
75
99
  const byEndpoint = credentials.get("byEndpoint") ?? {};
76
100
  delete byEndpoint[credentialsKey()];
77
101
  credentials.set("byEndpoint", byEndpoint);
102
+ hardenCredentialsPermissions();
78
103
  }
79
104
  function clearAllCredentials() {
80
105
  credentials.clear();
106
+ hardenCredentialsPermissions();
81
107
  }
82
108
  function getCliName() {
83
109
  const argv1 = process.argv[1] || "";
@@ -236,16 +262,28 @@ async function getToken() {
236
262
  }
237
263
  return null;
238
264
  }
265
+ function toError(err) {
266
+ return err instanceof Error ? err : new Error(String(err));
267
+ }
239
268
  async function deleteToken(options = {}) {
240
269
  const keytar = await getKeytar();
270
+ const failures = [];
241
271
  if (keytar) {
242
272
  if (options.all) {
243
- const all = await keytar.findCredentials(SERVICE_NAME).catch(() => []);
273
+ let accounts = [];
274
+ try {
275
+ accounts = await keytar.findCredentials(SERVICE_NAME);
276
+ } catch (err) {
277
+ failures.push({ type: "enumerate", error: toError(err) });
278
+ }
244
279
  await Promise.all(
245
- all.map(
246
- (entry) => keytar.deletePassword(SERVICE_NAME, entry.account).catch(() => {
247
- })
248
- )
280
+ accounts.map(async (entry) => {
281
+ try {
282
+ await keytar.deletePassword(SERVICE_NAME, entry.account);
283
+ } catch (err) {
284
+ failures.push({ type: "delete", account: entry.account, error: toError(err) });
285
+ }
286
+ })
249
287
  );
250
288
  } else {
251
289
  await keytar.deletePassword(SERVICE_NAME, keychainAccount());
@@ -256,6 +294,7 @@ async function deleteToken(options = {}) {
256
294
  } else {
257
295
  clearCredentials();
258
296
  }
297
+ return { failures };
259
298
  }
260
299
 
261
300
  // src/utils/ui.ts
@@ -285,14 +324,14 @@ function blank() {
285
324
  console.log();
286
325
  }
287
326
  function waitForEnter(prompt = "Press Enter to continue...") {
288
- return new Promise((resolve2) => {
327
+ return new Promise((resolve3) => {
289
328
  process.stdout.write(chalk.dim(prompt));
290
329
  const handler = () => {
291
330
  process.stdin.removeListener("data", handler);
292
331
  process.stdin.setRawMode?.(false);
293
332
  process.stdin.pause();
294
333
  console.log();
295
- resolve2();
334
+ resolve3();
296
335
  };
297
336
  if (process.stdin.isTTY) {
298
337
  process.stdin.setRawMode?.(true);
@@ -302,7 +341,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
302
341
  });
303
342
  }
304
343
  function sleep(ms) {
305
- return new Promise((resolve2) => setTimeout(resolve2, ms));
344
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
306
345
  }
307
346
 
308
347
  // src/commands/login.ts
@@ -373,22 +412,25 @@ async function deviceFlowLogin(options) {
373
412
  }
374
413
  async function tokenLogin() {
375
414
  console.log("Token login mode.");
376
- console.log("Visit your Evident dashboard to generate a CLI token.");
415
+ console.log("Create a token under Settings \u2192 CLI tokens in the dashboard, then paste it below.");
416
+ console.log(
417
+ "(Alternatively, run `evident login` on a machine with a browser, or set EVIDENT_TOKEN for CI.)"
418
+ );
377
419
  blank();
378
420
  process.stdout.write("Paste token: ");
379
- const token = await new Promise((resolve2) => {
421
+ const token = await new Promise((resolve3) => {
380
422
  let data = "";
381
423
  process.stdin.setEncoding("utf8");
382
424
  process.stdin.on("data", (chunk) => {
383
425
  data += chunk;
384
426
  });
385
427
  process.stdin.on("end", () => {
386
- resolve2(data.trim());
428
+ resolve3(data.trim());
387
429
  });
388
430
  if (process.stdin.isTTY) {
389
431
  process.stdin.once("data", (chunk) => {
390
432
  process.stdin.pause();
391
- resolve2(chunk.toString().trim());
433
+ resolve3(chunk.toString().trim());
392
434
  });
393
435
  process.stdin.resume();
394
436
  }
@@ -397,13 +439,22 @@ async function tokenLogin() {
397
439
  printError("No token provided.");
398
440
  process.exit(1);
399
441
  }
442
+ await validateAndStoreToken(token);
443
+ }
444
+ async function validateAndStoreToken(token) {
400
445
  const spinner = ora("Validating token...").start();
401
446
  try {
402
- const result = await api.post("/auth/token/validate", { token });
447
+ const result = await api.get("/me", {
448
+ headers: { Authorization: `Bearer ${token}` }
449
+ });
450
+ if (!result.user) {
451
+ throw new Error(
452
+ "This token is not a user login (e.g. a runner key). Paste a CLI token instead."
453
+ );
454
+ }
403
455
  await storeToken({
404
456
  token,
405
- user: result.user,
406
- expiresAt: result.expires_at
457
+ user: { email: result.user.email }
407
458
  });
408
459
  spinner.stop();
409
460
  printSuccess(`Logged in as ${chalk2.bold(result.user.email)}`);
@@ -423,9 +474,22 @@ async function login(options) {
423
474
  }
424
475
 
425
476
  // src/commands/logout.ts
477
+ function describeFailure(failure) {
478
+ if (failure.type === "enumerate") {
479
+ return `could not list stored keychain entries (${failure.error.message})`;
480
+ }
481
+ return `${failure.account} (${failure.error.message})`;
482
+ }
426
483
  async function logout(options = {}) {
427
484
  if (options.all) {
428
- await deleteToken({ all: true });
485
+ const result = await deleteToken({ all: true });
486
+ if (result.failures.length > 0) {
487
+ printError(
488
+ `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.`
489
+ );
490
+ process.exitCode = 1;
491
+ return;
492
+ }
429
493
  printSuccess("Logged out of all endpoints.");
430
494
  return;
431
495
  }
@@ -450,7 +514,9 @@ async function whoami() {
450
514
  blank();
451
515
  console.log(keyValue("Endpoint", apiUrl));
452
516
  console.log(keyValue("User", chalk3.bold(credentials2.user.email)));
453
- console.log(keyValue("User ID", credentials2.user.id));
517
+ if (credentials2.user.id) {
518
+ console.log(keyValue("User ID", credentials2.user.id));
519
+ }
454
520
  if (credentials2.expiresAt) {
455
521
  const expiresAt = new Date(credentials2.expiresAt);
456
522
  const now = /* @__PURE__ */ new Date();
@@ -463,13 +529,473 @@ async function whoami() {
463
529
  console.log(keyValue("Expires", `${daysRemaining} days`));
464
530
  }
465
531
  }
466
- blank();
532
+ blank();
533
+ }
534
+
535
+ // src/lib/auth.ts
536
+ async function getAuthCredentials() {
537
+ const runnerKey = process.env.EVIDENT_RUNNER_KEY;
538
+ const agentKey = process.env.EVIDENT_AGENT_KEY;
539
+ if (runnerKey) {
540
+ return {
541
+ token: runnerKey,
542
+ authType: "agent_key",
543
+ keySource: "runner_key",
544
+ notice: agentKey ? "Both EVIDENT_RUNNER_KEY and EVIDENT_AGENT_KEY are set; using EVIDENT_RUNNER_KEY." : void 0
545
+ };
546
+ }
547
+ if (agentKey) {
548
+ return { token: agentKey, authType: "agent_key", keySource: "agent_key" };
549
+ }
550
+ const userToken = process.env.EVIDENT_TOKEN;
551
+ if (userToken) {
552
+ return { token: userToken, authType: "bearer" };
553
+ }
554
+ const keychainCreds = await getToken();
555
+ if (keychainCreds) {
556
+ return {
557
+ token: keychainCreds.token,
558
+ authType: "bearer",
559
+ user: keychainCreds.user
560
+ };
561
+ }
562
+ return null;
563
+ }
564
+ function getAuthHeader(credentials2) {
565
+ if (credentials2.authType === "agent_key") {
566
+ return `SandboxKey ${credentials2.token}`;
567
+ }
568
+ return `Bearer ${credentials2.token}`;
569
+ }
570
+ function isInteractive(jsonOutput) {
571
+ if (jsonOutput) return false;
572
+ if (process.env.CI) return false;
573
+ if (process.env.GITHUB_ACTIONS) return false;
574
+ if (!process.stdin.isTTY) return false;
575
+ return true;
576
+ }
577
+
578
+ // src/commands/agent-lookup.ts
579
+ async function readErrorMessage(response) {
580
+ const text = await response.text().catch(() => "");
581
+ if (!text) return response.statusText || void 0;
582
+ try {
583
+ const data = JSON.parse(text);
584
+ const message = data.message ?? data.error;
585
+ if (typeof message === "string" && message.trim()) {
586
+ return message;
587
+ }
588
+ } catch {
589
+ }
590
+ return text.trim() || response.statusText || void 0;
591
+ }
592
+ function authFailureHint(apiUrl, serverMessage) {
593
+ const reason = serverMessage ? `: ${serverMessage}` : "";
594
+ return `Authentication failed${reason}. Your credentials were rejected by ${apiUrl}. This usually means you logged in against a different environment, or your session expired \u2014 log in again pointing at this endpoint and retry.`;
595
+ }
596
+ async function resolveAgentIdFromKey(authHeader) {
597
+ const apiUrl = getApiUrlConfig();
598
+ try {
599
+ const response = await fetch(`${apiUrl}/me`, {
600
+ headers: { Authorization: authHeader }
601
+ });
602
+ if (response.status === 401) {
603
+ const serverMessage = await readErrorMessage(response);
604
+ return { error: authFailureHint(apiUrl, serverMessage), authFailed: true };
605
+ }
606
+ if (!response.ok) {
607
+ const serverMessage = await readErrorMessage(response);
608
+ return {
609
+ error: `Failed to resolve runner from key (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
610
+ };
611
+ }
612
+ const data = await response.json();
613
+ if (data.auth_type === "agent_key" && data.agent_id) {
614
+ return { agent_id: data.agent_id };
615
+ }
616
+ return {
617
+ error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
618
+ };
619
+ } catch (error2) {
620
+ const message = error2 instanceof Error ? error2.message : "Unknown error";
621
+ return { error: `Failed to resolve runner from key: ${message}` };
622
+ }
623
+ }
624
+ var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
625
+ async function notifyAgentDisconnected(agentId, authHeader) {
626
+ const apiUrl = getApiUrlConfig();
627
+ try {
628
+ const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
629
+ method: "POST",
630
+ headers: { Authorization: authHeader },
631
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
632
+ });
633
+ if (!response.ok) {
634
+ const serverMessage = await readErrorMessage(response);
635
+ return {
636
+ ok: false,
637
+ error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
638
+ };
639
+ }
640
+ return { ok: true };
641
+ } catch (error2) {
642
+ return { ok: false, error: describeBestEffortError(error2) };
643
+ }
644
+ }
645
+ function describeBestEffortError(error2) {
646
+ const name = error2?.name;
647
+ if (name === "TimeoutError" || name === "AbortError") {
648
+ return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
649
+ }
650
+ return error2 instanceof Error ? error2.message : String(error2);
651
+ }
652
+ async function reportMicrovmId(agentId, authHeader, microvmId) {
653
+ try {
654
+ const apiUrl = getApiUrlConfig();
655
+ const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
656
+ method: "POST",
657
+ headers: { Authorization: authHeader, "Content-Type": "application/json" },
658
+ body: JSON.stringify({ microvm_id: microvmId }),
659
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
660
+ });
661
+ if (!response.ok) {
662
+ const serverMessage = await readErrorMessage(response);
663
+ return {
664
+ ok: false,
665
+ error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
666
+ };
667
+ }
668
+ return { ok: true };
669
+ } catch (error2) {
670
+ return { ok: false, error: describeBestEffortError(error2) };
671
+ }
672
+ }
673
+ function toReportedWindow(window) {
674
+ if (!window) return null;
675
+ return { utilization: window.utilization, resets_at: window.resetsAt };
676
+ }
677
+ async function reportClaudeUsage(agentId, authHeader, snapshot) {
678
+ try {
679
+ const apiUrl = getApiUrlConfig();
680
+ const response = await fetch(`${apiUrl}/runners/${agentId}/claude-usage`, {
681
+ method: "POST",
682
+ headers: { Authorization: authHeader, "Content-Type": "application/json" },
683
+ body: JSON.stringify({
684
+ five_hour: toReportedWindow(snapshot.fiveHour),
685
+ seven_day: toReportedWindow(snapshot.sevenDay)
686
+ }),
687
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
688
+ });
689
+ if (!response.ok) {
690
+ const serverMessage = await readErrorMessage(response);
691
+ return {
692
+ ok: false,
693
+ error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
694
+ };
695
+ }
696
+ return { ok: true };
697
+ } catch (error2) {
698
+ return { ok: false, error: describeBestEffortError(error2) };
699
+ }
700
+ }
701
+ async function getAgentInfo(agentId, authHeader) {
702
+ const apiUrl = getApiUrlConfig();
703
+ try {
704
+ const response = await fetch(`${apiUrl}/runners/${agentId}`, {
705
+ headers: { Authorization: authHeader }
706
+ });
707
+ if (response.status === 401) {
708
+ const serverMessage = await readErrorMessage(response);
709
+ return { valid: false, error: authFailureHint(apiUrl, serverMessage), authFailed: true };
710
+ }
711
+ if (response.status === 403) {
712
+ const serverMessage = await readErrorMessage(response);
713
+ return {
714
+ valid: false,
715
+ error: serverMessage ?? "You do not have access to this runner (it may belong to a different team or organization)."
716
+ };
717
+ }
718
+ if (response.status === 404) {
719
+ const serverMessage = await readErrorMessage(response);
720
+ return { valid: false, error: serverMessage ?? `Runner ${agentId} not found` };
721
+ }
722
+ if (!response.ok) {
723
+ const serverMessage = await readErrorMessage(response);
724
+ return {
725
+ valid: false,
726
+ error: `API error (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
727
+ };
728
+ }
729
+ const agent = await response.json();
730
+ if (agent.agent_type !== "local") {
731
+ return {
732
+ valid: false,
733
+ error: `Runner is type '${agent.agent_type}', must be 'local' for CLI connection`
734
+ };
735
+ }
736
+ return { valid: true, agent };
737
+ } catch (error2) {
738
+ const message = error2 instanceof Error ? error2.message : "Unknown error";
739
+ return { valid: false, error: `Failed to validate runner: ${message}` };
740
+ }
741
+ }
742
+
743
+ // src/commands/status.ts
744
+ var STATUS_TIMEOUT_MS = 1e4;
745
+ function authLabelFor(credentials2) {
746
+ if (credentials2.authType === "agent_key") {
747
+ return credentials2.keySource === "agent_key" ? "runner key (EVIDENT_AGENT_KEY)" : "runner key (EVIDENT_RUNNER_KEY)";
748
+ }
749
+ return "user token";
750
+ }
751
+ function describeFetchError(error2) {
752
+ const name = error2?.name;
753
+ if (name === "TimeoutError" || name === "AbortError") {
754
+ return `timed out after ${STATUS_TIMEOUT_MS}ms waiting for a response`;
755
+ }
756
+ return error2 instanceof Error ? error2.message : String(error2);
757
+ }
758
+ async function checkStatus(jsonMode) {
759
+ const apiUrl = getApiUrlConfig();
760
+ const credentials2 = await getAuthCredentials();
761
+ if (!credentials2) {
762
+ return {
763
+ ok: false,
764
+ endpoint: apiUrl,
765
+ reason: "no_credentials",
766
+ error: "No credentials configured. Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY), or EVIDENT_TOKEN, or run `evident login`.",
767
+ exitCode: 1
768
+ };
769
+ }
770
+ if (credentials2.notice && !jsonMode) {
771
+ printWarning(credentials2.notice);
772
+ }
773
+ let response;
774
+ try {
775
+ response = await fetch(`${apiUrl}/me`, {
776
+ headers: { Authorization: getAuthHeader(credentials2) },
777
+ signal: AbortSignal.timeout(STATUS_TIMEOUT_MS)
778
+ });
779
+ } catch (error2) {
780
+ return {
781
+ ok: false,
782
+ endpoint: apiUrl,
783
+ authLabel: authLabelFor(credentials2),
784
+ reason: "unreachable",
785
+ error: `Could not reach ${apiUrl}: ${describeFetchError(error2)}. The credentials were NOT validated.`,
786
+ exitCode: 75
787
+ };
788
+ }
789
+ if (response.status === 401) {
790
+ const serverMessage = await readErrorMessage(response);
791
+ return {
792
+ ok: false,
793
+ endpoint: apiUrl,
794
+ authLabel: authLabelFor(credentials2),
795
+ reason: "unauthorized",
796
+ error: authFailureHint(apiUrl, serverMessage),
797
+ exitCode: 1
798
+ };
799
+ }
800
+ if (response.status >= 500) {
801
+ const serverMessage = await readErrorMessage(response);
802
+ return {
803
+ ok: false,
804
+ endpoint: apiUrl,
805
+ authLabel: authLabelFor(credentials2),
806
+ reason: "unreachable",
807
+ error: `${apiUrl} returned HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}. The credentials were NOT validated.`,
808
+ exitCode: 75
809
+ };
810
+ }
811
+ if (!response.ok) {
812
+ const serverMessage = await readErrorMessage(response);
813
+ return {
814
+ ok: false,
815
+ endpoint: apiUrl,
816
+ authLabel: authLabelFor(credentials2),
817
+ reason: "http_error",
818
+ error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`,
819
+ exitCode: 1
820
+ };
821
+ }
822
+ const data = await response.json();
823
+ return {
824
+ ok: true,
825
+ endpoint: apiUrl,
826
+ authType: data.auth_type,
827
+ authLabel: authLabelFor(credentials2),
828
+ runnerId: data.auth_type === "agent_key" ? data.agent_id : void 0,
829
+ reason: "ok",
830
+ exitCode: 0
831
+ };
832
+ }
833
+ function printJson(result) {
834
+ const payload = {
835
+ ok: result.ok,
836
+ endpoint: result.endpoint
837
+ };
838
+ if (result.authType) payload.auth_type = result.authType;
839
+ if (result.runnerId) payload.runner_id = result.runnerId;
840
+ if (result.reason) payload.reason = result.reason;
841
+ if (result.error) payload.error = result.error;
842
+ console.log(JSON.stringify(payload));
843
+ }
844
+ function printHuman(result) {
845
+ blank();
846
+ console.log(keyValue("Endpoint", result.endpoint));
847
+ if (result.ok) {
848
+ console.log(keyValue("Auth", result.authLabel ?? "\u2014"));
849
+ if (result.runnerId) {
850
+ console.log(keyValue("Runner", result.runnerId));
851
+ }
852
+ console.log(keyValue("Status", "OK \u2014 credentials accepted"));
853
+ blank();
854
+ return;
855
+ }
856
+ if (result.authLabel) {
857
+ console.log(keyValue("Auth", result.authLabel));
858
+ }
859
+ blank();
860
+ printError(result.error ?? "Unknown error");
861
+ }
862
+ async function status(options = {}) {
863
+ const result = await checkStatus(Boolean(options.json));
864
+ if (options.json) {
865
+ printJson(result);
866
+ } else {
867
+ printHuman(result);
868
+ }
869
+ process.exit(result.exitCode);
870
+ }
871
+
872
+ // src/lib/claude-usage.ts
873
+ import { execFileSync } from "child_process";
874
+ import { readFileSync } from "fs";
875
+ import { homedir } from "os";
876
+ import { join } from "path";
877
+ var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
878
+ var KEYCHAIN_SERVICE = "Claude Code-credentials";
879
+ function parseClaudeCliCredentials(raw) {
880
+ let parsed;
881
+ try {
882
+ parsed = JSON.parse(raw);
883
+ } catch {
884
+ return null;
885
+ }
886
+ const data = parsed.claudeAiOauth ?? parsed;
887
+ const creds = data;
888
+ if (typeof creds.accessToken !== "string" || typeof creds.expiresAt !== "number") {
889
+ return null;
890
+ }
891
+ return { accessToken: creds.accessToken, expiresAt: creds.expiresAt };
892
+ }
893
+ function readClaudeCliCredentials() {
894
+ if (process.platform === "darwin") {
895
+ try {
896
+ const raw = execFileSync(
897
+ "/usr/bin/security",
898
+ ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-w"],
899
+ { encoding: "utf-8", timeout: 2e3, stdio: ["pipe", "pipe", "ignore"] }
900
+ );
901
+ return parseClaudeCliCredentials(raw);
902
+ } catch {
903
+ return null;
904
+ }
905
+ }
906
+ try {
907
+ const raw = readFileSync(join(homedir(), ".claude", ".credentials.json"), "utf-8");
908
+ return parseClaudeCliCredentials(raw);
909
+ } catch {
910
+ return null;
911
+ }
912
+ }
913
+ var ClaudeUsageError = class extends Error {
914
+ constructor(message, reason) {
915
+ super(message);
916
+ this.reason = reason;
917
+ }
918
+ };
919
+ function isLocalCredentialProblem(err) {
920
+ return err instanceof ClaudeUsageError && (err.reason === "no_credentials" || err.reason === "credentials_expired");
921
+ }
922
+ function normalizeResetsAt(value) {
923
+ const ms = Date.parse(value);
924
+ return Number.isNaN(ms) ? null : new Date(ms).toISOString();
925
+ }
926
+ function toWindow(value) {
927
+ if (!value || typeof value !== "object") {
928
+ return null;
929
+ }
930
+ const window = value;
931
+ if (typeof window.utilization !== "number" || typeof window.resets_at !== "string") {
932
+ return null;
933
+ }
934
+ const resetsAt = normalizeResetsAt(window.resets_at);
935
+ if (resetsAt === null) {
936
+ return null;
937
+ }
938
+ return { utilization: window.utilization, resetsAt };
939
+ }
940
+ async function getClaudeUsage() {
941
+ const credentials2 = readClaudeCliCredentials();
942
+ if (!credentials2) {
943
+ throw new ClaudeUsageError(
944
+ "No local Claude Code login found. Run `claude` once to sign in with your Claude subscription.",
945
+ "no_credentials"
946
+ );
947
+ }
948
+ if (credentials2.expiresAt < Date.now()) {
949
+ throw new ClaudeUsageError(
950
+ "Claude Code credentials have expired. Run `claude` to refresh them.",
951
+ "credentials_expired"
952
+ );
953
+ }
954
+ const res = await fetch(CLAUDE_USAGE_URL, {
955
+ headers: {
956
+ Authorization: `Bearer ${credentials2.accessToken}`,
957
+ "Content-Type": "application/json",
958
+ "anthropic-version": "2023-06-01"
959
+ }
960
+ });
961
+ if (!res.ok) {
962
+ throw new ClaudeUsageError(`Claude usage request failed: HTTP ${res.status}`, "request_failed");
963
+ }
964
+ const body = await res.json();
965
+ return {
966
+ fiveHour: toWindow(body.five_hour),
967
+ sevenDay: toWindow(body.seven_day)
968
+ };
969
+ }
970
+
971
+ // src/commands/claude-usage.ts
972
+ function formatWindow(label, window) {
973
+ if (!window) {
974
+ return keyValue(label, "not available for this plan");
975
+ }
976
+ const resetsAt = new Date(window.resetsAt);
977
+ return keyValue(label, `${window.utilization}% used, resets ${resetsAt.toLocaleString()}`);
978
+ }
979
+ async function claudeUsage() {
980
+ try {
981
+ const usage = await getClaudeUsage();
982
+ blank();
983
+ console.log(formatWindow("5-hour session", usage.fiveHour));
984
+ console.log(formatWindow("7-day", usage.sevenDay));
985
+ blank();
986
+ } catch (err) {
987
+ if (err instanceof ClaudeUsageError) {
988
+ printError(err.message);
989
+ process.exit(1);
990
+ }
991
+ throw err;
992
+ }
467
993
  }
468
994
 
469
995
  // src/commands/run.ts
996
+ import { homedir as homedir3 } from "os";
997
+ import { isAbsolute as isAbsolute2, join as join3, parse, resolve as resolvePath } from "path";
470
998
  import chalk6 from "chalk";
471
- import ora3 from "ora";
472
- import { select as select3 } from "@inquirer/prompts";
473
999
 
474
1000
  // ../../packages/types/src/telemetry/index.ts
475
1001
  var TelemetryEventTypes = {
@@ -478,13 +1004,20 @@ var TelemetryEventTypes = {
478
1004
  AGENT_DISCONNECTED: "agent.disconnected",
479
1005
  AGENT_MESSAGE_PROCESSING: "agent.message_processing",
480
1006
  AGENT_MESSAGE_DONE: "agent.message_done",
481
- AGENT_MESSAGE_FAILED: "agent.message_failed"
1007
+ AGENT_MESSAGE_FAILED: "agent.message_failed",
1008
+ // A `warn`/`error` runner-side log line forwarded server-side for
1009
+ // observability (issue #916) — see `apps/cli/src/lib/runner-activity-telemetry.ts`.
1010
+ RUNNER_ACTIVITY: "runner.activity"
482
1011
  };
483
1012
 
484
1013
  // ../../packages/types/src/tunnel/index.ts
485
1014
  var MAX_FRAME_BYTES = 256 * 1024;
486
1015
  var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
487
1016
 
1017
+ // ../../packages/types/src/runner-files.ts
1018
+ var MAX_FILE_PUSH_BYTES = 64 * 1024;
1019
+ var MAX_FILE_SYNC_DIRECTORIES = 16;
1020
+
488
1021
  // ../../packages/types/src/logging/index.ts
489
1022
  var CORRELATION_ID_HEADER = "x-evident-correlation-id";
490
1023
  function log(level, event, fields) {
@@ -499,6 +1032,12 @@ function log(level, event, fields) {
499
1032
  );
500
1033
  }
501
1034
  }
1035
+ function errorFields(err) {
1036
+ if (err instanceof Error) {
1037
+ return { error: err.message, error_name: err.name };
1038
+ }
1039
+ return { error: String(err) };
1040
+ }
502
1041
  function stripQuery(url) {
503
1042
  try {
504
1043
  return new URL(url).pathname;
@@ -508,6 +1047,10 @@ function stripQuery(url) {
508
1047
  }
509
1048
  }
510
1049
 
1050
+ // src/commands/run.ts
1051
+ import ora3 from "ora";
1052
+ import { select as select3 } from "@inquirer/prompts";
1053
+
511
1054
  // src/lib/telemetry.ts
512
1055
  var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
513
1056
  function getCliVersion() {
@@ -519,6 +1062,13 @@ var isShuttingDown = false;
519
1062
  var FLUSH_INTERVAL_MS = 5e3;
520
1063
  var MAX_BUFFER_SIZE = 50;
521
1064
  var FLUSH_TIMEOUT_MS = 3e3;
1065
+ var authProvider = null;
1066
+ function setTelemetryAuthProvider(provider) {
1067
+ authProvider = provider;
1068
+ }
1069
+ var FLUSH_FAILURE_LOG_INTERVAL_MS = 6e4;
1070
+ var lastFlushFailureLoggedAt = 0;
1071
+ var suppressedFlushFailureCount = 0;
522
1072
  function logEvent(eventType, options = {}) {
523
1073
  const event = {
524
1074
  event_type: eventType,
@@ -553,9 +1103,16 @@ async function flushEvents() {
553
1103
  flushTimeout = null;
554
1104
  }
555
1105
  try {
556
- const credentials2 = await getToken();
557
- if (!credentials2) {
558
- return;
1106
+ const providerContext = authProvider?.();
1107
+ let authHeader;
1108
+ if (providerContext?.authHeader) {
1109
+ authHeader = providerContext.authHeader;
1110
+ } else {
1111
+ const credentials2 = await getToken();
1112
+ if (!credentials2) {
1113
+ return;
1114
+ }
1115
+ authHeader = `Bearer ${credentials2.token}`;
559
1116
  }
560
1117
  const apiUrl = getApiUrlConfig();
561
1118
  const controller = new AbortController();
@@ -570,7 +1127,7 @@ async function flushEvents() {
570
1127
  method: "POST",
571
1128
  headers: {
572
1129
  "Content-Type": "application/json",
573
- Authorization: `Bearer ${credentials2.token}`
1130
+ Authorization: authHeader
574
1131
  },
575
1132
  body: JSON.stringify(request),
576
1133
  signal: controller.signal
@@ -582,8 +1139,15 @@ async function flushEvents() {
582
1139
  clearTimeout(timeout);
583
1140
  }
584
1141
  } catch (error2) {
585
- if (process.env.DEBUG) {
586
- console.error("Telemetry error:", error2);
1142
+ const now = Date.now();
1143
+ if (now - lastFlushFailureLoggedAt >= FLUSH_FAILURE_LOG_INTERVAL_MS) {
1144
+ const message = error2 instanceof Error ? error2.message : String(error2);
1145
+ const suffix = suppressedFlushFailureCount > 0 ? ` (${suppressedFlushFailureCount} more suppressed in the last ${FLUSH_FAILURE_LOG_INTERVAL_MS / 1e3}s)` : "";
1146
+ console.error(`Telemetry flush error: ${message}${suffix}`);
1147
+ lastFlushFailureLoggedAt = now;
1148
+ suppressedFlushFailureCount = 0;
1149
+ } else {
1150
+ suppressedFlushFailureCount++;
587
1151
  }
588
1152
  }
589
1153
  }
@@ -652,47 +1216,67 @@ var EventTypes = {
652
1216
  DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
653
1217
  };
654
1218
 
655
- // src/lib/auth.ts
656
- async function getAuthCredentials() {
657
- const runnerKey = process.env.EVIDENT_RUNNER_KEY;
658
- const agentKey = process.env.EVIDENT_AGENT_KEY;
659
- if (runnerKey) {
660
- return {
661
- token: runnerKey,
662
- authType: "agent_key",
663
- keySource: "runner_key",
664
- notice: agentKey ? "Both EVIDENT_RUNNER_KEY and EVIDENT_AGENT_KEY are set; using EVIDENT_RUNNER_KEY." : void 0
665
- };
666
- }
667
- if (agentKey) {
668
- return { token: agentKey, authType: "agent_key", keySource: "agent_key" };
669
- }
670
- const userToken = process.env.EVIDENT_TOKEN;
671
- if (userToken) {
672
- return { token: userToken, authType: "bearer" };
1219
+ // src/lib/runner-activity-telemetry.ts
1220
+ var FORWARDED_LEVELS = /* @__PURE__ */ new Set(["warn", "error"]);
1221
+ var SEVERITY_BY_LEVEL = {
1222
+ warn: "warning",
1223
+ error: "error"
1224
+ };
1225
+ var MAX_MESSAGE_LENGTH = 500;
1226
+ var TRUNCATION_MARKER = "\u2026";
1227
+ function redact(message) {
1228
+ return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
1229
+ }
1230
+ function truncate(message) {
1231
+ if (message.length <= MAX_MESSAGE_LENGTH) return message;
1232
+ return message.slice(0, MAX_MESSAGE_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
1233
+ }
1234
+ var RATE_LIMIT_WINDOW_MS = 6e4;
1235
+ var RATE_LIMIT_MAX_EVENTS = 30;
1236
+ var windowStartedAt = 0;
1237
+ var windowCount = 0;
1238
+ var windowDroppedCount = 0;
1239
+ function admitUnderRateLimit(now) {
1240
+ if (now - windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
1241
+ if (windowDroppedCount > 0) {
1242
+ console.error(
1243
+ `[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)`
1244
+ );
1245
+ }
1246
+ windowStartedAt = now;
1247
+ windowCount = 0;
1248
+ windowDroppedCount = 0;
673
1249
  }
674
- const keychainCreds = await getToken();
675
- if (keychainCreds) {
676
- return {
677
- token: keychainCreds.token,
678
- authType: "bearer",
679
- user: keychainCreds.user
680
- };
1250
+ if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
1251
+ windowDroppedCount++;
1252
+ if (windowDroppedCount === 1) {
1253
+ console.error(
1254
+ `[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
1255
+ );
1256
+ }
1257
+ return false;
681
1258
  }
682
- return null;
1259
+ windowCount++;
1260
+ return true;
683
1261
  }
684
- function getAuthHeader(credentials2) {
685
- if (credentials2.authType === "agent_key") {
686
- return `SandboxKey ${credentials2.token}`;
1262
+ function forwardRunnerActivity(entry, context) {
1263
+ try {
1264
+ if (!FORWARDED_LEVELS.has(entry.level)) return;
1265
+ if (!context.agentId || !context.authHeader) return;
1266
+ if (!admitUnderRateLimit(Date.now())) return;
1267
+ const rawMessage = entry.error ?? entry.message ?? "";
1268
+ const message = truncate(redact(rawMessage));
1269
+ logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
1270
+ severity: SEVERITY_BY_LEVEL[entry.level],
1271
+ message,
1272
+ metadata: { source: "cli.run" },
1273
+ agentId: context.agentId
1274
+ });
1275
+ } catch (err) {
1276
+ console.error(
1277
+ `[runner-activity-telemetry] failed to forward runner activity: ${err instanceof Error ? err.message : String(err)}`
1278
+ );
687
1279
  }
688
- return `Bearer ${credentials2.token}`;
689
- }
690
- function isInteractive(jsonOutput) {
691
- if (jsonOutput) return false;
692
- if (process.env.CI) return false;
693
- if (process.env.GITHUB_ACTIONS) return false;
694
- if (!process.stdin.isTTY) return false;
695
- return true;
696
1280
  }
697
1281
 
698
1282
  // src/lib/opencode/health.ts
@@ -719,7 +1303,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
719
1303
  if (health.healthy) {
720
1304
  return health;
721
1305
  }
722
- await new Promise((resolve2) => setTimeout(resolve2, 1e3));
1306
+ await new Promise((resolve3) => setTimeout(resolve3, 1e3));
723
1307
  }
724
1308
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
725
1309
  }
@@ -1267,6 +1851,16 @@ async function buildFileParts(attachments, capable) {
1267
1851
  );
1268
1852
  dataUrl = null;
1269
1853
  }
1854
+ if (dataUrl !== null && typeof dataUrl === "object") {
1855
+ outcomes.push({
1856
+ index: a.index,
1857
+ mime: a.mime,
1858
+ filename: a.filename,
1859
+ status: "failed",
1860
+ reason: "needs_reauth"
1861
+ });
1862
+ continue;
1863
+ }
1270
1864
  if (dataUrl == null) {
1271
1865
  outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
1272
1866
  continue;
@@ -1348,7 +1942,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
1348
1942
  }
1349
1943
  }
1350
1944
  if (attempt < READ_BACK_ATTEMPTS - 1) {
1351
- await new Promise((resolve2) => setTimeout(resolve2, READ_BACK_DELAY_MS));
1945
+ await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
1352
1946
  }
1353
1947
  }
1354
1948
  return null;
@@ -1476,6 +2070,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
1476
2070
  const reply = findLastAssistantReplyFor(messages, userMessageId);
1477
2071
  return completedOf(reply) != null && finishOf(reply) === "tool-calls";
1478
2072
  }
2073
+ function isB2AbandonmentConfirmed(params) {
2074
+ return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
2075
+ }
1479
2076
  function messageError(messages, userMessageId) {
1480
2077
  const reply = findLastAssistantReplyFor(messages, userMessageId);
1481
2078
  const error2 = errorOf(reply);
@@ -1489,6 +2086,42 @@ function messageError(messages, userMessageId) {
1489
2086
  }
1490
2087
  return "The agent run failed.";
1491
2088
  }
2089
+ function messageFailure(messages, userMessageId) {
2090
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
2091
+ const error2 = errorOf(reply);
2092
+ if (error2 == null || typeof error2 !== "object") return null;
2093
+ const e = error2;
2094
+ const replyProviderId = reply?.info?.providerID ?? null;
2095
+ const replyModelId = reply?.info?.modelID ?? null;
2096
+ if (e.name === "ProviderAuthError") {
2097
+ const data = e.data;
2098
+ const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
2099
+ return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
2100
+ }
2101
+ if (e.name === "APIError") {
2102
+ const data = e.data;
2103
+ const statusCode = data?.statusCode;
2104
+ if (statusCode === 401 || statusCode === 403) {
2105
+ return {
2106
+ kind: "model_auth",
2107
+ providerId: replyProviderId,
2108
+ modelId: replyModelId,
2109
+ reason: "rejected"
2110
+ };
2111
+ }
2112
+ }
2113
+ return null;
2114
+ }
2115
+ function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
2116
+ if (classified != null) return classified;
2117
+ if (hasConfiguredProvider !== false) return null;
2118
+ return {
2119
+ kind: "model_auth",
2120
+ providerId: replyProviderId,
2121
+ modelId: replyModelId,
2122
+ reason: "missing"
2123
+ };
2124
+ }
1492
2125
  function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1493
2126
  if (!messages || messages.length === 0) return false;
1494
2127
  return messages.some(
@@ -1684,10 +2317,11 @@ var StreamForwarder = class {
1684
2317
  * Abort every in-flight stream (e.g. on WebSocket close).
1685
2318
  */
1686
2319
  abortAll() {
1687
- for (const stream of this.inflight.values()) {
2320
+ for (const [sid, stream] of this.inflight.entries()) {
1688
2321
  try {
1689
2322
  stream.abort();
1690
- } catch {
2323
+ } catch (err) {
2324
+ log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
1691
2325
  }
1692
2326
  }
1693
2327
  this.inflight.clear();
@@ -1721,12 +2355,12 @@ var StreamForwarder = class {
1721
2355
  let endBody;
1722
2356
  if (has_body) {
1723
2357
  const chunks = [];
1724
- bodyPromise = new Promise((resolve2) => {
2358
+ bodyPromise = new Promise((resolve3) => {
1725
2359
  pushBody = (buf) => {
1726
2360
  chunks.push(buf);
1727
2361
  };
1728
2362
  endBody = () => {
1729
- resolve2(Buffer.concat(chunks));
2363
+ resolve3(Buffer.concat(chunks));
1730
2364
  };
1731
2365
  });
1732
2366
  }
@@ -1843,7 +2477,7 @@ function connectTunnel(options) {
1843
2477
  } = options;
1844
2478
  const tunnelUrl = getTunnelUrlConfig();
1845
2479
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
1846
- return new Promise((resolve2, reject) => {
2480
+ return new Promise((resolve3, reject) => {
1847
2481
  const ws = new WebSocket2(url, {
1848
2482
  headers: {
1849
2483
  Authorization: authHeader
@@ -1898,7 +2532,7 @@ function connectTunnel(options) {
1898
2532
  clearTimeout(connectionTimeout);
1899
2533
  const connectedAgentId = message.agent_id ?? agentId;
1900
2534
  onConnected?.(connectedAgentId);
1901
- resolve2({
2535
+ resolve3({
1902
2536
  ws,
1903
2537
  close: () => ws.close(1e3, "CLI shutdown")
1904
2538
  });
@@ -1960,7 +2594,11 @@ var RunnerConnection = class {
1960
2594
  if (this.connection) {
1961
2595
  try {
1962
2596
  this.connection.close();
1963
- } catch {
2597
+ } catch (err) {
2598
+ log("error", "runner_connection_close_failed", {
2599
+ agent_id: this.resolvedAgentId,
2600
+ ...errorFields(err)
2601
+ });
1964
2602
  }
1965
2603
  this.connection = null;
1966
2604
  }
@@ -2008,9 +2646,450 @@ var RunnerConnection = class {
2008
2646
  await this.sleep(delay);
2009
2647
  }
2010
2648
  }
2011
- this.reconnecting = false;
2649
+ this.reconnecting = false;
2650
+ }
2651
+ };
2652
+
2653
+ // src/lib/tunnel/ready-marker.ts
2654
+ import { writeFileSync } from "fs";
2655
+ function writeTunnelReadyMarker(path, agentId) {
2656
+ try {
2657
+ writeFileSync(path, `${agentId}
2658
+ `);
2659
+ return { ok: true };
2660
+ } catch (error2) {
2661
+ return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
2662
+ }
2663
+ }
2664
+
2665
+ // src/lib/claude-usage-reporting.ts
2666
+ var VALID_MODES = ["auto", "on", "off"];
2667
+ function resolveClaudeUsageReportingMode(flagValue, env) {
2668
+ const raw = flagValue ?? env.EVIDENT_CLAUDE_USAGE_REPORTING;
2669
+ if (raw === void 0 || raw === "") {
2670
+ return { mode: "auto", warnings: [] };
2671
+ }
2672
+ const normalized = raw.trim().toLowerCase();
2673
+ if (VALID_MODES.includes(normalized)) {
2674
+ return { mode: normalized, warnings: [] };
2675
+ }
2676
+ const source = flagValue !== void 0 ? "--claude-usage-reporting" : "EVIDENT_CLAUDE_USAGE_REPORTING";
2677
+ return {
2678
+ mode: "auto",
2679
+ warnings: [
2680
+ `Ignoring invalid ${source} "${raw}": expected one of ${VALID_MODES.join(", ")}; using auto`
2681
+ ]
2682
+ };
2683
+ }
2684
+ var BASE_REPORT_DELAY_MS = 10 * 6e4;
2685
+ var REPORT_DELAY_JITTER_FRACTION = 0.2;
2686
+ function nextReportDelayMs(random = Math.random) {
2687
+ const jitterRangeMs = BASE_REPORT_DELAY_MS * REPORT_DELAY_JITTER_FRACTION;
2688
+ return BASE_REPORT_DELAY_MS - jitterRangeMs + random() * (2 * jitterRangeMs);
2689
+ }
2690
+ var FIRST_REPORT_DELAY_MS = 5e3 + Math.random() * 1e4;
2691
+ var CLAUDE_USAGE_FAILURE_REESCALATION_TICKS = 6;
2692
+ function claudeUsageFailureLogLevel(consecutiveFailures) {
2693
+ return consecutiveFailures === 1 || consecutiveFailures % CLAUDE_USAGE_FAILURE_REESCALATION_TICKS === 0 ? "warn" : "debug";
2694
+ }
2695
+
2696
+ // src/lib/channels/driver.ts
2697
+ import { homedir as homedir2 } from "os";
2698
+
2699
+ // src/lib/file-push.ts
2700
+ import { randomUUID } from "crypto";
2701
+ import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
2702
+ import { basename, dirname as dirname2, isAbsolute, join as join2, relative, resolve as resolve2, sep } from "path";
2703
+ var FILE_MODE = 384;
2704
+ var DIRECTORY_MODE = 448;
2705
+ async function writePushedFile(request) {
2706
+ const { requestedPath, content, allowedDirectories, homeDir } = request;
2707
+ const bytes = content.byteLength;
2708
+ if (allowedDirectories.length === 0) {
2709
+ return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
2710
+ path: requestedPath,
2711
+ bytes
2712
+ });
2713
+ }
2714
+ if (bytes > MAX_FILE_PUSH_BYTES) {
2715
+ return refuse(
2716
+ "file_too_large",
2717
+ `File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
2718
+ {
2719
+ path: requestedPath,
2720
+ bytes
2721
+ }
2722
+ );
2723
+ }
2724
+ const candidate = expandAndValidate(requestedPath, homeDir);
2725
+ if (candidate === null) {
2726
+ return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
2727
+ path: requestedPath,
2728
+ bytes
2729
+ });
2730
+ }
2731
+ try {
2732
+ const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
2733
+ dirname2(candidate)
2734
+ );
2735
+ const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
2736
+ const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
2737
+ if (allowedDirectory === null) {
2738
+ return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
2739
+ path: realTarget,
2740
+ bytes
2741
+ });
2742
+ }
2743
+ if (missingSegments.length > 0) {
2744
+ await createMissingDirectories(existingAncestor, missingSegments);
2745
+ const realParent = await realpath(dirname2(realTarget));
2746
+ if (realParent !== dirname2(realTarget) || !contains(allowedDirectory, realTarget)) {
2747
+ return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
2748
+ path: realTarget,
2749
+ bytes,
2750
+ reason: "parent_changed_after_create"
2751
+ });
2752
+ }
2753
+ }
2754
+ await writeAtomically(realTarget, content);
2755
+ log("info", "file_push_written", { path: realTarget, bytes });
2756
+ return { ok: true, path: realTarget };
2757
+ } catch (err) {
2758
+ const errno = err.code ?? "UNKNOWN";
2759
+ return refuse("write_failed", `The runner could not write the file (${errno}).`, {
2760
+ path: candidate,
2761
+ bytes,
2762
+ errno,
2763
+ ...errorFields(err)
2764
+ });
2765
+ }
2766
+ }
2767
+ function expandAndValidate(requestedPath, homeDir) {
2768
+ if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
2769
+ return null;
2770
+ }
2771
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join2(homeDir, requestedPath.slice(2)) : requestedPath;
2772
+ if (expanded.split(/[/\\]/).includes("..")) {
2773
+ return null;
2774
+ }
2775
+ if (!isAbsolute(expanded)) {
2776
+ return null;
2777
+ }
2778
+ const candidate = resolve2(expanded);
2779
+ const name = basename(candidate);
2780
+ return name === "" || name === "." || name === ".." ? null : candidate;
2781
+ }
2782
+ async function resolveNearestExistingAncestor(directory) {
2783
+ const missingSegments = [];
2784
+ let current = directory;
2785
+ for (; ; ) {
2786
+ try {
2787
+ return { existingAncestor: await realpath(current), missingSegments };
2788
+ } catch (err) {
2789
+ const parent = dirname2(current);
2790
+ if (err.code !== "ENOENT" || parent === current) {
2791
+ throw err;
2792
+ }
2793
+ missingSegments.unshift(basename(current));
2794
+ current = parent;
2795
+ }
2796
+ }
2797
+ }
2798
+ async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
2799
+ for (const directory of allowedDirectories) {
2800
+ if (!isAbsolute(directory)) {
2801
+ log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
2802
+ continue;
2803
+ }
2804
+ const realDirectory = await realpathCreatingIfMissing(directory);
2805
+ if (realDirectory !== null && contains(realDirectory, realTarget)) {
2806
+ return realDirectory;
2807
+ }
2808
+ }
2809
+ return null;
2810
+ }
2811
+ async function realpathCreatingIfMissing(directory) {
2812
+ try {
2813
+ return await realpath(directory);
2814
+ } catch (err) {
2815
+ if (err.code !== "ENOENT") {
2816
+ log("warn", "file_push_allowed_directory_skipped", {
2817
+ directory,
2818
+ reason: "unresolvable",
2819
+ ...errorFields(err)
2820
+ });
2821
+ return null;
2822
+ }
2823
+ }
2824
+ try {
2825
+ await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
2826
+ await chmod(directory, DIRECTORY_MODE);
2827
+ return await realpath(directory);
2828
+ } catch (err) {
2829
+ log("warn", "file_push_allowed_directory_skipped", {
2830
+ directory,
2831
+ reason: "create_failed",
2832
+ ...errorFields(err)
2833
+ });
2834
+ return null;
2835
+ }
2836
+ }
2837
+ function contains(realDirectory, realTarget) {
2838
+ const rel = relative(realDirectory, realTarget);
2839
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
2840
+ }
2841
+ async function createMissingDirectories(existingAncestor, missingSegments) {
2842
+ let current = existingAncestor;
2843
+ for (const segment of missingSegments) {
2844
+ current = join2(current, segment);
2845
+ await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
2846
+ await chmod(current, DIRECTORY_MODE);
2847
+ }
2848
+ }
2849
+ async function writeAtomically(realTarget, content) {
2850
+ const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2851
+ let handle;
2852
+ try {
2853
+ handle = await open2(temporaryPath, "wx", FILE_MODE);
2854
+ await handle.writeFile(content);
2855
+ await handle.chmod(FILE_MODE);
2856
+ await handle.close();
2857
+ handle = void 0;
2858
+ await rename(temporaryPath, realTarget);
2859
+ } catch (err) {
2860
+ await discardTemporaryFile(temporaryPath, handle);
2861
+ throw err;
2862
+ }
2863
+ }
2864
+ async function discardTemporaryFile(temporaryPath, handle) {
2865
+ try {
2866
+ await handle?.close();
2867
+ } catch (err) {
2868
+ log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
2869
+ }
2870
+ try {
2871
+ await unlink(temporaryPath);
2872
+ } catch (err) {
2873
+ const errno = err.code;
2874
+ if (errno !== "ENOENT" && errno !== "ENOTDIR") {
2875
+ log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
2876
+ }
2877
+ }
2878
+ }
2879
+ function refuse(code, message, fields) {
2880
+ log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
2881
+ return { ok: false, code, message };
2882
+ }
2883
+
2884
+ // src/lib/runner-file-sync.ts
2885
+ var MAX_ACK_ATTEMPTS = 5;
2886
+ async function syncPendingRunnerFiles(options) {
2887
+ const pending = await listPendingFiles(options);
2888
+ const pendingIds = new Set(pending.map((file) => file.id));
2889
+ for (const id of options.ackFailures.keys()) {
2890
+ if (!pendingIds.has(id)) options.ackFailures.delete(id);
2891
+ }
2892
+ if (pending.length === 0) return 0;
2893
+ options.log({
2894
+ level: "info",
2895
+ message: `Runner file sync: ${pending.length} file(s) queued for this runner`
2896
+ });
2897
+ let applied = 0;
2898
+ for (const file of pending) {
2899
+ if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
2900
+ if (await applyOne(options, file)) applied += 1;
2901
+ }
2902
+ return applied;
2903
+ }
2904
+ async function listPendingFiles(options) {
2905
+ let res;
2906
+ try {
2907
+ res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
2908
+ headers: { Authorization: options.getAuthHeader() }
2909
+ });
2910
+ } catch (err) {
2911
+ options.log({
2912
+ level: "warn",
2913
+ message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
2914
+ });
2915
+ return [];
2916
+ }
2917
+ if (!res.ok) {
2918
+ options.log({
2919
+ level: res.status === 404 ? "debug" : "warn",
2920
+ message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
2921
+ });
2922
+ return [];
2923
+ }
2924
+ let body;
2925
+ try {
2926
+ body = await res.json();
2927
+ } catch (err) {
2928
+ options.log({
2929
+ level: "warn",
2930
+ message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
2931
+ });
2932
+ return [];
2933
+ }
2934
+ if (!Array.isArray(body)) {
2935
+ options.log({
2936
+ level: "warn",
2937
+ message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
2938
+ });
2939
+ return [];
2940
+ }
2941
+ const files = [];
2942
+ for (const entry of body) {
2943
+ const file = asPendingFile(entry);
2944
+ if (file === null) {
2945
+ options.log({
2946
+ level: "warn",
2947
+ message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
2948
+ });
2949
+ continue;
2950
+ }
2951
+ files.push(file);
2952
+ }
2953
+ return files;
2954
+ }
2955
+ function asPendingFile(entry) {
2956
+ if (entry === null || typeof entry !== "object") return null;
2957
+ const { id, path, size } = entry;
2958
+ if (typeof id !== "string" || id === "") return null;
2959
+ if (typeof path !== "string" || path === "") return null;
2960
+ if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
2961
+ return { id, path, size };
2962
+ }
2963
+ async function applyOne(options, file) {
2964
+ const label = `${file.id.slice(0, 8)} (${file.path})`;
2965
+ if (options.allowedDirectories.length === 0) {
2966
+ options.log({
2967
+ level: "warn",
2968
+ message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
2969
+ });
2970
+ await ack(options, file, "rejected", "file_sync_disabled");
2971
+ return false;
2972
+ }
2973
+ if (file.size > MAX_FILE_PUSH_BYTES) {
2974
+ options.log({
2975
+ level: "warn",
2976
+ message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
2977
+ });
2978
+ await ack(options, file, "rejected", "file_too_large");
2979
+ return false;
2980
+ }
2981
+ const download = await downloadContent(options, file, label);
2982
+ if (!download.ok) {
2983
+ if (download.terminal) await ack(options, file, "rejected", download.code);
2984
+ return false;
2985
+ }
2986
+ let outcome;
2987
+ try {
2988
+ outcome = await writePushedFile({
2989
+ requestedPath: file.path,
2990
+ content: download.content,
2991
+ allowedDirectories: options.allowedDirectories,
2992
+ homeDir: options.homeDir
2993
+ });
2994
+ } catch (err) {
2995
+ options.log({
2996
+ level: "error",
2997
+ message: `Runner file ${label} could not be written: ${describe(err)}`
2998
+ });
2999
+ await ack(options, file, "rejected", "write_failed");
3000
+ return false;
3001
+ }
3002
+ if (!outcome.ok) {
3003
+ options.log({
3004
+ level: "warn",
3005
+ message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
3006
+ });
3007
+ await ack(options, file, "rejected", outcome.code);
3008
+ return false;
3009
+ }
3010
+ options.log({
3011
+ level: "info",
3012
+ message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
3013
+ });
3014
+ await ack(options, file, "applied");
3015
+ return true;
3016
+ }
3017
+ function durableDownloadCode(status2) {
3018
+ return status2 === 413 ? "file_too_large" : "write_failed";
3019
+ }
3020
+ async function downloadContent(options, file, label) {
3021
+ try {
3022
+ const res = await options.fetchImpl(
3023
+ `${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
3024
+ { headers: { Authorization: options.getAuthHeader() } }
3025
+ );
3026
+ if (!res.ok) {
3027
+ const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
3028
+ if (!terminal) {
3029
+ options.log({
3030
+ level: "warn",
3031
+ message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
3032
+ });
3033
+ return { ok: false, terminal: false };
3034
+ }
3035
+ const code = durableDownloadCode(res.status);
3036
+ options.log({
3037
+ level: "error",
3038
+ message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
3039
+ });
3040
+ return { ok: false, terminal: true, code };
3041
+ }
3042
+ return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
3043
+ } catch (err) {
3044
+ options.log({
3045
+ level: "warn",
3046
+ message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
3047
+ });
3048
+ return { ok: false, terminal: false };
3049
+ }
3050
+ }
3051
+ async function ack(options, file, status2, reason) {
3052
+ const outcome = `${status2}${reason ? ` (${reason})` : ""}`;
3053
+ try {
3054
+ const res = await options.fetchImpl(
3055
+ `${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
3056
+ {
3057
+ method: "POST",
3058
+ headers: {
3059
+ Authorization: options.getAuthHeader(),
3060
+ "Content-Type": "application/json"
3061
+ },
3062
+ body: JSON.stringify(reason ? { status: status2, reason } : { status: status2 })
3063
+ }
3064
+ );
3065
+ if (!res.ok) {
3066
+ recordAckFailure(
3067
+ options,
3068
+ file,
3069
+ `Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
3070
+ );
3071
+ return;
3072
+ }
3073
+ options.ackFailures.delete(file.id);
3074
+ } catch (err) {
3075
+ recordAckFailure(
3076
+ options,
3077
+ file,
3078
+ `Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
3079
+ );
2012
3080
  }
2013
- };
3081
+ }
3082
+ function recordAckFailure(options, file, what) {
3083
+ const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
3084
+ options.ackFailures.set(file.id, attempts);
3085
+ options.log({
3086
+ level: "error",
3087
+ 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})`
3088
+ });
3089
+ }
3090
+ function describe(err) {
3091
+ return err instanceof Error ? err.message : String(err);
3092
+ }
2014
3093
 
2015
3094
  // src/lib/channels/driver.ts
2016
3095
  function messageIdOf(m) {
@@ -2040,7 +3119,10 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
2040
3119
  var DEFAULT_STUCK_QUEUED_MS = 6e4;
2041
3120
  var HEARTBEAT_MS = 6e4;
2042
3121
  var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
3122
+ var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
3123
+ var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
2043
3124
  var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
3125
+ var MAX_SUPERSEDED_CONVERSATIONS = 256;
2044
3126
  var ChannelAuthError = class extends Error {
2045
3127
  constructor(message) {
2046
3128
  super(message);
@@ -2049,10 +3131,10 @@ var ChannelAuthError = class extends Error {
2049
3131
  };
2050
3132
  var ChannelTerminalError = class extends Error {
2051
3133
  status;
2052
- constructor(message, status) {
3134
+ constructor(message, status2) {
2053
3135
  super(message);
2054
3136
  this.name = "ChannelTerminalError";
2055
- this.status = status;
3137
+ this.status = status2;
2056
3138
  }
2057
3139
  };
2058
3140
  function backoffDelay(attempt, policy) {
@@ -2060,10 +3142,10 @@ function backoffDelay(attempt, policy) {
2060
3142
  const capped = Math.min(policy.maxDelayMs, exp);
2061
3143
  return Math.floor(Math.random() * capped);
2062
3144
  }
2063
- function isRetryableStatus(status) {
2064
- return status === 429 || status >= 500 && status <= 599;
3145
+ function isRetryableStatus(status2) {
3146
+ return status2 === 429 || status2 >= 500 && status2 <= 599;
2065
3147
  }
2066
- var ChannelDriver = class {
3148
+ var ChannelDriver = class _ChannelDriver {
2067
3149
  agentId;
2068
3150
  port;
2069
3151
  apiUrl;
@@ -2077,8 +3159,38 @@ var ChannelDriver = class {
2077
3159
  pausedMaxWaitMs;
2078
3160
  stuckQueuedMs;
2079
3161
  now;
3162
+ fileSyncDirectories;
3163
+ homeDir;
2080
3164
  /** Cache of conversationId → opencode sessionId. */
2081
3165
  sessions = /* @__PURE__ */ new Map();
3166
+ /**
3167
+ * conversationId → the opencode session this runner has ABANDONED as that
3168
+ * conversation's binding (#553), after a genuine (`sessionExists === true`)
3169
+ * dispatch failure: the session still exists but is wedged, so #485's self-heal
3170
+ * must bind a fresh one.
3171
+ *
3172
+ * Dropping the local binding + clearing the server row is not enough on its own:
3173
+ * a SIBLING message dispatched earlier in the same drain is still in-flight under
3174
+ * the same session, and its watcher's routine status writes carry
3175
+ * `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
3176
+ * and `ensureSession`'s persisted-id fallback then reuses it, defeating the
3177
+ * self-heal. This map makes the runner authoritative instead of racing those
3178
+ * writes: *`ensureSession` never reuses an abandoned id for that conversation,
3179
+ * whatever the server row says* — which holds even when the resurrecting write
3180
+ * is one we deliberately keep (see `markDone`).
3181
+ *
3182
+ * Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
3183
+ * one conversation hold ONE entry (the newest abandonment replaces the older), and
3184
+ * hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
3185
+ * NEWEST abandoned id per conversation is guarded: after a second abandonment a
3186
+ * late sibling of the FIRST session can write that id back and `ensureSession`
3187
+ * will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
3188
+ * NOT dropped when the session's watcher tears down: `markDone` still writes the
3189
+ * abandoned id back (it must, or the reply is lost), so the guard has to outlive
3190
+ * the turn that resurrects it. In-memory only — a restart forgets it, at the same
3191
+ * bounded cost.
3192
+ */
3193
+ supersededSessions = /* @__PURE__ */ new Map();
2082
3194
  /**
2083
3195
  * Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
2084
3196
  * longer idempotent (no caller-supplied `messageID`), and its read-back picks
@@ -2188,9 +3300,12 @@ var ChannelDriver = class {
2188
3300
  sessionParents = /* @__PURE__ */ new Map();
2189
3301
  /**
2190
3302
  * Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
2191
- * NON-EMPTY name is stored (terminal — a real session name won't later un-name),
2192
- * so we do NOT re-GET `/session/:id` every tick. A missing entry = not yet
2193
- * resolved OR resolved-but-still-empty re-fetch on next need, since OpenCode
3303
+ * NON-EMPTY, non-placeholder name is stored (terminal — a real session name
3304
+ * won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
3305
+ * excludes OpenCode's synchronous default title (see
3306
+ * `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
3307
+ * as an empty title so it never latches. A missing entry = not yet resolved OR
3308
+ * resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
2194
3309
  * names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
2195
3310
  * the watcher completion path AND the restart-recovery re-adopt path (which has
2196
3311
  * no watcher) can resolve the title.
@@ -2198,6 +3313,24 @@ var ChannelDriver = class {
2198
3313
  sessionTitles = /* @__PURE__ */ new Map();
2199
3314
  /** Serialises drains so a reconnect during a drain doesn't double-process. */
2200
3315
  draining = false;
3316
+ /**
3317
+ * Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
3318
+ * drain ping don't download, write and ack the same file twice.
3319
+ */
3320
+ syncingFiles = false;
3321
+ /**
3322
+ * Consecutive failed acks per pending file (#559). Lives on the driver so it
3323
+ * survives across drains — without it, a file whose ack keeps failing is
3324
+ * re-downloaded and re-written every ~2s until the server expires it.
3325
+ */
3326
+ fileAckFailures = /* @__PURE__ */ new Map();
3327
+ /**
3328
+ * Monotonic count of files this runner has pulled and written (#559). Only
3329
+ * ever increases, so `run.ts` detects work by comparing it against the value
3330
+ * it saw on the previous cycle — including work that landed mid-sleep, the
3331
+ * same trick `lastProxiedActivityAt` uses.
3332
+ */
3333
+ appliedFileCount = 0;
2201
3334
  /**
2202
3335
  * The currently-executing `drainPending()` promise, or null when idle. Lets a
2203
3336
  * graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
@@ -2213,21 +3346,23 @@ var ChannelDriver = class {
2213
3346
  * and stops opencode.
2214
3347
  */
2215
3348
  stopped = false;
2216
- constructor(config2) {
2217
- this.agentId = config2.agentId;
2218
- this.port = config2.port;
2219
- this.apiUrl = config2.apiUrl.replace(/\/$/, "");
2220
- this.getAuthHeader = config2.getAuthHeader;
2221
- this.conversationFilter = config2.conversationFilter ?? null;
2222
- this.retry = { ...DEFAULT_RETRY_POLICY, ...config2.retry };
2223
- this.log = config2.log ?? (() => {
3349
+ constructor(config) {
3350
+ this.agentId = config.agentId;
3351
+ this.port = config.port;
3352
+ this.apiUrl = config.apiUrl.replace(/\/$/, "");
3353
+ this.getAuthHeader = config.getAuthHeader;
3354
+ this.conversationFilter = config.conversationFilter ?? null;
3355
+ this.retry = { ...DEFAULT_RETRY_POLICY, ...config.retry };
3356
+ this.log = config.log ?? (() => {
2224
3357
  });
2225
- this.fetchImpl = config2.fetchImpl ?? fetch;
2226
- this.sleep = config2.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
2227
- this.pausedPollIntervalMs = config2.pausedPollIntervalMs ?? DEFAULT_PAUSED_POLL_INTERVAL_MS;
2228
- this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
2229
- this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
2230
- this.now = config2.now ?? (() => Date.now());
3358
+ this.fetchImpl = config.fetchImpl ?? fetch;
3359
+ this.sleep = config.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
3360
+ this.pausedPollIntervalMs = config.pausedPollIntervalMs ?? DEFAULT_PAUSED_POLL_INTERVAL_MS;
3361
+ this.pausedMaxWaitMs = config.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
3362
+ this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
3363
+ this.now = config.now ?? (() => Date.now());
3364
+ this.fileSyncDirectories = config.fileSyncDirectories ?? [];
3365
+ this.homeDir = config.homeDir ?? homedir2();
2231
3366
  }
2232
3367
  /** The IPv4-loopback base URL for the local `opencode serve`. */
2233
3368
  get opencodeBase() {
@@ -2255,6 +3390,47 @@ var ChannelDriver = class {
2255
3390
  );
2256
3391
  return run2;
2257
3392
  }
3393
+ /**
3394
+ * Pull-and-apply any files Evident has queued for this runner (#559), riding
3395
+ * the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
3396
+ * and drain ping that call `drainPending()`. There is deliberately no channel,
3397
+ * control frame or poll loop of its own: worst-case latency is one poll tick.
3398
+ *
3399
+ * NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
3400
+ * cost a conversation turn. Failures are logged and either acked as a terminal
3401
+ * outcome or left pending for the next drain (see `runner-file-sync.ts`).
3402
+ *
3403
+ * Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
3404
+ *
3405
+ * @returns the number of files written to disk.
3406
+ */
3407
+ async syncPendingFiles() {
3408
+ if (this.stopped) return 0;
3409
+ if (this.syncingFiles) return 0;
3410
+ this.syncingFiles = true;
3411
+ try {
3412
+ const applied = await syncPendingRunnerFiles({
3413
+ agentId: this.agentId,
3414
+ apiUrl: this.apiUrl,
3415
+ getAuthHeader: this.getAuthHeader,
3416
+ fetchImpl: this.fetchImpl,
3417
+ allowedDirectories: this.fileSyncDirectories,
3418
+ homeDir: this.homeDir,
3419
+ ackFailures: this.fileAckFailures,
3420
+ log: this.log
3421
+ });
3422
+ this.appliedFileCount += applied;
3423
+ return applied;
3424
+ } catch (err) {
3425
+ this.log({
3426
+ level: "error",
3427
+ message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
3428
+ });
3429
+ return 0;
3430
+ } finally {
3431
+ this.syncingFiles = false;
3432
+ }
3433
+ }
2258
3434
  async runDrain() {
2259
3435
  let dispatched = 0;
2260
3436
  try {
@@ -2288,6 +3464,28 @@ var ChannelDriver = class {
2288
3464
  }
2289
3465
  return false;
2290
3466
  }
3467
+ /**
3468
+ * File-pull work, for `run.ts`'s idle accounting (#559).
3469
+ *
3470
+ * Pulling a file is real work that `drainPending()` knows nothing about, so
3471
+ * without this a near-idle runner counts a credential pull as an empty tick
3472
+ * and `--idle-timeout` can `process.exit` mid-pull — leaving a
3473
+ * `.evident-push-*.tmp` behind — or immediately after the write, before the
3474
+ * browser has run the authorize/callback that activates it (the user then sees
3475
+ * `saved_not_activated` for a runner that was fine).
3476
+ *
3477
+ * Two signals because one cannot cover both cases: `inFlight` is the pull
3478
+ * happening RIGHT NOW (it may outlive the tick that started it), and
3479
+ * `appliedFiles` is monotonic so a pull that started AND finished between two
3480
+ * idle checks still shows up as an advance.
3481
+ *
3482
+ * CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
3483
+ * the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
3484
+ * samples afterwards reads `true` every single cycle and can never idle out.
3485
+ */
3486
+ fileSyncActivity() {
3487
+ return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
3488
+ }
2291
3489
  /**
2292
3490
  * OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
2293
3491
  * exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
@@ -2349,7 +3547,7 @@ var ChannelDriver = class {
2349
3547
  await this.sleep(step);
2350
3548
  }
2351
3549
  }
2352
- while (this.hasInFlightWatchers()) {
3550
+ while (this.hasInFlightWatchers() || this.syncingFiles) {
2353
3551
  if (this.now() >= deadline) return false;
2354
3552
  await this.sleep(step);
2355
3553
  }
@@ -2384,10 +3582,15 @@ var ChannelDriver = class {
2384
3582
  * @returns the count of messages NEWLY dispatched (not already in-flight).
2385
3583
  */
2386
3584
  async processConversation(conv) {
2387
- const sessionId = await this.ensureSession(conv);
3585
+ const { sessionId, refusedSessionId } = await this.ensureSession(conv);
2388
3586
  const messages = await this.getPendingMessages(conv.id);
2389
3587
  let dispatched = 0;
2390
3588
  let skippedAlreadyDispatched = 0;
3589
+ if (refusedSessionId && messages.length > 0) {
3590
+ void this.postSignal(conv.id, messages[0].id, "session_superseded", {
3591
+ superseded_session_id: refusedSessionId
3592
+ });
3593
+ }
2391
3594
  for (const message of messages) {
2392
3595
  if (this.stopped) break;
2393
3596
  if (this.dispatched.has(message.id)) {
@@ -2414,7 +3617,8 @@ var ChannelDriver = class {
2414
3617
  } catch (err) {
2415
3618
  if (err instanceof ChannelAuthError) throw err;
2416
3619
  this.dispatched.delete(message.id);
2417
- if (await sessionExists(this.port, sessionId) === false) {
3620
+ const exists = await sessionExists(this.port, sessionId);
3621
+ if (exists === false) {
2418
3622
  this.sessions.delete(conv.id);
2419
3623
  this.log({
2420
3624
  level: "warn",
@@ -2424,15 +3628,39 @@ var ChannelDriver = class {
2424
3628
  });
2425
3629
  break;
2426
3630
  }
2427
- await this.markFailed(conv.id, message.id).catch(() => {
3631
+ if (exists === null) {
3632
+ this.log({
3633
+ level: "warn",
3634
+ 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.`,
3635
+ conversation_id: conv.id,
3636
+ message_id: message.id
3637
+ });
3638
+ break;
3639
+ }
3640
+ const errorMessage = err instanceof Error ? err.message : String(err);
3641
+ this.sessions.delete(conv.id);
3642
+ this.supersede(conv.id, sessionId);
3643
+ this.log({
3644
+ level: "warn",
3645
+ 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.`,
3646
+ conversation_id: conv.id,
3647
+ message_id: message.id
3648
+ });
3649
+ await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
3650
+ this.log({
3651
+ level: "warn",
3652
+ 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)}`,
3653
+ conversation_id: conv.id,
3654
+ message_id: message.id
3655
+ });
2428
3656
  });
2429
3657
  this.log({
2430
3658
  level: "error",
2431
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${err instanceof Error ? err.message : String(err)}`,
3659
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
2432
3660
  conversation_id: conv.id,
2433
3661
  message_id: message.id
2434
3662
  });
2435
- continue;
3663
+ break;
2436
3664
  }
2437
3665
  if (opencodeMessageId === null) {
2438
3666
  this.log({
@@ -2458,8 +3686,42 @@ var ChannelDriver = class {
2458
3686
  this.ensureWatcherRunning(sessionId);
2459
3687
  return dispatched;
2460
3688
  }
3689
+ /**
3690
+ * Record that `sessionId` is no longer a valid binding for `conversationId`
3691
+ * (#553). Keyed by conversation and hard-capped, so it cannot grow with the
3692
+ * number of failures — see the `supersededSessions` field doc.
3693
+ */
3694
+ supersede(conversationId, sessionId) {
3695
+ this.supersededSessions.delete(conversationId);
3696
+ this.supersededSessions.set(conversationId, sessionId);
3697
+ while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
3698
+ const oldest = this.supersededSessions.keys().next().value;
3699
+ if (oldest === void 0) return;
3700
+ this.supersededSessions.delete(oldest);
3701
+ }
3702
+ }
3703
+ /** Whether `sessionId` is the session this conversation has abandoned (#553). */
3704
+ isSuperseded(conversationId, sessionId) {
3705
+ return this.supersededSessions.get(conversationId) === sessionId;
3706
+ }
3707
+ /**
3708
+ * Resolve the opencode session to run this conversation's turns in.
3709
+ *
3710
+ * `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
3711
+ * binding was an id this runner had abandoned, so a resurrection genuinely
3712
+ * happened and a fresh session was bound instead. The caller reports it.
3713
+ */
2461
3714
  async ensureSession(conv) {
2462
3715
  const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
3716
+ if (bound && this.isSuperseded(conv.id, bound)) {
3717
+ this.log({
3718
+ level: "warn",
3719
+ 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.`,
3720
+ conversation_id: conv.id
3721
+ });
3722
+ this.sessions.delete(conv.id);
3723
+ return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
3724
+ }
2463
3725
  if (bound) {
2464
3726
  const exists = await sessionExists(this.port, bound);
2465
3727
  if (exists === false) {
@@ -2469,12 +3731,12 @@ var ChannelDriver = class {
2469
3731
  conversation_id: conv.id
2470
3732
  });
2471
3733
  this.sessions.delete(conv.id);
2472
- return this.createAndBindSession(conv.id);
3734
+ return { sessionId: await this.createAndBindSession(conv.id) };
2473
3735
  }
2474
3736
  this.sessions.set(conv.id, bound);
2475
- return bound;
3737
+ return { sessionId: bound };
2476
3738
  }
2477
- return this.createAndBindSession(conv.id);
3739
+ return { sessionId: await this.createAndBindSession(conv.id) };
2478
3740
  }
2479
3741
  /**
2480
3742
  * Create a fresh OpenCode session for a conversation, cache the binding, and
@@ -2485,7 +3747,12 @@ var ChannelDriver = class {
2485
3747
  const directory = await this.resolveOpenCodeDirectory();
2486
3748
  const sessionId = await createOpenCodeSession(this.port, directory);
2487
3749
  this.sessions.set(conversationId, sessionId);
2488
- await this.persistSession(conversationId, sessionId).catch(() => {
3750
+ await this.persistSession(conversationId, sessionId).catch((err) => {
3751
+ this.log({
3752
+ level: "warn",
3753
+ message: `Persisting the OpenCode session binding ${sessionId.slice(0, 8)} for conversation ${conversationId.slice(0, 8)} failed (best-effort, not retried) \u2014 the completion PATCH also carries opencode_session_id, so the binding is repaired when the turn finishes: ${err instanceof Error ? err.message : String(err)}`,
3754
+ conversation_id: conversationId
3755
+ });
2489
3756
  });
2490
3757
  return sessionId;
2491
3758
  }
@@ -2562,7 +3829,11 @@ var ChannelDriver = class {
2562
3829
  * (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
2563
3830
  * (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
2564
3831
  * OMITS that one image and the text turn still sends — NEVER throws the turn.
2565
- * Failures are logged with context (no silent swallow).
3832
+ * A 404 body carrying `{ reason: 'needs_reauth' }` (#547 the server CONFIRMED
3833
+ * a Slack `files:read` scope problem via `files.info`) instead resolves the
3834
+ * `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
3835
+ * user to reconnect Slack instead of a generic "unavailable". Failures are
3836
+ * logged with context (no silent swallow).
2566
3837
  */
2567
3838
  async fetchAttachmentDataUrl(messageId, index, mime) {
2568
3839
  try {
@@ -2571,6 +3842,25 @@ var ChannelDriver = class {
2571
3842
  { headers: { Authorization: this.getAuthHeader() } }
2572
3843
  );
2573
3844
  if (!res.ok) {
3845
+ let reason;
3846
+ try {
3847
+ const body = await res.json();
3848
+ if (body && typeof body.reason === "string") reason = body.reason;
3849
+ } catch (parseErr) {
3850
+ this.log({
3851
+ level: "debug",
3852
+ 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`,
3853
+ message_id: messageId
3854
+ });
3855
+ }
3856
+ if (reason === "needs_reauth") {
3857
+ this.log({
3858
+ level: "error",
3859
+ 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)`,
3860
+ message_id: messageId
3861
+ });
3862
+ return { needsReauth: true };
3863
+ }
2574
3864
  this.log({
2575
3865
  level: "error",
2576
3866
  message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
@@ -2610,6 +3900,9 @@ var ChannelDriver = class {
2610
3900
  if (this.attachmentsSkippedSignalled.has(messageId)) return;
2611
3901
  this.attachmentsSkippedSignalled.add(messageId);
2612
3902
  const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
3903
+ const failedReason = outcomes.some(
3904
+ (o) => o.status === "failed" && o.reason === "needs_reauth"
3905
+ ) ? "needs_reauth" : void 0;
2613
3906
  this.log({
2614
3907
  level: "info",
2615
3908
  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`,
@@ -2619,7 +3912,8 @@ var ChannelDriver = class {
2619
3912
  void this.postSignal(conversationId, messageId, "attachments_skipped", {
2620
3913
  skipped,
2621
3914
  failed,
2622
- ...skipped > 0 ? { skipped_reason: skippedReason } : {}
3915
+ ...skipped > 0 ? { skipped_reason: skippedReason } : {},
3916
+ ...failedReason ? { failed_reason: failedReason } : {}
2623
3917
  });
2624
3918
  }
2625
3919
  /** Register a freshly-dispatched message with its session's watcher state. */
@@ -2650,12 +3944,17 @@ var ChannelDriver = class {
2650
3944
  stuckReported: false,
2651
3945
  lastAliveAt: 0,
2652
3946
  aliveInFlight: false,
3947
+ titleSynced: false,
3948
+ titleSyncInFlight: false,
2653
3949
  awaitingHumanLatched: false,
2654
3950
  pausedOnQuestion: false,
2655
3951
  pausedOnPermission: false,
2656
3952
  pausedClearConfirmed: false,
2657
3953
  pausedInFlight: false,
2658
- deliveryDeadlineAnchored: false
3954
+ deliveryDeadlineAnchored: false,
3955
+ b2PinnedSinceMs: 0,
3956
+ b2LastDescendantCheckMs: 0,
3957
+ b2AbandonedSignalled: false
2659
3958
  });
2660
3959
  }
2661
3960
  /**
@@ -2723,12 +4022,17 @@ var ChannelDriver = class {
2723
4022
  // with no extra `re_adopted` signal needed (folds old WI-6).
2724
4023
  lastAliveAt: 0,
2725
4024
  aliveInFlight: false,
4025
+ titleSynced: false,
4026
+ titleSyncInFlight: false,
2726
4027
  awaitingHumanLatched: false,
2727
4028
  pausedOnQuestion: false,
2728
4029
  pausedOnPermission: false,
2729
4030
  pausedClearConfirmed: false,
2730
4031
  pausedInFlight: false,
2731
- deliveryDeadlineAnchored: false
4032
+ deliveryDeadlineAnchored: false,
4033
+ b2PinnedSinceMs: 0,
4034
+ b2LastDescendantCheckMs: 0,
4035
+ b2AbandonedSignalled: false
2732
4036
  });
2733
4037
  }
2734
4038
  /**
@@ -2890,58 +4194,7 @@ var ChannelDriver = class {
2890
4194
  }
2891
4195
  }
2892
4196
  if (state === "done") {
2893
- this.anchorDeliveryDeadline(inFlight);
2894
- if (!inFlight.done) {
2895
- this.log({
2896
- level: "info",
2897
- message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
2898
- conversation_id: conv.id,
2899
- message_id: inFlight.evidentMessageId
2900
- });
2901
- const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
2902
- const usage = messageUsage(messages, inFlight.opencodeMessageId);
2903
- try {
2904
- await this.markDone(
2905
- conv.id,
2906
- inFlight.evidentMessageId,
2907
- sessionId,
2908
- inFlight.opencodeMessageId,
2909
- title,
2910
- usage
2911
- );
2912
- } catch (err) {
2913
- if (err instanceof ChannelAuthError) throw err;
2914
- if (err instanceof ChannelTerminalError) {
2915
- this.log({
2916
- level: "warn",
2917
- message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
2918
- conversation_id: conv.id,
2919
- message_id: inFlight.evidentMessageId
2920
- });
2921
- this.removeInFlight(watcher, inFlight.evidentMessageId);
2922
- return;
2923
- }
2924
- if (this.now() >= inFlight.deadline) {
2925
- this.log({
2926
- level: "warn",
2927
- 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)}`,
2928
- conversation_id: conv.id,
2929
- message_id: inFlight.evidentMessageId
2930
- });
2931
- this.removeInFlight(watcher, inFlight.evidentMessageId);
2932
- return;
2933
- }
2934
- this.log({
2935
- level: "warn",
2936
- message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
2937
- conversation_id: conv.id,
2938
- message_id: inFlight.evidentMessageId
2939
- });
2940
- return;
2941
- }
2942
- inFlight.done = true;
2943
- }
2944
- this.removeInFlight(watcher, inFlight.evidentMessageId);
4197
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
2945
4198
  return;
2946
4199
  }
2947
4200
  if (state === "failed") {
@@ -2955,8 +4208,16 @@ var ChannelDriver = class {
2955
4208
  message_id: inFlight.evidentMessageId
2956
4209
  });
2957
4210
  const usage = messageUsage(messages, inFlight.opencodeMessageId);
4211
+ const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
2958
4212
  try {
2959
- await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2, usage);
4213
+ await this.markFailed(
4214
+ conv.id,
4215
+ inFlight.evidentMessageId,
4216
+ sessionId,
4217
+ error2,
4218
+ usage,
4219
+ failure
4220
+ );
2960
4221
  } catch (err) {
2961
4222
  if (err instanceof ChannelAuthError) throw err;
2962
4223
  if (err instanceof ChannelTerminalError) {
@@ -3001,6 +4262,44 @@ var ChannelDriver = class {
3001
4262
  });
3002
4263
  }
3003
4264
  const activelyRunning = state === "running" && !awaitingHuman;
4265
+ const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
4266
+ const snapshotReadable = messages != null && messages.length > 0;
4267
+ if (!pinnedNow) {
4268
+ if (snapshotReadable) {
4269
+ inFlight.b2PinnedSinceMs = 0;
4270
+ inFlight.b2LastDescendantCheckMs = 0;
4271
+ inFlight.b2AbandonedSignalled = false;
4272
+ }
4273
+ } else {
4274
+ if (inFlight.b2AbandonedSignalled) {
4275
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
4276
+ return;
4277
+ }
4278
+ if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
4279
+ const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
4280
+ if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
4281
+ inFlight.b2LastDescendantCheckMs = this.now();
4282
+ const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
4283
+ if (isB2AbandonmentConfirmed({
4284
+ pinnedForMs,
4285
+ minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
4286
+ descendantOngoing
4287
+ })) {
4288
+ inFlight.b2AbandonedSignalled = true;
4289
+ this.log({
4290
+ level: "warn",
4291
+ 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`,
4292
+ conversation_id: conv.id,
4293
+ message_id: id
4294
+ });
4295
+ void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
4296
+ watched_for_ms: pinnedForMs
4297
+ });
4298
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
4299
+ return;
4300
+ }
4301
+ }
4302
+ }
3004
4303
  if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
3005
4304
  this.log({
3006
4305
  level: "warn",
@@ -3020,6 +4319,18 @@ var ChannelDriver = class {
3020
4319
  inFlight.aliveInFlight = false;
3021
4320
  if (ok) inFlight.lastAliveAt = this.now();
3022
4321
  });
4322
+ if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
4323
+ inFlight.titleSyncInFlight = true;
4324
+ void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
4325
+ if (!title) {
4326
+ inFlight.titleSyncInFlight = false;
4327
+ return;
4328
+ }
4329
+ const ok = await this.patchConversationTitle(conv.id, title);
4330
+ inFlight.titleSyncInFlight = false;
4331
+ if (ok) inFlight.titleSynced = true;
4332
+ });
4333
+ }
3023
4334
  }
3024
4335
  if (awaitingHuman) {
3025
4336
  if (!inFlight.awaitingHumanLatched) {
@@ -3057,6 +4368,70 @@ var ChannelDriver = class {
3057
4368
  this.removeInFlight(watcher, inFlight.evidentMessageId);
3058
4369
  }
3059
4370
  }
4371
+ /**
4372
+ * Settle a message whose run-state has resolved `'done'` — extracted verbatim
4373
+ * (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
4374
+ * inline `state === 'done'` branch body, so a SECOND caller (the #721
4375
+ * b2-abandonment resolution) can reach the exact same completion behavior
4376
+ * (delivery-deadline anchoring, title resolution, usage extraction, and
4377
+ * `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
4378
+ * and risking the two copies silently drifting apart.
4379
+ */
4380
+ async settleMessageDone(sessionId, watcher, inFlight, messages) {
4381
+ const conv = watcher.conv;
4382
+ this.anchorDeliveryDeadline(inFlight);
4383
+ if (!inFlight.done) {
4384
+ this.log({
4385
+ level: "info",
4386
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
4387
+ conversation_id: conv.id,
4388
+ message_id: inFlight.evidentMessageId
4389
+ });
4390
+ const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
4391
+ const usage = messageUsage(messages, inFlight.opencodeMessageId);
4392
+ try {
4393
+ await this.markDone(
4394
+ conv.id,
4395
+ inFlight.evidentMessageId,
4396
+ sessionId,
4397
+ inFlight.opencodeMessageId,
4398
+ title,
4399
+ usage
4400
+ );
4401
+ } catch (err) {
4402
+ if (err instanceof ChannelAuthError) throw err;
4403
+ if (err instanceof ChannelTerminalError) {
4404
+ this.log({
4405
+ level: "warn",
4406
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
4407
+ conversation_id: conv.id,
4408
+ message_id: inFlight.evidentMessageId
4409
+ });
4410
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
4411
+ return;
4412
+ }
4413
+ if (this.now() >= inFlight.deadline) {
4414
+ this.log({
4415
+ level: "warn",
4416
+ 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)}`,
4417
+ conversation_id: conv.id,
4418
+ message_id: inFlight.evidentMessageId
4419
+ });
4420
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
4421
+ return;
4422
+ }
4423
+ this.log({
4424
+ level: "warn",
4425
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
4426
+ conversation_id: conv.id,
4427
+ message_id: inFlight.evidentMessageId
4428
+ });
4429
+ return;
4430
+ }
4431
+ inFlight.done = true;
4432
+ }
4433
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
4434
+ }
3060
4435
  // Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
3061
4436
  /**
3062
4437
  * Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
@@ -3223,6 +4598,7 @@ var ChannelDriver = class {
3223
4598
  if (state === "failed") {
3224
4599
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
3225
4600
  const usage = messageUsage(messages, ocId ?? "");
4601
+ const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
3226
4602
  this.log({
3227
4603
  level: "error",
3228
4604
  message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
@@ -3230,7 +4606,7 @@ var ChannelDriver = class {
3230
4606
  message_id: row.id
3231
4607
  });
3232
4608
  try {
3233
- await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
4609
+ await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
3234
4610
  } catch (err) {
3235
4611
  if (err instanceof ChannelAuthError) throw err;
3236
4612
  if (err instanceof ChannelTerminalError) {
@@ -3636,6 +5012,47 @@ var ChannelDriver = class {
3636
5012
  }
3637
5013
  return false;
3638
5014
  }
5015
+ /**
5016
+ * Tri-state variant of the upward parentID membership walk (#721), used ONLY
5017
+ * by `isAnyDescendantSessionOngoing`. Walks the SAME cached
5018
+ * `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
5019
+ * `sessionBelongsTo`, which deliberately collapses "confirmed not a
5020
+ * descendant" and "the walk's fetch failed" into the same `false` (safe for
5021
+ * its OTHER callers: interaction attribution and the recovery-path
5022
+ * `isAnyDescendantSessionAlive`, both of which just retry next tick with no
5023
+ * safety consequence either way) — this variant keeps those two outcomes
5024
+ * SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
5025
+ * (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
5026
+ * not ongoing".
5027
+ *
5028
+ * Return contract:
5029
+ * - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
5030
+ * - `false` → the walk reached a definitive, parent-less root session
5031
+ * WITHOUT ever matching `rootSessionId` — `sessionId` is
5032
+ * CONFIRMED NOT a descendant of it.
5033
+ * - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
5034
+ * through the walk (`resolveSessionParent` returned `undefined`),
5035
+ * or the depth cap (32) was hit without a definitive answer (a
5036
+ * pathological/cyclic chain proves nothing either way). NEVER
5037
+ * treat this the same as `false` — see `sessionBelongsTo`'s own
5038
+ * doc comment above for why that collapse is safe THERE but not
5039
+ * here.
5040
+ *
5041
+ * `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
5042
+ * to the live-path descendant check, not a modification of shared code used
5043
+ * by interaction attribution or the recovery path.
5044
+ */
5045
+ async resolveSessionMembership(sessionId, rootSessionId) {
5046
+ let current = sessionId;
5047
+ for (let depth = 0; current && depth < 32; depth++) {
5048
+ if (current === rootSessionId) return true;
5049
+ const parent = await this.resolveSessionParent(current);
5050
+ if (parent === void 0) return null;
5051
+ if (parent === null) return false;
5052
+ current = parent;
5053
+ }
5054
+ return null;
5055
+ }
3639
5056
  /**
3640
5057
  * Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
3641
5058
  * `null` for a root session (no parent) and `undefined` when opencode is
@@ -3658,19 +5075,36 @@ var ChannelDriver = class {
3658
5075
  if (parent !== void 0) this.sessionParents.set(sessionId, parent);
3659
5076
  return parent;
3660
5077
  }
5078
+ /**
5079
+ * OpenCode's synchronous default session title (e.g.
5080
+ * `"New session - 1737800000000"`), assigned immediately when a session is
5081
+ * created — before OpenCode's async LLM-based auto-titling later renames it
5082
+ * mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
5083
+ * timestamp suffix's exact format is deliberately NOT matched, since the prefix
5084
+ * alone is the stable, cheap signal and over-anchoring on the timestamp
5085
+ * representation risks silently breaking if OpenCode ever changes it. Accepted
5086
+ * trade-off: a genuine LLM-assigned title that happens to literally start with
5087
+ * this prefix would also fail to latch (see `resolveSessionTitle`) —
5088
+ * vanishingly unlikely in practice, and deliberately not engineered around.
5089
+ */
5090
+ static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
3661
5091
  /**
3662
5092
  * Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
3663
5093
  * status PATCH can carry it into the "Live sessions" list. Driver-level cache so
3664
5094
  * BOTH the watcher completion path and the restart-recovery re-adopt path (which
3665
5095
  * has no watcher) can use it. `conversationId` is passed only for log context.
3666
5096
  * Best-effort:
3667
- * - a resolved NON-EMPTY title is cached and terminal (a real session name
5097
+ * - a resolved NON-EMPTY title that does NOT match
5098
+ * `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
3668
5099
  * won't later un-name), so we do NOT re-GET `/session/:id` every tick;
3669
- * - while the title is still absent/empty we do NOT latch it — OpenCode names
3670
- * sessions asynchronously mid-turn, so an early call (e.g. at `processing`)
3671
- * must leave the cache unresolved and re-fetch on the next need so a later
3672
- * call (e.g. at `done`) picks up the name assigned in the meantime. Such a
3673
- * call returns `null` (omit the title on THIS PATCH) without caching;
5100
+ * - while the title is still absent, empty, or matches the OpenCode
5101
+ * placeholder prefix (#549) we do NOT latch it OpenCode names sessions
5102
+ * asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
5103
+ * the cache unresolved and re-fetch on the next need so a later call (e.g. at
5104
+ * `done`) picks up the name assigned in the meantime. Such a call returns
5105
+ * `null` (omit the title on THIS PATCH) without caching. If a session is
5106
+ * never renamed, the title is omitted forever rather than ever persisting
5107
+ * the placeholder as a last resort;
3674
5108
  * - a failed request likewise leaves the cache unresolved (retry next need)
3675
5109
  * and returns `null` — it must NEVER throw or block completion.
3676
5110
  * A failure is logged with agent/session context (no silent catch).
@@ -3683,7 +5117,7 @@ var ChannelDriver = class {
3683
5117
  if (res.ok) {
3684
5118
  const body = await res.json();
3685
5119
  const title = body && typeof body.title === "string" ? body.title.trim() : "";
3686
- if (title.length > 0) {
5120
+ if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
3687
5121
  this.sessionTitles.set(sessionId, title);
3688
5122
  return title;
3689
5123
  }
@@ -3703,6 +5137,54 @@ var ChannelDriver = class {
3703
5137
  }
3704
5138
  return null;
3705
5139
  }
5140
+ /**
5141
+ * Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
5142
+ * session title onto the conversation via the PLAIN conversation-update
5143
+ * endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
5144
+ * message-status endpoint `markProcessing`/`markDone` use. Deliberately a
5145
+ * separate, lighter call: it carries no `status`, so it cannot re-trigger the
5146
+ * `processing`/`done` transition side effects (Slack notices, activity-log
5147
+ * rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
5148
+ * ever touches `conversations.title`. That route (`routes/conversations.ts`)
5149
+ * skips a title write matching the stored value, so a redundant call with the
5150
+ * same title is a real no-op — it does not bump `updated_at`, which the
5151
+ * conversation list sorts and paginates on. (Note this is a DIFFERENT guard
5152
+ * from `threads.ts`'s "non-empty AND changed" one, which only covers the
5153
+ * message-status PATCH; the non-empty half is enforced here instead, by
5154
+ * `resolveSessionTitle` never returning an empty/placeholder title.)
5155
+ *
5156
+ * Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
5157
+ * is logged and the title is simply retried on the next heartbeat tick (the
5158
+ * caller only latches `titleSynced` on `true`).
5159
+ */
5160
+ async patchConversationTitle(conversationId, title) {
5161
+ try {
5162
+ const res = await this.fetchImpl(
5163
+ `${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
5164
+ {
5165
+ method: "PATCH",
5166
+ headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
5167
+ body: JSON.stringify({ title })
5168
+ }
5169
+ );
5170
+ if (!res.ok) {
5171
+ this.log({
5172
+ level: "debug",
5173
+ message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
5174
+ conversation_id: conversationId
5175
+ });
5176
+ return false;
5177
+ }
5178
+ return true;
5179
+ } catch (err) {
5180
+ this.log({
5181
+ level: "debug",
5182
+ 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)}`,
5183
+ conversation_id: conversationId
5184
+ });
5185
+ return false;
5186
+ }
5187
+ }
3706
5188
  /**
3707
5189
  * DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
3708
5190
  * (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
@@ -3761,6 +5243,84 @@ var ChannelDriver = class {
3761
5243
  }
3762
5244
  return false;
3763
5245
  }
5246
+ /**
5247
+ * LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
5248
+ * sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
5249
+ * in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
5250
+ *
5251
+ * Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
5252
+ * cross-check above): that method judges liveness from the child's OWN
5253
+ * TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
5254
+ * on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
5255
+ * path the local opencode server IS running, so its in-memory status map is
5256
+ * live and authoritative — and per ADR-0047 §4a ("the child has its own entry
5257
+ * [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
5258
+ * ENTIRE turn (including any tool call it is itself executing), not a
5259
+ * per-message transcript snapshot. This sidesteps the "child's own tool is
5260
+ * executing, between its step's completion and the next generation step"
5261
+ * transcript gap that a transcript-based check would need a second,
5262
+ * sustained-window bound to guard against — it is simply not derived from
5263
+ * message timestamps at all.
5264
+ *
5265
+ * Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
5266
+ * status, as the recovery path does per §4a)? Because on the LIVE path the
5267
+ * root session can be shared: a SECOND, unrelated user message can land on the
5268
+ * SAME session (issue #721's own root cause) and keep the root `busy` for a
5269
+ * reason that has nothing to do with THIS message's delegation. A `task`
5270
+ * descendant session is spawned for exactly one delegated turn and never
5271
+ * reused, so its OWN status-map entry is unambiguous evidence about that one
5272
+ * delegation — which the root's status is not.
5273
+ *
5274
+ * Why membership is checked via `resolveSessionMembership`, NOT
5275
+ * `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
5276
+ * `GET /session/:id` fetch failure into "not a descendant", which would
5277
+ * silently drop a genuinely-live candidate from consideration on the one
5278
+ * unlucky tick its membership-walk fetch hiccups (#721).
5279
+ * `resolveSessionMembership` keeps that failure mode as a distinct `null`
5280
+ * (indeterminate) so it is folded into THIS method's own `indeterminate` flag
5281
+ * instead.
5282
+ *
5283
+ * Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
5284
+ * - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
5285
+ * - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
5286
+ * confirmed either way (`resolveSessionMembership` never
5287
+ * returned `null`), and every CONFIRMED descendant's status read
5288
+ * succeeded and is not ongoing (includes "no descendant session
5289
+ * exists at all" — e.g. a plain, non-`task` tool call).
5290
+ * - `null` → INDETERMINATE: `listSessions` failed, OR at least one
5291
+ * candidate's MEMBERSHIP could not be confirmed
5292
+ * (`resolveSessionMembership` returned `null` — a fetch failure
5293
+ * or pathological chain partway through the parent walk), OR at
5294
+ * least one CONFIRMED descendant's `isSessionOngoing` read
5295
+ * failed — and no OTHER candidate was already confirmed `true`.
5296
+ * The caller MUST NOT treat `null` the same as `false` here
5297
+ * (unlike the recovery cross-check's contract) — see
5298
+ * `isB2AbandonmentConfirmed`.
5299
+ */
5300
+ async isAnyDescendantSessionOngoing(rootSessionId) {
5301
+ const sessions = await listSessions(this.port);
5302
+ if (!sessions) {
5303
+ this.log({
5304
+ level: "warn",
5305
+ message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
5306
+ });
5307
+ return null;
5308
+ }
5309
+ let indeterminate = false;
5310
+ for (const candidate of sessions) {
5311
+ if (!candidate?.id || candidate.id === rootSessionId) continue;
5312
+ const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
5313
+ if (membership === null) {
5314
+ indeterminate = true;
5315
+ continue;
5316
+ }
5317
+ if (membership === false) continue;
5318
+ const ongoing = await isSessionOngoing(this.port, candidate.id);
5319
+ if (ongoing === true) return true;
5320
+ if (ongoing === null) indeterminate = true;
5321
+ }
5322
+ return indeterminate ? null : false;
5323
+ }
3764
5324
  /**
3765
5325
  * Cheap decision-telemetry label for a running row's LAST correlated reply
3766
5326
  * (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
@@ -3889,6 +5449,32 @@ var ChannelDriver = class {
3889
5449
  }
3890
5450
  return messages;
3891
5451
  }
5452
+ /**
5453
+ * The `opencode_session_id` fragment of a status PATCH body — `{}` when this
5454
+ * conversation has ABANDONED that session (#553). The field is optional
5455
+ * server-side and an absent one leaves the persisted binding untouched, so
5456
+ * omitting it is how a routine status write stops resurrecting it.
5457
+ *
5458
+ * ONLY for writes whose sole cost is a lost deep link. The `processing` notice
5459
+ * degrades to no "View in Evident" link (the reaction swap still fires) and the
5460
+ * turn-failure notice is built from the PATCH's own `error` text with a link off
5461
+ * the persisted row — neither loses content the user came for. `markDone`
5462
+ * deliberately does NOT use this helper: the server fetches the reply text
5463
+ * THROUGH the session id it is given, so suppressing there would replace the
5464
+ * agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
5465
+ * `ensureSession` guard, not this suppression, is what makes the self-heal
5466
+ * stick.
5467
+ */
5468
+ sessionIdBody(sessionId, conversationId, messageId, status2) {
5469
+ if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
5470
+ this.log({
5471
+ level: "debug",
5472
+ message: `Omitting the abandoned OpenCode session ${sessionId.slice(0, 8)} from the '${status2}' update for message ${messageId.slice(0, 8)} so it is not re-bound to conversation ${conversationId.slice(0, 8)}`,
5473
+ conversation_id: conversationId,
5474
+ message_id: messageId
5475
+ });
5476
+ return {};
5477
+ }
3892
5478
  /**
3893
5479
  * EXISTING combinedAuth route — now fired by the watcher on queued→running
3894
5480
  * (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
@@ -3918,7 +5504,7 @@ var ChannelDriver = class {
3918
5504
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3919
5505
  body: JSON.stringify({
3920
5506
  status: "processing",
3921
- opencode_session_id: sessionId,
5507
+ ...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
3922
5508
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3923
5509
  ...title ? { title } : {}
3924
5510
  })
@@ -3967,6 +5553,11 @@ var ChannelDriver = class {
3967
5553
  headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
3968
5554
  body: JSON.stringify({
3969
5555
  status: "done",
5556
+ // ALWAYS sent, even for a session this conversation has abandoned
5557
+ // (#553): the server reads the reply text back out of THIS session id
5558
+ // to deliver it. Omitting it would leave the user with "✅ Done!"
5559
+ // instead of the answer — a worse regression than the resurrection it
5560
+ // would prevent, which `ensureSession`'s guard handles anyway.
3970
5561
  opencode_session_id: sessionId,
3971
5562
  ...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
3972
5563
  ...title ? { title } : {},
@@ -3983,16 +5574,31 @@ var ChannelDriver = class {
3983
5574
  }
3984
5575
  /**
3985
5576
  * Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
3986
- * when provided (issue #182): a bare `markFailed(conv, msg)` sends
3987
- * `{status:'failed'}` unchanged (the dispatch-failure path), while an errored
3988
- * OpenCode turn sends `{status:'failed', opencode_session_id, error}` so the
3989
- * failure reason reaches the channel.
5577
+ * when provided (issue #182). Three states for `sessionId`:
5578
+ * - omitted (`undefined`) → don't send the field, leave the persisted
5579
+ * session untouched (unused today; kept for API symmetry).
5580
+ * - a real id (`string`) → send it, update the persisted session (the
5581
+ * turn-failure call sites: an errored OpenCode turn).
5582
+ * - explicit `null` → send it, CLEAR the persisted session (issue
5583
+ * #485's dispatch-handoff-failure call site: the session id still
5584
+ * exists but is wedged, so the next attempt must get a fresh one
5585
+ * instead of reusing it — see WI-1's server-side null-clearing PATCH).
3990
5586
  */
3991
- async markFailed(conversationId, messageId, sessionId, error2, usage) {
5587
+ async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
3992
5588
  const body = { status: "failed" };
3993
- if (sessionId !== void 0) body.opencode_session_id = sessionId;
5589
+ if (sessionId === null) {
5590
+ body.opencode_session_id = null;
5591
+ } else if (sessionId !== void 0) {
5592
+ Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
5593
+ }
3994
5594
  if (error2 !== void 0) body.error = error2;
3995
5595
  if (usage) Object.assign(body, usage);
5596
+ if (failure) {
5597
+ body.failure_kind = failure.kind;
5598
+ body.failure_provider_id = failure.providerId;
5599
+ body.failure_model_id = failure.modelId;
5600
+ body.failure_reason = failure.reason;
5601
+ }
3996
5602
  await this.callWithRetry(
3997
5603
  "marking message as failed",
3998
5604
  () => this.fetchImpl(
@@ -4005,6 +5611,29 @@ var ChannelDriver = class {
4005
5611
  )
4006
5612
  );
4007
5613
  }
5614
+ /**
5615
+ * Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
5616
+ *
5617
+ * `messageFailure` alone (structured OpenCode error → `model_auth`) covers
5618
+ * most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
5619
+ * to the P1-2b zero-provider check — one extra loopback call to
5620
+ * `hasAnyConfiguredProvider`, only reached when the structured classifier
5621
+ * couldn't place it. Fails open (never throws): a fallback probe failure
5622
+ * (`null`/indeterminate) leaves the classification `null`, which produces
5623
+ * today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
5624
+ */
5625
+ async classifyModelAuthFailure(messages, userMessageId) {
5626
+ const classified = messageFailure(messages, userMessageId);
5627
+ if (classified != null) return classified;
5628
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
5629
+ const hasProvider = await hasAnyConfiguredProvider(this.port);
5630
+ return applyZeroProviderFallback(
5631
+ classified,
5632
+ hasProvider,
5633
+ reply?.info?.providerID ?? null,
5634
+ reply?.info?.modelID ?? null
5635
+ );
5636
+ }
4008
5637
  /**
4009
5638
  * Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
4010
5639
  * (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
@@ -4157,10 +5786,16 @@ var ChannelDriver = class {
4157
5786
  import chalk5 from "chalk";
4158
5787
  import ora2 from "ora";
4159
5788
  import { select as select2 } from "@inquirer/prompts";
5789
+ var INTERACTIVE_START_TIMEOUT_MS = 3e4;
4160
5790
  async function ensureOpenCodeRunning(ctx) {
4161
5791
  const healthCheck = await checkOpenCodeHealth(ctx.port);
4162
5792
  if (healthCheck.healthy) {
4163
- return { port: ctx.port, process: null, version: healthCheck.version ?? null };
5793
+ return {
5794
+ port: ctx.port,
5795
+ process: null,
5796
+ version: healthCheck.version ?? null,
5797
+ notReadyReason: null
5798
+ };
4164
5799
  }
4165
5800
  const runningInstances = await findHealthyOpenCodeInstances();
4166
5801
  if (runningInstances.length > 0) {
@@ -4181,7 +5816,7 @@ async function ensureOpenCodeRunning(ctx) {
4181
5816
  console.log(chalk5.yellow("Tip: Run with the correct port:"));
4182
5817
  console.log(
4183
5818
  chalk5.dim(
4184
- ` ${getCliName()} run --agent ${ctx.agentId} --port ${runningInstances[0].port}`
5819
+ ` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
4185
5820
  )
4186
5821
  );
4187
5822
  }
@@ -4201,14 +5836,22 @@ async function ensureOpenCodeRunning(ctx) {
4201
5836
  if (!ctx.interactive) {
4202
5837
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
4203
5838
  const proc = await startOpenCode(ctx.port);
4204
- const health = await waitForOpenCodeHealth(ctx.port, 3e4);
5839
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
4205
5840
  if (!health.healthy) {
4206
- throw new Error(
4207
- `OpenCode failed to start on port ${ctx.port}. Install with: npm install -g opencode-ai`
4208
- );
5841
+ return {
5842
+ port: ctx.port,
5843
+ process: proc,
5844
+ version: null,
5845
+ notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
5846
+ };
4209
5847
  }
4210
5848
  ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
4211
- return { port: ctx.port, process: proc, version: health.version ?? null };
5849
+ return {
5850
+ port: ctx.port,
5851
+ process: proc,
5852
+ version: health.version ?? null,
5853
+ notReadyReason: null
5854
+ };
4212
5855
  }
4213
5856
  let port = ctx.port;
4214
5857
  if (isPortInUse(port)) {
@@ -4261,122 +5904,15 @@ Port ${port} is already in use.`));
4261
5904
  if (action === "start") {
4262
5905
  const spinner = ora2("Starting OpenCode...").start();
4263
5906
  const proc = await startOpenCode(port);
4264
- const health = await waitForOpenCodeHealth(port, 3e4);
5907
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
4265
5908
  if (!health.healthy) {
4266
5909
  spinner.fail("Failed to start OpenCode");
4267
5910
  throw new Error("OpenCode failed to start");
4268
5911
  }
4269
5912
  spinner.stop();
4270
- return { port, process: proc, version: health.version ?? null };
4271
- }
4272
- return { port, process: null, version: null };
4273
- }
4274
-
4275
- // src/commands/agent-lookup.ts
4276
- async function readErrorMessage(response) {
4277
- const text = await response.text().catch(() => "");
4278
- if (!text) return response.statusText || void 0;
4279
- try {
4280
- const data = JSON.parse(text);
4281
- const message = data.message ?? data.error;
4282
- if (typeof message === "string" && message.trim()) {
4283
- return message;
4284
- }
4285
- } catch {
4286
- }
4287
- return text.trim() || response.statusText || void 0;
4288
- }
4289
- function authFailureHint(apiUrl, serverMessage) {
4290
- const reason = serverMessage ? `: ${serverMessage}` : "";
4291
- return `Authentication failed${reason}. Your credentials were rejected by ${apiUrl}. This usually means you logged in against a different environment, or your session expired \u2014 log in again pointing at this endpoint and retry.`;
4292
- }
4293
- async function resolveAgentIdFromKey(authHeader) {
4294
- const apiUrl = getApiUrlConfig();
4295
- try {
4296
- const response = await fetch(`${apiUrl}/me`, {
4297
- headers: { Authorization: authHeader }
4298
- });
4299
- if (response.status === 401) {
4300
- const serverMessage = await readErrorMessage(response);
4301
- return { error: authFailureHint(apiUrl, serverMessage), authFailed: true };
4302
- }
4303
- if (!response.ok) {
4304
- const serverMessage = await readErrorMessage(response);
4305
- return {
4306
- error: `Failed to resolve runner from key (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
4307
- };
4308
- }
4309
- const data = await response.json();
4310
- if (data.auth_type === "agent_key" && data.agent_id) {
4311
- return { agent_id: data.agent_id };
4312
- }
4313
- return {
4314
- error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --agent explicitly."
4315
- };
4316
- } catch (error2) {
4317
- const message = error2 instanceof Error ? error2.message : "Unknown error";
4318
- return { error: `Failed to resolve runner from key: ${message}` };
4319
- }
4320
- }
4321
- async function notifyAgentDisconnected(agentId, authHeader) {
4322
- const apiUrl = getApiUrlConfig();
4323
- try {
4324
- const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
4325
- method: "POST",
4326
- headers: { Authorization: authHeader }
4327
- });
4328
- if (!response.ok) {
4329
- const serverMessage = await readErrorMessage(response);
4330
- return {
4331
- ok: false,
4332
- error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
4333
- };
4334
- }
4335
- return { ok: true };
4336
- } catch (error2) {
4337
- return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
4338
- }
4339
- }
4340
- async function getAgentInfo(agentId, authHeader) {
4341
- const apiUrl = getApiUrlConfig();
4342
- try {
4343
- const response = await fetch(`${apiUrl}/runners/${agentId}`, {
4344
- headers: { Authorization: authHeader }
4345
- });
4346
- if (response.status === 401) {
4347
- const serverMessage = await readErrorMessage(response);
4348
- return { valid: false, error: authFailureHint(apiUrl, serverMessage), authFailed: true };
4349
- }
4350
- if (response.status === 403) {
4351
- const serverMessage = await readErrorMessage(response);
4352
- return {
4353
- valid: false,
4354
- error: serverMessage ?? "You do not have access to this runner (it may belong to a different team or organization)."
4355
- };
4356
- }
4357
- if (response.status === 404) {
4358
- const serverMessage = await readErrorMessage(response);
4359
- return { valid: false, error: serverMessage ?? `Runner ${agentId} not found` };
4360
- }
4361
- if (!response.ok) {
4362
- const serverMessage = await readErrorMessage(response);
4363
- return {
4364
- valid: false,
4365
- error: `API error (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
4366
- };
4367
- }
4368
- const agent = await response.json();
4369
- if (agent.agent_type !== "local") {
4370
- return {
4371
- valid: false,
4372
- error: `Runner is type '${agent.agent_type}', must be 'local' for CLI connection`
4373
- };
4374
- }
4375
- return { valid: true, agent };
4376
- } catch (error2) {
4377
- const message = error2 instanceof Error ? error2.message : "Unknown error";
4378
- return { valid: false, error: `Failed to validate runner: ${message}` };
5913
+ return { port, process: proc, version: health.version ?? null, notReadyReason: null };
4379
5914
  }
5915
+ return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
4380
5916
  }
4381
5917
 
4382
5918
  // src/commands/run.ts
@@ -4384,6 +5920,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
4384
5920
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
4385
5921
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
4386
5922
  var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
5923
+ var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
4387
5924
  function resolveLogLevel(options) {
4388
5925
  const accepted = Object.keys(LOG_LEVELS);
4389
5926
  const validate = (value, source) => {
@@ -4407,6 +5944,63 @@ function resolveLogLevel(options) {
4407
5944
  }
4408
5945
  return "info";
4409
5946
  }
5947
+ function resolveFileSyncDirectories(raw, homeDir) {
5948
+ const directories = [];
5949
+ for (const entry of raw ?? []) {
5950
+ const trimmed = entry.trim();
5951
+ if (trimmed === "") {
5952
+ throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
5953
+ }
5954
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join3(homeDir, trimmed.slice(2)) : trimmed;
5955
+ if (!isAbsolute2(expanded)) {
5956
+ throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
5957
+ }
5958
+ const normalized = resolvePath(expanded);
5959
+ if (parse(normalized).root === normalized) {
5960
+ throw new Error(
5961
+ `--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
5962
+ );
5963
+ }
5964
+ if (!directories.includes(normalized)) {
5965
+ directories.push(normalized);
5966
+ }
5967
+ }
5968
+ if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
5969
+ throw new Error(
5970
+ `--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
5971
+ );
5972
+ }
5973
+ return directories;
5974
+ }
5975
+ var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
5976
+ var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
5977
+ var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
5978
+ function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
5979
+ const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
5980
+ let raw;
5981
+ let source;
5982
+ if (options.opencodeStartTimeout !== void 0) {
5983
+ raw = options.opencodeStartTimeout;
5984
+ source = "--opencode-start-timeout";
5985
+ } else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
5986
+ raw = env[OPENCODE_START_TIMEOUT_ENV];
5987
+ source = OPENCODE_START_TIMEOUT_ENV;
5988
+ } else {
5989
+ return { timeoutMs: defaultMs, warnings: [] };
5990
+ }
5991
+ const trimmed = raw.trim();
5992
+ const seconds = Number(trimmed);
5993
+ const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
5994
+ if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
5995
+ return {
5996
+ timeoutMs: defaultMs,
5997
+ warnings: [
5998
+ `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`
5999
+ ]
6000
+ };
6001
+ }
6002
+ return { timeoutMs: seconds * 1e3, warnings: [] };
6003
+ }
4410
6004
  function meetsThreshold(state, level) {
4411
6005
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
4412
6006
  }
@@ -4428,6 +6022,10 @@ function log2(state, message, level = "info") {
4428
6022
  function logActivity(state, entry) {
4429
6023
  const level = entry.level ?? (entry.type === "error" ? "error" : "info");
4430
6024
  if (!meetsThreshold(state, level)) return;
6025
+ forwardRunnerActivity(
6026
+ { level, message: entry.message, error: entry.error },
6027
+ { agentId: state.agentId, authHeader: state.authHeader }
6028
+ );
4431
6029
  const fullEntry = {
4432
6030
  ...entry,
4433
6031
  level,
@@ -4527,19 +6125,32 @@ async function handleAuthError(state, error2) {
4527
6125
  }
4528
6126
  async function driveChannels(state, driver) {
4529
6127
  let idlePolls = 0;
6128
+ let consecutiveDrainFailures = 0;
4530
6129
  let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
6130
+ let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
4531
6131
  while (state.running) {
4532
6132
  if (state.connection?.reconnecting && state.connection.reconnectPromise) {
4533
6133
  logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
4534
6134
  if (state.interactive) displayStatus(state);
4535
6135
  await state.connection.reconnectPromise;
4536
6136
  }
6137
+ const carriedOverFileSync = driver.fileSyncActivity().inFlight;
6138
+ void driver.syncPendingFiles().catch(
6139
+ (error2) => logActivity(state, {
6140
+ type: "error",
6141
+ error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
6142
+ })
6143
+ );
4537
6144
  try {
4538
6145
  const processed = await driver.drainPending();
6146
+ consecutiveDrainFailures = 0;
4539
6147
  state.messageCount += processed;
4540
6148
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
4541
6149
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
4542
- if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity) {
6150
+ const appliedFiles = driver.fileSyncActivity().appliedFiles;
6151
+ const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
6152
+ lastSeenAppliedFiles = appliedFiles;
6153
+ if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
4543
6154
  idlePolls = 0;
4544
6155
  if (processed > 0 && state.interactive) displayStatus(state);
4545
6156
  } else if (state.idleTimeout !== null) {
@@ -4567,8 +6178,32 @@ async function driveChannels(state, driver) {
4567
6178
  const errorMessage = error2 instanceof Error ? error2.message : String(error2);
4568
6179
  logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
4569
6180
  if (state.interactive) displayStatus(state);
6181
+ if (driver.hasInFlightWatchers()) {
6182
+ consecutiveDrainFailures = 0;
6183
+ } else if (state.idleTimeout !== null) {
6184
+ consecutiveDrainFailures++;
6185
+ if (consecutiveDrainFailures === 1) {
6186
+ logActivity(state, {
6187
+ type: "info",
6188
+ message: `Cannot reach Evident, will exit if this persists past the idle timeout (timeout: ${state.idleTimeout}s)...`
6189
+ });
6190
+ if (state.interactive) displayStatus(state);
6191
+ }
6192
+ }
6193
+ }
6194
+ await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
6195
+ if (state.idleTimeout !== null && consecutiveDrainFailures >= 2) {
6196
+ const unreachableMs = consecutiveDrainFailures * CHANNEL_POLL_INTERVAL_MS;
6197
+ if (unreachableMs > state.idleTimeout * 1e3) {
6198
+ logActivity(state, {
6199
+ type: "info",
6200
+ level: "warn",
6201
+ message: `Exiting: could not reach Evident for ${consecutiveDrainFailures} consecutive polls (${Math.round(unreachableMs / 1e3)}s)`
6202
+ });
6203
+ if (state.interactive) displayStatus(state);
6204
+ break;
6205
+ }
4570
6206
  }
4571
- await new Promise((resolve2) => setTimeout(resolve2, CHANNEL_POLL_INTERVAL_MS));
4572
6207
  if (state.idleTimeout !== null && idlePolls >= 2) {
4573
6208
  const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
4574
6209
  if (idleMs > state.idleTimeout * 1e3) {
@@ -4580,8 +6215,8 @@ async function driveChannels(state, driver) {
4580
6215
  }
4581
6216
  }
4582
6217
  var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
4583
- async function runSweep(state, driver, config2) {
4584
- const mode = `age=${config2.maxAgeMs ?? "\u2014"} count=${config2.maxCount ?? "\u2014"}`;
6218
+ async function runSweep(state, driver, config) {
6219
+ const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
4585
6220
  try {
4586
6221
  const sessions = await listSessions(state.port);
4587
6222
  if (sessions === null) {
@@ -4594,8 +6229,8 @@ async function runSweep(state, driver, config2) {
4594
6229
  const toDelete = selectSessionsToDelete(
4595
6230
  sessions.map((s) => ({ id: s.id, lastActivityMs: sessionLastActivityMs(s) })),
4596
6231
  {
4597
- maxAgeMs: config2.maxAgeMs,
4598
- maxCount: config2.maxCount,
6232
+ maxAgeMs: config.maxAgeMs,
6233
+ maxCount: config.maxCount,
4599
6234
  nowMs: Date.now(),
4600
6235
  protectedIds: driver.protectedSessionIds()
4601
6236
  }
@@ -4631,7 +6266,7 @@ async function runSweep(state, driver, config2) {
4631
6266
  }
4632
6267
  }
4633
6268
  function scheduleSessionCleanup(state, driver, options) {
4634
- const config2 = resolveSessionCleanupConfig(
6269
+ const config = resolveSessionCleanupConfig(
4635
6270
  {
4636
6271
  maxAge: options.sessionCleanupMaxAge,
4637
6272
  maxCount: options.sessionCleanupMaxCount,
@@ -4639,21 +6274,112 @@ function scheduleSessionCleanup(state, driver, options) {
4639
6274
  },
4640
6275
  process.env
4641
6276
  );
4642
- for (const warning2 of config2.warnings) {
6277
+ for (const warning2 of config.warnings) {
4643
6278
  logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
4644
6279
  }
4645
- if (!config2.enabled) return;
6280
+ if (!config.enabled) return;
4646
6281
  logActivity(state, {
4647
6282
  type: "info",
4648
- message: `Session cleanup enabled (age=${config2.maxAgeMs ?? "\u2014"}, count=${config2.maxCount ?? "\u2014"}, interval=${config2.intervalMs}ms)`
6283
+ message: `Session cleanup enabled (age=${config.maxAgeMs ?? "\u2014"}, count=${config.maxCount ?? "\u2014"}, interval=${config.intervalMs}ms)`
4649
6284
  });
4650
- const interval = setInterval(() => void runSweep(state, driver, config2), config2.intervalMs);
6285
+ const interval = setInterval(() => void runSweep(state, driver, config), config.intervalMs);
4651
6286
  const firstSweep = setTimeout(
4652
- () => void runSweep(state, driver, config2),
6287
+ () => void runSweep(state, driver, config),
4653
6288
  SESSION_CLEANUP_FIRST_SWEEP_MS
4654
6289
  );
4655
6290
  state.sessionCleanupTimers.push(interval, firstSweep);
4656
6291
  }
6292
+ function claudeUsageFailureStreakSuffix(consecutiveFailures) {
6293
+ return consecutiveFailures > 1 ? ` (${consecutiveFailures} consecutive failures)` : "";
6294
+ }
6295
+ function scheduleClaudeUsageReporting(state, options) {
6296
+ const { mode, warnings } = resolveClaudeUsageReportingMode(
6297
+ options.claudeUsageReporting,
6298
+ process.env
6299
+ );
6300
+ for (const warning2 of warnings) {
6301
+ logActivity(state, {
6302
+ type: "info",
6303
+ level: "warn",
6304
+ message: `Claude usage reporting: ${warning2}`
6305
+ });
6306
+ }
6307
+ if (mode === "off") {
6308
+ logActivity(state, {
6309
+ type: "info",
6310
+ level: "debug",
6311
+ message: "Claude usage reporting is off (--claude-usage-reporting off)"
6312
+ });
6313
+ return;
6314
+ }
6315
+ let consecutiveFailures = 0;
6316
+ const scheduleNextTick = () => {
6317
+ state.claudeUsageTimer = setTimeout(() => void tick(false), nextReportDelayMs());
6318
+ };
6319
+ const tick = async (isFirst) => {
6320
+ try {
6321
+ const usage = await getClaudeUsage();
6322
+ const result = await reportClaudeUsage(state.agentId, state.authHeader, usage);
6323
+ if (result.ok) {
6324
+ if (consecutiveFailures > 0) {
6325
+ logActivity(state, {
6326
+ type: "info",
6327
+ level: "info",
6328
+ message: "Claude usage reporting recovered"
6329
+ });
6330
+ }
6331
+ consecutiveFailures = 0;
6332
+ logActivity(state, {
6333
+ type: "info",
6334
+ level: "debug",
6335
+ message: "Reported Claude usage to Evident"
6336
+ });
6337
+ } else {
6338
+ consecutiveFailures++;
6339
+ logActivity(state, {
6340
+ type: "info",
6341
+ level: claudeUsageFailureLogLevel(consecutiveFailures),
6342
+ message: `Failed to report Claude usage: ${result.error}${claudeUsageFailureStreakSuffix(consecutiveFailures)}`
6343
+ });
6344
+ }
6345
+ scheduleNextTick();
6346
+ } catch (error2) {
6347
+ if (error2 instanceof ClaudeUsageError && isLocalCredentialProblem(error2)) {
6348
+ if (mode === "on") {
6349
+ logActivity(state, {
6350
+ type: "info",
6351
+ level: "warn",
6352
+ message: "Claude usage reporting is forced on but no usable Claude Code login was found \u2014 run `claude` to sign in; reporting will keep retrying"
6353
+ });
6354
+ scheduleNextTick();
6355
+ } else if (isFirst) {
6356
+ logActivity(state, {
6357
+ type: "info",
6358
+ level: "debug",
6359
+ message: `Claude usage reporting: ${error2.message}`
6360
+ });
6361
+ } else {
6362
+ logActivity(state, {
6363
+ type: "info",
6364
+ level: "debug",
6365
+ message: `Claude usage reporting: ${error2.message}`
6366
+ });
6367
+ scheduleNextTick();
6368
+ }
6369
+ } else {
6370
+ consecutiveFailures++;
6371
+ const message = error2 instanceof Error ? error2.message : String(error2);
6372
+ logActivity(state, {
6373
+ type: "info",
6374
+ level: claudeUsageFailureLogLevel(consecutiveFailures),
6375
+ message: `Claude usage reporting failed: ${message}${claudeUsageFailureStreakSuffix(consecutiveFailures)}`
6376
+ });
6377
+ scheduleNextTick();
6378
+ }
6379
+ }
6380
+ };
6381
+ state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
6382
+ }
4657
6383
  async function notifyOffline(state) {
4658
6384
  if (!state.agentId || !state.authHeader) return;
4659
6385
  if (!state.connected) {
@@ -4671,13 +6397,28 @@ async function notifyOffline(state) {
4671
6397
  if (state.interactive) displayStatus(state);
4672
6398
  }
4673
6399
  }
6400
+ async function timeShutdownPhase(state, durations, name, run2) {
6401
+ const startedAt = Date.now();
6402
+ try {
6403
+ return await run2();
6404
+ } finally {
6405
+ const elapsedMs = Date.now() - startedAt;
6406
+ durations[name] = elapsedMs;
6407
+ log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
6408
+ }
6409
+ }
4674
6410
  async function cleanup(state, opts = {}) {
6411
+ const durations = {};
4675
6412
  state.running = false;
4676
6413
  for (const timer of state.sessionCleanupTimers) {
4677
6414
  clearInterval(timer);
4678
6415
  clearTimeout(timer);
4679
6416
  }
4680
6417
  state.sessionCleanupTimers = [];
6418
+ if (state.claudeUsageTimer) {
6419
+ clearTimeout(state.claudeUsageTimer);
6420
+ state.claudeUsageTimer = null;
6421
+ }
4681
6422
  if (opts.graceful && state.channelDriver) {
4682
6423
  state.channelDriver.stop();
4683
6424
  log2(state, "Draining in-flight channel work before shutdown...");
@@ -4685,7 +6426,13 @@ async function cleanup(state, opts = {}) {
4685
6426
  logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
4686
6427
  displayStatus(state);
4687
6428
  }
4688
- const settled = await state.channelDriver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS);
6429
+ const driver = state.channelDriver;
6430
+ const settled = await timeShutdownPhase(
6431
+ state,
6432
+ durations,
6433
+ "drain",
6434
+ () => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
6435
+ );
4689
6436
  if (!settled) {
4690
6437
  logActivity(state, {
4691
6438
  type: "info",
@@ -4694,13 +6441,15 @@ async function cleanup(state, opts = {}) {
4694
6441
  if (state.interactive) displayStatus(state);
4695
6442
  }
4696
6443
  }
4697
- await notifyOffline(state);
6444
+ await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
4698
6445
  if (state.connection) {
4699
- state.connection.close();
6446
+ const connection = state.connection;
6447
+ await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
4700
6448
  state.connection = null;
4701
6449
  }
4702
6450
  if (state.opencodeProcess) {
4703
- stopOpenCode(state.opencodeProcess);
6451
+ const opencodeProcess = state.opencodeProcess;
6452
+ await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
4704
6453
  if (state.interactive) {
4705
6454
  logActivity(state, { type: "info", message: "Stopped OpenCode process" });
4706
6455
  displayStatus(state);
@@ -4709,12 +6458,15 @@ async function cleanup(state, opts = {}) {
4709
6458
  }
4710
6459
  state.opencodeProcess = null;
4711
6460
  }
6461
+ return durations;
4712
6462
  }
4713
6463
  async function run(options) {
4714
6464
  const interactive = isInteractive(options.json);
4715
6465
  let logLevel;
6466
+ let fileSyncDirectories;
4716
6467
  try {
4717
6468
  logLevel = resolveLogLevel(options);
6469
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
4718
6470
  } catch (error2) {
4719
6471
  const message = error2 instanceof Error ? error2.message : String(error2);
4720
6472
  if (options.json) {
@@ -4747,8 +6499,15 @@ async function run(options) {
4747
6499
  messageCount: 0,
4748
6500
  lastProxiedActivityAt: null,
4749
6501
  sessionCleanupTimers: [],
6502
+ claudeUsageTimer: null,
4750
6503
  authHeader: ""
4751
6504
  };
6505
+ setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
6506
+ if (fileSyncDirectories.length > 0) {
6507
+ log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
6508
+ } else {
6509
+ log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
6510
+ }
4752
6511
  if (!options.runner && options.agent) {
4753
6512
  telemetry.info(
4754
6513
  EventTypes.DEPRECATED_AGENT_FLAG_USED,
@@ -4772,14 +6531,38 @@ async function run(options) {
4772
6531
  const handleSignal = async () => {
4773
6532
  if (state.shuttingDown) return;
4774
6533
  state.shuttingDown = true;
6534
+ const shutdownStartedAt = Date.now();
4775
6535
  if (state.interactive) {
4776
6536
  logActivity(state, { type: "info", message: "Shutting down..." });
4777
6537
  displayStatus(state);
4778
6538
  } else {
4779
6539
  log2(state, "Shutting down...");
4780
6540
  }
4781
- await cleanup(state, { graceful: true });
4782
- await shutdownTelemetry();
6541
+ const durations = await cleanup(state, { graceful: true });
6542
+ const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
6543
+ await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
6544
+ let timer;
6545
+ const flushed = shutdownTelemetry().then(
6546
+ () => true,
6547
+ (error2) => {
6548
+ log2(
6549
+ state,
6550
+ `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
6551
+ "warn"
6552
+ );
6553
+ return true;
6554
+ }
6555
+ );
6556
+ const timedOut = new Promise((resolve3) => {
6557
+ timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
6558
+ });
6559
+ if (!await Promise.race([flushed, timedOut])) {
6560
+ log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
6561
+ }
6562
+ clearTimeout(timer);
6563
+ });
6564
+ const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
6565
+ log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
4783
6566
  process.exit(0);
4784
6567
  };
4785
6568
  process.on("SIGINT", handleSignal);
@@ -4796,6 +6579,7 @@ async function run(options) {
4796
6579
  console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
4797
6580
  blank();
4798
6581
  process.exit(1);
6582
+ return;
4799
6583
  }
4800
6584
  blank();
4801
6585
  console.log(chalk6.yellow("You are not logged in to Evident."));
@@ -4840,6 +6624,7 @@ async function run(options) {
4840
6624
  } else {
4841
6625
  printError(resolved.error || "Failed to resolve runner ID from key");
4842
6626
  process.exit(1);
6627
+ return;
4843
6628
  }
4844
6629
  } else {
4845
6630
  printError(
@@ -4853,6 +6638,7 @@ async function run(options) {
4853
6638
  );
4854
6639
  blank();
4855
6640
  process.exit(1);
6641
+ return;
4856
6642
  }
4857
6643
  }
4858
6644
  telemetry.info(
@@ -4893,40 +6679,67 @@ async function run(options) {
4893
6679
  }
4894
6680
  spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
4895
6681
  state.agentName = validation.agent.name;
6682
+ const microvmId = process.env.MICROVM_ID?.trim();
6683
+ if (microvmId) {
6684
+ const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
6685
+ if (reported.ok) {
6686
+ log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
6687
+ } else {
6688
+ const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
6689
+ log2(state, message, "warn");
6690
+ if (state.interactive && !state.json) {
6691
+ logActivity(state, { type: "info", level: "warn", message });
6692
+ }
6693
+ }
6694
+ } else {
6695
+ log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
6696
+ }
6697
+ const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
6698
+ for (const warning2 of opencodeStartTimeoutWarnings) {
6699
+ logActivity(state, { type: "info", level: "warn", message: warning2 });
6700
+ }
4896
6701
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
4897
6702
  try {
4898
6703
  const oc = await ensureOpenCodeRunning({
4899
6704
  port: state.port,
4900
6705
  interactive: state.interactive,
4901
6706
  agentId: state.agentId,
4902
- log: (message) => log2(state, message)
6707
+ log: (message) => log2(state, message),
6708
+ startTimeoutMs: opencodeStartTimeoutMs
4903
6709
  });
4904
6710
  state.port = oc.port;
4905
6711
  state.opencodeProcess = oc.process;
4906
6712
  state.opencodeVersion = oc.version;
4907
- state.opencodeConnected = oc.process !== null || oc.version !== null;
6713
+ state.opencodeConnected = oc.notReadyReason === null;
4908
6714
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
4909
6715
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
4910
- const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
4911
- if (versionWarning) {
4912
- log2(state, versionWarning, "warn");
4913
- if (state.interactive && !state.json) {
4914
- logActivity(state, { type: "info", level: "warn", message: versionWarning });
6716
+ if (!state.interactive && oc.notReadyReason !== null) {
6717
+ 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}).`;
6718
+ logActivity(state, { type: "info", level: "warn", message });
6719
+ } else {
6720
+ const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
6721
+ if (versionWarning) {
6722
+ log2(state, versionWarning, "warn");
6723
+ if (state.interactive && !state.json) {
6724
+ logActivity(state, { type: "info", level: "warn", message: versionWarning });
6725
+ }
4915
6726
  }
4916
- }
4917
- const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
4918
- if (noProviderWarning) {
4919
- log2(state, noProviderWarning, "warn");
4920
- if (state.interactive && !state.json) {
4921
- logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
4922
- blank();
4923
- console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
4924
- console.log(
4925
- chalk6.dim(
4926
- `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
4927
- )
4928
- );
4929
- blank();
6727
+ const noProviderWarning = buildNoProviderWarning(
6728
+ await hasAnyConfiguredProvider(state.port)
6729
+ );
6730
+ if (noProviderWarning) {
6731
+ log2(state, noProviderWarning, "warn");
6732
+ if (state.interactive && !state.json) {
6733
+ logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
6734
+ blank();
6735
+ console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
6736
+ console.log(
6737
+ chalk6.dim(
6738
+ `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
6739
+ )
6740
+ );
6741
+ blank();
6742
+ }
4930
6743
  }
4931
6744
  }
4932
6745
  } catch (error2) {
@@ -4941,6 +6754,10 @@ async function run(options) {
4941
6754
  getAuthHeader: () => state.authHeader,
4942
6755
  conversationFilter: state.conversationFilter,
4943
6756
  stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
6757
+ // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
6758
+ // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
6759
+ fileSyncDirectories,
6760
+ homeDir: homedir3(),
4944
6761
  log: (entry) => (
4945
6762
  // Thread the driver's real level straight through so `debug`/`warn`
4946
6763
  // survive the sink filter (they no longer collapse to info). `type`
@@ -4967,6 +6784,18 @@ async function run(options) {
4967
6784
  type: "info",
4968
6785
  message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
4969
6786
  });
6787
+ if (options.tunnelReadyFile) {
6788
+ const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
6789
+ if (marker.ok) {
6790
+ log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
6791
+ } else {
6792
+ log2(
6793
+ state,
6794
+ `Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
6795
+ "error"
6796
+ );
6797
+ }
6798
+ }
4970
6799
  emitAgentConnected(state.agentId, {
4971
6800
  port: state.port,
4972
6801
  cli_version: getCliVersion(),
@@ -5022,6 +6851,12 @@ async function run(options) {
5022
6851
  onDrainPing: () => {
5023
6852
  if (!state.running) return;
5024
6853
  logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
6854
+ void channelDriver.syncPendingFiles().catch(
6855
+ (error2) => logActivity(state, {
6856
+ type: "error",
6857
+ error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
6858
+ })
6859
+ );
5025
6860
  channelDriver.drainPending().then((processed) => {
5026
6861
  if (processed > 0) {
5027
6862
  state.messageCount += processed;
@@ -5051,6 +6886,7 @@ async function run(options) {
5051
6886
  throw error2;
5052
6887
  }
5053
6888
  scheduleSessionCleanup(state, channelDriver, options);
6889
+ scheduleClaudeUsageReporting(state, options);
5054
6890
  if (!interactive || state.json) {
5055
6891
  log2(state, "Driving channel messages...");
5056
6892
  }
@@ -5105,10 +6941,18 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
5105
6941
  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);
5106
6942
  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 }));
5107
6943
  program.command("whoami").description("Show the currently logged in user").action(whoami);
5108
- program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Runner ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("--runner [id]", "Alias for --agent (preferred name; wins if both are given)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
6944
+ program.command("status").description("Check whether the configured credentials can reach Evident").option("--json", "Output in JSON format").action((options) => status({ json: options.json }));
6945
+ program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);
6946
+ 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(
6947
+ "-a, --agent [id]",
6948
+ "Deprecated alias for --runner (still supported; --runner wins if both are given)"
6949
+ ).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
5109
6950
  "--log-level <level>",
5110
6951
  "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
5111
- ).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(
6952
+ ).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(
6953
+ "--opencode-start-timeout <seconds>",
6954
+ "Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
6955
+ ).option("--json", "Output in JSON format").option(
5112
6956
  "--session-cleanup-max-age <duration>",
5113
6957
  "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
5114
6958
  ).option(
@@ -5117,6 +6961,17 @@ program.command("run").description("Connect to Evident and process messages").op
5117
6961
  ).option(
5118
6962
  "--session-cleanup-interval <duration>",
5119
6963
  "How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
6964
+ ).option(
6965
+ "--claude-usage-reporting <mode>",
6966
+ "Report Claude subscription usage to Evident: auto | on | off (default: auto). Env: EVIDENT_CLAUDE_USAGE_REPORTING"
6967
+ ).option(
6968
+ "--enable-file-sync-to <dir>",
6969
+ "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
6970
+ (value, previous) => previous.concat([value]),
6971
+ []
6972
+ ).option(
6973
+ "--tunnel-ready-file <path>",
6974
+ "Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
5120
6975
  ).action(
5121
6976
  (options) => {
5122
6977
  run({
@@ -5129,11 +6984,21 @@ program.command("run").description("Connect to Evident and process messages").op
5129
6984
  verbose: options.verbose,
5130
6985
  conversation: options.conversation,
5131
6986
  idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
6987
+ // Raw string — validation/precedence is single-sourced in run.ts's
6988
+ // resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
6989
+ opencodeStartTimeout: options.opencodeStartTimeout,
5132
6990
  json: options.json,
5133
6991
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
5134
6992
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
5135
6993
  sessionCleanupMaxCount: options.sessionCleanupMaxCount,
5136
- sessionCleanupInterval: options.sessionCleanupInterval
6994
+ sessionCleanupInterval: options.sessionCleanupInterval,
6995
+ // Raw string — the resolver in run.ts single-sources parsing
6996
+ // (resolveClaudeUsageReportingMode).
6997
+ claudeUsageReporting: options.claudeUsageReporting,
6998
+ // Raw values — expansion/validation is single-sourced in run.ts's
6999
+ // resolveFileSyncDirectories.
7000
+ enableFileSyncTo: options.enableFileSyncTo,
7001
+ tunnelReadyFile: options.tunnelReadyFile
5137
7002
  });
5138
7003
  }
5139
7004
  );