@evident-ai/cli 3.1.0 → 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(
@@ -2076,13 +2353,52 @@ var RunnerConnection = class {
2076
2353
  }
2077
2354
  };
2078
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
+
2079
2395
  // src/lib/channels/driver.ts
2080
- import { homedir } from "os";
2396
+ import { homedir as homedir2 } from "os";
2081
2397
 
2082
2398
  // src/lib/file-push.ts
2083
2399
  import { randomUUID } from "crypto";
2084
2400
  import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
2085
- 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";
2086
2402
  var FILE_MODE = 384;
2087
2403
  var DIRECTORY_MODE = 448;
2088
2404
  async function writePushedFile(request) {
@@ -2115,7 +2431,7 @@ async function writePushedFile(request) {
2115
2431
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
2116
2432
  dirname2(candidate)
2117
2433
  );
2118
- const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
2434
+ const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
2119
2435
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
2120
2436
  if (allowedDirectory === null) {
2121
2437
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -2151,7 +2467,7 @@ function expandAndValidate(requestedPath, homeDir) {
2151
2467
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
2152
2468
  return null;
2153
2469
  }
2154
- 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;
2155
2471
  if (expanded.split(/[/\\]/).includes("..")) {
2156
2472
  return null;
2157
2473
  }
@@ -2224,13 +2540,13 @@ function contains(realDirectory, realTarget) {
2224
2540
  async function createMissingDirectories(existingAncestor, missingSegments) {
2225
2541
  let current = existingAncestor;
2226
2542
  for (const segment of missingSegments) {
2227
- current = join(current, segment);
2543
+ current = join2(current, segment);
2228
2544
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
2229
2545
  await chmod(current, DIRECTORY_MODE);
2230
2546
  }
2231
2547
  }
2232
2548
  async function writeAtomically(realTarget, content) {
2233
- const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2549
+ const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2234
2550
  let handle;
2235
2551
  try {
2236
2552
  handle = await open2(temporaryPath, "wx", FILE_MODE);
@@ -2745,7 +3061,7 @@ var ChannelDriver = class _ChannelDriver {
2745
3061
  this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
2746
3062
  this.now = config2.now ?? (() => Date.now());
2747
3063
  this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
2748
- this.homeDir = config2.homeDir ?? homedir();
3064
+ this.homeDir = config2.homeDir ?? homedir2();
2749
3065
  }
2750
3066
  /** The IPv4-loopback base URL for the local `opencode serve`. */
2751
3067
  get opencodeBase() {
@@ -3130,7 +3446,12 @@ var ChannelDriver = class _ChannelDriver {
3130
3446
  const directory = await this.resolveOpenCodeDirectory();
3131
3447
  const sessionId = await createOpenCodeSession(this.port, directory);
3132
3448
  this.sessions.set(conversationId, sessionId);
3133
- 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
+ });
3134
3455
  });
3135
3456
  return sessionId;
3136
3457
  }
@@ -3586,8 +3907,16 @@ var ChannelDriver = class _ChannelDriver {
3586
3907
  message_id: inFlight.evidentMessageId
3587
3908
  });
3588
3909
  const usage = messageUsage(messages, inFlight.opencodeMessageId);
3910
+ const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
3589
3911
  try {
3590
- 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
+ );
3591
3920
  } catch (err) {
3592
3921
  if (err instanceof ChannelAuthError) throw err;
3593
3922
  if (err instanceof ChannelTerminalError) {
@@ -3968,6 +4297,7 @@ var ChannelDriver = class _ChannelDriver {
3968
4297
  if (state === "failed") {
3969
4298
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
3970
4299
  const usage = messageUsage(messages, ocId ?? "");
4300
+ const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
3971
4301
  this.log({
3972
4302
  level: "error",
3973
4303
  message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
@@ -3975,7 +4305,7 @@ var ChannelDriver = class _ChannelDriver {
3975
4305
  message_id: row.id
3976
4306
  });
3977
4307
  try {
3978
- await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
4308
+ await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
3979
4309
  } catch (err) {
3980
4310
  if (err instanceof ChannelAuthError) throw err;
3981
4311
  if (err instanceof ChannelTerminalError) {
@@ -4953,7 +5283,7 @@ var ChannelDriver = class _ChannelDriver {
4953
5283
  * exists but is wedged, so the next attempt must get a fresh one
4954
5284
  * instead of reusing it — see WI-1's server-side null-clearing PATCH).
4955
5285
  */
4956
- async markFailed(conversationId, messageId, sessionId, error2, usage) {
5286
+ async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
4957
5287
  const body = { status: "failed" };
4958
5288
  if (sessionId === null) {
4959
5289
  body.opencode_session_id = null;
@@ -4962,6 +5292,12 @@ var ChannelDriver = class _ChannelDriver {
4962
5292
  }
4963
5293
  if (error2 !== void 0) body.error = error2;
4964
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
+ }
4965
5301
  await this.callWithRetry(
4966
5302
  "marking message as failed",
4967
5303
  () => this.fetchImpl(
@@ -4974,6 +5310,29 @@ var ChannelDriver = class _ChannelDriver {
4974
5310
  )
4975
5311
  );
4976
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
+ }
4977
5336
  /**
4978
5337
  * Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
4979
5338
  * (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
@@ -5126,10 +5485,16 @@ var ChannelDriver = class _ChannelDriver {
5126
5485
  import chalk5 from "chalk";
5127
5486
  import ora2 from "ora";
5128
5487
  import { select as select2 } from "@inquirer/prompts";
5488
+ var INTERACTIVE_START_TIMEOUT_MS = 3e4;
5129
5489
  async function ensureOpenCodeRunning(ctx) {
5130
5490
  const healthCheck = await checkOpenCodeHealth(ctx.port);
5131
5491
  if (healthCheck.healthy) {
5132
- 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
+ };
5133
5498
  }
5134
5499
  const runningInstances = await findHealthyOpenCodeInstances();
5135
5500
  if (runningInstances.length > 0) {
@@ -5150,7 +5515,7 @@ async function ensureOpenCodeRunning(ctx) {
5150
5515
  console.log(chalk5.yellow("Tip: Run with the correct port:"));
5151
5516
  console.log(
5152
5517
  chalk5.dim(
5153
- ` ${getCliName()} run --agent ${ctx.agentId} --port ${runningInstances[0].port}`
5518
+ ` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
5154
5519
  )
5155
5520
  );
5156
5521
  }
@@ -5170,14 +5535,22 @@ async function ensureOpenCodeRunning(ctx) {
5170
5535
  if (!ctx.interactive) {
5171
5536
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
5172
5537
  const proc = await startOpenCode(ctx.port);
5173
- const health = await waitForOpenCodeHealth(ctx.port, 3e4);
5538
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
5174
5539
  if (!health.healthy) {
5175
- throw new Error(
5176
- `OpenCode failed to start on port ${ctx.port}. Install with: npm install -g opencode-ai`
5177
- );
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
+ };
5178
5546
  }
5179
5547
  ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
5180
- 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
+ };
5181
5554
  }
5182
5555
  let port = ctx.port;
5183
5556
  if (isPortInUse(port)) {
@@ -5230,15 +5603,15 @@ Port ${port} is already in use.`));
5230
5603
  if (action === "start") {
5231
5604
  const spinner = ora2("Starting OpenCode...").start();
5232
5605
  const proc = await startOpenCode(port);
5233
- const health = await waitForOpenCodeHealth(port, 3e4);
5606
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
5234
5607
  if (!health.healthy) {
5235
5608
  spinner.fail("Failed to start OpenCode");
5236
5609
  throw new Error("OpenCode failed to start");
5237
5610
  }
5238
5611
  spinner.stop();
5239
- return { port, process: proc, version: health.version ?? null };
5612
+ return { port, process: proc, version: health.version ?? null, notReadyReason: null };
5240
5613
  }
5241
- return { port, process: null, version: null };
5614
+ return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
5242
5615
  }
5243
5616
 
5244
5617
  // src/commands/agent-lookup.ts
@@ -5280,7 +5653,7 @@ async function resolveAgentIdFromKey(authHeader) {
5280
5653
  return { agent_id: data.agent_id };
5281
5654
  }
5282
5655
  return {
5283
- 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."
5284
5657
  };
5285
5658
  } catch (error2) {
5286
5659
  const message = error2 instanceof Error ? error2.message : "Unknown error";
@@ -5336,6 +5709,34 @@ async function reportMicrovmId(agentId, authHeader, microvmId) {
5336
5709
  return { ok: false, error: describeBestEffortError(error2) };
5337
5710
  }
5338
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
+ }
5339
5740
  async function getAgentInfo(agentId, authHeader) {
5340
5741
  const apiUrl = getApiUrlConfig();
5341
5742
  try {
@@ -5414,7 +5815,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
5414
5815
  if (trimmed === "") {
5415
5816
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
5416
5817
  }
5417
- 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;
5418
5819
  if (!isAbsolute2(expanded)) {
5419
5820
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
5420
5821
  }
@@ -5435,6 +5836,35 @@ function resolveFileSyncDirectories(raw, homeDir) {
5435
5836
  }
5436
5837
  return directories;
5437
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
+ }
5438
5868
  function meetsThreshold(state, level) {
5439
5869
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
5440
5870
  }
@@ -5456,6 +5886,10 @@ function log2(state, message, level = "info") {
5456
5886
  function logActivity(state, entry) {
5457
5887
  const level = entry.level ?? (entry.type === "error" ? "error" : "info");
5458
5888
  if (!meetsThreshold(state, level)) return;
5889
+ forwardRunnerActivity(
5890
+ { level, message: entry.message, error: entry.error },
5891
+ { agentId: state.agentId, authHeader: state.authHeader }
5892
+ );
5459
5893
  const fullEntry = {
5460
5894
  ...entry,
5461
5895
  level,
@@ -5693,6 +6127,94 @@ function scheduleSessionCleanup(state, driver, options) {
5693
6127
  );
5694
6128
  state.sessionCleanupTimers.push(interval, firstSweep);
5695
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
+ }
5696
6218
  async function notifyOffline(state) {
5697
6219
  if (!state.agentId || !state.authHeader) return;
5698
6220
  if (!state.connected) {
@@ -5728,6 +6250,10 @@ async function cleanup(state, opts = {}) {
5728
6250
  clearTimeout(timer);
5729
6251
  }
5730
6252
  state.sessionCleanupTimers = [];
6253
+ if (state.claudeUsageTimer) {
6254
+ clearTimeout(state.claudeUsageTimer);
6255
+ state.claudeUsageTimer = null;
6256
+ }
5731
6257
  if (opts.graceful && state.channelDriver) {
5732
6258
  state.channelDriver.stop();
5733
6259
  log2(state, "Draining in-flight channel work before shutdown...");
@@ -5775,7 +6301,7 @@ async function run(options) {
5775
6301
  let fileSyncDirectories;
5776
6302
  try {
5777
6303
  logLevel = resolveLogLevel(options);
5778
- fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
6304
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
5779
6305
  } catch (error2) {
5780
6306
  const message = error2 instanceof Error ? error2.message : String(error2);
5781
6307
  if (options.json) {
@@ -5808,8 +6334,10 @@ async function run(options) {
5808
6334
  messageCount: 0,
5809
6335
  lastProxiedActivityAt: null,
5810
6336
  sessionCleanupTimers: [],
6337
+ claudeUsageTimer: null,
5811
6338
  authHeader: ""
5812
6339
  };
6340
+ setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
5813
6341
  if (fileSyncDirectories.length > 0) {
5814
6342
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
5815
6343
  } else {
@@ -5998,40 +6526,52 @@ async function run(options) {
5998
6526
  } else {
5999
6527
  log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
6000
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
+ }
6001
6533
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
6002
6534
  try {
6003
6535
  const oc = await ensureOpenCodeRunning({
6004
6536
  port: state.port,
6005
6537
  interactive: state.interactive,
6006
6538
  agentId: state.agentId,
6007
- log: (message) => log2(state, message)
6539
+ log: (message) => log2(state, message),
6540
+ startTimeoutMs: opencodeStartTimeoutMs
6008
6541
  });
6009
6542
  state.port = oc.port;
6010
6543
  state.opencodeProcess = oc.process;
6011
6544
  state.opencodeVersion = oc.version;
6012
- state.opencodeConnected = oc.process !== null || oc.version !== null;
6545
+ state.opencodeConnected = oc.notReadyReason === null;
6013
6546
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
6014
6547
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
6015
- const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
6016
- if (versionWarning) {
6017
- log2(state, versionWarning, "warn");
6018
- if (state.interactive && !state.json) {
6019
- 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
+ }
6020
6558
  }
6021
- }
6022
- const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
6023
- if (noProviderWarning) {
6024
- log2(state, noProviderWarning, "warn");
6025
- if (state.interactive && !state.json) {
6026
- logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
6027
- blank();
6028
- console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
6029
- console.log(
6030
- chalk6.dim(
6031
- `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
6032
- )
6033
- );
6034
- 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
+ }
6035
6575
  }
6036
6576
  }
6037
6577
  } catch (error2) {
@@ -6049,7 +6589,7 @@ async function run(options) {
6049
6589
  // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
6050
6590
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
6051
6591
  fileSyncDirectories,
6052
- homeDir: homedir2(),
6592
+ homeDir: homedir3(),
6053
6593
  log: (entry) => (
6054
6594
  // Thread the driver's real level straight through so `debug`/`warn`
6055
6595
  // survive the sink filter (they no longer collapse to info). `type`
@@ -6076,6 +6616,18 @@ async function run(options) {
6076
6616
  type: "info",
6077
6617
  message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
6078
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
+ }
6079
6631
  emitAgentConnected(state.agentId, {
6080
6632
  port: state.port,
6081
6633
  cli_version: getCliVersion(),
@@ -6166,6 +6718,7 @@ async function run(options) {
6166
6718
  throw error2;
6167
6719
  }
6168
6720
  scheduleSessionCleanup(state, channelDriver, options);
6721
+ scheduleClaudeUsageReporting(state, options);
6169
6722
  if (!interactive || state.json) {
6170
6723
  log2(state, "Driving channel messages...");
6171
6724
  }
@@ -6220,13 +6773,17 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
6220
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);
6221
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 }));
6222
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);
6223
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(
6224
6778
  "-a, --agent [id]",
6225
6779
  "Deprecated alias for --runner (still supported; --runner wins if both are given)"
6226
6780
  ).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
6227
6781
  "--log-level <level>",
6228
6782
  "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
6229
- ).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(
6230
6787
  "--session-cleanup-max-age <duration>",
6231
6788
  "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
6232
6789
  ).option(
@@ -6235,11 +6792,17 @@ program.command("run").description("Connect to Evident and process messages").op
6235
6792
  ).option(
6236
6793
  "--session-cleanup-interval <duration>",
6237
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"
6238
6798
  ).option(
6239
6799
  "--enable-file-sync-to <dir>",
6240
6800
  "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
6241
6801
  (value, previous) => previous.concat([value]),
6242
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)"
6243
6806
  ).action(
6244
6807
  (options) => {
6245
6808
  run({
@@ -6252,14 +6815,21 @@ program.command("run").description("Connect to Evident and process messages").op
6252
6815
  verbose: options.verbose,
6253
6816
  conversation: options.conversation,
6254
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,
6255
6821
  json: options.json,
6256
6822
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
6257
6823
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
6258
6824
  sessionCleanupMaxCount: options.sessionCleanupMaxCount,
6259
6825
  sessionCleanupInterval: options.sessionCleanupInterval,
6826
+ // Raw string — the resolver in run.ts single-sources parsing
6827
+ // (resolveClaudeUsageReportingMode).
6828
+ claudeUsageReporting: options.claudeUsageReporting,
6260
6829
  // Raw values — expansion/validation is single-sourced in run.ts's
6261
6830
  // resolveFileSyncDirectories.
6262
- enableFileSyncTo: options.enableFileSyncTo
6831
+ enableFileSyncTo: options.enableFileSyncTo,
6832
+ tunnelReadyFile: options.tunnelReadyFile
6263
6833
  });
6264
6834
  }
6265
6835
  );