@evident-ai/cli 3.1.1-dev.019c4e9 → 3.1.1-dev.098bf94

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;
@@ -1548,6 +1789,42 @@ function messageError(messages, userMessageId) {
1548
1789
  }
1549
1790
  return "The agent run failed.";
1550
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
+ }
1551
1828
  function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1552
1829
  if (!messages || messages.length === 0) return false;
1553
1830
  return messages.some(
@@ -2088,13 +2365,40 @@ function writeTunnelReadyMarker(path, agentId) {
2088
2365
  }
2089
2366
  }
2090
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
+
2091
2395
  // src/lib/channels/driver.ts
2092
- import { homedir } from "os";
2396
+ import { homedir as homedir2 } from "os";
2093
2397
 
2094
2398
  // src/lib/file-push.ts
2095
2399
  import { randomUUID } from "crypto";
2096
2400
  import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
2097
- 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";
2098
2402
  var FILE_MODE = 384;
2099
2403
  var DIRECTORY_MODE = 448;
2100
2404
  async function writePushedFile(request) {
@@ -2127,7 +2431,7 @@ async function writePushedFile(request) {
2127
2431
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
2128
2432
  dirname2(candidate)
2129
2433
  );
2130
- const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
2434
+ const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
2131
2435
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
2132
2436
  if (allowedDirectory === null) {
2133
2437
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -2163,7 +2467,7 @@ function expandAndValidate(requestedPath, homeDir) {
2163
2467
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
2164
2468
  return null;
2165
2469
  }
2166
- 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;
2167
2471
  if (expanded.split(/[/\\]/).includes("..")) {
2168
2472
  return null;
2169
2473
  }
@@ -2236,13 +2540,13 @@ function contains(realDirectory, realTarget) {
2236
2540
  async function createMissingDirectories(existingAncestor, missingSegments) {
2237
2541
  let current = existingAncestor;
2238
2542
  for (const segment of missingSegments) {
2239
- current = join(current, segment);
2543
+ current = join2(current, segment);
2240
2544
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
2241
2545
  await chmod(current, DIRECTORY_MODE);
2242
2546
  }
2243
2547
  }
2244
2548
  async function writeAtomically(realTarget, content) {
2245
- const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2549
+ const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2246
2550
  let handle;
2247
2551
  try {
2248
2552
  handle = await open2(temporaryPath, "wx", FILE_MODE);
@@ -2757,7 +3061,7 @@ var ChannelDriver = class _ChannelDriver {
2757
3061
  this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
2758
3062
  this.now = config2.now ?? (() => Date.now());
2759
3063
  this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
2760
- this.homeDir = config2.homeDir ?? homedir();
3064
+ this.homeDir = config2.homeDir ?? homedir2();
2761
3065
  }
2762
3066
  /** The IPv4-loopback base URL for the local `opencode serve`. */
2763
3067
  get opencodeBase() {
@@ -3142,7 +3446,12 @@ var ChannelDriver = class _ChannelDriver {
3142
3446
  const directory = await this.resolveOpenCodeDirectory();
3143
3447
  const sessionId = await createOpenCodeSession(this.port, directory);
3144
3448
  this.sessions.set(conversationId, sessionId);
3145
- 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
+ });
3146
3455
  });
3147
3456
  return sessionId;
3148
3457
  }
@@ -3598,8 +3907,16 @@ var ChannelDriver = class _ChannelDriver {
3598
3907
  message_id: inFlight.evidentMessageId
3599
3908
  });
3600
3909
  const usage = messageUsage(messages, inFlight.opencodeMessageId);
3910
+ const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
3601
3911
  try {
3602
- 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
+ );
3603
3920
  } catch (err) {
3604
3921
  if (err instanceof ChannelAuthError) throw err;
3605
3922
  if (err instanceof ChannelTerminalError) {
@@ -3980,6 +4297,7 @@ var ChannelDriver = class _ChannelDriver {
3980
4297
  if (state === "failed") {
3981
4298
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
3982
4299
  const usage = messageUsage(messages, ocId ?? "");
4300
+ const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
3983
4301
  this.log({
3984
4302
  level: "error",
3985
4303
  message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
@@ -3987,7 +4305,7 @@ var ChannelDriver = class _ChannelDriver {
3987
4305
  message_id: row.id
3988
4306
  });
3989
4307
  try {
3990
- await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
4308
+ await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
3991
4309
  } catch (err) {
3992
4310
  if (err instanceof ChannelAuthError) throw err;
3993
4311
  if (err instanceof ChannelTerminalError) {
@@ -4965,7 +5283,7 @@ var ChannelDriver = class _ChannelDriver {
4965
5283
  * exists but is wedged, so the next attempt must get a fresh one
4966
5284
  * instead of reusing it — see WI-1's server-side null-clearing PATCH).
4967
5285
  */
4968
- async markFailed(conversationId, messageId, sessionId, error2, usage) {
5286
+ async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
4969
5287
  const body = { status: "failed" };
4970
5288
  if (sessionId === null) {
4971
5289
  body.opencode_session_id = null;
@@ -4974,6 +5292,12 @@ var ChannelDriver = class _ChannelDriver {
4974
5292
  }
4975
5293
  if (error2 !== void 0) body.error = error2;
4976
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
+ }
4977
5301
  await this.callWithRetry(
4978
5302
  "marking message as failed",
4979
5303
  () => this.fetchImpl(
@@ -4986,6 +5310,29 @@ var ChannelDriver = class _ChannelDriver {
4986
5310
  )
4987
5311
  );
4988
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
+ }
4989
5336
  /**
4990
5337
  * Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
4991
5338
  * (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
@@ -5138,10 +5485,16 @@ var ChannelDriver = class _ChannelDriver {
5138
5485
  import chalk5 from "chalk";
5139
5486
  import ora2 from "ora";
5140
5487
  import { select as select2 } from "@inquirer/prompts";
5488
+ var INTERACTIVE_START_TIMEOUT_MS = 3e4;
5141
5489
  async function ensureOpenCodeRunning(ctx) {
5142
5490
  const healthCheck = await checkOpenCodeHealth(ctx.port);
5143
5491
  if (healthCheck.healthy) {
5144
- 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
+ };
5145
5498
  }
5146
5499
  const runningInstances = await findHealthyOpenCodeInstances();
5147
5500
  if (runningInstances.length > 0) {
@@ -5182,14 +5535,22 @@ async function ensureOpenCodeRunning(ctx) {
5182
5535
  if (!ctx.interactive) {
5183
5536
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
5184
5537
  const proc = await startOpenCode(ctx.port);
5185
- const health = await waitForOpenCodeHealth(ctx.port, 3e4);
5538
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
5186
5539
  if (!health.healthy) {
5187
- throw new Error(
5188
- `OpenCode failed to start on port ${ctx.port}. Install with: npm install -g opencode-ai`
5189
- );
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
+ };
5190
5546
  }
5191
5547
  ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
5192
- 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
+ };
5193
5554
  }
5194
5555
  let port = ctx.port;
5195
5556
  if (isPortInUse(port)) {
@@ -5242,15 +5603,15 @@ Port ${port} is already in use.`));
5242
5603
  if (action === "start") {
5243
5604
  const spinner = ora2("Starting OpenCode...").start();
5244
5605
  const proc = await startOpenCode(port);
5245
- const health = await waitForOpenCodeHealth(port, 3e4);
5606
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
5246
5607
  if (!health.healthy) {
5247
5608
  spinner.fail("Failed to start OpenCode");
5248
5609
  throw new Error("OpenCode failed to start");
5249
5610
  }
5250
5611
  spinner.stop();
5251
- return { port, process: proc, version: health.version ?? null };
5612
+ return { port, process: proc, version: health.version ?? null, notReadyReason: null };
5252
5613
  }
5253
- return { port, process: null, version: null };
5614
+ return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
5254
5615
  }
5255
5616
 
5256
5617
  // src/commands/agent-lookup.ts
@@ -5348,6 +5709,34 @@ async function reportMicrovmId(agentId, authHeader, microvmId) {
5348
5709
  return { ok: false, error: describeBestEffortError(error2) };
5349
5710
  }
5350
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
+ };
5734
+ }
5735
+ return { ok: true };
5736
+ } catch (error2) {
5737
+ return { ok: false, error: describeBestEffortError(error2) };
5738
+ }
5739
+ }
5351
5740
  async function getAgentInfo(agentId, authHeader) {
5352
5741
  const apiUrl = getApiUrlConfig();
5353
5742
  try {
@@ -5426,7 +5815,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
5426
5815
  if (trimmed === "") {
5427
5816
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
5428
5817
  }
5429
- 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;
5430
5819
  if (!isAbsolute2(expanded)) {
5431
5820
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
5432
5821
  }
@@ -5447,6 +5836,35 @@ function resolveFileSyncDirectories(raw, homeDir) {
5447
5836
  }
5448
5837
  return directories;
5449
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
+ }
5450
5868
  function meetsThreshold(state, level) {
5451
5869
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
5452
5870
  }
@@ -5468,6 +5886,10 @@ function log2(state, message, level = "info") {
5468
5886
  function logActivity(state, entry) {
5469
5887
  const level = entry.level ?? (entry.type === "error" ? "error" : "info");
5470
5888
  if (!meetsThreshold(state, level)) return;
5889
+ forwardRunnerActivity(
5890
+ { level, message: entry.message, error: entry.error },
5891
+ { agentId: state.agentId, authHeader: state.authHeader }
5892
+ );
5471
5893
  const fullEntry = {
5472
5894
  ...entry,
5473
5895
  level,
@@ -5705,6 +6127,94 @@ function scheduleSessionCleanup(state, driver, options) {
5705
6127
  );
5706
6128
  state.sessionCleanupTimers.push(interval, firstSweep);
5707
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
+ }
5708
6218
  async function notifyOffline(state) {
5709
6219
  if (!state.agentId || !state.authHeader) return;
5710
6220
  if (!state.connected) {
@@ -5740,6 +6250,10 @@ async function cleanup(state, opts = {}) {
5740
6250
  clearTimeout(timer);
5741
6251
  }
5742
6252
  state.sessionCleanupTimers = [];
6253
+ if (state.claudeUsageTimer) {
6254
+ clearTimeout(state.claudeUsageTimer);
6255
+ state.claudeUsageTimer = null;
6256
+ }
5743
6257
  if (opts.graceful && state.channelDriver) {
5744
6258
  state.channelDriver.stop();
5745
6259
  log2(state, "Draining in-flight channel work before shutdown...");
@@ -5787,7 +6301,7 @@ async function run(options) {
5787
6301
  let fileSyncDirectories;
5788
6302
  try {
5789
6303
  logLevel = resolveLogLevel(options);
5790
- fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
6304
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
5791
6305
  } catch (error2) {
5792
6306
  const message = error2 instanceof Error ? error2.message : String(error2);
5793
6307
  if (options.json) {
@@ -5820,8 +6334,10 @@ async function run(options) {
5820
6334
  messageCount: 0,
5821
6335
  lastProxiedActivityAt: null,
5822
6336
  sessionCleanupTimers: [],
6337
+ claudeUsageTimer: null,
5823
6338
  authHeader: ""
5824
6339
  };
6340
+ setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
5825
6341
  if (fileSyncDirectories.length > 0) {
5826
6342
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
5827
6343
  } else {
@@ -6010,40 +6526,52 @@ async function run(options) {
6010
6526
  } else {
6011
6527
  log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
6012
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
+ }
6013
6533
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
6014
6534
  try {
6015
6535
  const oc = await ensureOpenCodeRunning({
6016
6536
  port: state.port,
6017
6537
  interactive: state.interactive,
6018
6538
  agentId: state.agentId,
6019
- log: (message) => log2(state, message)
6539
+ log: (message) => log2(state, message),
6540
+ startTimeoutMs: opencodeStartTimeoutMs
6020
6541
  });
6021
6542
  state.port = oc.port;
6022
6543
  state.opencodeProcess = oc.process;
6023
6544
  state.opencodeVersion = oc.version;
6024
- state.opencodeConnected = oc.process !== null || oc.version !== null;
6545
+ state.opencodeConnected = oc.notReadyReason === null;
6025
6546
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
6026
6547
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
6027
- const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
6028
- if (versionWarning) {
6029
- log2(state, versionWarning, "warn");
6030
- if (state.interactive && !state.json) {
6031
- 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
+ }
6032
6558
  }
6033
- }
6034
- const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
6035
- if (noProviderWarning) {
6036
- log2(state, noProviderWarning, "warn");
6037
- if (state.interactive && !state.json) {
6038
- logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
6039
- blank();
6040
- console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
6041
- console.log(
6042
- chalk6.dim(
6043
- `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
6044
- )
6045
- );
6046
- 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
+ }
6047
6575
  }
6048
6576
  }
6049
6577
  } catch (error2) {
@@ -6061,7 +6589,7 @@ async function run(options) {
6061
6589
  // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
6062
6590
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
6063
6591
  fileSyncDirectories,
6064
- homeDir: homedir2(),
6592
+ homeDir: homedir3(),
6065
6593
  log: (entry) => (
6066
6594
  // Thread the driver's real level straight through so `debug`/`warn`
6067
6595
  // survive the sink filter (they no longer collapse to info). `type`
@@ -6190,6 +6718,7 @@ async function run(options) {
6190
6718
  throw error2;
6191
6719
  }
6192
6720
  scheduleSessionCleanup(state, channelDriver, options);
6721
+ scheduleClaudeUsageReporting(state, options);
6193
6722
  if (!interactive || state.json) {
6194
6723
  log2(state, "Driving channel messages...");
6195
6724
  }
@@ -6244,13 +6773,17 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
6244
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);
6245
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 }));
6246
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);
6247
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(
6248
6778
  "-a, --agent [id]",
6249
6779
  "Deprecated alias for --runner (still supported; --runner wins if both are given)"
6250
6780
  ).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
6251
6781
  "--log-level <level>",
6252
6782
  "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
6253
- ).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(
6254
6787
  "--session-cleanup-max-age <duration>",
6255
6788
  "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
6256
6789
  ).option(
@@ -6259,6 +6792,9 @@ program.command("run").description("Connect to Evident and process messages").op
6259
6792
  ).option(
6260
6793
  "--session-cleanup-interval <duration>",
6261
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"
6262
6798
  ).option(
6263
6799
  "--enable-file-sync-to <dir>",
6264
6800
  "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
@@ -6279,11 +6815,17 @@ program.command("run").description("Connect to Evident and process messages").op
6279
6815
  verbose: options.verbose,
6280
6816
  conversation: options.conversation,
6281
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,
6282
6821
  json: options.json,
6283
6822
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
6284
6823
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
6285
6824
  sessionCleanupMaxCount: options.sessionCleanupMaxCount,
6286
6825
  sessionCleanupInterval: options.sessionCleanupInterval,
6826
+ // Raw string — the resolver in run.ts single-sources parsing
6827
+ // (resolveClaudeUsageReportingMode).
6828
+ claudeUsageReporting: options.claudeUsageReporting,
6287
6829
  // Raw values — expansion/validation is single-sourced in run.ts's
6288
6830
  // resolveFileSyncDirectories.
6289
6831
  enableFileSyncTo: options.enableFileSyncTo,