@evident-ai/cli 3.1.1-dev.2f79773 → 3.1.1-dev.315e29d
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 +41 -0
- package/dist/index.js +308 -42
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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: "",
|
|
@@ -537,9 +532,124 @@ async function whoami() {
|
|
|
537
532
|
blank();
|
|
538
533
|
}
|
|
539
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
|
+
|
|
540
650
|
// src/commands/run.ts
|
|
541
|
-
import { homedir as
|
|
542
|
-
import { isAbsolute as isAbsolute2, join as
|
|
651
|
+
import { homedir as homedir3 } from "os";
|
|
652
|
+
import { isAbsolute as isAbsolute2, join as join3, parse, resolve as resolvePath } from "path";
|
|
543
653
|
import chalk6 from "chalk";
|
|
544
654
|
|
|
545
655
|
// ../../packages/types/src/telemetry/index.ts
|
|
@@ -2250,13 +2360,40 @@ function writeTunnelReadyMarker(path, agentId) {
|
|
|
2250
2360
|
}
|
|
2251
2361
|
}
|
|
2252
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
|
+
|
|
2253
2390
|
// src/lib/channels/driver.ts
|
|
2254
|
-
import { homedir } from "os";
|
|
2391
|
+
import { homedir as homedir2 } from "os";
|
|
2255
2392
|
|
|
2256
2393
|
// src/lib/file-push.ts
|
|
2257
2394
|
import { randomUUID } from "crypto";
|
|
2258
2395
|
import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
|
|
2259
|
-
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";
|
|
2260
2397
|
var FILE_MODE = 384;
|
|
2261
2398
|
var DIRECTORY_MODE = 448;
|
|
2262
2399
|
async function writePushedFile(request) {
|
|
@@ -2289,7 +2426,7 @@ async function writePushedFile(request) {
|
|
|
2289
2426
|
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2290
2427
|
dirname2(candidate)
|
|
2291
2428
|
);
|
|
2292
|
-
const realTarget =
|
|
2429
|
+
const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
|
|
2293
2430
|
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2294
2431
|
if (allowedDirectory === null) {
|
|
2295
2432
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
@@ -2325,7 +2462,7 @@ function expandAndValidate(requestedPath, homeDir) {
|
|
|
2325
2462
|
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2326
2463
|
return null;
|
|
2327
2464
|
}
|
|
2328
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
2465
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join2(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2329
2466
|
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2330
2467
|
return null;
|
|
2331
2468
|
}
|
|
@@ -2398,13 +2535,13 @@ function contains(realDirectory, realTarget) {
|
|
|
2398
2535
|
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2399
2536
|
let current = existingAncestor;
|
|
2400
2537
|
for (const segment of missingSegments) {
|
|
2401
|
-
current =
|
|
2538
|
+
current = join2(current, segment);
|
|
2402
2539
|
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2403
2540
|
await chmod(current, DIRECTORY_MODE);
|
|
2404
2541
|
}
|
|
2405
2542
|
}
|
|
2406
2543
|
async function writeAtomically(realTarget, content) {
|
|
2407
|
-
const temporaryPath =
|
|
2544
|
+
const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2408
2545
|
let handle;
|
|
2409
2546
|
try {
|
|
2410
2547
|
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
@@ -2903,23 +3040,23 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2903
3040
|
* and stops opencode.
|
|
2904
3041
|
*/
|
|
2905
3042
|
stopped = false;
|
|
2906
|
-
constructor(
|
|
2907
|
-
this.agentId =
|
|
2908
|
-
this.port =
|
|
2909
|
-
this.apiUrl =
|
|
2910
|
-
this.getAuthHeader =
|
|
2911
|
-
this.conversationFilter =
|
|
2912
|
-
this.retry = { ...DEFAULT_RETRY_POLICY, ...
|
|
2913
|
-
this.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 ?? (() => {
|
|
2914
3051
|
});
|
|
2915
|
-
this.fetchImpl =
|
|
2916
|
-
this.sleep =
|
|
2917
|
-
this.pausedPollIntervalMs =
|
|
2918
|
-
this.pausedMaxWaitMs =
|
|
2919
|
-
this.stuckQueuedMs =
|
|
2920
|
-
this.now =
|
|
2921
|
-
this.fileSyncDirectories =
|
|
2922
|
-
this.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();
|
|
2923
3060
|
}
|
|
2924
3061
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2925
3062
|
get opencodeBase() {
|
|
@@ -5567,6 +5704,34 @@ async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
|
5567
5704
|
return { ok: false, error: describeBestEffortError(error2) };
|
|
5568
5705
|
}
|
|
5569
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
|
+
}
|
|
5570
5735
|
async function getAgentInfo(agentId, authHeader) {
|
|
5571
5736
|
const apiUrl = getApiUrlConfig();
|
|
5572
5737
|
try {
|
|
@@ -5645,7 +5810,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
5645
5810
|
if (trimmed === "") {
|
|
5646
5811
|
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5647
5812
|
}
|
|
5648
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
5813
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join3(homeDir, trimmed.slice(2)) : trimmed;
|
|
5649
5814
|
if (!isAbsolute2(expanded)) {
|
|
5650
5815
|
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5651
5816
|
}
|
|
@@ -5883,8 +6048,8 @@ async function driveChannels(state, driver) {
|
|
|
5883
6048
|
}
|
|
5884
6049
|
}
|
|
5885
6050
|
var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
|
|
5886
|
-
async function runSweep(state, driver,
|
|
5887
|
-
const mode = `age=${
|
|
6051
|
+
async function runSweep(state, driver, config) {
|
|
6052
|
+
const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
|
|
5888
6053
|
try {
|
|
5889
6054
|
const sessions = await listSessions(state.port);
|
|
5890
6055
|
if (sessions === null) {
|
|
@@ -5897,8 +6062,8 @@ async function runSweep(state, driver, config2) {
|
|
|
5897
6062
|
const toDelete = selectSessionsToDelete(
|
|
5898
6063
|
sessions.map((s) => ({ id: s.id, lastActivityMs: sessionLastActivityMs(s) })),
|
|
5899
6064
|
{
|
|
5900
|
-
maxAgeMs:
|
|
5901
|
-
maxCount:
|
|
6065
|
+
maxAgeMs: config.maxAgeMs,
|
|
6066
|
+
maxCount: config.maxCount,
|
|
5902
6067
|
nowMs: Date.now(),
|
|
5903
6068
|
protectedIds: driver.protectedSessionIds()
|
|
5904
6069
|
}
|
|
@@ -5934,7 +6099,7 @@ async function runSweep(state, driver, config2) {
|
|
|
5934
6099
|
}
|
|
5935
6100
|
}
|
|
5936
6101
|
function scheduleSessionCleanup(state, driver, options) {
|
|
5937
|
-
const
|
|
6102
|
+
const config = resolveSessionCleanupConfig(
|
|
5938
6103
|
{
|
|
5939
6104
|
maxAge: options.sessionCleanupMaxAge,
|
|
5940
6105
|
maxCount: options.sessionCleanupMaxCount,
|
|
@@ -5942,21 +6107,109 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
5942
6107
|
},
|
|
5943
6108
|
process.env
|
|
5944
6109
|
);
|
|
5945
|
-
for (const warning2 of
|
|
6110
|
+
for (const warning2 of config.warnings) {
|
|
5946
6111
|
logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
|
|
5947
6112
|
}
|
|
5948
|
-
if (!
|
|
6113
|
+
if (!config.enabled) return;
|
|
5949
6114
|
logActivity(state, {
|
|
5950
6115
|
type: "info",
|
|
5951
|
-
message: `Session cleanup enabled (age=${
|
|
6116
|
+
message: `Session cleanup enabled (age=${config.maxAgeMs ?? "\u2014"}, count=${config.maxCount ?? "\u2014"}, interval=${config.intervalMs}ms)`
|
|
5952
6117
|
});
|
|
5953
|
-
const interval = setInterval(() => void runSweep(state, driver,
|
|
6118
|
+
const interval = setInterval(() => void runSweep(state, driver, config), config.intervalMs);
|
|
5954
6119
|
const firstSweep = setTimeout(
|
|
5955
|
-
() => void runSweep(state, driver,
|
|
6120
|
+
() => void runSweep(state, driver, config),
|
|
5956
6121
|
SESSION_CLEANUP_FIRST_SWEEP_MS
|
|
5957
6122
|
);
|
|
5958
6123
|
state.sessionCleanupTimers.push(interval, firstSweep);
|
|
5959
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
|
+
}
|
|
5960
6213
|
async function notifyOffline(state) {
|
|
5961
6214
|
if (!state.agentId || !state.authHeader) return;
|
|
5962
6215
|
if (!state.connected) {
|
|
@@ -5992,6 +6245,10 @@ async function cleanup(state, opts = {}) {
|
|
|
5992
6245
|
clearTimeout(timer);
|
|
5993
6246
|
}
|
|
5994
6247
|
state.sessionCleanupTimers = [];
|
|
6248
|
+
if (state.claudeUsageTimer) {
|
|
6249
|
+
clearTimeout(state.claudeUsageTimer);
|
|
6250
|
+
state.claudeUsageTimer = null;
|
|
6251
|
+
}
|
|
5995
6252
|
if (opts.graceful && state.channelDriver) {
|
|
5996
6253
|
state.channelDriver.stop();
|
|
5997
6254
|
log2(state, "Draining in-flight channel work before shutdown...");
|
|
@@ -6039,7 +6296,7 @@ async function run(options) {
|
|
|
6039
6296
|
let fileSyncDirectories;
|
|
6040
6297
|
try {
|
|
6041
6298
|
logLevel = resolveLogLevel(options);
|
|
6042
|
-
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo,
|
|
6299
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
|
|
6043
6300
|
} catch (error2) {
|
|
6044
6301
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
6045
6302
|
if (options.json) {
|
|
@@ -6072,6 +6329,7 @@ async function run(options) {
|
|
|
6072
6329
|
messageCount: 0,
|
|
6073
6330
|
lastProxiedActivityAt: null,
|
|
6074
6331
|
sessionCleanupTimers: [],
|
|
6332
|
+
claudeUsageTimer: null,
|
|
6075
6333
|
authHeader: ""
|
|
6076
6334
|
};
|
|
6077
6335
|
setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
|
|
@@ -6326,7 +6584,7 @@ async function run(options) {
|
|
|
6326
6584
|
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
6327
6585
|
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
6328
6586
|
fileSyncDirectories,
|
|
6329
|
-
homeDir:
|
|
6587
|
+
homeDir: homedir3(),
|
|
6330
6588
|
log: (entry) => (
|
|
6331
6589
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
6332
6590
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -6455,6 +6713,7 @@ async function run(options) {
|
|
|
6455
6713
|
throw error2;
|
|
6456
6714
|
}
|
|
6457
6715
|
scheduleSessionCleanup(state, channelDriver, options);
|
|
6716
|
+
scheduleClaudeUsageReporting(state, options);
|
|
6458
6717
|
if (!interactive || state.json) {
|
|
6459
6718
|
log2(state, "Driving channel messages...");
|
|
6460
6719
|
}
|
|
@@ -6509,6 +6768,7 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
6509
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);
|
|
6510
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 }));
|
|
6511
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);
|
|
6512
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(
|
|
6513
6773
|
"-a, --agent [id]",
|
|
6514
6774
|
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
@@ -6527,6 +6787,9 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
6527
6787
|
).option(
|
|
6528
6788
|
"--session-cleanup-interval <duration>",
|
|
6529
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"
|
|
6530
6793
|
).option(
|
|
6531
6794
|
"--enable-file-sync-to <dir>",
|
|
6532
6795
|
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
@@ -6555,6 +6818,9 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
6555
6818
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
6556
6819
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
6557
6820
|
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
6821
|
+
// Raw string — the resolver in run.ts single-sources parsing
|
|
6822
|
+
// (resolveClaudeUsageReportingMode).
|
|
6823
|
+
claudeUsageReporting: options.claudeUsageReporting,
|
|
6558
6824
|
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
6559
6825
|
// resolveFileSyncDirectories.
|
|
6560
6826
|
enableFileSyncTo: options.enableFileSyncTo,
|