@evident-ai/cli 3.1.1-dev.0d69ecc → 3.1.1-dev.0ff9c93

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;
@@ -2124,13 +2365,40 @@ function writeTunnelReadyMarker(path, agentId) {
2124
2365
  }
2125
2366
  }
2126
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
+
2127
2395
  // src/lib/channels/driver.ts
2128
- import { homedir } from "os";
2396
+ import { homedir as homedir2 } from "os";
2129
2397
 
2130
2398
  // src/lib/file-push.ts
2131
2399
  import { randomUUID } from "crypto";
2132
2400
  import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
2133
- 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";
2134
2402
  var FILE_MODE = 384;
2135
2403
  var DIRECTORY_MODE = 448;
2136
2404
  async function writePushedFile(request) {
@@ -2163,7 +2431,7 @@ async function writePushedFile(request) {
2163
2431
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
2164
2432
  dirname2(candidate)
2165
2433
  );
2166
- const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
2434
+ const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
2167
2435
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
2168
2436
  if (allowedDirectory === null) {
2169
2437
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -2199,7 +2467,7 @@ function expandAndValidate(requestedPath, homeDir) {
2199
2467
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
2200
2468
  return null;
2201
2469
  }
2202
- 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;
2203
2471
  if (expanded.split(/[/\\]/).includes("..")) {
2204
2472
  return null;
2205
2473
  }
@@ -2272,13 +2540,13 @@ function contains(realDirectory, realTarget) {
2272
2540
  async function createMissingDirectories(existingAncestor, missingSegments) {
2273
2541
  let current = existingAncestor;
2274
2542
  for (const segment of missingSegments) {
2275
- current = join(current, segment);
2543
+ current = join2(current, segment);
2276
2544
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
2277
2545
  await chmod(current, DIRECTORY_MODE);
2278
2546
  }
2279
2547
  }
2280
2548
  async function writeAtomically(realTarget, content) {
2281
- const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2549
+ const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2282
2550
  let handle;
2283
2551
  try {
2284
2552
  handle = await open2(temporaryPath, "wx", FILE_MODE);
@@ -2793,7 +3061,7 @@ var ChannelDriver = class _ChannelDriver {
2793
3061
  this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
2794
3062
  this.now = config2.now ?? (() => Date.now());
2795
3063
  this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
2796
- this.homeDir = config2.homeDir ?? homedir();
3064
+ this.homeDir = config2.homeDir ?? homedir2();
2797
3065
  }
2798
3066
  /** The IPv4-loopback base URL for the local `opencode serve`. */
2799
3067
  get opencodeBase() {
@@ -3178,7 +3446,12 @@ var ChannelDriver = class _ChannelDriver {
3178
3446
  const directory = await this.resolveOpenCodeDirectory();
3179
3447
  const sessionId = await createOpenCodeSession(this.port, directory);
3180
3448
  this.sessions.set(conversationId, sessionId);
3181
- 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
+ });
3182
3455
  });
3183
3456
  return sessionId;
3184
3457
  }
@@ -5212,10 +5485,16 @@ var ChannelDriver = class _ChannelDriver {
5212
5485
  import chalk5 from "chalk";
5213
5486
  import ora2 from "ora";
5214
5487
  import { select as select2 } from "@inquirer/prompts";
5488
+ var INTERACTIVE_START_TIMEOUT_MS = 3e4;
5215
5489
  async function ensureOpenCodeRunning(ctx) {
5216
5490
  const healthCheck = await checkOpenCodeHealth(ctx.port);
5217
5491
  if (healthCheck.healthy) {
5218
- 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
+ };
5219
5498
  }
5220
5499
  const runningInstances = await findHealthyOpenCodeInstances();
5221
5500
  if (runningInstances.length > 0) {
@@ -5256,14 +5535,22 @@ async function ensureOpenCodeRunning(ctx) {
5256
5535
  if (!ctx.interactive) {
5257
5536
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
5258
5537
  const proc = await startOpenCode(ctx.port);
5259
- const health = await waitForOpenCodeHealth(ctx.port, 3e4);
5538
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
5260
5539
  if (!health.healthy) {
5261
- throw new Error(
5262
- `OpenCode failed to start on port ${ctx.port}. Install with: npm install -g opencode-ai`
5263
- );
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
+ };
5264
5546
  }
5265
5547
  ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
5266
- 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
+ };
5267
5554
  }
5268
5555
  let port = ctx.port;
5269
5556
  if (isPortInUse(port)) {
@@ -5316,15 +5603,15 @@ Port ${port} is already in use.`));
5316
5603
  if (action === "start") {
5317
5604
  const spinner = ora2("Starting OpenCode...").start();
5318
5605
  const proc = await startOpenCode(port);
5319
- const health = await waitForOpenCodeHealth(port, 3e4);
5606
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
5320
5607
  if (!health.healthy) {
5321
5608
  spinner.fail("Failed to start OpenCode");
5322
5609
  throw new Error("OpenCode failed to start");
5323
5610
  }
5324
5611
  spinner.stop();
5325
- return { port, process: proc, version: health.version ?? null };
5612
+ return { port, process: proc, version: health.version ?? null, notReadyReason: null };
5326
5613
  }
5327
- return { port, process: null, version: null };
5614
+ return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
5328
5615
  }
5329
5616
 
5330
5617
  // src/commands/agent-lookup.ts
@@ -5422,6 +5709,34 @@ async function reportMicrovmId(agentId, authHeader, microvmId) {
5422
5709
  return { ok: false, error: describeBestEffortError(error2) };
5423
5710
  }
5424
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
+ }
5425
5740
  async function getAgentInfo(agentId, authHeader) {
5426
5741
  const apiUrl = getApiUrlConfig();
5427
5742
  try {
@@ -5500,7 +5815,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
5500
5815
  if (trimmed === "") {
5501
5816
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
5502
5817
  }
5503
- 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;
5504
5819
  if (!isAbsolute2(expanded)) {
5505
5820
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
5506
5821
  }
@@ -5521,6 +5836,35 @@ function resolveFileSyncDirectories(raw, homeDir) {
5521
5836
  }
5522
5837
  return directories;
5523
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
+ }
5524
5868
  function meetsThreshold(state, level) {
5525
5869
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
5526
5870
  }
@@ -5542,6 +5886,10 @@ function log2(state, message, level = "info") {
5542
5886
  function logActivity(state, entry) {
5543
5887
  const level = entry.level ?? (entry.type === "error" ? "error" : "info");
5544
5888
  if (!meetsThreshold(state, level)) return;
5889
+ forwardRunnerActivity(
5890
+ { level, message: entry.message, error: entry.error },
5891
+ { agentId: state.agentId, authHeader: state.authHeader }
5892
+ );
5545
5893
  const fullEntry = {
5546
5894
  ...entry,
5547
5895
  level,
@@ -5779,6 +6127,94 @@ function scheduleSessionCleanup(state, driver, options) {
5779
6127
  );
5780
6128
  state.sessionCleanupTimers.push(interval, firstSweep);
5781
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
+ }
5782
6218
  async function notifyOffline(state) {
5783
6219
  if (!state.agentId || !state.authHeader) return;
5784
6220
  if (!state.connected) {
@@ -5814,6 +6250,10 @@ async function cleanup(state, opts = {}) {
5814
6250
  clearTimeout(timer);
5815
6251
  }
5816
6252
  state.sessionCleanupTimers = [];
6253
+ if (state.claudeUsageTimer) {
6254
+ clearTimeout(state.claudeUsageTimer);
6255
+ state.claudeUsageTimer = null;
6256
+ }
5817
6257
  if (opts.graceful && state.channelDriver) {
5818
6258
  state.channelDriver.stop();
5819
6259
  log2(state, "Draining in-flight channel work before shutdown...");
@@ -5861,7 +6301,7 @@ async function run(options) {
5861
6301
  let fileSyncDirectories;
5862
6302
  try {
5863
6303
  logLevel = resolveLogLevel(options);
5864
- fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
6304
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
5865
6305
  } catch (error2) {
5866
6306
  const message = error2 instanceof Error ? error2.message : String(error2);
5867
6307
  if (options.json) {
@@ -5894,8 +6334,10 @@ async function run(options) {
5894
6334
  messageCount: 0,
5895
6335
  lastProxiedActivityAt: null,
5896
6336
  sessionCleanupTimers: [],
6337
+ claudeUsageTimer: null,
5897
6338
  authHeader: ""
5898
6339
  };
6340
+ setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
5899
6341
  if (fileSyncDirectories.length > 0) {
5900
6342
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
5901
6343
  } else {
@@ -6084,40 +6526,52 @@ async function run(options) {
6084
6526
  } else {
6085
6527
  log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
6086
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
+ }
6087
6533
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
6088
6534
  try {
6089
6535
  const oc = await ensureOpenCodeRunning({
6090
6536
  port: state.port,
6091
6537
  interactive: state.interactive,
6092
6538
  agentId: state.agentId,
6093
- log: (message) => log2(state, message)
6539
+ log: (message) => log2(state, message),
6540
+ startTimeoutMs: opencodeStartTimeoutMs
6094
6541
  });
6095
6542
  state.port = oc.port;
6096
6543
  state.opencodeProcess = oc.process;
6097
6544
  state.opencodeVersion = oc.version;
6098
- state.opencodeConnected = oc.process !== null || oc.version !== null;
6545
+ state.opencodeConnected = oc.notReadyReason === null;
6099
6546
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
6100
6547
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
6101
- const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
6102
- if (versionWarning) {
6103
- log2(state, versionWarning, "warn");
6104
- if (state.interactive && !state.json) {
6105
- 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
+ }
6106
6558
  }
6107
- }
6108
- const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
6109
- if (noProviderWarning) {
6110
- log2(state, noProviderWarning, "warn");
6111
- if (state.interactive && !state.json) {
6112
- logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
6113
- blank();
6114
- console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
6115
- console.log(
6116
- chalk6.dim(
6117
- `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
6118
- )
6119
- );
6120
- 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
+ }
6121
6575
  }
6122
6576
  }
6123
6577
  } catch (error2) {
@@ -6135,7 +6589,7 @@ async function run(options) {
6135
6589
  // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
6136
6590
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
6137
6591
  fileSyncDirectories,
6138
- homeDir: homedir2(),
6592
+ homeDir: homedir3(),
6139
6593
  log: (entry) => (
6140
6594
  // Thread the driver's real level straight through so `debug`/`warn`
6141
6595
  // survive the sink filter (they no longer collapse to info). `type`
@@ -6264,6 +6718,7 @@ async function run(options) {
6264
6718
  throw error2;
6265
6719
  }
6266
6720
  scheduleSessionCleanup(state, channelDriver, options);
6721
+ scheduleClaudeUsageReporting(state, options);
6267
6722
  if (!interactive || state.json) {
6268
6723
  log2(state, "Driving channel messages...");
6269
6724
  }
@@ -6318,13 +6773,17 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
6318
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);
6319
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 }));
6320
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);
6321
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(
6322
6778
  "-a, --agent [id]",
6323
6779
  "Deprecated alias for --runner (still supported; --runner wins if both are given)"
6324
6780
  ).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
6325
6781
  "--log-level <level>",
6326
6782
  "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
6327
- ).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(
6328
6787
  "--session-cleanup-max-age <duration>",
6329
6788
  "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
6330
6789
  ).option(
@@ -6333,6 +6792,9 @@ program.command("run").description("Connect to Evident and process messages").op
6333
6792
  ).option(
6334
6793
  "--session-cleanup-interval <duration>",
6335
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"
6336
6798
  ).option(
6337
6799
  "--enable-file-sync-to <dir>",
6338
6800
  "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
@@ -6353,11 +6815,17 @@ program.command("run").description("Connect to Evident and process messages").op
6353
6815
  verbose: options.verbose,
6354
6816
  conversation: options.conversation,
6355
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,
6356
6821
  json: options.json,
6357
6822
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
6358
6823
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
6359
6824
  sessionCleanupMaxCount: options.sessionCleanupMaxCount,
6360
6825
  sessionCleanupInterval: options.sessionCleanupInterval,
6826
+ // Raw string — the resolver in run.ts single-sources parsing
6827
+ // (resolveClaudeUsageReportingMode).
6828
+ claudeUsageReporting: options.claudeUsageReporting,
6361
6829
  // Raw values — expansion/validation is single-sourced in run.ts's
6362
6830
  // resolveFileSyncDirectories.
6363
6831
  enableFileSyncTo: options.enableFileSyncTo,