@evident-ai/cli 3.1.1-dev.1b62144 → 3.1.1-dev.1e66164

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/README.md CHANGED
@@ -98,7 +98,36 @@ Options:
98
98
  healthy when the runner starts it itself (default: `180`). On expiry the runner
99
99
  warns and comes online anyway rather than failing. Env:
100
100
  `EVIDENT_OPENCODE_START_TIMEOUT` (seconds).
101
+ - `--claude-usage-reporting <mode>` — Whether to report the local Claude Code
102
+ subscription's rate-limit usage to Evident, so it shows on the runner page:
103
+ `auto` (default) reports it when a usable Claude Code login is found on this
104
+ machine and stays silent otherwise; `on` forces reporting and warns loudly (and
105
+ keeps retrying) if no usable login is found; `off` disables it entirely — no
106
+ Claude credential is ever read. An unrecognized value falls back to `auto` with
107
+ a warning. Env: `EVIDENT_CLAUDE_USAGE_REPORTING`.
101
108
  - `--json` — Output in JSON format (forces non-interactive mode).
109
+ - `--session-cleanup-max-age <duration>` — Delete OpenCode sessions idle longer
110
+ than this window (format `<number><unit>`, unit one of `s, m, h, d` — e.g.
111
+ `7d`, `24h`). Setting this (or `--session-cleanup-max-count`) is what enables
112
+ cleanup — there is no separate on/off flag. An invalid value is warned about
113
+ and ignored, which can leave cleanup off if it was the only rule set. Env:
114
+ `EVIDENT_SESSION_CLEANUP_MAX_AGE`.
115
+ - `--session-cleanup-max-count <n>` — Keep only the newest N OpenCode sessions
116
+ by last activity, deleting the rest. Also enables cleanup; combines with
117
+ `--session-cleanup-max-age` as OR. A session with a turn actively in progress
118
+ is never deleted, regardless of either rule. Env:
119
+ `EVIDENT_SESSION_CLEANUP_MAX_COUNT`.
120
+ - `--session-cleanup-interval <duration>` — How often the cleanup sweep runs
121
+ (default: `1h`). An invalid value falls back to the default rather than
122
+ disabling cleanup. Env: `EVIDENT_SESSION_CLEANUP_INTERVAL`.
123
+ - `--enable-file-sync-to <dir>` — Let the runner write files Evident has queued
124
+ for it into this directory — it collects them as part of the polling it
125
+ already does, so they land a couple of seconds after you hand them over.
126
+ Repeatable (up to 16); each value must be absolute once a leading `~` is
127
+ expanded, and the filesystem root is rejected. Omit it entirely and the
128
+ runner collects nothing and refuses any queued file, telling you why. Use
129
+ `--enable-file-sync-to ~/.claude` to connect a Claude subscription from the
130
+ web — see the website's Model providers doc.
102
131
 
103
132
  ## Global flags
104
133
 
@@ -122,6 +151,18 @@ targets the **production** Evident platform by default.
122
151
  keychain login from `evident login`).
123
152
  - `EVIDENT_API_URL` — Override the API base URL (equivalent to `--endpoint`).
124
153
  - `EVIDENT_TUNNEL_URL` — Override the tunnel relay URL (equivalent to `--tunnel`).
154
+ - `EVIDENT_CLAUDE_USAGE_REPORTING` — Equivalent to `--claude-usage-reporting`; the
155
+ flag wins if both are set.
156
+ - `EVIDENT_LOG_LEVEL` — Equivalent to `--log-level`; the flag wins if both are
157
+ set, and `-v`/`--verbose` also outranks this env var.
158
+ - `EVIDENT_OPENCODE_START_TIMEOUT` — Equivalent to `--opencode-start-timeout`
159
+ (seconds); the flag wins if both are set.
160
+ - `EVIDENT_SESSION_CLEANUP_MAX_AGE` — Equivalent to `--session-cleanup-max-age`;
161
+ the flag wins if both are set.
162
+ - `EVIDENT_SESSION_CLEANUP_MAX_COUNT` — Equivalent to
163
+ `--session-cleanup-max-count`; the flag wins if both are set.
164
+ - `EVIDENT_SESSION_CLEANUP_INTERVAL` — Equivalent to
165
+ `--session-cleanup-interval`; the flag wins if both are set.
125
166
 
126
167
  Authentication precedence for `run`: `EVIDENT_RUNNER_KEY`/`EVIDENT_AGENT_KEY`
127
168
  (tied; `EVIDENT_RUNNER_KEY` wins if both are set) → `EVIDENT_TOKEN` →
package/dist/index.js CHANGED
@@ -38,11 +38,6 @@ function getApiUrl() {
38
38
  function getTunnelUrl() {
39
39
  return tunnelOverride ?? process.env.EVIDENT_TUNNEL_URL ?? defaults.tunnelUrl;
40
40
  }
41
- var config = new Conf({
42
- projectName: "evident",
43
- projectSuffix: "",
44
- defaults
45
- });
46
41
  var credentials = new Conf({
47
42
  projectName: "evident",
48
43
  projectSuffix: "",
@@ -417,8 +412,10 @@ async function deviceFlowLogin(options) {
417
412
  }
418
413
  async function tokenLogin() {
419
414
  console.log("Token login mode.");
420
- console.log("Run `evident login` on a machine with a browser to get a token.");
421
- console.log("Manage or revoke existing tokens under Settings \u2192 CLI tokens.");
415
+ console.log("Create a token under Settings \u2192 CLI tokens in the dashboard, then paste it below.");
416
+ console.log(
417
+ "(Alternatively, run `evident login` on a machine with a browser, or set EVIDENT_TOKEN for CI.)"
418
+ );
422
419
  blank();
423
420
  process.stdout.write("Paste token: ");
424
421
  const token = await new Promise((resolve3) => {
@@ -442,13 +439,22 @@ async function tokenLogin() {
442
439
  printError("No token provided.");
443
440
  process.exit(1);
444
441
  }
442
+ await validateAndStoreToken(token);
443
+ }
444
+ async function validateAndStoreToken(token) {
445
445
  const spinner = ora("Validating token...").start();
446
446
  try {
447
- const result = await api.post("/auth/token/validate", { token });
447
+ const result = await api.get("/me", {
448
+ headers: { Authorization: `Bearer ${token}` }
449
+ });
450
+ if (!result.user) {
451
+ throw new Error(
452
+ "This token is not a user login (e.g. a runner key). Paste a CLI token instead."
453
+ );
454
+ }
448
455
  await storeToken({
449
456
  token,
450
- user: result.user,
451
- expiresAt: result.expires_at
457
+ user: { email: result.user.email }
452
458
  });
453
459
  spinner.stop();
454
460
  printSuccess(`Logged in as ${chalk2.bold(result.user.email)}`);
@@ -508,7 +514,9 @@ async function whoami() {
508
514
  blank();
509
515
  console.log(keyValue("Endpoint", apiUrl));
510
516
  console.log(keyValue("User", chalk3.bold(credentials2.user.email)));
511
- console.log(keyValue("User ID", credentials2.user.id));
517
+ if (credentials2.user.id) {
518
+ console.log(keyValue("User ID", credentials2.user.id));
519
+ }
512
520
  if (credentials2.expiresAt) {
513
521
  const expiresAt = new Date(credentials2.expiresAt);
514
522
  const now = /* @__PURE__ */ new Date();
@@ -524,9 +532,124 @@ async function whoami() {
524
532
  blank();
525
533
  }
526
534
 
535
+ // src/lib/claude-usage.ts
536
+ import { execFileSync } from "child_process";
537
+ import { readFileSync } from "fs";
538
+ import { homedir } from "os";
539
+ import { join } from "path";
540
+ var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
541
+ var KEYCHAIN_SERVICE = "Claude Code-credentials";
542
+ function parseClaudeCliCredentials(raw) {
543
+ let parsed;
544
+ try {
545
+ parsed = JSON.parse(raw);
546
+ } catch {
547
+ return null;
548
+ }
549
+ const data = parsed.claudeAiOauth ?? parsed;
550
+ const creds = data;
551
+ if (typeof creds.accessToken !== "string" || typeof creds.expiresAt !== "number") {
552
+ return null;
553
+ }
554
+ return { accessToken: creds.accessToken, expiresAt: creds.expiresAt };
555
+ }
556
+ function readClaudeCliCredentials() {
557
+ if (process.platform === "darwin") {
558
+ try {
559
+ const raw = execFileSync(
560
+ "/usr/bin/security",
561
+ ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-w"],
562
+ { encoding: "utf-8", timeout: 2e3, stdio: ["pipe", "pipe", "ignore"] }
563
+ );
564
+ return parseClaudeCliCredentials(raw);
565
+ } catch {
566
+ return null;
567
+ }
568
+ }
569
+ try {
570
+ const raw = readFileSync(join(homedir(), ".claude", ".credentials.json"), "utf-8");
571
+ return parseClaudeCliCredentials(raw);
572
+ } catch {
573
+ return null;
574
+ }
575
+ }
576
+ var ClaudeUsageError = class extends Error {
577
+ constructor(message, reason) {
578
+ super(message);
579
+ this.reason = reason;
580
+ }
581
+ };
582
+ function isLocalCredentialProblem(err) {
583
+ return err instanceof ClaudeUsageError && (err.reason === "no_credentials" || err.reason === "credentials_expired");
584
+ }
585
+ function toWindow(value) {
586
+ if (!value || typeof value !== "object") {
587
+ return null;
588
+ }
589
+ const window = value;
590
+ if (typeof window.utilization !== "number" || typeof window.resets_at !== "string") {
591
+ return null;
592
+ }
593
+ return { utilization: window.utilization, resetsAt: window.resets_at };
594
+ }
595
+ async function getClaudeUsage() {
596
+ const credentials2 = readClaudeCliCredentials();
597
+ if (!credentials2) {
598
+ throw new ClaudeUsageError(
599
+ "No local Claude Code login found. Run `claude` once to sign in with your Claude subscription.",
600
+ "no_credentials"
601
+ );
602
+ }
603
+ if (credentials2.expiresAt < Date.now()) {
604
+ throw new ClaudeUsageError(
605
+ "Claude Code credentials have expired. Run `claude` to refresh them.",
606
+ "credentials_expired"
607
+ );
608
+ }
609
+ const res = await fetch(CLAUDE_USAGE_URL, {
610
+ headers: {
611
+ Authorization: `Bearer ${credentials2.accessToken}`,
612
+ "Content-Type": "application/json",
613
+ "anthropic-version": "2023-06-01"
614
+ }
615
+ });
616
+ if (!res.ok) {
617
+ throw new ClaudeUsageError(`Claude usage request failed: HTTP ${res.status}`, "request_failed");
618
+ }
619
+ const body = await res.json();
620
+ return {
621
+ fiveHour: toWindow(body.five_hour),
622
+ sevenDay: toWindow(body.seven_day)
623
+ };
624
+ }
625
+
626
+ // src/commands/claude-usage.ts
627
+ function formatWindow(label, window) {
628
+ if (!window) {
629
+ return keyValue(label, "not available for this plan");
630
+ }
631
+ const resetsAt = new Date(window.resetsAt);
632
+ return keyValue(label, `${window.utilization}% used, resets ${resetsAt.toLocaleString()}`);
633
+ }
634
+ async function claudeUsage() {
635
+ try {
636
+ const usage = await getClaudeUsage();
637
+ blank();
638
+ console.log(formatWindow("5-hour session", usage.fiveHour));
639
+ console.log(formatWindow("7-day", usage.sevenDay));
640
+ blank();
641
+ } catch (err) {
642
+ if (err instanceof ClaudeUsageError) {
643
+ printError(err.message);
644
+ process.exit(1);
645
+ }
646
+ throw err;
647
+ }
648
+ }
649
+
527
650
  // src/commands/run.ts
528
- import { homedir as homedir2 } from "os";
529
- import { isAbsolute as isAbsolute2, join as join2, parse, resolve as resolvePath } from "path";
651
+ import { homedir as homedir3 } from "os";
652
+ import { isAbsolute as isAbsolute2, join as join3, parse, resolve as resolvePath } from "path";
530
653
  import chalk6 from "chalk";
531
654
 
532
655
  // ../../packages/types/src/telemetry/index.ts
@@ -2237,13 +2360,40 @@ function writeTunnelReadyMarker(path, agentId) {
2237
2360
  }
2238
2361
  }
2239
2362
 
2363
+ // src/lib/claude-usage-reporting.ts
2364
+ var VALID_MODES = ["auto", "on", "off"];
2365
+ function resolveClaudeUsageReportingMode(flagValue, env) {
2366
+ const raw = flagValue ?? env.EVIDENT_CLAUDE_USAGE_REPORTING;
2367
+ if (raw === void 0 || raw === "") {
2368
+ return { mode: "auto", warnings: [] };
2369
+ }
2370
+ const normalized = raw.trim().toLowerCase();
2371
+ if (VALID_MODES.includes(normalized)) {
2372
+ return { mode: normalized, warnings: [] };
2373
+ }
2374
+ const source = flagValue !== void 0 ? "--claude-usage-reporting" : "EVIDENT_CLAUDE_USAGE_REPORTING";
2375
+ return {
2376
+ mode: "auto",
2377
+ warnings: [
2378
+ `Ignoring invalid ${source} "${raw}": expected one of ${VALID_MODES.join(", ")}; using auto`
2379
+ ]
2380
+ };
2381
+ }
2382
+ var BASE_REPORT_DELAY_MS = 10 * 6e4;
2383
+ var REPORT_DELAY_JITTER_FRACTION = 0.2;
2384
+ function nextReportDelayMs(random = Math.random) {
2385
+ const jitterRangeMs = BASE_REPORT_DELAY_MS * REPORT_DELAY_JITTER_FRACTION;
2386
+ return BASE_REPORT_DELAY_MS - jitterRangeMs + random() * (2 * jitterRangeMs);
2387
+ }
2388
+ var FIRST_REPORT_DELAY_MS = 5e3 + Math.random() * 1e4;
2389
+
2240
2390
  // src/lib/channels/driver.ts
2241
- import { homedir } from "os";
2391
+ import { homedir as homedir2 } from "os";
2242
2392
 
2243
2393
  // src/lib/file-push.ts
2244
2394
  import { randomUUID } from "crypto";
2245
2395
  import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
2246
- import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
2396
+ import { basename, dirname as dirname2, isAbsolute, join as join2, relative, resolve as resolve2, sep } from "path";
2247
2397
  var FILE_MODE = 384;
2248
2398
  var DIRECTORY_MODE = 448;
2249
2399
  async function writePushedFile(request) {
@@ -2276,7 +2426,7 @@ async function writePushedFile(request) {
2276
2426
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
2277
2427
  dirname2(candidate)
2278
2428
  );
2279
- const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
2429
+ const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
2280
2430
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
2281
2431
  if (allowedDirectory === null) {
2282
2432
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -2312,7 +2462,7 @@ function expandAndValidate(requestedPath, homeDir) {
2312
2462
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
2313
2463
  return null;
2314
2464
  }
2315
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join(homeDir, requestedPath.slice(2)) : requestedPath;
2465
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join2(homeDir, requestedPath.slice(2)) : requestedPath;
2316
2466
  if (expanded.split(/[/\\]/).includes("..")) {
2317
2467
  return null;
2318
2468
  }
@@ -2385,13 +2535,13 @@ function contains(realDirectory, realTarget) {
2385
2535
  async function createMissingDirectories(existingAncestor, missingSegments) {
2386
2536
  let current = existingAncestor;
2387
2537
  for (const segment of missingSegments) {
2388
- current = join(current, segment);
2538
+ current = join2(current, segment);
2389
2539
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
2390
2540
  await chmod(current, DIRECTORY_MODE);
2391
2541
  }
2392
2542
  }
2393
2543
  async function writeAtomically(realTarget, content) {
2394
- const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2544
+ const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2395
2545
  let handle;
2396
2546
  try {
2397
2547
  handle = await open2(temporaryPath, "wx", FILE_MODE);
@@ -2890,23 +3040,23 @@ var ChannelDriver = class _ChannelDriver {
2890
3040
  * and stops opencode.
2891
3041
  */
2892
3042
  stopped = false;
2893
- constructor(config2) {
2894
- this.agentId = config2.agentId;
2895
- this.port = config2.port;
2896
- this.apiUrl = config2.apiUrl.replace(/\/$/, "");
2897
- this.getAuthHeader = config2.getAuthHeader;
2898
- this.conversationFilter = config2.conversationFilter ?? null;
2899
- this.retry = { ...DEFAULT_RETRY_POLICY, ...config2.retry };
2900
- this.log = config2.log ?? (() => {
3043
+ constructor(config) {
3044
+ this.agentId = config.agentId;
3045
+ this.port = config.port;
3046
+ this.apiUrl = config.apiUrl.replace(/\/$/, "");
3047
+ this.getAuthHeader = config.getAuthHeader;
3048
+ this.conversationFilter = config.conversationFilter ?? null;
3049
+ this.retry = { ...DEFAULT_RETRY_POLICY, ...config.retry };
3050
+ this.log = config.log ?? (() => {
2901
3051
  });
2902
- this.fetchImpl = config2.fetchImpl ?? fetch;
2903
- this.sleep = config2.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
2904
- this.pausedPollIntervalMs = config2.pausedPollIntervalMs ?? DEFAULT_PAUSED_POLL_INTERVAL_MS;
2905
- this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
2906
- this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
2907
- this.now = config2.now ?? (() => Date.now());
2908
- this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
2909
- this.homeDir = config2.homeDir ?? homedir();
3052
+ this.fetchImpl = config.fetchImpl ?? fetch;
3053
+ this.sleep = config.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
3054
+ this.pausedPollIntervalMs = config.pausedPollIntervalMs ?? DEFAULT_PAUSED_POLL_INTERVAL_MS;
3055
+ this.pausedMaxWaitMs = config.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
3056
+ this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
3057
+ this.now = config.now ?? (() => Date.now());
3058
+ this.fileSyncDirectories = config.fileSyncDirectories ?? [];
3059
+ this.homeDir = config.homeDir ?? homedir2();
2910
3060
  }
2911
3061
  /** The IPv4-loopback base URL for the local `opencode serve`. */
2912
3062
  get opencodeBase() {
@@ -3291,7 +3441,12 @@ var ChannelDriver = class _ChannelDriver {
3291
3441
  const directory = await this.resolveOpenCodeDirectory();
3292
3442
  const sessionId = await createOpenCodeSession(this.port, directory);
3293
3443
  this.sessions.set(conversationId, sessionId);
3294
- await this.persistSession(conversationId, sessionId).catch(() => {
3444
+ await this.persistSession(conversationId, sessionId).catch((err) => {
3445
+ this.log({
3446
+ level: "warn",
3447
+ 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)}`,
3448
+ conversation_id: conversationId
3449
+ });
3295
3450
  });
3296
3451
  return sessionId;
3297
3452
  }
@@ -5549,6 +5704,34 @@ async function reportMicrovmId(agentId, authHeader, microvmId) {
5549
5704
  return { ok: false, error: describeBestEffortError(error2) };
5550
5705
  }
5551
5706
  }
5707
+ function toReportedWindow(window) {
5708
+ if (!window) return null;
5709
+ return { utilization: window.utilization, resets_at: window.resetsAt };
5710
+ }
5711
+ async function reportClaudeUsage(agentId, authHeader, snapshot) {
5712
+ try {
5713
+ const apiUrl = getApiUrlConfig();
5714
+ const response = await fetch(`${apiUrl}/runners/${agentId}/claude-usage`, {
5715
+ method: "POST",
5716
+ headers: { Authorization: authHeader, "Content-Type": "application/json" },
5717
+ body: JSON.stringify({
5718
+ five_hour: toReportedWindow(snapshot.fiveHour),
5719
+ seven_day: toReportedWindow(snapshot.sevenDay)
5720
+ }),
5721
+ signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
5722
+ });
5723
+ if (!response.ok) {
5724
+ const serverMessage = await readErrorMessage(response);
5725
+ return {
5726
+ ok: false,
5727
+ error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
5728
+ };
5729
+ }
5730
+ return { ok: true };
5731
+ } catch (error2) {
5732
+ return { ok: false, error: describeBestEffortError(error2) };
5733
+ }
5734
+ }
5552
5735
  async function getAgentInfo(agentId, authHeader) {
5553
5736
  const apiUrl = getApiUrlConfig();
5554
5737
  try {
@@ -5627,7 +5810,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
5627
5810
  if (trimmed === "") {
5628
5811
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
5629
5812
  }
5630
- const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join2(homeDir, trimmed.slice(2)) : trimmed;
5813
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join3(homeDir, trimmed.slice(2)) : trimmed;
5631
5814
  if (!isAbsolute2(expanded)) {
5632
5815
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
5633
5816
  }
@@ -5865,8 +6048,8 @@ async function driveChannels(state, driver) {
5865
6048
  }
5866
6049
  }
5867
6050
  var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
5868
- async function runSweep(state, driver, config2) {
5869
- const mode = `age=${config2.maxAgeMs ?? "\u2014"} count=${config2.maxCount ?? "\u2014"}`;
6051
+ async function runSweep(state, driver, config) {
6052
+ const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
5870
6053
  try {
5871
6054
  const sessions = await listSessions(state.port);
5872
6055
  if (sessions === null) {
@@ -5879,8 +6062,8 @@ async function runSweep(state, driver, config2) {
5879
6062
  const toDelete = selectSessionsToDelete(
5880
6063
  sessions.map((s) => ({ id: s.id, lastActivityMs: sessionLastActivityMs(s) })),
5881
6064
  {
5882
- maxAgeMs: config2.maxAgeMs,
5883
- maxCount: config2.maxCount,
6065
+ maxAgeMs: config.maxAgeMs,
6066
+ maxCount: config.maxCount,
5884
6067
  nowMs: Date.now(),
5885
6068
  protectedIds: driver.protectedSessionIds()
5886
6069
  }
@@ -5916,7 +6099,7 @@ async function runSweep(state, driver, config2) {
5916
6099
  }
5917
6100
  }
5918
6101
  function scheduleSessionCleanup(state, driver, options) {
5919
- const config2 = resolveSessionCleanupConfig(
6102
+ const config = resolveSessionCleanupConfig(
5920
6103
  {
5921
6104
  maxAge: options.sessionCleanupMaxAge,
5922
6105
  maxCount: options.sessionCleanupMaxCount,
@@ -5924,21 +6107,109 @@ function scheduleSessionCleanup(state, driver, options) {
5924
6107
  },
5925
6108
  process.env
5926
6109
  );
5927
- for (const warning2 of config2.warnings) {
6110
+ for (const warning2 of config.warnings) {
5928
6111
  logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
5929
6112
  }
5930
- if (!config2.enabled) return;
6113
+ if (!config.enabled) return;
5931
6114
  logActivity(state, {
5932
6115
  type: "info",
5933
- message: `Session cleanup enabled (age=${config2.maxAgeMs ?? "\u2014"}, count=${config2.maxCount ?? "\u2014"}, interval=${config2.intervalMs}ms)`
6116
+ message: `Session cleanup enabled (age=${config.maxAgeMs ?? "\u2014"}, count=${config.maxCount ?? "\u2014"}, interval=${config.intervalMs}ms)`
5934
6117
  });
5935
- const interval = setInterval(() => void runSweep(state, driver, config2), config2.intervalMs);
6118
+ const interval = setInterval(() => void runSweep(state, driver, config), config.intervalMs);
5936
6119
  const firstSweep = setTimeout(
5937
- () => void runSweep(state, driver, config2),
6120
+ () => void runSweep(state, driver, config),
5938
6121
  SESSION_CLEANUP_FIRST_SWEEP_MS
5939
6122
  );
5940
6123
  state.sessionCleanupTimers.push(interval, firstSweep);
5941
6124
  }
6125
+ function scheduleClaudeUsageReporting(state, options) {
6126
+ const { mode, warnings } = resolveClaudeUsageReportingMode(
6127
+ options.claudeUsageReporting,
6128
+ process.env
6129
+ );
6130
+ for (const warning2 of warnings) {
6131
+ logActivity(state, {
6132
+ type: "info",
6133
+ level: "warn",
6134
+ message: `Claude usage reporting: ${warning2}`
6135
+ });
6136
+ }
6137
+ if (mode === "off") {
6138
+ logActivity(state, {
6139
+ type: "info",
6140
+ level: "debug",
6141
+ message: "Claude usage reporting is off (--claude-usage-reporting off)"
6142
+ });
6143
+ return;
6144
+ }
6145
+ let consecutiveFailures = 0;
6146
+ const scheduleNextTick = () => {
6147
+ state.claudeUsageTimer = setTimeout(() => void tick(false), nextReportDelayMs());
6148
+ };
6149
+ const tick = async (isFirst) => {
6150
+ try {
6151
+ const usage = await getClaudeUsage();
6152
+ const result = await reportClaudeUsage(state.agentId, state.authHeader, usage);
6153
+ if (result.ok) {
6154
+ if (consecutiveFailures > 0) {
6155
+ logActivity(state, {
6156
+ type: "info",
6157
+ level: "info",
6158
+ message: "Claude usage reporting recovered"
6159
+ });
6160
+ }
6161
+ consecutiveFailures = 0;
6162
+ logActivity(state, {
6163
+ type: "info",
6164
+ level: "debug",
6165
+ message: "Reported Claude usage to Evident"
6166
+ });
6167
+ } else {
6168
+ consecutiveFailures++;
6169
+ logActivity(state, {
6170
+ type: "info",
6171
+ level: consecutiveFailures === 1 ? "warn" : "debug",
6172
+ message: `Failed to report Claude usage: ${result.error}`
6173
+ });
6174
+ }
6175
+ scheduleNextTick();
6176
+ } catch (error2) {
6177
+ if (error2 instanceof ClaudeUsageError && isLocalCredentialProblem(error2)) {
6178
+ if (mode === "on") {
6179
+ logActivity(state, {
6180
+ type: "info",
6181
+ level: "warn",
6182
+ 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"
6183
+ });
6184
+ scheduleNextTick();
6185
+ } else if (isFirst) {
6186
+ logActivity(state, {
6187
+ type: "info",
6188
+ level: "debug",
6189
+ message: `Claude usage reporting: ${error2.message}`
6190
+ });
6191
+ } else {
6192
+ logActivity(state, {
6193
+ type: "info",
6194
+ level: "debug",
6195
+ message: `Claude usage reporting: ${error2.message}`
6196
+ });
6197
+ scheduleNextTick();
6198
+ }
6199
+ } else {
6200
+ consecutiveFailures++;
6201
+ const message = error2 instanceof Error ? error2.message : String(error2);
6202
+ logActivity(state, {
6203
+ type: "info",
6204
+ level: consecutiveFailures === 1 ? "warn" : "debug",
6205
+ message: `Claude usage reporting failed: ${message}`
6206
+ });
6207
+ scheduleNextTick();
6208
+ }
6209
+ }
6210
+ };
6211
+ state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
6212
+ }
5942
6213
  async function notifyOffline(state) {
5943
6214
  if (!state.agentId || !state.authHeader) return;
5944
6215
  if (!state.connected) {
@@ -5974,6 +6245,10 @@ async function cleanup(state, opts = {}) {
5974
6245
  clearTimeout(timer);
5975
6246
  }
5976
6247
  state.sessionCleanupTimers = [];
6248
+ if (state.claudeUsageTimer) {
6249
+ clearTimeout(state.claudeUsageTimer);
6250
+ state.claudeUsageTimer = null;
6251
+ }
5977
6252
  if (opts.graceful && state.channelDriver) {
5978
6253
  state.channelDriver.stop();
5979
6254
  log2(state, "Draining in-flight channel work before shutdown...");
@@ -6021,7 +6296,7 @@ async function run(options) {
6021
6296
  let fileSyncDirectories;
6022
6297
  try {
6023
6298
  logLevel = resolveLogLevel(options);
6024
- fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
6299
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
6025
6300
  } catch (error2) {
6026
6301
  const message = error2 instanceof Error ? error2.message : String(error2);
6027
6302
  if (options.json) {
@@ -6054,6 +6329,7 @@ async function run(options) {
6054
6329
  messageCount: 0,
6055
6330
  lastProxiedActivityAt: null,
6056
6331
  sessionCleanupTimers: [],
6332
+ claudeUsageTimer: null,
6057
6333
  authHeader: ""
6058
6334
  };
6059
6335
  setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
@@ -6308,7 +6584,7 @@ async function run(options) {
6308
6584
  // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
6309
6585
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
6310
6586
  fileSyncDirectories,
6311
- homeDir: homedir2(),
6587
+ homeDir: homedir3(),
6312
6588
  log: (entry) => (
6313
6589
  // Thread the driver's real level straight through so `debug`/`warn`
6314
6590
  // survive the sink filter (they no longer collapse to info). `type`
@@ -6437,6 +6713,7 @@ async function run(options) {
6437
6713
  throw error2;
6438
6714
  }
6439
6715
  scheduleSessionCleanup(state, channelDriver, options);
6716
+ scheduleClaudeUsageReporting(state, options);
6440
6717
  if (!interactive || state.json) {
6441
6718
  log2(state, "Driving channel messages...");
6442
6719
  }
@@ -6491,6 +6768,7 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
6491
6768
  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);
6492
6769
  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 }));
6493
6770
  program.command("whoami").description("Show the currently logged in user").action(whoami);
6771
+ program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);
6494
6772
  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(
6495
6773
  "-a, --agent [id]",
6496
6774
  "Deprecated alias for --runner (still supported; --runner wins if both are given)"
@@ -6509,6 +6787,9 @@ program.command("run").description("Connect to Evident and process messages").op
6509
6787
  ).option(
6510
6788
  "--session-cleanup-interval <duration>",
6511
6789
  "How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
6790
+ ).option(
6791
+ "--claude-usage-reporting <mode>",
6792
+ "Report Claude subscription usage to Evident: auto | on | off (default: auto). Env: EVIDENT_CLAUDE_USAGE_REPORTING"
6512
6793
  ).option(
6513
6794
  "--enable-file-sync-to <dir>",
6514
6795
  "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
@@ -6537,6 +6818,9 @@ program.command("run").description("Connect to Evident and process messages").op
6537
6818
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
6538
6819
  sessionCleanupMaxCount: options.sessionCleanupMaxCount,
6539
6820
  sessionCleanupInterval: options.sessionCleanupInterval,
6821
+ // Raw string — the resolver in run.ts single-sources parsing
6822
+ // (resolveClaudeUsageReportingMode).
6823
+ claudeUsageReporting: options.claudeUsageReporting,
6540
6824
  // Raw values — expansion/validation is single-sourced in run.ts's
6541
6825
  // resolveFileSyncDirectories.
6542
6826
  enableFileSyncTo: options.enableFileSyncTo,