@evident-ai/cli 3.1.1-dev.97fd633 → 3.1.1-dev.9e90301

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
@@ -267,16 +267,28 @@ async function getToken() {
267
267
  }
268
268
  return null;
269
269
  }
270
+ function toError(err) {
271
+ return err instanceof Error ? err : new Error(String(err));
272
+ }
270
273
  async function deleteToken(options = {}) {
271
274
  const keytar = await getKeytar();
275
+ const failures = [];
272
276
  if (keytar) {
273
277
  if (options.all) {
274
- const all = await keytar.findCredentials(SERVICE_NAME).catch(() => []);
278
+ let accounts = [];
279
+ try {
280
+ accounts = await keytar.findCredentials(SERVICE_NAME);
281
+ } catch (err) {
282
+ failures.push({ type: "enumerate", error: toError(err) });
283
+ }
275
284
  await Promise.all(
276
- all.map(
277
- (entry) => keytar.deletePassword(SERVICE_NAME, entry.account).catch(() => {
278
- })
279
- )
285
+ accounts.map(async (entry) => {
286
+ try {
287
+ await keytar.deletePassword(SERVICE_NAME, entry.account);
288
+ } catch (err) {
289
+ failures.push({ type: "delete", account: entry.account, error: toError(err) });
290
+ }
291
+ })
280
292
  );
281
293
  } else {
282
294
  await keytar.deletePassword(SERVICE_NAME, keychainAccount());
@@ -287,6 +299,7 @@ async function deleteToken(options = {}) {
287
299
  } else {
288
300
  clearCredentials();
289
301
  }
302
+ return { failures };
290
303
  }
291
304
 
292
305
  // src/utils/ui.ts
@@ -404,8 +417,10 @@ async function deviceFlowLogin(options) {
404
417
  }
405
418
  async function tokenLogin() {
406
419
  console.log("Token login mode.");
407
- console.log("Run `evident login` on a machine with a browser to get a token.");
408
- console.log("Manage or revoke existing tokens under Settings \u2192 CLI tokens.");
420
+ console.log("Create a token under Settings \u2192 CLI tokens in the dashboard, then paste it below.");
421
+ console.log(
422
+ "(Alternatively, run `evident login` on a machine with a browser, or set EVIDENT_TOKEN for CI.)"
423
+ );
409
424
  blank();
410
425
  process.stdout.write("Paste token: ");
411
426
  const token = await new Promise((resolve3) => {
@@ -429,13 +444,22 @@ async function tokenLogin() {
429
444
  printError("No token provided.");
430
445
  process.exit(1);
431
446
  }
447
+ await validateAndStoreToken(token);
448
+ }
449
+ async function validateAndStoreToken(token) {
432
450
  const spinner = ora("Validating token...").start();
433
451
  try {
434
- const result = await api.post("/auth/token/validate", { token });
452
+ const result = await api.get("/me", {
453
+ headers: { Authorization: `Bearer ${token}` }
454
+ });
455
+ if (!result.user) {
456
+ throw new Error(
457
+ "This token is not a user login (e.g. a runner key). Paste a CLI token instead."
458
+ );
459
+ }
435
460
  await storeToken({
436
461
  token,
437
- user: result.user,
438
- expiresAt: result.expires_at
462
+ user: { email: result.user.email }
439
463
  });
440
464
  spinner.stop();
441
465
  printSuccess(`Logged in as ${chalk2.bold(result.user.email)}`);
@@ -455,9 +479,22 @@ async function login(options) {
455
479
  }
456
480
 
457
481
  // src/commands/logout.ts
482
+ function describeFailure(failure) {
483
+ if (failure.type === "enumerate") {
484
+ return `could not list stored keychain entries (${failure.error.message})`;
485
+ }
486
+ return `${failure.account} (${failure.error.message})`;
487
+ }
458
488
  async function logout(options = {}) {
459
489
  if (options.all) {
460
- await deleteToken({ all: true });
490
+ const result = await deleteToken({ all: true });
491
+ if (result.failures.length > 0) {
492
+ printError(
493
+ `Failed to fully clear your keychain: ${result.failures.map(describeFailure).join("; ")}. Your local credentials file was cleared, but stale keychain entries may remain \u2014 run \`evident logout --all\` again, or remove them manually from your OS keychain / credential manager.`
494
+ );
495
+ process.exitCode = 1;
496
+ return;
497
+ }
461
498
  printSuccess("Logged out of all endpoints.");
462
499
  return;
463
500
  }
@@ -482,7 +519,9 @@ async function whoami() {
482
519
  blank();
483
520
  console.log(keyValue("Endpoint", apiUrl));
484
521
  console.log(keyValue("User", chalk3.bold(credentials2.user.email)));
485
- console.log(keyValue("User ID", credentials2.user.id));
522
+ if (credentials2.user.id) {
523
+ console.log(keyValue("User ID", credentials2.user.id));
524
+ }
486
525
  if (credentials2.expiresAt) {
487
526
  const expiresAt = new Date(credentials2.expiresAt);
488
527
  const now = /* @__PURE__ */ new Date();
@@ -498,9 +537,124 @@ async function whoami() {
498
537
  blank();
499
538
  }
500
539
 
540
+ // src/lib/claude-usage.ts
541
+ import { execFileSync } from "child_process";
542
+ import { readFileSync } from "fs";
543
+ import { homedir } from "os";
544
+ import { join } from "path";
545
+ var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
546
+ var KEYCHAIN_SERVICE = "Claude Code-credentials";
547
+ function parseClaudeCliCredentials(raw) {
548
+ let parsed;
549
+ try {
550
+ parsed = JSON.parse(raw);
551
+ } catch {
552
+ return null;
553
+ }
554
+ const data = parsed.claudeAiOauth ?? parsed;
555
+ const creds = data;
556
+ if (typeof creds.accessToken !== "string" || typeof creds.expiresAt !== "number") {
557
+ return null;
558
+ }
559
+ return { accessToken: creds.accessToken, expiresAt: creds.expiresAt };
560
+ }
561
+ function readClaudeCliCredentials() {
562
+ if (process.platform === "darwin") {
563
+ try {
564
+ const raw = execFileSync(
565
+ "/usr/bin/security",
566
+ ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-w"],
567
+ { encoding: "utf-8", timeout: 2e3, stdio: ["pipe", "pipe", "ignore"] }
568
+ );
569
+ return parseClaudeCliCredentials(raw);
570
+ } catch {
571
+ return null;
572
+ }
573
+ }
574
+ try {
575
+ const raw = readFileSync(join(homedir(), ".claude", ".credentials.json"), "utf-8");
576
+ return parseClaudeCliCredentials(raw);
577
+ } catch {
578
+ return null;
579
+ }
580
+ }
581
+ var ClaudeUsageError = class extends Error {
582
+ constructor(message, reason) {
583
+ super(message);
584
+ this.reason = reason;
585
+ }
586
+ };
587
+ function isLocalCredentialProblem(err) {
588
+ return err instanceof ClaudeUsageError && (err.reason === "no_credentials" || err.reason === "credentials_expired");
589
+ }
590
+ function toWindow(value) {
591
+ if (!value || typeof value !== "object") {
592
+ return null;
593
+ }
594
+ const window = value;
595
+ if (typeof window.utilization !== "number" || typeof window.resets_at !== "string") {
596
+ return null;
597
+ }
598
+ return { utilization: window.utilization, resetsAt: window.resets_at };
599
+ }
600
+ async function getClaudeUsage() {
601
+ const credentials2 = readClaudeCliCredentials();
602
+ if (!credentials2) {
603
+ throw new ClaudeUsageError(
604
+ "No local Claude Code login found. Run `claude` once to sign in with your Claude subscription.",
605
+ "no_credentials"
606
+ );
607
+ }
608
+ if (credentials2.expiresAt < Date.now()) {
609
+ throw new ClaudeUsageError(
610
+ "Claude Code credentials have expired. Run `claude` to refresh them.",
611
+ "credentials_expired"
612
+ );
613
+ }
614
+ const res = await fetch(CLAUDE_USAGE_URL, {
615
+ headers: {
616
+ Authorization: `Bearer ${credentials2.accessToken}`,
617
+ "Content-Type": "application/json",
618
+ "anthropic-version": "2023-06-01"
619
+ }
620
+ });
621
+ if (!res.ok) {
622
+ throw new ClaudeUsageError(`Claude usage request failed: HTTP ${res.status}`, "request_failed");
623
+ }
624
+ const body = await res.json();
625
+ return {
626
+ fiveHour: toWindow(body.five_hour),
627
+ sevenDay: toWindow(body.seven_day)
628
+ };
629
+ }
630
+
631
+ // src/commands/claude-usage.ts
632
+ function formatWindow(label, window) {
633
+ if (!window) {
634
+ return keyValue(label, "not available for this plan");
635
+ }
636
+ const resetsAt = new Date(window.resetsAt);
637
+ return keyValue(label, `${window.utilization}% used, resets ${resetsAt.toLocaleString()}`);
638
+ }
639
+ async function claudeUsage() {
640
+ try {
641
+ const usage = await getClaudeUsage();
642
+ blank();
643
+ console.log(formatWindow("5-hour session", usage.fiveHour));
644
+ console.log(formatWindow("7-day", usage.sevenDay));
645
+ blank();
646
+ } catch (err) {
647
+ if (err instanceof ClaudeUsageError) {
648
+ printError(err.message);
649
+ process.exit(1);
650
+ }
651
+ throw err;
652
+ }
653
+ }
654
+
501
655
  // src/commands/run.ts
502
- import { homedir as homedir2 } from "os";
503
- import { isAbsolute as isAbsolute2, join as join2, parse, resolve as resolvePath } from "path";
656
+ import { homedir as homedir3 } from "os";
657
+ import { isAbsolute as isAbsolute2, join as join3, parse, resolve as resolvePath } from "path";
504
658
  import chalk6 from "chalk";
505
659
 
506
660
  // ../../packages/types/src/telemetry/index.ts
@@ -510,7 +664,10 @@ var TelemetryEventTypes = {
510
664
  AGENT_DISCONNECTED: "agent.disconnected",
511
665
  AGENT_MESSAGE_PROCESSING: "agent.message_processing",
512
666
  AGENT_MESSAGE_DONE: "agent.message_done",
513
- AGENT_MESSAGE_FAILED: "agent.message_failed"
667
+ AGENT_MESSAGE_FAILED: "agent.message_failed",
668
+ // A `warn`/`error` runner-side log line forwarded server-side for
669
+ // observability (issue #916) — see `apps/cli/src/lib/runner-activity-telemetry.ts`.
670
+ RUNNER_ACTIVITY: "runner.activity"
514
671
  };
515
672
 
516
673
  // ../../packages/types/src/tunnel/index.ts
@@ -565,6 +722,13 @@ var isShuttingDown = false;
565
722
  var FLUSH_INTERVAL_MS = 5e3;
566
723
  var MAX_BUFFER_SIZE = 50;
567
724
  var FLUSH_TIMEOUT_MS = 3e3;
725
+ var authProvider = null;
726
+ function setTelemetryAuthProvider(provider) {
727
+ authProvider = provider;
728
+ }
729
+ var FLUSH_FAILURE_LOG_INTERVAL_MS = 6e4;
730
+ var lastFlushFailureLoggedAt = 0;
731
+ var suppressedFlushFailureCount = 0;
568
732
  function logEvent(eventType, options = {}) {
569
733
  const event = {
570
734
  event_type: eventType,
@@ -599,9 +763,16 @@ async function flushEvents() {
599
763
  flushTimeout = null;
600
764
  }
601
765
  try {
602
- const credentials2 = await getToken();
603
- if (!credentials2) {
604
- return;
766
+ const providerContext = authProvider?.();
767
+ let authHeader;
768
+ if (providerContext?.authHeader) {
769
+ authHeader = providerContext.authHeader;
770
+ } else {
771
+ const credentials2 = await getToken();
772
+ if (!credentials2) {
773
+ return;
774
+ }
775
+ authHeader = `Bearer ${credentials2.token}`;
605
776
  }
606
777
  const apiUrl = getApiUrlConfig();
607
778
  const controller = new AbortController();
@@ -616,7 +787,7 @@ async function flushEvents() {
616
787
  method: "POST",
617
788
  headers: {
618
789
  "Content-Type": "application/json",
619
- Authorization: `Bearer ${credentials2.token}`
790
+ Authorization: authHeader
620
791
  },
621
792
  body: JSON.stringify(request),
622
793
  signal: controller.signal
@@ -628,8 +799,15 @@ async function flushEvents() {
628
799
  clearTimeout(timeout);
629
800
  }
630
801
  } catch (error2) {
631
- if (process.env.DEBUG) {
632
- console.error("Telemetry error:", error2);
802
+ const now = Date.now();
803
+ if (now - lastFlushFailureLoggedAt >= FLUSH_FAILURE_LOG_INTERVAL_MS) {
804
+ const message = error2 instanceof Error ? error2.message : String(error2);
805
+ const suffix = suppressedFlushFailureCount > 0 ? ` (${suppressedFlushFailureCount} more suppressed in the last ${FLUSH_FAILURE_LOG_INTERVAL_MS / 1e3}s)` : "";
806
+ console.error(`Telemetry flush error: ${message}${suffix}`);
807
+ lastFlushFailureLoggedAt = now;
808
+ suppressedFlushFailureCount = 0;
809
+ } else {
810
+ suppressedFlushFailureCount++;
633
811
  }
634
812
  }
635
813
  }
@@ -698,6 +876,69 @@ var EventTypes = {
698
876
  DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
699
877
  };
700
878
 
879
+ // src/lib/runner-activity-telemetry.ts
880
+ var FORWARDED_LEVELS = /* @__PURE__ */ new Set(["warn", "error"]);
881
+ var SEVERITY_BY_LEVEL = {
882
+ warn: "warning",
883
+ error: "error"
884
+ };
885
+ var MAX_MESSAGE_LENGTH = 500;
886
+ var TRUNCATION_MARKER = "\u2026";
887
+ function redact(message) {
888
+ return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
889
+ }
890
+ function truncate(message) {
891
+ if (message.length <= MAX_MESSAGE_LENGTH) return message;
892
+ return message.slice(0, MAX_MESSAGE_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
893
+ }
894
+ var RATE_LIMIT_WINDOW_MS = 6e4;
895
+ var RATE_LIMIT_MAX_EVENTS = 30;
896
+ var windowStartedAt = 0;
897
+ var windowCount = 0;
898
+ var windowDroppedCount = 0;
899
+ function admitUnderRateLimit(now) {
900
+ if (now - windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
901
+ if (windowDroppedCount > 0) {
902
+ console.error(
903
+ `[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)`
904
+ );
905
+ }
906
+ windowStartedAt = now;
907
+ windowCount = 0;
908
+ windowDroppedCount = 0;
909
+ }
910
+ if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
911
+ windowDroppedCount++;
912
+ if (windowDroppedCount === 1) {
913
+ console.error(
914
+ `[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
915
+ );
916
+ }
917
+ return false;
918
+ }
919
+ windowCount++;
920
+ return true;
921
+ }
922
+ function forwardRunnerActivity(entry, context) {
923
+ try {
924
+ if (!FORWARDED_LEVELS.has(entry.level)) return;
925
+ if (!context.agentId || !context.authHeader) return;
926
+ if (!admitUnderRateLimit(Date.now())) return;
927
+ const rawMessage = entry.error ?? entry.message ?? "";
928
+ const message = truncate(redact(rawMessage));
929
+ logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
930
+ severity: SEVERITY_BY_LEVEL[entry.level],
931
+ message,
932
+ metadata: { source: "cli.run" },
933
+ agentId: context.agentId
934
+ });
935
+ } catch (err) {
936
+ console.error(
937
+ `[runner-activity-telemetry] failed to forward runner activity: ${err instanceof Error ? err.message : String(err)}`
938
+ );
939
+ }
940
+ }
941
+
701
942
  // src/lib/auth.ts
702
943
  async function getAuthCredentials() {
703
944
  const runnerKey = process.env.EVIDENT_RUNNER_KEY;
@@ -1532,6 +1773,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
1532
1773
  const reply = findLastAssistantReplyFor(messages, userMessageId);
1533
1774
  return completedOf(reply) != null && finishOf(reply) === "tool-calls";
1534
1775
  }
1776
+ function isB2AbandonmentConfirmed(params) {
1777
+ return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
1778
+ }
1535
1779
  function messageError(messages, userMessageId) {
1536
1780
  const reply = findLastAssistantReplyFor(messages, userMessageId);
1537
1781
  const error2 = errorOf(reply);
@@ -1545,6 +1789,42 @@ function messageError(messages, userMessageId) {
1545
1789
  }
1546
1790
  return "The agent run failed.";
1547
1791
  }
1792
+ function messageFailure(messages, userMessageId) {
1793
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
1794
+ const error2 = errorOf(reply);
1795
+ if (error2 == null || typeof error2 !== "object") return null;
1796
+ const e = error2;
1797
+ const replyProviderId = reply?.info?.providerID ?? null;
1798
+ const replyModelId = reply?.info?.modelID ?? null;
1799
+ if (e.name === "ProviderAuthError") {
1800
+ const data = e.data;
1801
+ const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
1802
+ return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
1803
+ }
1804
+ if (e.name === "APIError") {
1805
+ const data = e.data;
1806
+ const statusCode = data?.statusCode;
1807
+ if (statusCode === 401 || statusCode === 403) {
1808
+ return {
1809
+ kind: "model_auth",
1810
+ providerId: replyProviderId,
1811
+ modelId: replyModelId,
1812
+ reason: "rejected"
1813
+ };
1814
+ }
1815
+ }
1816
+ return null;
1817
+ }
1818
+ function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
1819
+ if (classified != null) return classified;
1820
+ if (hasConfiguredProvider !== false) return null;
1821
+ return {
1822
+ kind: "model_auth",
1823
+ providerId: replyProviderId,
1824
+ modelId: replyModelId,
1825
+ reason: "missing"
1826
+ };
1827
+ }
1548
1828
  function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1549
1829
  if (!messages || messages.length === 0) return false;
1550
1830
  return messages.some(
@@ -2073,13 +2353,52 @@ var RunnerConnection = class {
2073
2353
  }
2074
2354
  };
2075
2355
 
2356
+ // src/lib/tunnel/ready-marker.ts
2357
+ import { writeFileSync } from "fs";
2358
+ function writeTunnelReadyMarker(path, agentId) {
2359
+ try {
2360
+ writeFileSync(path, `${agentId}
2361
+ `);
2362
+ return { ok: true };
2363
+ } catch (error2) {
2364
+ return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
2365
+ }
2366
+ }
2367
+
2368
+ // src/lib/claude-usage-reporting.ts
2369
+ var VALID_MODES = ["auto", "on", "off"];
2370
+ function resolveClaudeUsageReportingMode(flagValue, env) {
2371
+ const raw = flagValue ?? env.EVIDENT_CLAUDE_USAGE_REPORTING;
2372
+ if (raw === void 0 || raw === "") {
2373
+ return { mode: "auto", warnings: [] };
2374
+ }
2375
+ const normalized = raw.trim().toLowerCase();
2376
+ if (VALID_MODES.includes(normalized)) {
2377
+ return { mode: normalized, warnings: [] };
2378
+ }
2379
+ const source = flagValue !== void 0 ? "--claude-usage-reporting" : "EVIDENT_CLAUDE_USAGE_REPORTING";
2380
+ return {
2381
+ mode: "auto",
2382
+ warnings: [
2383
+ `Ignoring invalid ${source} "${raw}": expected one of ${VALID_MODES.join(", ")}; using auto`
2384
+ ]
2385
+ };
2386
+ }
2387
+ var BASE_REPORT_DELAY_MS = 10 * 6e4;
2388
+ var REPORT_DELAY_JITTER_FRACTION = 0.2;
2389
+ function nextReportDelayMs(random = Math.random) {
2390
+ const jitterRangeMs = BASE_REPORT_DELAY_MS * REPORT_DELAY_JITTER_FRACTION;
2391
+ return BASE_REPORT_DELAY_MS - jitterRangeMs + random() * (2 * jitterRangeMs);
2392
+ }
2393
+ var FIRST_REPORT_DELAY_MS = 5e3 + Math.random() * 1e4;
2394
+
2076
2395
  // src/lib/channels/driver.ts
2077
- import { homedir } from "os";
2396
+ import { homedir as homedir2 } from "os";
2078
2397
 
2079
2398
  // src/lib/file-push.ts
2080
2399
  import { randomUUID } from "crypto";
2081
2400
  import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
2082
- import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
2401
+ import { basename, dirname as dirname2, isAbsolute, join as join2, relative, resolve as resolve2, sep } from "path";
2083
2402
  var FILE_MODE = 384;
2084
2403
  var DIRECTORY_MODE = 448;
2085
2404
  async function writePushedFile(request) {
@@ -2112,7 +2431,7 @@ async function writePushedFile(request) {
2112
2431
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
2113
2432
  dirname2(candidate)
2114
2433
  );
2115
- const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
2434
+ const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
2116
2435
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
2117
2436
  if (allowedDirectory === null) {
2118
2437
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -2148,7 +2467,7 @@ function expandAndValidate(requestedPath, homeDir) {
2148
2467
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
2149
2468
  return null;
2150
2469
  }
2151
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join(homeDir, requestedPath.slice(2)) : requestedPath;
2470
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join2(homeDir, requestedPath.slice(2)) : requestedPath;
2152
2471
  if (expanded.split(/[/\\]/).includes("..")) {
2153
2472
  return null;
2154
2473
  }
@@ -2221,13 +2540,13 @@ function contains(realDirectory, realTarget) {
2221
2540
  async function createMissingDirectories(existingAncestor, missingSegments) {
2222
2541
  let current = existingAncestor;
2223
2542
  for (const segment of missingSegments) {
2224
- current = join(current, segment);
2543
+ current = join2(current, segment);
2225
2544
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
2226
2545
  await chmod(current, DIRECTORY_MODE);
2227
2546
  }
2228
2547
  }
2229
2548
  async function writeAtomically(realTarget, content) {
2230
- const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2549
+ const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2231
2550
  let handle;
2232
2551
  try {
2233
2552
  handle = await open2(temporaryPath, "wx", FILE_MODE);
@@ -2499,6 +2818,8 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
2499
2818
  var DEFAULT_STUCK_QUEUED_MS = 6e4;
2500
2819
  var HEARTBEAT_MS = 6e4;
2501
2820
  var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
2821
+ var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
2822
+ var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
2502
2823
  var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
2503
2824
  var MAX_SUPERSEDED_CONVERSATIONS = 256;
2504
2825
  var ChannelAuthError = class extends Error {
@@ -2740,7 +3061,7 @@ var ChannelDriver = class _ChannelDriver {
2740
3061
  this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
2741
3062
  this.now = config2.now ?? (() => Date.now());
2742
3063
  this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
2743
- this.homeDir = config2.homeDir ?? homedir();
3064
+ this.homeDir = config2.homeDir ?? homedir2();
2744
3065
  }
2745
3066
  /** The IPv4-loopback base URL for the local `opencode serve`. */
2746
3067
  get opencodeBase() {
@@ -3125,7 +3446,12 @@ var ChannelDriver = class _ChannelDriver {
3125
3446
  const directory = await this.resolveOpenCodeDirectory();
3126
3447
  const sessionId = await createOpenCodeSession(this.port, directory);
3127
3448
  this.sessions.set(conversationId, sessionId);
3128
- await this.persistSession(conversationId, sessionId).catch(() => {
3449
+ await this.persistSession(conversationId, sessionId).catch((err) => {
3450
+ this.log({
3451
+ level: "warn",
3452
+ 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)}`,
3453
+ conversation_id: conversationId
3454
+ });
3129
3455
  });
3130
3456
  return sessionId;
3131
3457
  }
@@ -3317,12 +3643,17 @@ var ChannelDriver = class _ChannelDriver {
3317
3643
  stuckReported: false,
3318
3644
  lastAliveAt: 0,
3319
3645
  aliveInFlight: false,
3646
+ titleSynced: false,
3647
+ titleSyncInFlight: false,
3320
3648
  awaitingHumanLatched: false,
3321
3649
  pausedOnQuestion: false,
3322
3650
  pausedOnPermission: false,
3323
3651
  pausedClearConfirmed: false,
3324
3652
  pausedInFlight: false,
3325
- deliveryDeadlineAnchored: false
3653
+ deliveryDeadlineAnchored: false,
3654
+ b2PinnedSinceMs: 0,
3655
+ b2LastDescendantCheckMs: 0,
3656
+ b2AbandonedSignalled: false
3326
3657
  });
3327
3658
  }
3328
3659
  /**
@@ -3390,12 +3721,17 @@ var ChannelDriver = class _ChannelDriver {
3390
3721
  // with no extra `re_adopted` signal needed (folds old WI-6).
3391
3722
  lastAliveAt: 0,
3392
3723
  aliveInFlight: false,
3724
+ titleSynced: false,
3725
+ titleSyncInFlight: false,
3393
3726
  awaitingHumanLatched: false,
3394
3727
  pausedOnQuestion: false,
3395
3728
  pausedOnPermission: false,
3396
3729
  pausedClearConfirmed: false,
3397
3730
  pausedInFlight: false,
3398
- deliveryDeadlineAnchored: false
3731
+ deliveryDeadlineAnchored: false,
3732
+ b2PinnedSinceMs: 0,
3733
+ b2LastDescendantCheckMs: 0,
3734
+ b2AbandonedSignalled: false
3399
3735
  });
3400
3736
  }
3401
3737
  /**
@@ -3557,58 +3893,7 @@ var ChannelDriver = class _ChannelDriver {
3557
3893
  }
3558
3894
  }
3559
3895
  if (state === "done") {
3560
- this.anchorDeliveryDeadline(inFlight);
3561
- if (!inFlight.done) {
3562
- this.log({
3563
- level: "info",
3564
- message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
3565
- conversation_id: conv.id,
3566
- message_id: inFlight.evidentMessageId
3567
- });
3568
- const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
3569
- const usage = messageUsage(messages, inFlight.opencodeMessageId);
3570
- try {
3571
- await this.markDone(
3572
- conv.id,
3573
- inFlight.evidentMessageId,
3574
- sessionId,
3575
- inFlight.opencodeMessageId,
3576
- title,
3577
- usage
3578
- );
3579
- } catch (err) {
3580
- if (err instanceof ChannelAuthError) throw err;
3581
- if (err instanceof ChannelTerminalError) {
3582
- this.log({
3583
- level: "warn",
3584
- message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
3585
- conversation_id: conv.id,
3586
- message_id: inFlight.evidentMessageId
3587
- });
3588
- this.removeInFlight(watcher, inFlight.evidentMessageId);
3589
- return;
3590
- }
3591
- if (this.now() >= inFlight.deadline) {
3592
- this.log({
3593
- level: "warn",
3594
- 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)}`,
3595
- conversation_id: conv.id,
3596
- message_id: inFlight.evidentMessageId
3597
- });
3598
- this.removeInFlight(watcher, inFlight.evidentMessageId);
3599
- return;
3600
- }
3601
- this.log({
3602
- level: "warn",
3603
- message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
3604
- conversation_id: conv.id,
3605
- message_id: inFlight.evidentMessageId
3606
- });
3607
- return;
3608
- }
3609
- inFlight.done = true;
3610
- }
3611
- this.removeInFlight(watcher, inFlight.evidentMessageId);
3896
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
3612
3897
  return;
3613
3898
  }
3614
3899
  if (state === "failed") {
@@ -3622,8 +3907,16 @@ var ChannelDriver = class _ChannelDriver {
3622
3907
  message_id: inFlight.evidentMessageId
3623
3908
  });
3624
3909
  const usage = messageUsage(messages, inFlight.opencodeMessageId);
3910
+ const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
3625
3911
  try {
3626
- await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2, usage);
3912
+ await this.markFailed(
3913
+ conv.id,
3914
+ inFlight.evidentMessageId,
3915
+ sessionId,
3916
+ error2,
3917
+ usage,
3918
+ failure
3919
+ );
3627
3920
  } catch (err) {
3628
3921
  if (err instanceof ChannelAuthError) throw err;
3629
3922
  if (err instanceof ChannelTerminalError) {
@@ -3668,6 +3961,44 @@ var ChannelDriver = class _ChannelDriver {
3668
3961
  });
3669
3962
  }
3670
3963
  const activelyRunning = state === "running" && !awaitingHuman;
3964
+ const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
3965
+ const snapshotReadable = messages != null && messages.length > 0;
3966
+ if (!pinnedNow) {
3967
+ if (snapshotReadable) {
3968
+ inFlight.b2PinnedSinceMs = 0;
3969
+ inFlight.b2LastDescendantCheckMs = 0;
3970
+ inFlight.b2AbandonedSignalled = false;
3971
+ }
3972
+ } else {
3973
+ if (inFlight.b2AbandonedSignalled) {
3974
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
3975
+ return;
3976
+ }
3977
+ if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
3978
+ const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
3979
+ if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
3980
+ inFlight.b2LastDescendantCheckMs = this.now();
3981
+ const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
3982
+ if (isB2AbandonmentConfirmed({
3983
+ pinnedForMs,
3984
+ minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
3985
+ descendantOngoing
3986
+ })) {
3987
+ inFlight.b2AbandonedSignalled = true;
3988
+ this.log({
3989
+ level: "warn",
3990
+ 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`,
3991
+ conversation_id: conv.id,
3992
+ message_id: id
3993
+ });
3994
+ void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
3995
+ watched_for_ms: pinnedForMs
3996
+ });
3997
+ await this.settleMessageDone(sessionId, watcher, inFlight, messages);
3998
+ return;
3999
+ }
4000
+ }
4001
+ }
3671
4002
  if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
3672
4003
  this.log({
3673
4004
  level: "warn",
@@ -3687,6 +4018,18 @@ var ChannelDriver = class _ChannelDriver {
3687
4018
  inFlight.aliveInFlight = false;
3688
4019
  if (ok) inFlight.lastAliveAt = this.now();
3689
4020
  });
4021
+ if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
4022
+ inFlight.titleSyncInFlight = true;
4023
+ void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
4024
+ if (!title) {
4025
+ inFlight.titleSyncInFlight = false;
4026
+ return;
4027
+ }
4028
+ const ok = await this.patchConversationTitle(conv.id, title);
4029
+ inFlight.titleSyncInFlight = false;
4030
+ if (ok) inFlight.titleSynced = true;
4031
+ });
4032
+ }
3690
4033
  }
3691
4034
  if (awaitingHuman) {
3692
4035
  if (!inFlight.awaitingHumanLatched) {
@@ -3724,6 +4067,70 @@ var ChannelDriver = class _ChannelDriver {
3724
4067
  this.removeInFlight(watcher, inFlight.evidentMessageId);
3725
4068
  }
3726
4069
  }
4070
+ /**
4071
+ * Settle a message whose run-state has resolved `'done'` — extracted verbatim
4072
+ * (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
4073
+ * inline `state === 'done'` branch body, so a SECOND caller (the #721
4074
+ * b2-abandonment resolution) can reach the exact same completion behavior
4075
+ * (delivery-deadline anchoring, title resolution, usage extraction, and
4076
+ * `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
4077
+ * and risking the two copies silently drifting apart.
4078
+ */
4079
+ async settleMessageDone(sessionId, watcher, inFlight, messages) {
4080
+ const conv = watcher.conv;
4081
+ this.anchorDeliveryDeadline(inFlight);
4082
+ if (!inFlight.done) {
4083
+ this.log({
4084
+ level: "info",
4085
+ message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
4086
+ conversation_id: conv.id,
4087
+ message_id: inFlight.evidentMessageId
4088
+ });
4089
+ const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
4090
+ const usage = messageUsage(messages, inFlight.opencodeMessageId);
4091
+ try {
4092
+ await this.markDone(
4093
+ conv.id,
4094
+ inFlight.evidentMessageId,
4095
+ sessionId,
4096
+ inFlight.opencodeMessageId,
4097
+ title,
4098
+ usage
4099
+ );
4100
+ } catch (err) {
4101
+ if (err instanceof ChannelAuthError) throw err;
4102
+ if (err instanceof ChannelTerminalError) {
4103
+ this.log({
4104
+ level: "warn",
4105
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
4106
+ conversation_id: conv.id,
4107
+ message_id: inFlight.evidentMessageId
4108
+ });
4109
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
4110
+ return;
4111
+ }
4112
+ if (this.now() >= inFlight.deadline) {
4113
+ this.log({
4114
+ level: "warn",
4115
+ 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)}`,
4116
+ conversation_id: conv.id,
4117
+ message_id: inFlight.evidentMessageId
4118
+ });
4119
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
4120
+ return;
4121
+ }
4122
+ this.log({
4123
+ level: "warn",
4124
+ message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
4125
+ conversation_id: conv.id,
4126
+ message_id: inFlight.evidentMessageId
4127
+ });
4128
+ return;
4129
+ }
4130
+ inFlight.done = true;
4131
+ }
4132
+ this.removeInFlight(watcher, inFlight.evidentMessageId);
4133
+ }
3727
4134
  // Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
3728
4135
  /**
3729
4136
  * Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
@@ -3890,6 +4297,7 @@ var ChannelDriver = class _ChannelDriver {
3890
4297
  if (state === "failed") {
3891
4298
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
3892
4299
  const usage = messageUsage(messages, ocId ?? "");
4300
+ const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
3893
4301
  this.log({
3894
4302
  level: "error",
3895
4303
  message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
@@ -3897,7 +4305,7 @@ var ChannelDriver = class _ChannelDriver {
3897
4305
  message_id: row.id
3898
4306
  });
3899
4307
  try {
3900
- await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
4308
+ await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
3901
4309
  } catch (err) {
3902
4310
  if (err instanceof ChannelAuthError) throw err;
3903
4311
  if (err instanceof ChannelTerminalError) {
@@ -4303,6 +4711,47 @@ var ChannelDriver = class _ChannelDriver {
4303
4711
  }
4304
4712
  return false;
4305
4713
  }
4714
+ /**
4715
+ * Tri-state variant of the upward parentID membership walk (#721), used ONLY
4716
+ * by `isAnyDescendantSessionOngoing`. Walks the SAME cached
4717
+ * `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
4718
+ * `sessionBelongsTo`, which deliberately collapses "confirmed not a
4719
+ * descendant" and "the walk's fetch failed" into the same `false` (safe for
4720
+ * its OTHER callers: interaction attribution and the recovery-path
4721
+ * `isAnyDescendantSessionAlive`, both of which just retry next tick with no
4722
+ * safety consequence either way) — this variant keeps those two outcomes
4723
+ * SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
4724
+ * (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
4725
+ * not ongoing".
4726
+ *
4727
+ * Return contract:
4728
+ * - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
4729
+ * - `false` → the walk reached a definitive, parent-less root session
4730
+ * WITHOUT ever matching `rootSessionId` — `sessionId` is
4731
+ * CONFIRMED NOT a descendant of it.
4732
+ * - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
4733
+ * through the walk (`resolveSessionParent` returned `undefined`),
4734
+ * or the depth cap (32) was hit without a definitive answer (a
4735
+ * pathological/cyclic chain proves nothing either way). NEVER
4736
+ * treat this the same as `false` — see `sessionBelongsTo`'s own
4737
+ * doc comment above for why that collapse is safe THERE but not
4738
+ * here.
4739
+ *
4740
+ * `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
4741
+ * to the live-path descendant check, not a modification of shared code used
4742
+ * by interaction attribution or the recovery path.
4743
+ */
4744
+ async resolveSessionMembership(sessionId, rootSessionId) {
4745
+ let current = sessionId;
4746
+ for (let depth = 0; current && depth < 32; depth++) {
4747
+ if (current === rootSessionId) return true;
4748
+ const parent = await this.resolveSessionParent(current);
4749
+ if (parent === void 0) return null;
4750
+ if (parent === null) return false;
4751
+ current = parent;
4752
+ }
4753
+ return null;
4754
+ }
4306
4755
  /**
4307
4756
  * Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
4308
4757
  * `null` for a root session (no parent) and `undefined` when opencode is
@@ -4387,6 +4836,54 @@ var ChannelDriver = class _ChannelDriver {
4387
4836
  }
4388
4837
  return null;
4389
4838
  }
4839
+ /**
4840
+ * Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
4841
+ * session title onto the conversation via the PLAIN conversation-update
4842
+ * endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
4843
+ * message-status endpoint `markProcessing`/`markDone` use. Deliberately a
4844
+ * separate, lighter call: it carries no `status`, so it cannot re-trigger the
4845
+ * `processing`/`done` transition side effects (Slack notices, activity-log
4846
+ * rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
4847
+ * ever touches `conversations.title`. That route (`routes/conversations.ts`)
4848
+ * skips a title write matching the stored value, so a redundant call with the
4849
+ * same title is a real no-op — it does not bump `updated_at`, which the
4850
+ * conversation list sorts and paginates on. (Note this is a DIFFERENT guard
4851
+ * from `threads.ts`'s "non-empty AND changed" one, which only covers the
4852
+ * message-status PATCH; the non-empty half is enforced here instead, by
4853
+ * `resolveSessionTitle` never returning an empty/placeholder title.)
4854
+ *
4855
+ * Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
4856
+ * is logged and the title is simply retried on the next heartbeat tick (the
4857
+ * caller only latches `titleSynced` on `true`).
4858
+ */
4859
+ async patchConversationTitle(conversationId, title) {
4860
+ try {
4861
+ const res = await this.fetchImpl(
4862
+ `${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
4863
+ {
4864
+ method: "PATCH",
4865
+ headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
4866
+ body: JSON.stringify({ title })
4867
+ }
4868
+ );
4869
+ if (!res.ok) {
4870
+ this.log({
4871
+ level: "debug",
4872
+ message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
4873
+ conversation_id: conversationId
4874
+ });
4875
+ return false;
4876
+ }
4877
+ return true;
4878
+ } catch (err) {
4879
+ this.log({
4880
+ level: "debug",
4881
+ 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)}`,
4882
+ conversation_id: conversationId
4883
+ });
4884
+ return false;
4885
+ }
4886
+ }
4390
4887
  /**
4391
4888
  * DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
4392
4889
  * (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
@@ -4445,6 +4942,84 @@ var ChannelDriver = class _ChannelDriver {
4445
4942
  }
4446
4943
  return false;
4447
4944
  }
4945
+ /**
4946
+ * LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
4947
+ * sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
4948
+ * in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
4949
+ *
4950
+ * Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
4951
+ * cross-check above): that method judges liveness from the child's OWN
4952
+ * TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
4953
+ * on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
4954
+ * path the local opencode server IS running, so its in-memory status map is
4955
+ * live and authoritative — and per ADR-0047 §4a ("the child has its own entry
4956
+ * [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
4957
+ * ENTIRE turn (including any tool call it is itself executing), not a
4958
+ * per-message transcript snapshot. This sidesteps the "child's own tool is
4959
+ * executing, between its step's completion and the next generation step"
4960
+ * transcript gap that a transcript-based check would need a second,
4961
+ * sustained-window bound to guard against — it is simply not derived from
4962
+ * message timestamps at all.
4963
+ *
4964
+ * Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
4965
+ * status, as the recovery path does per §4a)? Because on the LIVE path the
4966
+ * root session can be shared: a SECOND, unrelated user message can land on the
4967
+ * SAME session (issue #721's own root cause) and keep the root `busy` for a
4968
+ * reason that has nothing to do with THIS message's delegation. A `task`
4969
+ * descendant session is spawned for exactly one delegated turn and never
4970
+ * reused, so its OWN status-map entry is unambiguous evidence about that one
4971
+ * delegation — which the root's status is not.
4972
+ *
4973
+ * Why membership is checked via `resolveSessionMembership`, NOT
4974
+ * `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
4975
+ * `GET /session/:id` fetch failure into "not a descendant", which would
4976
+ * silently drop a genuinely-live candidate from consideration on the one
4977
+ * unlucky tick its membership-walk fetch hiccups (#721).
4978
+ * `resolveSessionMembership` keeps that failure mode as a distinct `null`
4979
+ * (indeterminate) so it is folded into THIS method's own `indeterminate` flag
4980
+ * instead.
4981
+ *
4982
+ * Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
4983
+ * - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
4984
+ * - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
4985
+ * confirmed either way (`resolveSessionMembership` never
4986
+ * returned `null`), and every CONFIRMED descendant's status read
4987
+ * succeeded and is not ongoing (includes "no descendant session
4988
+ * exists at all" — e.g. a plain, non-`task` tool call).
4989
+ * - `null` → INDETERMINATE: `listSessions` failed, OR at least one
4990
+ * candidate's MEMBERSHIP could not be confirmed
4991
+ * (`resolveSessionMembership` returned `null` — a fetch failure
4992
+ * or pathological chain partway through the parent walk), OR at
4993
+ * least one CONFIRMED descendant's `isSessionOngoing` read
4994
+ * failed — and no OTHER candidate was already confirmed `true`.
4995
+ * The caller MUST NOT treat `null` the same as `false` here
4996
+ * (unlike the recovery cross-check's contract) — see
4997
+ * `isB2AbandonmentConfirmed`.
4998
+ */
4999
+ async isAnyDescendantSessionOngoing(rootSessionId) {
5000
+ const sessions = await listSessions(this.port);
5001
+ if (!sessions) {
5002
+ this.log({
5003
+ level: "warn",
5004
+ message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
5005
+ });
5006
+ return null;
5007
+ }
5008
+ let indeterminate = false;
5009
+ for (const candidate of sessions) {
5010
+ if (!candidate?.id || candidate.id === rootSessionId) continue;
5011
+ const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
5012
+ if (membership === null) {
5013
+ indeterminate = true;
5014
+ continue;
5015
+ }
5016
+ if (membership === false) continue;
5017
+ const ongoing = await isSessionOngoing(this.port, candidate.id);
5018
+ if (ongoing === true) return true;
5019
+ if (ongoing === null) indeterminate = true;
5020
+ }
5021
+ return indeterminate ? null : false;
5022
+ }
4448
5023
  /**
4449
5024
  * Cheap decision-telemetry label for a running row's LAST correlated reply
4450
5025
  * (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
@@ -4708,7 +5283,7 @@ var ChannelDriver = class _ChannelDriver {
4708
5283
  * exists but is wedged, so the next attempt must get a fresh one
4709
5284
  * instead of reusing it — see WI-1's server-side null-clearing PATCH).
4710
5285
  */
4711
- async markFailed(conversationId, messageId, sessionId, error2, usage) {
5286
+ async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
4712
5287
  const body = { status: "failed" };
4713
5288
  if (sessionId === null) {
4714
5289
  body.opencode_session_id = null;
@@ -4717,6 +5292,12 @@ var ChannelDriver = class _ChannelDriver {
4717
5292
  }
4718
5293
  if (error2 !== void 0) body.error = error2;
4719
5294
  if (usage) Object.assign(body, usage);
5295
+ if (failure) {
5296
+ body.failure_kind = failure.kind;
5297
+ body.failure_provider_id = failure.providerId;
5298
+ body.failure_model_id = failure.modelId;
5299
+ body.failure_reason = failure.reason;
5300
+ }
4720
5301
  await this.callWithRetry(
4721
5302
  "marking message as failed",
4722
5303
  () => this.fetchImpl(
@@ -4729,6 +5310,29 @@ var ChannelDriver = class _ChannelDriver {
4729
5310
  )
4730
5311
  );
4731
5312
  }
5313
+ /**
5314
+ * Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
5315
+ *
5316
+ * `messageFailure` alone (structured OpenCode error → `model_auth`) covers
5317
+ * most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
5318
+ * to the P1-2b zero-provider check — one extra loopback call to
5319
+ * `hasAnyConfiguredProvider`, only reached when the structured classifier
5320
+ * couldn't place it. Fails open (never throws): a fallback probe failure
5321
+ * (`null`/indeterminate) leaves the classification `null`, which produces
5322
+ * today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
5323
+ */
5324
+ async classifyModelAuthFailure(messages, userMessageId) {
5325
+ const classified = messageFailure(messages, userMessageId);
5326
+ if (classified != null) return classified;
5327
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
5328
+ const hasProvider = await hasAnyConfiguredProvider(this.port);
5329
+ return applyZeroProviderFallback(
5330
+ classified,
5331
+ hasProvider,
5332
+ reply?.info?.providerID ?? null,
5333
+ reply?.info?.modelID ?? null
5334
+ );
5335
+ }
4732
5336
  /**
4733
5337
  * Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
4734
5338
  * (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
@@ -4881,10 +5485,16 @@ var ChannelDriver = class _ChannelDriver {
4881
5485
  import chalk5 from "chalk";
4882
5486
  import ora2 from "ora";
4883
5487
  import { select as select2 } from "@inquirer/prompts";
5488
+ var INTERACTIVE_START_TIMEOUT_MS = 3e4;
4884
5489
  async function ensureOpenCodeRunning(ctx) {
4885
5490
  const healthCheck = await checkOpenCodeHealth(ctx.port);
4886
5491
  if (healthCheck.healthy) {
4887
- return { port: ctx.port, process: null, version: healthCheck.version ?? null };
5492
+ return {
5493
+ port: ctx.port,
5494
+ process: null,
5495
+ version: healthCheck.version ?? null,
5496
+ notReadyReason: null
5497
+ };
4888
5498
  }
4889
5499
  const runningInstances = await findHealthyOpenCodeInstances();
4890
5500
  if (runningInstances.length > 0) {
@@ -4905,7 +5515,7 @@ async function ensureOpenCodeRunning(ctx) {
4905
5515
  console.log(chalk5.yellow("Tip: Run with the correct port:"));
4906
5516
  console.log(
4907
5517
  chalk5.dim(
4908
- ` ${getCliName()} run --agent ${ctx.agentId} --port ${runningInstances[0].port}`
5518
+ ` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
4909
5519
  )
4910
5520
  );
4911
5521
  }
@@ -4925,14 +5535,22 @@ async function ensureOpenCodeRunning(ctx) {
4925
5535
  if (!ctx.interactive) {
4926
5536
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
4927
5537
  const proc = await startOpenCode(ctx.port);
4928
- const health = await waitForOpenCodeHealth(ctx.port, 3e4);
5538
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
4929
5539
  if (!health.healthy) {
4930
- throw new Error(
4931
- `OpenCode failed to start on port ${ctx.port}. Install with: npm install -g opencode-ai`
4932
- );
5540
+ return {
5541
+ port: ctx.port,
5542
+ process: proc,
5543
+ version: null,
5544
+ notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
5545
+ };
4933
5546
  }
4934
5547
  ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
4935
- return { port: ctx.port, process: proc, version: health.version ?? null };
5548
+ return {
5549
+ port: ctx.port,
5550
+ process: proc,
5551
+ version: health.version ?? null,
5552
+ notReadyReason: null
5553
+ };
4936
5554
  }
4937
5555
  let port = ctx.port;
4938
5556
  if (isPortInUse(port)) {
@@ -4985,15 +5603,15 @@ Port ${port} is already in use.`));
4985
5603
  if (action === "start") {
4986
5604
  const spinner = ora2("Starting OpenCode...").start();
4987
5605
  const proc = await startOpenCode(port);
4988
- const health = await waitForOpenCodeHealth(port, 3e4);
5606
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
4989
5607
  if (!health.healthy) {
4990
5608
  spinner.fail("Failed to start OpenCode");
4991
5609
  throw new Error("OpenCode failed to start");
4992
5610
  }
4993
5611
  spinner.stop();
4994
- return { port, process: proc, version: health.version ?? null };
5612
+ return { port, process: proc, version: health.version ?? null, notReadyReason: null };
4995
5613
  }
4996
- return { port, process: null, version: null };
5614
+ return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
4997
5615
  }
4998
5616
 
4999
5617
  // src/commands/agent-lookup.ts
@@ -5035,21 +5653,49 @@ async function resolveAgentIdFromKey(authHeader) {
5035
5653
  return { agent_id: data.agent_id };
5036
5654
  }
5037
5655
  return {
5038
- error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --agent explicitly."
5656
+ error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
5039
5657
  };
5040
5658
  } catch (error2) {
5041
5659
  const message = error2 instanceof Error ? error2.message : "Unknown error";
5042
5660
  return { error: `Failed to resolve runner from key: ${message}` };
5043
5661
  }
5044
5662
  }
5045
- var OFFLINE_NOTIFY_TIMEOUT_MS = 2e3;
5663
+ var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
5046
5664
  async function notifyAgentDisconnected(agentId, authHeader) {
5047
5665
  const apiUrl = getApiUrlConfig();
5048
5666
  try {
5049
5667
  const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
5050
5668
  method: "POST",
5051
5669
  headers: { Authorization: authHeader },
5052
- signal: AbortSignal.timeout(OFFLINE_NOTIFY_TIMEOUT_MS)
5670
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
5671
+ });
5672
+ if (!response.ok) {
5673
+ const serverMessage = await readErrorMessage(response);
5674
+ return {
5675
+ ok: false,
5676
+ error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
5677
+ };
5678
+ }
5679
+ return { ok: true };
5680
+ } catch (error2) {
5681
+ return { ok: false, error: describeBestEffortError(error2) };
5682
+ }
5683
+ }
5684
+ function describeBestEffortError(error2) {
5685
+ const name = error2?.name;
5686
+ if (name === "TimeoutError" || name === "AbortError") {
5687
+ return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
5688
+ }
5689
+ return error2 instanceof Error ? error2.message : String(error2);
5690
+ }
5691
+ async function reportMicrovmId(agentId, authHeader, microvmId) {
5692
+ try {
5693
+ const apiUrl = getApiUrlConfig();
5694
+ const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
5695
+ method: "POST",
5696
+ headers: { Authorization: authHeader, "Content-Type": "application/json" },
5697
+ body: JSON.stringify({ microvm_id: microvmId }),
5698
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
5053
5699
  });
5054
5700
  if (!response.ok) {
5055
5701
  const serverMessage = await readErrorMessage(response);
@@ -5060,11 +5706,35 @@ async function notifyAgentDisconnected(agentId, authHeader) {
5060
5706
  }
5061
5707
  return { ok: true };
5062
5708
  } catch (error2) {
5063
- const name = error2?.name;
5064
- if (name === "TimeoutError" || name === "AbortError") {
5065
- return { ok: false, error: `timed out after ${OFFLINE_NOTIFY_TIMEOUT_MS}ms` };
5709
+ return { ok: false, error: describeBestEffortError(error2) };
5710
+ }
5711
+ }
5712
+ function toReportedWindow(window) {
5713
+ if (!window) return null;
5714
+ return { utilization: window.utilization, resets_at: window.resetsAt };
5715
+ }
5716
+ async function reportClaudeUsage(agentId, authHeader, snapshot) {
5717
+ try {
5718
+ const apiUrl = getApiUrlConfig();
5719
+ const response = await fetch(`${apiUrl}/runners/${agentId}/claude-usage`, {
5720
+ method: "POST",
5721
+ headers: { Authorization: authHeader, "Content-Type": "application/json" },
5722
+ body: JSON.stringify({
5723
+ five_hour: toReportedWindow(snapshot.fiveHour),
5724
+ seven_day: toReportedWindow(snapshot.sevenDay)
5725
+ }),
5726
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
5727
+ });
5728
+ if (!response.ok) {
5729
+ const serverMessage = await readErrorMessage(response);
5730
+ return {
5731
+ ok: false,
5732
+ error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
5733
+ };
5066
5734
  }
5067
- return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
5735
+ return { ok: true };
5736
+ } catch (error2) {
5737
+ return { ok: false, error: describeBestEffortError(error2) };
5068
5738
  }
5069
5739
  }
5070
5740
  async function getAgentInfo(agentId, authHeader) {
@@ -5145,7 +5815,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
5145
5815
  if (trimmed === "") {
5146
5816
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
5147
5817
  }
5148
- const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join2(homeDir, trimmed.slice(2)) : trimmed;
5818
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join3(homeDir, trimmed.slice(2)) : trimmed;
5149
5819
  if (!isAbsolute2(expanded)) {
5150
5820
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
5151
5821
  }
@@ -5166,6 +5836,35 @@ function resolveFileSyncDirectories(raw, homeDir) {
5166
5836
  }
5167
5837
  return directories;
5168
5838
  }
5839
+ var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
5840
+ var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
5841
+ var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
5842
+ function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
5843
+ const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
5844
+ let raw;
5845
+ let source;
5846
+ if (options.opencodeStartTimeout !== void 0) {
5847
+ raw = options.opencodeStartTimeout;
5848
+ source = "--opencode-start-timeout";
5849
+ } else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
5850
+ raw = env[OPENCODE_START_TIMEOUT_ENV];
5851
+ source = OPENCODE_START_TIMEOUT_ENV;
5852
+ } else {
5853
+ return { timeoutMs: defaultMs, warnings: [] };
5854
+ }
5855
+ const trimmed = raw.trim();
5856
+ const seconds = Number(trimmed);
5857
+ const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
5858
+ if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
5859
+ return {
5860
+ timeoutMs: defaultMs,
5861
+ warnings: [
5862
+ `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`
5863
+ ]
5864
+ };
5865
+ }
5866
+ return { timeoutMs: seconds * 1e3, warnings: [] };
5867
+ }
5169
5868
  function meetsThreshold(state, level) {
5170
5869
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
5171
5870
  }
@@ -5187,6 +5886,10 @@ function log2(state, message, level = "info") {
5187
5886
  function logActivity(state, entry) {
5188
5887
  const level = entry.level ?? (entry.type === "error" ? "error" : "info");
5189
5888
  if (!meetsThreshold(state, level)) return;
5889
+ forwardRunnerActivity(
5890
+ { level, message: entry.message, error: entry.error },
5891
+ { agentId: state.agentId, authHeader: state.authHeader }
5892
+ );
5190
5893
  const fullEntry = {
5191
5894
  ...entry,
5192
5895
  level,
@@ -5424,6 +6127,94 @@ function scheduleSessionCleanup(state, driver, options) {
5424
6127
  );
5425
6128
  state.sessionCleanupTimers.push(interval, firstSweep);
5426
6129
  }
6130
+ function scheduleClaudeUsageReporting(state, options) {
6131
+ const { mode, warnings } = resolveClaudeUsageReportingMode(
6132
+ options.claudeUsageReporting,
6133
+ process.env
6134
+ );
6135
+ for (const warning2 of warnings) {
6136
+ logActivity(state, {
6137
+ type: "info",
6138
+ level: "warn",
6139
+ message: `Claude usage reporting: ${warning2}`
6140
+ });
6141
+ }
6142
+ if (mode === "off") {
6143
+ logActivity(state, {
6144
+ type: "info",
6145
+ level: "debug",
6146
+ message: "Claude usage reporting is off (--claude-usage-reporting off)"
6147
+ });
6148
+ return;
6149
+ }
6150
+ let consecutiveFailures = 0;
6151
+ const scheduleNextTick = () => {
6152
+ state.claudeUsageTimer = setTimeout(() => void tick(false), nextReportDelayMs());
6153
+ };
6154
+ const tick = async (isFirst) => {
6155
+ try {
6156
+ const usage = await getClaudeUsage();
6157
+ const result = await reportClaudeUsage(state.agentId, state.authHeader, usage);
6158
+ if (result.ok) {
6159
+ if (consecutiveFailures > 0) {
6160
+ logActivity(state, {
6161
+ type: "info",
6162
+ level: "info",
6163
+ message: "Claude usage reporting recovered"
6164
+ });
6165
+ }
6166
+ consecutiveFailures = 0;
6167
+ logActivity(state, {
6168
+ type: "info",
6169
+ level: "debug",
6170
+ message: "Reported Claude usage to Evident"
6171
+ });
6172
+ } else {
6173
+ consecutiveFailures++;
6174
+ logActivity(state, {
6175
+ type: "info",
6176
+ level: consecutiveFailures === 1 ? "warn" : "debug",
6177
+ message: `Failed to report Claude usage: ${result.error}`
6178
+ });
6179
+ }
6180
+ scheduleNextTick();
6181
+ } catch (error2) {
6182
+ if (error2 instanceof ClaudeUsageError && isLocalCredentialProblem(error2)) {
6183
+ if (mode === "on") {
6184
+ logActivity(state, {
6185
+ type: "info",
6186
+ level: "warn",
6187
+ 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"
6188
+ });
6189
+ scheduleNextTick();
6190
+ } else if (isFirst) {
6191
+ logActivity(state, {
6192
+ type: "info",
6193
+ level: "debug",
6194
+ message: `Claude usage reporting: ${error2.message}`
6195
+ });
6196
+ } else {
6197
+ logActivity(state, {
6198
+ type: "info",
6199
+ level: "debug",
6200
+ message: `Claude usage reporting: ${error2.message}`
6201
+ });
6202
+ scheduleNextTick();
6203
+ }
6204
+ } else {
6205
+ consecutiveFailures++;
6206
+ const message = error2 instanceof Error ? error2.message : String(error2);
6207
+ logActivity(state, {
6208
+ type: "info",
6209
+ level: consecutiveFailures === 1 ? "warn" : "debug",
6210
+ message: `Claude usage reporting failed: ${message}`
6211
+ });
6212
+ scheduleNextTick();
6213
+ }
6214
+ }
6215
+ };
6216
+ state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
6217
+ }
5427
6218
  async function notifyOffline(state) {
5428
6219
  if (!state.agentId || !state.authHeader) return;
5429
6220
  if (!state.connected) {
@@ -5459,6 +6250,10 @@ async function cleanup(state, opts = {}) {
5459
6250
  clearTimeout(timer);
5460
6251
  }
5461
6252
  state.sessionCleanupTimers = [];
6253
+ if (state.claudeUsageTimer) {
6254
+ clearTimeout(state.claudeUsageTimer);
6255
+ state.claudeUsageTimer = null;
6256
+ }
5462
6257
  if (opts.graceful && state.channelDriver) {
5463
6258
  state.channelDriver.stop();
5464
6259
  log2(state, "Draining in-flight channel work before shutdown...");
@@ -5506,7 +6301,7 @@ async function run(options) {
5506
6301
  let fileSyncDirectories;
5507
6302
  try {
5508
6303
  logLevel = resolveLogLevel(options);
5509
- fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
6304
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
5510
6305
  } catch (error2) {
5511
6306
  const message = error2 instanceof Error ? error2.message : String(error2);
5512
6307
  if (options.json) {
@@ -5539,8 +6334,10 @@ async function run(options) {
5539
6334
  messageCount: 0,
5540
6335
  lastProxiedActivityAt: null,
5541
6336
  sessionCleanupTimers: [],
6337
+ claudeUsageTimer: null,
5542
6338
  authHeader: ""
5543
6339
  };
6340
+ setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
5544
6341
  if (fileSyncDirectories.length > 0) {
5545
6342
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
5546
6343
  } else {
@@ -5714,40 +6511,67 @@ async function run(options) {
5714
6511
  }
5715
6512
  spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
5716
6513
  state.agentName = validation.agent.name;
6514
+ const microvmId = process.env.MICROVM_ID?.trim();
6515
+ if (microvmId) {
6516
+ const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
6517
+ if (reported.ok) {
6518
+ log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
6519
+ } else {
6520
+ const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
6521
+ log2(state, message, "warn");
6522
+ if (state.interactive && !state.json) {
6523
+ logActivity(state, { type: "info", level: "warn", message });
6524
+ }
6525
+ }
6526
+ } else {
6527
+ log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
6528
+ }
6529
+ const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
6530
+ for (const warning2 of opencodeStartTimeoutWarnings) {
6531
+ logActivity(state, { type: "info", level: "warn", message: warning2 });
6532
+ }
5717
6533
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
5718
6534
  try {
5719
6535
  const oc = await ensureOpenCodeRunning({
5720
6536
  port: state.port,
5721
6537
  interactive: state.interactive,
5722
6538
  agentId: state.agentId,
5723
- log: (message) => log2(state, message)
6539
+ log: (message) => log2(state, message),
6540
+ startTimeoutMs: opencodeStartTimeoutMs
5724
6541
  });
5725
6542
  state.port = oc.port;
5726
6543
  state.opencodeProcess = oc.process;
5727
6544
  state.opencodeVersion = oc.version;
5728
- state.opencodeConnected = oc.process !== null || oc.version !== null;
6545
+ state.opencodeConnected = oc.notReadyReason === null;
5729
6546
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
5730
6547
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
5731
- const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
5732
- if (versionWarning) {
5733
- log2(state, versionWarning, "warn");
5734
- if (state.interactive && !state.json) {
5735
- logActivity(state, { type: "info", level: "warn", message: versionWarning });
6548
+ if (!state.interactive && oc.notReadyReason !== null) {
6549
+ 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}).`;
6550
+ logActivity(state, { type: "info", level: "warn", message });
6551
+ } else {
6552
+ const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
6553
+ if (versionWarning) {
6554
+ log2(state, versionWarning, "warn");
6555
+ if (state.interactive && !state.json) {
6556
+ logActivity(state, { type: "info", level: "warn", message: versionWarning });
6557
+ }
5736
6558
  }
5737
- }
5738
- const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
5739
- if (noProviderWarning) {
5740
- log2(state, noProviderWarning, "warn");
5741
- if (state.interactive && !state.json) {
5742
- logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
5743
- blank();
5744
- console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
5745
- console.log(
5746
- chalk6.dim(
5747
- `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
5748
- )
5749
- );
5750
- blank();
6559
+ const noProviderWarning = buildNoProviderWarning(
6560
+ await hasAnyConfiguredProvider(state.port)
6561
+ );
6562
+ if (noProviderWarning) {
6563
+ log2(state, noProviderWarning, "warn");
6564
+ if (state.interactive && !state.json) {
6565
+ logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
6566
+ blank();
6567
+ console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
6568
+ console.log(
6569
+ chalk6.dim(
6570
+ `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
6571
+ )
6572
+ );
6573
+ blank();
6574
+ }
5751
6575
  }
5752
6576
  }
5753
6577
  } catch (error2) {
@@ -5765,7 +6589,7 @@ async function run(options) {
5765
6589
  // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
5766
6590
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
5767
6591
  fileSyncDirectories,
5768
- homeDir: homedir2(),
6592
+ homeDir: homedir3(),
5769
6593
  log: (entry) => (
5770
6594
  // Thread the driver's real level straight through so `debug`/`warn`
5771
6595
  // survive the sink filter (they no longer collapse to info). `type`
@@ -5792,6 +6616,18 @@ async function run(options) {
5792
6616
  type: "info",
5793
6617
  message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
5794
6618
  });
6619
+ if (options.tunnelReadyFile) {
6620
+ const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
6621
+ if (marker.ok) {
6622
+ log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
6623
+ } else {
6624
+ log2(
6625
+ state,
6626
+ `Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
6627
+ "error"
6628
+ );
6629
+ }
6630
+ }
5795
6631
  emitAgentConnected(state.agentId, {
5796
6632
  port: state.port,
5797
6633
  cli_version: getCliVersion(),
@@ -5882,6 +6718,7 @@ async function run(options) {
5882
6718
  throw error2;
5883
6719
  }
5884
6720
  scheduleSessionCleanup(state, channelDriver, options);
6721
+ scheduleClaudeUsageReporting(state, options);
5885
6722
  if (!interactive || state.json) {
5886
6723
  log2(state, "Driving channel messages...");
5887
6724
  }
@@ -5936,13 +6773,17 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
5936
6773
  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);
5937
6774
  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 }));
5938
6775
  program.command("whoami").description("Show the currently logged in user").action(whoami);
6776
+ program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);
5939
6777
  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(
5940
6778
  "-a, --agent [id]",
5941
6779
  "Deprecated alias for --runner (still supported; --runner wins if both are given)"
5942
6780
  ).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
5943
6781
  "--log-level <level>",
5944
6782
  "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
5945
- ).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(
6783
+ ).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(
6784
+ "--opencode-start-timeout <seconds>",
6785
+ "Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
6786
+ ).option("--json", "Output in JSON format").option(
5946
6787
  "--session-cleanup-max-age <duration>",
5947
6788
  "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
5948
6789
  ).option(
@@ -5951,11 +6792,17 @@ program.command("run").description("Connect to Evident and process messages").op
5951
6792
  ).option(
5952
6793
  "--session-cleanup-interval <duration>",
5953
6794
  "How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
6795
+ ).option(
6796
+ "--claude-usage-reporting <mode>",
6797
+ "Report Claude subscription usage to Evident: auto | on | off (default: auto). Env: EVIDENT_CLAUDE_USAGE_REPORTING"
5954
6798
  ).option(
5955
6799
  "--enable-file-sync-to <dir>",
5956
6800
  "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
5957
6801
  (value, previous) => previous.concat([value]),
5958
6802
  []
6803
+ ).option(
6804
+ "--tunnel-ready-file <path>",
6805
+ "Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
5959
6806
  ).action(
5960
6807
  (options) => {
5961
6808
  run({
@@ -5968,14 +6815,21 @@ program.command("run").description("Connect to Evident and process messages").op
5968
6815
  verbose: options.verbose,
5969
6816
  conversation: options.conversation,
5970
6817
  idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
6818
+ // Raw string — validation/precedence is single-sourced in run.ts's
6819
+ // resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
6820
+ opencodeStartTimeout: options.opencodeStartTimeout,
5971
6821
  json: options.json,
5972
6822
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
5973
6823
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
5974
6824
  sessionCleanupMaxCount: options.sessionCleanupMaxCount,
5975
6825
  sessionCleanupInterval: options.sessionCleanupInterval,
6826
+ // Raw string — the resolver in run.ts single-sources parsing
6827
+ // (resolveClaudeUsageReportingMode).
6828
+ claudeUsageReporting: options.claudeUsageReporting,
5976
6829
  // Raw values — expansion/validation is single-sourced in run.ts's
5977
6830
  // resolveFileSyncDirectories.
5978
- enableFileSyncTo: options.enableFileSyncTo
6831
+ enableFileSyncTo: options.enableFileSyncTo,
6832
+ tunnelReadyFile: options.tunnelReadyFile
5979
6833
  });
5980
6834
  }
5981
6835
  );