@evident-ai/cli 3.1.1-dev.0d69ecc → 3.1.1-dev.0d8ac46
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 +45 -0
- package/dist/index.js +556 -93
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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: "",
|
|
@@ -267,16 +262,28 @@ async function getToken() {
|
|
|
267
262
|
}
|
|
268
263
|
return null;
|
|
269
264
|
}
|
|
265
|
+
function toError(err) {
|
|
266
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
267
|
+
}
|
|
270
268
|
async function deleteToken(options = {}) {
|
|
271
269
|
const keytar = await getKeytar();
|
|
270
|
+
const failures = [];
|
|
272
271
|
if (keytar) {
|
|
273
272
|
if (options.all) {
|
|
274
|
-
|
|
273
|
+
let accounts = [];
|
|
274
|
+
try {
|
|
275
|
+
accounts = await keytar.findCredentials(SERVICE_NAME);
|
|
276
|
+
} catch (err) {
|
|
277
|
+
failures.push({ type: "enumerate", error: toError(err) });
|
|
278
|
+
}
|
|
275
279
|
await Promise.all(
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
+
accounts.map(async (entry) => {
|
|
281
|
+
try {
|
|
282
|
+
await keytar.deletePassword(SERVICE_NAME, entry.account);
|
|
283
|
+
} catch (err) {
|
|
284
|
+
failures.push({ type: "delete", account: entry.account, error: toError(err) });
|
|
285
|
+
}
|
|
286
|
+
})
|
|
280
287
|
);
|
|
281
288
|
} else {
|
|
282
289
|
await keytar.deletePassword(SERVICE_NAME, keychainAccount());
|
|
@@ -287,6 +294,7 @@ async function deleteToken(options = {}) {
|
|
|
287
294
|
} else {
|
|
288
295
|
clearCredentials();
|
|
289
296
|
}
|
|
297
|
+
return { failures };
|
|
290
298
|
}
|
|
291
299
|
|
|
292
300
|
// src/utils/ui.ts
|
|
@@ -404,8 +412,10 @@ async function deviceFlowLogin(options) {
|
|
|
404
412
|
}
|
|
405
413
|
async function tokenLogin() {
|
|
406
414
|
console.log("Token login mode.");
|
|
407
|
-
console.log("
|
|
408
|
-
console.log(
|
|
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
|
+
);
|
|
409
419
|
blank();
|
|
410
420
|
process.stdout.write("Paste token: ");
|
|
411
421
|
const token = await new Promise((resolve3) => {
|
|
@@ -429,13 +439,22 @@ async function tokenLogin() {
|
|
|
429
439
|
printError("No token provided.");
|
|
430
440
|
process.exit(1);
|
|
431
441
|
}
|
|
442
|
+
await validateAndStoreToken(token);
|
|
443
|
+
}
|
|
444
|
+
async function validateAndStoreToken(token) {
|
|
432
445
|
const spinner = ora("Validating token...").start();
|
|
433
446
|
try {
|
|
434
|
-
const result = await api.
|
|
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
|
+
}
|
|
435
455
|
await storeToken({
|
|
436
456
|
token,
|
|
437
|
-
user: result.user
|
|
438
|
-
expiresAt: result.expires_at
|
|
457
|
+
user: { email: result.user.email }
|
|
439
458
|
});
|
|
440
459
|
spinner.stop();
|
|
441
460
|
printSuccess(`Logged in as ${chalk2.bold(result.user.email)}`);
|
|
@@ -455,9 +474,22 @@ async function login(options) {
|
|
|
455
474
|
}
|
|
456
475
|
|
|
457
476
|
// src/commands/logout.ts
|
|
477
|
+
function describeFailure(failure) {
|
|
478
|
+
if (failure.type === "enumerate") {
|
|
479
|
+
return `could not list stored keychain entries (${failure.error.message})`;
|
|
480
|
+
}
|
|
481
|
+
return `${failure.account} (${failure.error.message})`;
|
|
482
|
+
}
|
|
458
483
|
async function logout(options = {}) {
|
|
459
484
|
if (options.all) {
|
|
460
|
-
await deleteToken({ all: true });
|
|
485
|
+
const result = await deleteToken({ all: true });
|
|
486
|
+
if (result.failures.length > 0) {
|
|
487
|
+
printError(
|
|
488
|
+
`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.`
|
|
489
|
+
);
|
|
490
|
+
process.exitCode = 1;
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
461
493
|
printSuccess("Logged out of all endpoints.");
|
|
462
494
|
return;
|
|
463
495
|
}
|
|
@@ -482,7 +514,9 @@ async function whoami() {
|
|
|
482
514
|
blank();
|
|
483
515
|
console.log(keyValue("Endpoint", apiUrl));
|
|
484
516
|
console.log(keyValue("User", chalk3.bold(credentials2.user.email)));
|
|
485
|
-
|
|
517
|
+
if (credentials2.user.id) {
|
|
518
|
+
console.log(keyValue("User ID", credentials2.user.id));
|
|
519
|
+
}
|
|
486
520
|
if (credentials2.expiresAt) {
|
|
487
521
|
const expiresAt = new Date(credentials2.expiresAt);
|
|
488
522
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -498,9 +532,124 @@ async function whoami() {
|
|
|
498
532
|
blank();
|
|
499
533
|
}
|
|
500
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
|
+
|
|
501
650
|
// src/commands/run.ts
|
|
502
|
-
import { homedir as
|
|
503
|
-
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";
|
|
504
653
|
import chalk6 from "chalk";
|
|
505
654
|
|
|
506
655
|
// ../../packages/types/src/telemetry/index.ts
|
|
@@ -510,7 +659,10 @@ var TelemetryEventTypes = {
|
|
|
510
659
|
AGENT_DISCONNECTED: "agent.disconnected",
|
|
511
660
|
AGENT_MESSAGE_PROCESSING: "agent.message_processing",
|
|
512
661
|
AGENT_MESSAGE_DONE: "agent.message_done",
|
|
513
|
-
AGENT_MESSAGE_FAILED: "agent.message_failed"
|
|
662
|
+
AGENT_MESSAGE_FAILED: "agent.message_failed",
|
|
663
|
+
// A `warn`/`error` runner-side log line forwarded server-side for
|
|
664
|
+
// observability (issue #916) — see `apps/cli/src/lib/runner-activity-telemetry.ts`.
|
|
665
|
+
RUNNER_ACTIVITY: "runner.activity"
|
|
514
666
|
};
|
|
515
667
|
|
|
516
668
|
// ../../packages/types/src/tunnel/index.ts
|
|
@@ -565,6 +717,13 @@ var isShuttingDown = false;
|
|
|
565
717
|
var FLUSH_INTERVAL_MS = 5e3;
|
|
566
718
|
var MAX_BUFFER_SIZE = 50;
|
|
567
719
|
var FLUSH_TIMEOUT_MS = 3e3;
|
|
720
|
+
var authProvider = null;
|
|
721
|
+
function setTelemetryAuthProvider(provider) {
|
|
722
|
+
authProvider = provider;
|
|
723
|
+
}
|
|
724
|
+
var FLUSH_FAILURE_LOG_INTERVAL_MS = 6e4;
|
|
725
|
+
var lastFlushFailureLoggedAt = 0;
|
|
726
|
+
var suppressedFlushFailureCount = 0;
|
|
568
727
|
function logEvent(eventType, options = {}) {
|
|
569
728
|
const event = {
|
|
570
729
|
event_type: eventType,
|
|
@@ -599,9 +758,16 @@ async function flushEvents() {
|
|
|
599
758
|
flushTimeout = null;
|
|
600
759
|
}
|
|
601
760
|
try {
|
|
602
|
-
const
|
|
603
|
-
|
|
604
|
-
|
|
761
|
+
const providerContext = authProvider?.();
|
|
762
|
+
let authHeader;
|
|
763
|
+
if (providerContext?.authHeader) {
|
|
764
|
+
authHeader = providerContext.authHeader;
|
|
765
|
+
} else {
|
|
766
|
+
const credentials2 = await getToken();
|
|
767
|
+
if (!credentials2) {
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
authHeader = `Bearer ${credentials2.token}`;
|
|
605
771
|
}
|
|
606
772
|
const apiUrl = getApiUrlConfig();
|
|
607
773
|
const controller = new AbortController();
|
|
@@ -616,7 +782,7 @@ async function flushEvents() {
|
|
|
616
782
|
method: "POST",
|
|
617
783
|
headers: {
|
|
618
784
|
"Content-Type": "application/json",
|
|
619
|
-
Authorization:
|
|
785
|
+
Authorization: authHeader
|
|
620
786
|
},
|
|
621
787
|
body: JSON.stringify(request),
|
|
622
788
|
signal: controller.signal
|
|
@@ -628,8 +794,15 @@ async function flushEvents() {
|
|
|
628
794
|
clearTimeout(timeout);
|
|
629
795
|
}
|
|
630
796
|
} catch (error2) {
|
|
631
|
-
|
|
632
|
-
|
|
797
|
+
const now = Date.now();
|
|
798
|
+
if (now - lastFlushFailureLoggedAt >= FLUSH_FAILURE_LOG_INTERVAL_MS) {
|
|
799
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
800
|
+
const suffix = suppressedFlushFailureCount > 0 ? ` (${suppressedFlushFailureCount} more suppressed in the last ${FLUSH_FAILURE_LOG_INTERVAL_MS / 1e3}s)` : "";
|
|
801
|
+
console.error(`Telemetry flush error: ${message}${suffix}`);
|
|
802
|
+
lastFlushFailureLoggedAt = now;
|
|
803
|
+
suppressedFlushFailureCount = 0;
|
|
804
|
+
} else {
|
|
805
|
+
suppressedFlushFailureCount++;
|
|
633
806
|
}
|
|
634
807
|
}
|
|
635
808
|
}
|
|
@@ -698,6 +871,69 @@ var EventTypes = {
|
|
|
698
871
|
DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
|
|
699
872
|
};
|
|
700
873
|
|
|
874
|
+
// src/lib/runner-activity-telemetry.ts
|
|
875
|
+
var FORWARDED_LEVELS = /* @__PURE__ */ new Set(["warn", "error"]);
|
|
876
|
+
var SEVERITY_BY_LEVEL = {
|
|
877
|
+
warn: "warning",
|
|
878
|
+
error: "error"
|
|
879
|
+
};
|
|
880
|
+
var MAX_MESSAGE_LENGTH = 500;
|
|
881
|
+
var TRUNCATION_MARKER = "\u2026";
|
|
882
|
+
function redact(message) {
|
|
883
|
+
return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
|
|
884
|
+
}
|
|
885
|
+
function truncate(message) {
|
|
886
|
+
if (message.length <= MAX_MESSAGE_LENGTH) return message;
|
|
887
|
+
return message.slice(0, MAX_MESSAGE_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
|
|
888
|
+
}
|
|
889
|
+
var RATE_LIMIT_WINDOW_MS = 6e4;
|
|
890
|
+
var RATE_LIMIT_MAX_EVENTS = 30;
|
|
891
|
+
var windowStartedAt = 0;
|
|
892
|
+
var windowCount = 0;
|
|
893
|
+
var windowDroppedCount = 0;
|
|
894
|
+
function admitUnderRateLimit(now) {
|
|
895
|
+
if (now - windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
|
|
896
|
+
if (windowDroppedCount > 0) {
|
|
897
|
+
console.error(
|
|
898
|
+
`[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)`
|
|
899
|
+
);
|
|
900
|
+
}
|
|
901
|
+
windowStartedAt = now;
|
|
902
|
+
windowCount = 0;
|
|
903
|
+
windowDroppedCount = 0;
|
|
904
|
+
}
|
|
905
|
+
if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
|
|
906
|
+
windowDroppedCount++;
|
|
907
|
+
if (windowDroppedCount === 1) {
|
|
908
|
+
console.error(
|
|
909
|
+
`[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
return false;
|
|
913
|
+
}
|
|
914
|
+
windowCount++;
|
|
915
|
+
return true;
|
|
916
|
+
}
|
|
917
|
+
function forwardRunnerActivity(entry, context) {
|
|
918
|
+
try {
|
|
919
|
+
if (!FORWARDED_LEVELS.has(entry.level)) return;
|
|
920
|
+
if (!context.agentId || !context.authHeader) return;
|
|
921
|
+
if (!admitUnderRateLimit(Date.now())) return;
|
|
922
|
+
const rawMessage = entry.error ?? entry.message ?? "";
|
|
923
|
+
const message = truncate(redact(rawMessage));
|
|
924
|
+
logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
|
|
925
|
+
severity: SEVERITY_BY_LEVEL[entry.level],
|
|
926
|
+
message,
|
|
927
|
+
metadata: { source: "cli.run" },
|
|
928
|
+
agentId: context.agentId
|
|
929
|
+
});
|
|
930
|
+
} catch (err) {
|
|
931
|
+
console.error(
|
|
932
|
+
`[runner-activity-telemetry] failed to forward runner activity: ${err instanceof Error ? err.message : String(err)}`
|
|
933
|
+
);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
701
937
|
// src/lib/auth.ts
|
|
702
938
|
async function getAuthCredentials() {
|
|
703
939
|
const runnerKey = process.env.EVIDENT_RUNNER_KEY;
|
|
@@ -2124,13 +2360,40 @@ function writeTunnelReadyMarker(path, agentId) {
|
|
|
2124
2360
|
}
|
|
2125
2361
|
}
|
|
2126
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
|
+
|
|
2127
2390
|
// src/lib/channels/driver.ts
|
|
2128
|
-
import { homedir } from "os";
|
|
2391
|
+
import { homedir as homedir2 } from "os";
|
|
2129
2392
|
|
|
2130
2393
|
// src/lib/file-push.ts
|
|
2131
2394
|
import { randomUUID } from "crypto";
|
|
2132
2395
|
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";
|
|
2396
|
+
import { basename, dirname as dirname2, isAbsolute, join as join2, relative, resolve as resolve2, sep } from "path";
|
|
2134
2397
|
var FILE_MODE = 384;
|
|
2135
2398
|
var DIRECTORY_MODE = 448;
|
|
2136
2399
|
async function writePushedFile(request) {
|
|
@@ -2163,7 +2426,7 @@ async function writePushedFile(request) {
|
|
|
2163
2426
|
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2164
2427
|
dirname2(candidate)
|
|
2165
2428
|
);
|
|
2166
|
-
const realTarget =
|
|
2429
|
+
const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
|
|
2167
2430
|
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2168
2431
|
if (allowedDirectory === null) {
|
|
2169
2432
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
@@ -2199,7 +2462,7 @@ function expandAndValidate(requestedPath, homeDir) {
|
|
|
2199
2462
|
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2200
2463
|
return null;
|
|
2201
2464
|
}
|
|
2202
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
2465
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join2(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2203
2466
|
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2204
2467
|
return null;
|
|
2205
2468
|
}
|
|
@@ -2272,13 +2535,13 @@ function contains(realDirectory, realTarget) {
|
|
|
2272
2535
|
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2273
2536
|
let current = existingAncestor;
|
|
2274
2537
|
for (const segment of missingSegments) {
|
|
2275
|
-
current =
|
|
2538
|
+
current = join2(current, segment);
|
|
2276
2539
|
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2277
2540
|
await chmod(current, DIRECTORY_MODE);
|
|
2278
2541
|
}
|
|
2279
2542
|
}
|
|
2280
2543
|
async function writeAtomically(realTarget, content) {
|
|
2281
|
-
const temporaryPath =
|
|
2544
|
+
const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2282
2545
|
let handle;
|
|
2283
2546
|
try {
|
|
2284
2547
|
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
@@ -2777,23 +3040,23 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2777
3040
|
* and stops opencode.
|
|
2778
3041
|
*/
|
|
2779
3042
|
stopped = false;
|
|
2780
|
-
constructor(
|
|
2781
|
-
this.agentId =
|
|
2782
|
-
this.port =
|
|
2783
|
-
this.apiUrl =
|
|
2784
|
-
this.getAuthHeader =
|
|
2785
|
-
this.conversationFilter =
|
|
2786
|
-
this.retry = { ...DEFAULT_RETRY_POLICY, ...
|
|
2787
|
-
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 ?? (() => {
|
|
2788
3051
|
});
|
|
2789
|
-
this.fetchImpl =
|
|
2790
|
-
this.sleep =
|
|
2791
|
-
this.pausedPollIntervalMs =
|
|
2792
|
-
this.pausedMaxWaitMs =
|
|
2793
|
-
this.stuckQueuedMs =
|
|
2794
|
-
this.now =
|
|
2795
|
-
this.fileSyncDirectories =
|
|
2796
|
-
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();
|
|
2797
3060
|
}
|
|
2798
3061
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2799
3062
|
get opencodeBase() {
|
|
@@ -3178,7 +3441,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3178
3441
|
const directory = await this.resolveOpenCodeDirectory();
|
|
3179
3442
|
const sessionId = await createOpenCodeSession(this.port, directory);
|
|
3180
3443
|
this.sessions.set(conversationId, sessionId);
|
|
3181
|
-
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
|
+
});
|
|
3182
3450
|
});
|
|
3183
3451
|
return sessionId;
|
|
3184
3452
|
}
|
|
@@ -5212,10 +5480,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5212
5480
|
import chalk5 from "chalk";
|
|
5213
5481
|
import ora2 from "ora";
|
|
5214
5482
|
import { select as select2 } from "@inquirer/prompts";
|
|
5483
|
+
var INTERACTIVE_START_TIMEOUT_MS = 3e4;
|
|
5215
5484
|
async function ensureOpenCodeRunning(ctx) {
|
|
5216
5485
|
const healthCheck = await checkOpenCodeHealth(ctx.port);
|
|
5217
5486
|
if (healthCheck.healthy) {
|
|
5218
|
-
return {
|
|
5487
|
+
return {
|
|
5488
|
+
port: ctx.port,
|
|
5489
|
+
process: null,
|
|
5490
|
+
version: healthCheck.version ?? null,
|
|
5491
|
+
notReadyReason: null
|
|
5492
|
+
};
|
|
5219
5493
|
}
|
|
5220
5494
|
const runningInstances = await findHealthyOpenCodeInstances();
|
|
5221
5495
|
if (runningInstances.length > 0) {
|
|
@@ -5256,14 +5530,22 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
5256
5530
|
if (!ctx.interactive) {
|
|
5257
5531
|
ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
|
|
5258
5532
|
const proc = await startOpenCode(ctx.port);
|
|
5259
|
-
const health = await waitForOpenCodeHealth(ctx.port,
|
|
5533
|
+
const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
|
|
5260
5534
|
if (!health.healthy) {
|
|
5261
|
-
|
|
5262
|
-
|
|
5263
|
-
|
|
5535
|
+
return {
|
|
5536
|
+
port: ctx.port,
|
|
5537
|
+
process: proc,
|
|
5538
|
+
version: null,
|
|
5539
|
+
notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
|
|
5540
|
+
};
|
|
5264
5541
|
}
|
|
5265
5542
|
ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
|
|
5266
|
-
return {
|
|
5543
|
+
return {
|
|
5544
|
+
port: ctx.port,
|
|
5545
|
+
process: proc,
|
|
5546
|
+
version: health.version ?? null,
|
|
5547
|
+
notReadyReason: null
|
|
5548
|
+
};
|
|
5267
5549
|
}
|
|
5268
5550
|
let port = ctx.port;
|
|
5269
5551
|
if (isPortInUse(port)) {
|
|
@@ -5316,15 +5598,15 @@ Port ${port} is already in use.`));
|
|
|
5316
5598
|
if (action === "start") {
|
|
5317
5599
|
const spinner = ora2("Starting OpenCode...").start();
|
|
5318
5600
|
const proc = await startOpenCode(port);
|
|
5319
|
-
const health = await waitForOpenCodeHealth(port,
|
|
5601
|
+
const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
|
|
5320
5602
|
if (!health.healthy) {
|
|
5321
5603
|
spinner.fail("Failed to start OpenCode");
|
|
5322
5604
|
throw new Error("OpenCode failed to start");
|
|
5323
5605
|
}
|
|
5324
5606
|
spinner.stop();
|
|
5325
|
-
return { port, process: proc, version: health.version ?? null };
|
|
5607
|
+
return { port, process: proc, version: health.version ?? null, notReadyReason: null };
|
|
5326
5608
|
}
|
|
5327
|
-
return { port, process: null, version: null };
|
|
5609
|
+
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
5328
5610
|
}
|
|
5329
5611
|
|
|
5330
5612
|
// src/commands/agent-lookup.ts
|
|
@@ -5422,6 +5704,34 @@ async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
|
5422
5704
|
return { ok: false, error: describeBestEffortError(error2) };
|
|
5423
5705
|
}
|
|
5424
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
|
+
}
|
|
5425
5735
|
async function getAgentInfo(agentId, authHeader) {
|
|
5426
5736
|
const apiUrl = getApiUrlConfig();
|
|
5427
5737
|
try {
|
|
@@ -5500,7 +5810,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
5500
5810
|
if (trimmed === "") {
|
|
5501
5811
|
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5502
5812
|
}
|
|
5503
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
5813
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join3(homeDir, trimmed.slice(2)) : trimmed;
|
|
5504
5814
|
if (!isAbsolute2(expanded)) {
|
|
5505
5815
|
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5506
5816
|
}
|
|
@@ -5521,6 +5831,35 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
5521
5831
|
}
|
|
5522
5832
|
return directories;
|
|
5523
5833
|
}
|
|
5834
|
+
var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
|
|
5835
|
+
var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
|
|
5836
|
+
var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
|
|
5837
|
+
function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
|
|
5838
|
+
const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
|
|
5839
|
+
let raw;
|
|
5840
|
+
let source;
|
|
5841
|
+
if (options.opencodeStartTimeout !== void 0) {
|
|
5842
|
+
raw = options.opencodeStartTimeout;
|
|
5843
|
+
source = "--opencode-start-timeout";
|
|
5844
|
+
} else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
|
|
5845
|
+
raw = env[OPENCODE_START_TIMEOUT_ENV];
|
|
5846
|
+
source = OPENCODE_START_TIMEOUT_ENV;
|
|
5847
|
+
} else {
|
|
5848
|
+
return { timeoutMs: defaultMs, warnings: [] };
|
|
5849
|
+
}
|
|
5850
|
+
const trimmed = raw.trim();
|
|
5851
|
+
const seconds = Number(trimmed);
|
|
5852
|
+
const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
|
|
5853
|
+
if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
|
|
5854
|
+
return {
|
|
5855
|
+
timeoutMs: defaultMs,
|
|
5856
|
+
warnings: [
|
|
5857
|
+
`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`
|
|
5858
|
+
]
|
|
5859
|
+
};
|
|
5860
|
+
}
|
|
5861
|
+
return { timeoutMs: seconds * 1e3, warnings: [] };
|
|
5862
|
+
}
|
|
5524
5863
|
function meetsThreshold(state, level) {
|
|
5525
5864
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
5526
5865
|
}
|
|
@@ -5542,6 +5881,10 @@ function log2(state, message, level = "info") {
|
|
|
5542
5881
|
function logActivity(state, entry) {
|
|
5543
5882
|
const level = entry.level ?? (entry.type === "error" ? "error" : "info");
|
|
5544
5883
|
if (!meetsThreshold(state, level)) return;
|
|
5884
|
+
forwardRunnerActivity(
|
|
5885
|
+
{ level, message: entry.message, error: entry.error },
|
|
5886
|
+
{ agentId: state.agentId, authHeader: state.authHeader }
|
|
5887
|
+
);
|
|
5545
5888
|
const fullEntry = {
|
|
5546
5889
|
...entry,
|
|
5547
5890
|
level,
|
|
@@ -5705,8 +6048,8 @@ async function driveChannels(state, driver) {
|
|
|
5705
6048
|
}
|
|
5706
6049
|
}
|
|
5707
6050
|
var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
|
|
5708
|
-
async function runSweep(state, driver,
|
|
5709
|
-
const mode = `age=${
|
|
6051
|
+
async function runSweep(state, driver, config) {
|
|
6052
|
+
const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
|
|
5710
6053
|
try {
|
|
5711
6054
|
const sessions = await listSessions(state.port);
|
|
5712
6055
|
if (sessions === null) {
|
|
@@ -5719,8 +6062,8 @@ async function runSweep(state, driver, config2) {
|
|
|
5719
6062
|
const toDelete = selectSessionsToDelete(
|
|
5720
6063
|
sessions.map((s) => ({ id: s.id, lastActivityMs: sessionLastActivityMs(s) })),
|
|
5721
6064
|
{
|
|
5722
|
-
maxAgeMs:
|
|
5723
|
-
maxCount:
|
|
6065
|
+
maxAgeMs: config.maxAgeMs,
|
|
6066
|
+
maxCount: config.maxCount,
|
|
5724
6067
|
nowMs: Date.now(),
|
|
5725
6068
|
protectedIds: driver.protectedSessionIds()
|
|
5726
6069
|
}
|
|
@@ -5756,7 +6099,7 @@ async function runSweep(state, driver, config2) {
|
|
|
5756
6099
|
}
|
|
5757
6100
|
}
|
|
5758
6101
|
function scheduleSessionCleanup(state, driver, options) {
|
|
5759
|
-
const
|
|
6102
|
+
const config = resolveSessionCleanupConfig(
|
|
5760
6103
|
{
|
|
5761
6104
|
maxAge: options.sessionCleanupMaxAge,
|
|
5762
6105
|
maxCount: options.sessionCleanupMaxCount,
|
|
@@ -5764,21 +6107,109 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
5764
6107
|
},
|
|
5765
6108
|
process.env
|
|
5766
6109
|
);
|
|
5767
|
-
for (const warning2 of
|
|
6110
|
+
for (const warning2 of config.warnings) {
|
|
5768
6111
|
logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
|
|
5769
6112
|
}
|
|
5770
|
-
if (!
|
|
6113
|
+
if (!config.enabled) return;
|
|
5771
6114
|
logActivity(state, {
|
|
5772
6115
|
type: "info",
|
|
5773
|
-
message: `Session cleanup enabled (age=${
|
|
6116
|
+
message: `Session cleanup enabled (age=${config.maxAgeMs ?? "\u2014"}, count=${config.maxCount ?? "\u2014"}, interval=${config.intervalMs}ms)`
|
|
5774
6117
|
});
|
|
5775
|
-
const interval = setInterval(() => void runSweep(state, driver,
|
|
6118
|
+
const interval = setInterval(() => void runSweep(state, driver, config), config.intervalMs);
|
|
5776
6119
|
const firstSweep = setTimeout(
|
|
5777
|
-
() => void runSweep(state, driver,
|
|
6120
|
+
() => void runSweep(state, driver, config),
|
|
5778
6121
|
SESSION_CLEANUP_FIRST_SWEEP_MS
|
|
5779
6122
|
);
|
|
5780
6123
|
state.sessionCleanupTimers.push(interval, firstSweep);
|
|
5781
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
|
+
}
|
|
5782
6213
|
async function notifyOffline(state) {
|
|
5783
6214
|
if (!state.agentId || !state.authHeader) return;
|
|
5784
6215
|
if (!state.connected) {
|
|
@@ -5814,6 +6245,10 @@ async function cleanup(state, opts = {}) {
|
|
|
5814
6245
|
clearTimeout(timer);
|
|
5815
6246
|
}
|
|
5816
6247
|
state.sessionCleanupTimers = [];
|
|
6248
|
+
if (state.claudeUsageTimer) {
|
|
6249
|
+
clearTimeout(state.claudeUsageTimer);
|
|
6250
|
+
state.claudeUsageTimer = null;
|
|
6251
|
+
}
|
|
5817
6252
|
if (opts.graceful && state.channelDriver) {
|
|
5818
6253
|
state.channelDriver.stop();
|
|
5819
6254
|
log2(state, "Draining in-flight channel work before shutdown...");
|
|
@@ -5861,7 +6296,7 @@ async function run(options) {
|
|
|
5861
6296
|
let fileSyncDirectories;
|
|
5862
6297
|
try {
|
|
5863
6298
|
logLevel = resolveLogLevel(options);
|
|
5864
|
-
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo,
|
|
6299
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
|
|
5865
6300
|
} catch (error2) {
|
|
5866
6301
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
5867
6302
|
if (options.json) {
|
|
@@ -5894,8 +6329,10 @@ async function run(options) {
|
|
|
5894
6329
|
messageCount: 0,
|
|
5895
6330
|
lastProxiedActivityAt: null,
|
|
5896
6331
|
sessionCleanupTimers: [],
|
|
6332
|
+
claudeUsageTimer: null,
|
|
5897
6333
|
authHeader: ""
|
|
5898
6334
|
};
|
|
6335
|
+
setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
|
|
5899
6336
|
if (fileSyncDirectories.length > 0) {
|
|
5900
6337
|
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
5901
6338
|
} else {
|
|
@@ -6084,40 +6521,52 @@ async function run(options) {
|
|
|
6084
6521
|
} else {
|
|
6085
6522
|
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
6086
6523
|
}
|
|
6524
|
+
const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
|
|
6525
|
+
for (const warning2 of opencodeStartTimeoutWarnings) {
|
|
6526
|
+
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
6527
|
+
}
|
|
6087
6528
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
6088
6529
|
try {
|
|
6089
6530
|
const oc = await ensureOpenCodeRunning({
|
|
6090
6531
|
port: state.port,
|
|
6091
6532
|
interactive: state.interactive,
|
|
6092
6533
|
agentId: state.agentId,
|
|
6093
|
-
log: (message) => log2(state, message)
|
|
6534
|
+
log: (message) => log2(state, message),
|
|
6535
|
+
startTimeoutMs: opencodeStartTimeoutMs
|
|
6094
6536
|
});
|
|
6095
6537
|
state.port = oc.port;
|
|
6096
6538
|
state.opencodeProcess = oc.process;
|
|
6097
6539
|
state.opencodeVersion = oc.version;
|
|
6098
|
-
state.opencodeConnected = oc.
|
|
6540
|
+
state.opencodeConnected = oc.notReadyReason === null;
|
|
6099
6541
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
6100
6542
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
6101
|
-
|
|
6102
|
-
|
|
6103
|
-
|
|
6104
|
-
|
|
6105
|
-
|
|
6543
|
+
if (!state.interactive && oc.notReadyReason !== null) {
|
|
6544
|
+
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}).`;
|
|
6545
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6546
|
+
} else {
|
|
6547
|
+
const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
|
|
6548
|
+
if (versionWarning) {
|
|
6549
|
+
log2(state, versionWarning, "warn");
|
|
6550
|
+
if (state.interactive && !state.json) {
|
|
6551
|
+
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
6552
|
+
}
|
|
6106
6553
|
}
|
|
6107
|
-
|
|
6108
|
-
|
|
6109
|
-
|
|
6110
|
-
|
|
6111
|
-
|
|
6112
|
-
|
|
6113
|
-
|
|
6114
|
-
|
|
6115
|
-
|
|
6116
|
-
|
|
6117
|
-
|
|
6118
|
-
|
|
6119
|
-
|
|
6120
|
-
|
|
6554
|
+
const noProviderWarning = buildNoProviderWarning(
|
|
6555
|
+
await hasAnyConfiguredProvider(state.port)
|
|
6556
|
+
);
|
|
6557
|
+
if (noProviderWarning) {
|
|
6558
|
+
log2(state, noProviderWarning, "warn");
|
|
6559
|
+
if (state.interactive && !state.json) {
|
|
6560
|
+
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
6561
|
+
blank();
|
|
6562
|
+
console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
6563
|
+
console.log(
|
|
6564
|
+
chalk6.dim(
|
|
6565
|
+
`Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
6566
|
+
)
|
|
6567
|
+
);
|
|
6568
|
+
blank();
|
|
6569
|
+
}
|
|
6121
6570
|
}
|
|
6122
6571
|
}
|
|
6123
6572
|
} catch (error2) {
|
|
@@ -6135,7 +6584,7 @@ async function run(options) {
|
|
|
6135
6584
|
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
6136
6585
|
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
6137
6586
|
fileSyncDirectories,
|
|
6138
|
-
homeDir:
|
|
6587
|
+
homeDir: homedir3(),
|
|
6139
6588
|
log: (entry) => (
|
|
6140
6589
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
6141
6590
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -6264,6 +6713,7 @@ async function run(options) {
|
|
|
6264
6713
|
throw error2;
|
|
6265
6714
|
}
|
|
6266
6715
|
scheduleSessionCleanup(state, channelDriver, options);
|
|
6716
|
+
scheduleClaudeUsageReporting(state, options);
|
|
6267
6717
|
if (!interactive || state.json) {
|
|
6268
6718
|
log2(state, "Driving channel messages...");
|
|
6269
6719
|
}
|
|
@@ -6318,13 +6768,17 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
6318
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);
|
|
6319
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 }));
|
|
6320
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);
|
|
6321
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(
|
|
6322
6773
|
"-a, --agent [id]",
|
|
6323
6774
|
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
6324
6775
|
).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
6325
6776
|
"--log-level <level>",
|
|
6326
6777
|
"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(
|
|
6778
|
+
).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(
|
|
6779
|
+
"--opencode-start-timeout <seconds>",
|
|
6780
|
+
"Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
|
|
6781
|
+
).option("--json", "Output in JSON format").option(
|
|
6328
6782
|
"--session-cleanup-max-age <duration>",
|
|
6329
6783
|
"Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
|
|
6330
6784
|
).option(
|
|
@@ -6333,6 +6787,9 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
6333
6787
|
).option(
|
|
6334
6788
|
"--session-cleanup-interval <duration>",
|
|
6335
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"
|
|
6336
6793
|
).option(
|
|
6337
6794
|
"--enable-file-sync-to <dir>",
|
|
6338
6795
|
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
@@ -6353,11 +6810,17 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
6353
6810
|
verbose: options.verbose,
|
|
6354
6811
|
conversation: options.conversation,
|
|
6355
6812
|
idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
|
|
6813
|
+
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
6814
|
+
// resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
|
|
6815
|
+
opencodeStartTimeout: options.opencodeStartTimeout,
|
|
6356
6816
|
json: options.json,
|
|
6357
6817
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
6358
6818
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
6359
6819
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
6360
6820
|
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
6821
|
+
// Raw string — the resolver in run.ts single-sources parsing
|
|
6822
|
+
// (resolveClaudeUsageReportingMode).
|
|
6823
|
+
claudeUsageReporting: options.claudeUsageReporting,
|
|
6361
6824
|
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
6362
6825
|
// resolveFileSyncDirectories.
|
|
6363
6826
|
enableFileSyncTo: options.enableFileSyncTo,
|