@evident-ai/cli 3.1.1-dev.0d1732f → 3.1.1-dev.0ff9c93
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -0
- package/dist/index.js +874 -123
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -267,16 +267,28 @@ async function getToken() {
|
|
|
267
267
|
}
|
|
268
268
|
return null;
|
|
269
269
|
}
|
|
270
|
+
function toError(err) {
|
|
271
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
272
|
+
}
|
|
270
273
|
async function deleteToken(options = {}) {
|
|
271
274
|
const keytar = await getKeytar();
|
|
275
|
+
const failures = [];
|
|
272
276
|
if (keytar) {
|
|
273
277
|
if (options.all) {
|
|
274
|
-
|
|
278
|
+
let accounts = [];
|
|
279
|
+
try {
|
|
280
|
+
accounts = await keytar.findCredentials(SERVICE_NAME);
|
|
281
|
+
} catch (err) {
|
|
282
|
+
failures.push({ type: "enumerate", error: toError(err) });
|
|
283
|
+
}
|
|
275
284
|
await Promise.all(
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
285
|
+
accounts.map(async (entry) => {
|
|
286
|
+
try {
|
|
287
|
+
await keytar.deletePassword(SERVICE_NAME, entry.account);
|
|
288
|
+
} catch (err) {
|
|
289
|
+
failures.push({ type: "delete", account: entry.account, error: toError(err) });
|
|
290
|
+
}
|
|
291
|
+
})
|
|
280
292
|
);
|
|
281
293
|
} else {
|
|
282
294
|
await keytar.deletePassword(SERVICE_NAME, keychainAccount());
|
|
@@ -287,6 +299,7 @@ async function deleteToken(options = {}) {
|
|
|
287
299
|
} else {
|
|
288
300
|
clearCredentials();
|
|
289
301
|
}
|
|
302
|
+
return { failures };
|
|
290
303
|
}
|
|
291
304
|
|
|
292
305
|
// src/utils/ui.ts
|
|
@@ -404,8 +417,10 @@ async function deviceFlowLogin(options) {
|
|
|
404
417
|
}
|
|
405
418
|
async function tokenLogin() {
|
|
406
419
|
console.log("Token login mode.");
|
|
407
|
-
console.log("
|
|
408
|
-
console.log(
|
|
420
|
+
console.log("Create a token under Settings \u2192 CLI tokens in the dashboard, then paste it below.");
|
|
421
|
+
console.log(
|
|
422
|
+
"(Alternatively, run `evident login` on a machine with a browser, or set EVIDENT_TOKEN for CI.)"
|
|
423
|
+
);
|
|
409
424
|
blank();
|
|
410
425
|
process.stdout.write("Paste token: ");
|
|
411
426
|
const token = await new Promise((resolve3) => {
|
|
@@ -429,13 +444,22 @@ async function tokenLogin() {
|
|
|
429
444
|
printError("No token provided.");
|
|
430
445
|
process.exit(1);
|
|
431
446
|
}
|
|
447
|
+
await validateAndStoreToken(token);
|
|
448
|
+
}
|
|
449
|
+
async function validateAndStoreToken(token) {
|
|
432
450
|
const spinner = ora("Validating token...").start();
|
|
433
451
|
try {
|
|
434
|
-
const result = await api.
|
|
452
|
+
const result = await api.get("/me", {
|
|
453
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
454
|
+
});
|
|
455
|
+
if (!result.user) {
|
|
456
|
+
throw new Error(
|
|
457
|
+
"This token is not a user login (e.g. a runner key). Paste a CLI token instead."
|
|
458
|
+
);
|
|
459
|
+
}
|
|
435
460
|
await storeToken({
|
|
436
461
|
token,
|
|
437
|
-
user: result.user
|
|
438
|
-
expiresAt: result.expires_at
|
|
462
|
+
user: { email: result.user.email }
|
|
439
463
|
});
|
|
440
464
|
spinner.stop();
|
|
441
465
|
printSuccess(`Logged in as ${chalk2.bold(result.user.email)}`);
|
|
@@ -455,9 +479,22 @@ async function login(options) {
|
|
|
455
479
|
}
|
|
456
480
|
|
|
457
481
|
// src/commands/logout.ts
|
|
482
|
+
function describeFailure(failure) {
|
|
483
|
+
if (failure.type === "enumerate") {
|
|
484
|
+
return `could not list stored keychain entries (${failure.error.message})`;
|
|
485
|
+
}
|
|
486
|
+
return `${failure.account} (${failure.error.message})`;
|
|
487
|
+
}
|
|
458
488
|
async function logout(options = {}) {
|
|
459
489
|
if (options.all) {
|
|
460
|
-
await deleteToken({ all: true });
|
|
490
|
+
const result = await deleteToken({ all: true });
|
|
491
|
+
if (result.failures.length > 0) {
|
|
492
|
+
printError(
|
|
493
|
+
`Failed to fully clear your keychain: ${result.failures.map(describeFailure).join("; ")}. Your local credentials file was cleared, but stale keychain entries may remain \u2014 run \`evident logout --all\` again, or remove them manually from your OS keychain / credential manager.`
|
|
494
|
+
);
|
|
495
|
+
process.exitCode = 1;
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
461
498
|
printSuccess("Logged out of all endpoints.");
|
|
462
499
|
return;
|
|
463
500
|
}
|
|
@@ -482,7 +519,9 @@ async function whoami() {
|
|
|
482
519
|
blank();
|
|
483
520
|
console.log(keyValue("Endpoint", apiUrl));
|
|
484
521
|
console.log(keyValue("User", chalk3.bold(credentials2.user.email)));
|
|
485
|
-
|
|
522
|
+
if (credentials2.user.id) {
|
|
523
|
+
console.log(keyValue("User ID", credentials2.user.id));
|
|
524
|
+
}
|
|
486
525
|
if (credentials2.expiresAt) {
|
|
487
526
|
const expiresAt = new Date(credentials2.expiresAt);
|
|
488
527
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -498,9 +537,124 @@ async function whoami() {
|
|
|
498
537
|
blank();
|
|
499
538
|
}
|
|
500
539
|
|
|
540
|
+
// src/lib/claude-usage.ts
|
|
541
|
+
import { execFileSync } from "child_process";
|
|
542
|
+
import { readFileSync } from "fs";
|
|
543
|
+
import { homedir } from "os";
|
|
544
|
+
import { join } from "path";
|
|
545
|
+
var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
546
|
+
var KEYCHAIN_SERVICE = "Claude Code-credentials";
|
|
547
|
+
function parseClaudeCliCredentials(raw) {
|
|
548
|
+
let parsed;
|
|
549
|
+
try {
|
|
550
|
+
parsed = JSON.parse(raw);
|
|
551
|
+
} catch {
|
|
552
|
+
return null;
|
|
553
|
+
}
|
|
554
|
+
const data = parsed.claudeAiOauth ?? parsed;
|
|
555
|
+
const creds = data;
|
|
556
|
+
if (typeof creds.accessToken !== "string" || typeof creds.expiresAt !== "number") {
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
return { accessToken: creds.accessToken, expiresAt: creds.expiresAt };
|
|
560
|
+
}
|
|
561
|
+
function readClaudeCliCredentials() {
|
|
562
|
+
if (process.platform === "darwin") {
|
|
563
|
+
try {
|
|
564
|
+
const raw = execFileSync(
|
|
565
|
+
"/usr/bin/security",
|
|
566
|
+
["find-generic-password", "-s", KEYCHAIN_SERVICE, "-w"],
|
|
567
|
+
{ encoding: "utf-8", timeout: 2e3, stdio: ["pipe", "pipe", "ignore"] }
|
|
568
|
+
);
|
|
569
|
+
return parseClaudeCliCredentials(raw);
|
|
570
|
+
} catch {
|
|
571
|
+
return null;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
try {
|
|
575
|
+
const raw = readFileSync(join(homedir(), ".claude", ".credentials.json"), "utf-8");
|
|
576
|
+
return parseClaudeCliCredentials(raw);
|
|
577
|
+
} catch {
|
|
578
|
+
return null;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
var ClaudeUsageError = class extends Error {
|
|
582
|
+
constructor(message, reason) {
|
|
583
|
+
super(message);
|
|
584
|
+
this.reason = reason;
|
|
585
|
+
}
|
|
586
|
+
};
|
|
587
|
+
function isLocalCredentialProblem(err) {
|
|
588
|
+
return err instanceof ClaudeUsageError && (err.reason === "no_credentials" || err.reason === "credentials_expired");
|
|
589
|
+
}
|
|
590
|
+
function toWindow(value) {
|
|
591
|
+
if (!value || typeof value !== "object") {
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
const window = value;
|
|
595
|
+
if (typeof window.utilization !== "number" || typeof window.resets_at !== "string") {
|
|
596
|
+
return null;
|
|
597
|
+
}
|
|
598
|
+
return { utilization: window.utilization, resetsAt: window.resets_at };
|
|
599
|
+
}
|
|
600
|
+
async function getClaudeUsage() {
|
|
601
|
+
const credentials2 = readClaudeCliCredentials();
|
|
602
|
+
if (!credentials2) {
|
|
603
|
+
throw new ClaudeUsageError(
|
|
604
|
+
"No local Claude Code login found. Run `claude` once to sign in with your Claude subscription.",
|
|
605
|
+
"no_credentials"
|
|
606
|
+
);
|
|
607
|
+
}
|
|
608
|
+
if (credentials2.expiresAt < Date.now()) {
|
|
609
|
+
throw new ClaudeUsageError(
|
|
610
|
+
"Claude Code credentials have expired. Run `claude` to refresh them.",
|
|
611
|
+
"credentials_expired"
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
const res = await fetch(CLAUDE_USAGE_URL, {
|
|
615
|
+
headers: {
|
|
616
|
+
Authorization: `Bearer ${credentials2.accessToken}`,
|
|
617
|
+
"Content-Type": "application/json",
|
|
618
|
+
"anthropic-version": "2023-06-01"
|
|
619
|
+
}
|
|
620
|
+
});
|
|
621
|
+
if (!res.ok) {
|
|
622
|
+
throw new ClaudeUsageError(`Claude usage request failed: HTTP ${res.status}`, "request_failed");
|
|
623
|
+
}
|
|
624
|
+
const body = await res.json();
|
|
625
|
+
return {
|
|
626
|
+
fiveHour: toWindow(body.five_hour),
|
|
627
|
+
sevenDay: toWindow(body.seven_day)
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// src/commands/claude-usage.ts
|
|
632
|
+
function formatWindow(label, window) {
|
|
633
|
+
if (!window) {
|
|
634
|
+
return keyValue(label, "not available for this plan");
|
|
635
|
+
}
|
|
636
|
+
const resetsAt = new Date(window.resetsAt);
|
|
637
|
+
return keyValue(label, `${window.utilization}% used, resets ${resetsAt.toLocaleString()}`);
|
|
638
|
+
}
|
|
639
|
+
async function claudeUsage() {
|
|
640
|
+
try {
|
|
641
|
+
const usage = await getClaudeUsage();
|
|
642
|
+
blank();
|
|
643
|
+
console.log(formatWindow("5-hour session", usage.fiveHour));
|
|
644
|
+
console.log(formatWindow("7-day", usage.sevenDay));
|
|
645
|
+
blank();
|
|
646
|
+
} catch (err) {
|
|
647
|
+
if (err instanceof ClaudeUsageError) {
|
|
648
|
+
printError(err.message);
|
|
649
|
+
process.exit(1);
|
|
650
|
+
}
|
|
651
|
+
throw err;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
501
655
|
// src/commands/run.ts
|
|
502
|
-
import { homedir as
|
|
503
|
-
import { isAbsolute as isAbsolute2, join as
|
|
656
|
+
import { homedir as homedir3 } from "os";
|
|
657
|
+
import { isAbsolute as isAbsolute2, join as join3, parse, resolve as resolvePath } from "path";
|
|
504
658
|
import chalk6 from "chalk";
|
|
505
659
|
|
|
506
660
|
// ../../packages/types/src/telemetry/index.ts
|
|
@@ -510,7 +664,10 @@ var TelemetryEventTypes = {
|
|
|
510
664
|
AGENT_DISCONNECTED: "agent.disconnected",
|
|
511
665
|
AGENT_MESSAGE_PROCESSING: "agent.message_processing",
|
|
512
666
|
AGENT_MESSAGE_DONE: "agent.message_done",
|
|
513
|
-
AGENT_MESSAGE_FAILED: "agent.message_failed"
|
|
667
|
+
AGENT_MESSAGE_FAILED: "agent.message_failed",
|
|
668
|
+
// A `warn`/`error` runner-side log line forwarded server-side for
|
|
669
|
+
// observability (issue #916) — see `apps/cli/src/lib/runner-activity-telemetry.ts`.
|
|
670
|
+
RUNNER_ACTIVITY: "runner.activity"
|
|
514
671
|
};
|
|
515
672
|
|
|
516
673
|
// ../../packages/types/src/tunnel/index.ts
|
|
@@ -565,6 +722,13 @@ var isShuttingDown = false;
|
|
|
565
722
|
var FLUSH_INTERVAL_MS = 5e3;
|
|
566
723
|
var MAX_BUFFER_SIZE = 50;
|
|
567
724
|
var FLUSH_TIMEOUT_MS = 3e3;
|
|
725
|
+
var authProvider = null;
|
|
726
|
+
function setTelemetryAuthProvider(provider) {
|
|
727
|
+
authProvider = provider;
|
|
728
|
+
}
|
|
729
|
+
var FLUSH_FAILURE_LOG_INTERVAL_MS = 6e4;
|
|
730
|
+
var lastFlushFailureLoggedAt = 0;
|
|
731
|
+
var suppressedFlushFailureCount = 0;
|
|
568
732
|
function logEvent(eventType, options = {}) {
|
|
569
733
|
const event = {
|
|
570
734
|
event_type: eventType,
|
|
@@ -599,9 +763,16 @@ async function flushEvents() {
|
|
|
599
763
|
flushTimeout = null;
|
|
600
764
|
}
|
|
601
765
|
try {
|
|
602
|
-
const
|
|
603
|
-
|
|
604
|
-
|
|
766
|
+
const providerContext = authProvider?.();
|
|
767
|
+
let authHeader;
|
|
768
|
+
if (providerContext?.authHeader) {
|
|
769
|
+
authHeader = providerContext.authHeader;
|
|
770
|
+
} else {
|
|
771
|
+
const credentials2 = await getToken();
|
|
772
|
+
if (!credentials2) {
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
authHeader = `Bearer ${credentials2.token}`;
|
|
605
776
|
}
|
|
606
777
|
const apiUrl = getApiUrlConfig();
|
|
607
778
|
const controller = new AbortController();
|
|
@@ -616,7 +787,7 @@ async function flushEvents() {
|
|
|
616
787
|
method: "POST",
|
|
617
788
|
headers: {
|
|
618
789
|
"Content-Type": "application/json",
|
|
619
|
-
Authorization:
|
|
790
|
+
Authorization: authHeader
|
|
620
791
|
},
|
|
621
792
|
body: JSON.stringify(request),
|
|
622
793
|
signal: controller.signal
|
|
@@ -628,8 +799,15 @@ async function flushEvents() {
|
|
|
628
799
|
clearTimeout(timeout);
|
|
629
800
|
}
|
|
630
801
|
} catch (error2) {
|
|
631
|
-
|
|
632
|
-
|
|
802
|
+
const now = Date.now();
|
|
803
|
+
if (now - lastFlushFailureLoggedAt >= FLUSH_FAILURE_LOG_INTERVAL_MS) {
|
|
804
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
805
|
+
const suffix = suppressedFlushFailureCount > 0 ? ` (${suppressedFlushFailureCount} more suppressed in the last ${FLUSH_FAILURE_LOG_INTERVAL_MS / 1e3}s)` : "";
|
|
806
|
+
console.error(`Telemetry flush error: ${message}${suffix}`);
|
|
807
|
+
lastFlushFailureLoggedAt = now;
|
|
808
|
+
suppressedFlushFailureCount = 0;
|
|
809
|
+
} else {
|
|
810
|
+
suppressedFlushFailureCount++;
|
|
633
811
|
}
|
|
634
812
|
}
|
|
635
813
|
}
|
|
@@ -698,6 +876,69 @@ var EventTypes = {
|
|
|
698
876
|
DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
|
|
699
877
|
};
|
|
700
878
|
|
|
879
|
+
// src/lib/runner-activity-telemetry.ts
|
|
880
|
+
var FORWARDED_LEVELS = /* @__PURE__ */ new Set(["warn", "error"]);
|
|
881
|
+
var SEVERITY_BY_LEVEL = {
|
|
882
|
+
warn: "warning",
|
|
883
|
+
error: "error"
|
|
884
|
+
};
|
|
885
|
+
var MAX_MESSAGE_LENGTH = 500;
|
|
886
|
+
var TRUNCATION_MARKER = "\u2026";
|
|
887
|
+
function redact(message) {
|
|
888
|
+
return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
|
|
889
|
+
}
|
|
890
|
+
function truncate(message) {
|
|
891
|
+
if (message.length <= MAX_MESSAGE_LENGTH) return message;
|
|
892
|
+
return message.slice(0, MAX_MESSAGE_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
|
|
893
|
+
}
|
|
894
|
+
var RATE_LIMIT_WINDOW_MS = 6e4;
|
|
895
|
+
var RATE_LIMIT_MAX_EVENTS = 30;
|
|
896
|
+
var windowStartedAt = 0;
|
|
897
|
+
var windowCount = 0;
|
|
898
|
+
var windowDroppedCount = 0;
|
|
899
|
+
function admitUnderRateLimit(now) {
|
|
900
|
+
if (now - windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
|
|
901
|
+
if (windowDroppedCount > 0) {
|
|
902
|
+
console.error(
|
|
903
|
+
`[runner-activity-telemetry] rate cap reached: dropped ${windowDroppedCount} ${windowDroppedCount === 1 ? "entry" : "entries"} in the last ${RATE_LIMIT_WINDOW_MS / 1e3}s (cap ${RATE_LIMIT_MAX_EVENTS}/min)`
|
|
904
|
+
);
|
|
905
|
+
}
|
|
906
|
+
windowStartedAt = now;
|
|
907
|
+
windowCount = 0;
|
|
908
|
+
windowDroppedCount = 0;
|
|
909
|
+
}
|
|
910
|
+
if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
|
|
911
|
+
windowDroppedCount++;
|
|
912
|
+
if (windowDroppedCount === 1) {
|
|
913
|
+
console.error(
|
|
914
|
+
`[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
|
|
915
|
+
);
|
|
916
|
+
}
|
|
917
|
+
return false;
|
|
918
|
+
}
|
|
919
|
+
windowCount++;
|
|
920
|
+
return true;
|
|
921
|
+
}
|
|
922
|
+
function forwardRunnerActivity(entry, context) {
|
|
923
|
+
try {
|
|
924
|
+
if (!FORWARDED_LEVELS.has(entry.level)) return;
|
|
925
|
+
if (!context.agentId || !context.authHeader) return;
|
|
926
|
+
if (!admitUnderRateLimit(Date.now())) return;
|
|
927
|
+
const rawMessage = entry.error ?? entry.message ?? "";
|
|
928
|
+
const message = truncate(redact(rawMessage));
|
|
929
|
+
logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
|
|
930
|
+
severity: SEVERITY_BY_LEVEL[entry.level],
|
|
931
|
+
message,
|
|
932
|
+
metadata: { source: "cli.run" },
|
|
933
|
+
agentId: context.agentId
|
|
934
|
+
});
|
|
935
|
+
} catch (err) {
|
|
936
|
+
console.error(
|
|
937
|
+
`[runner-activity-telemetry] failed to forward runner activity: ${err instanceof Error ? err.message : String(err)}`
|
|
938
|
+
);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
|
|
701
942
|
// src/lib/auth.ts
|
|
702
943
|
async function getAuthCredentials() {
|
|
703
944
|
const runnerKey = process.env.EVIDENT_RUNNER_KEY;
|
|
@@ -1532,6 +1773,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
|
|
|
1532
1773
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1533
1774
|
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
1534
1775
|
}
|
|
1776
|
+
function isB2AbandonmentConfirmed(params) {
|
|
1777
|
+
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
|
|
1778
|
+
}
|
|
1535
1779
|
function messageError(messages, userMessageId) {
|
|
1536
1780
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1537
1781
|
const error2 = errorOf(reply);
|
|
@@ -1545,6 +1789,42 @@ function messageError(messages, userMessageId) {
|
|
|
1545
1789
|
}
|
|
1546
1790
|
return "The agent run failed.";
|
|
1547
1791
|
}
|
|
1792
|
+
function messageFailure(messages, userMessageId) {
|
|
1793
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1794
|
+
const error2 = errorOf(reply);
|
|
1795
|
+
if (error2 == null || typeof error2 !== "object") return null;
|
|
1796
|
+
const e = error2;
|
|
1797
|
+
const replyProviderId = reply?.info?.providerID ?? null;
|
|
1798
|
+
const replyModelId = reply?.info?.modelID ?? null;
|
|
1799
|
+
if (e.name === "ProviderAuthError") {
|
|
1800
|
+
const data = e.data;
|
|
1801
|
+
const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
|
|
1802
|
+
return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
|
|
1803
|
+
}
|
|
1804
|
+
if (e.name === "APIError") {
|
|
1805
|
+
const data = e.data;
|
|
1806
|
+
const statusCode = data?.statusCode;
|
|
1807
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
1808
|
+
return {
|
|
1809
|
+
kind: "model_auth",
|
|
1810
|
+
providerId: replyProviderId,
|
|
1811
|
+
modelId: replyModelId,
|
|
1812
|
+
reason: "rejected"
|
|
1813
|
+
};
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
return null;
|
|
1817
|
+
}
|
|
1818
|
+
function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
|
|
1819
|
+
if (classified != null) return classified;
|
|
1820
|
+
if (hasConfiguredProvider !== false) return null;
|
|
1821
|
+
return {
|
|
1822
|
+
kind: "model_auth",
|
|
1823
|
+
providerId: replyProviderId,
|
|
1824
|
+
modelId: replyModelId,
|
|
1825
|
+
reason: "missing"
|
|
1826
|
+
};
|
|
1827
|
+
}
|
|
1548
1828
|
function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
1549
1829
|
if (!messages || messages.length === 0) return false;
|
|
1550
1830
|
return messages.some(
|
|
@@ -2073,13 +2353,52 @@ var RunnerConnection = class {
|
|
|
2073
2353
|
}
|
|
2074
2354
|
};
|
|
2075
2355
|
|
|
2356
|
+
// src/lib/tunnel/ready-marker.ts
|
|
2357
|
+
import { writeFileSync } from "fs";
|
|
2358
|
+
function writeTunnelReadyMarker(path, agentId) {
|
|
2359
|
+
try {
|
|
2360
|
+
writeFileSync(path, `${agentId}
|
|
2361
|
+
`);
|
|
2362
|
+
return { ok: true };
|
|
2363
|
+
} catch (error2) {
|
|
2364
|
+
return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
|
|
2368
|
+
// src/lib/claude-usage-reporting.ts
|
|
2369
|
+
var VALID_MODES = ["auto", "on", "off"];
|
|
2370
|
+
function resolveClaudeUsageReportingMode(flagValue, env) {
|
|
2371
|
+
const raw = flagValue ?? env.EVIDENT_CLAUDE_USAGE_REPORTING;
|
|
2372
|
+
if (raw === void 0 || raw === "") {
|
|
2373
|
+
return { mode: "auto", warnings: [] };
|
|
2374
|
+
}
|
|
2375
|
+
const normalized = raw.trim().toLowerCase();
|
|
2376
|
+
if (VALID_MODES.includes(normalized)) {
|
|
2377
|
+
return { mode: normalized, warnings: [] };
|
|
2378
|
+
}
|
|
2379
|
+
const source = flagValue !== void 0 ? "--claude-usage-reporting" : "EVIDENT_CLAUDE_USAGE_REPORTING";
|
|
2380
|
+
return {
|
|
2381
|
+
mode: "auto",
|
|
2382
|
+
warnings: [
|
|
2383
|
+
`Ignoring invalid ${source} "${raw}": expected one of ${VALID_MODES.join(", ")}; using auto`
|
|
2384
|
+
]
|
|
2385
|
+
};
|
|
2386
|
+
}
|
|
2387
|
+
var BASE_REPORT_DELAY_MS = 10 * 6e4;
|
|
2388
|
+
var REPORT_DELAY_JITTER_FRACTION = 0.2;
|
|
2389
|
+
function nextReportDelayMs(random = Math.random) {
|
|
2390
|
+
const jitterRangeMs = BASE_REPORT_DELAY_MS * REPORT_DELAY_JITTER_FRACTION;
|
|
2391
|
+
return BASE_REPORT_DELAY_MS - jitterRangeMs + random() * (2 * jitterRangeMs);
|
|
2392
|
+
}
|
|
2393
|
+
var FIRST_REPORT_DELAY_MS = 5e3 + Math.random() * 1e4;
|
|
2394
|
+
|
|
2076
2395
|
// src/lib/channels/driver.ts
|
|
2077
|
-
import { homedir } from "os";
|
|
2396
|
+
import { homedir as homedir2 } from "os";
|
|
2078
2397
|
|
|
2079
2398
|
// src/lib/file-push.ts
|
|
2080
2399
|
import { randomUUID } from "crypto";
|
|
2081
2400
|
import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
|
|
2082
|
-
import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
|
|
2401
|
+
import { basename, dirname as dirname2, isAbsolute, join as join2, relative, resolve as resolve2, sep } from "path";
|
|
2083
2402
|
var FILE_MODE = 384;
|
|
2084
2403
|
var DIRECTORY_MODE = 448;
|
|
2085
2404
|
async function writePushedFile(request) {
|
|
@@ -2112,7 +2431,7 @@ async function writePushedFile(request) {
|
|
|
2112
2431
|
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2113
2432
|
dirname2(candidate)
|
|
2114
2433
|
);
|
|
2115
|
-
const realTarget =
|
|
2434
|
+
const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
|
|
2116
2435
|
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2117
2436
|
if (allowedDirectory === null) {
|
|
2118
2437
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
@@ -2148,7 +2467,7 @@ function expandAndValidate(requestedPath, homeDir) {
|
|
|
2148
2467
|
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2149
2468
|
return null;
|
|
2150
2469
|
}
|
|
2151
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
2470
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join2(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2152
2471
|
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2153
2472
|
return null;
|
|
2154
2473
|
}
|
|
@@ -2221,13 +2540,13 @@ function contains(realDirectory, realTarget) {
|
|
|
2221
2540
|
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2222
2541
|
let current = existingAncestor;
|
|
2223
2542
|
for (const segment of missingSegments) {
|
|
2224
|
-
current =
|
|
2543
|
+
current = join2(current, segment);
|
|
2225
2544
|
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2226
2545
|
await chmod(current, DIRECTORY_MODE);
|
|
2227
2546
|
}
|
|
2228
2547
|
}
|
|
2229
2548
|
async function writeAtomically(realTarget, content) {
|
|
2230
|
-
const temporaryPath =
|
|
2549
|
+
const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2231
2550
|
let handle;
|
|
2232
2551
|
try {
|
|
2233
2552
|
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
@@ -2499,6 +2818,8 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
|
2499
2818
|
var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
2500
2819
|
var HEARTBEAT_MS = 6e4;
|
|
2501
2820
|
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
2821
|
+
var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
|
|
2822
|
+
var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
|
|
2502
2823
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2503
2824
|
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
2504
2825
|
var ChannelAuthError = class extends Error {
|
|
@@ -2740,7 +3061,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2740
3061
|
this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
2741
3062
|
this.now = config2.now ?? (() => Date.now());
|
|
2742
3063
|
this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
|
|
2743
|
-
this.homeDir = config2.homeDir ??
|
|
3064
|
+
this.homeDir = config2.homeDir ?? homedir2();
|
|
2744
3065
|
}
|
|
2745
3066
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2746
3067
|
get opencodeBase() {
|
|
@@ -3125,7 +3446,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3125
3446
|
const directory = await this.resolveOpenCodeDirectory();
|
|
3126
3447
|
const sessionId = await createOpenCodeSession(this.port, directory);
|
|
3127
3448
|
this.sessions.set(conversationId, sessionId);
|
|
3128
|
-
await this.persistSession(conversationId, sessionId).catch(() => {
|
|
3449
|
+
await this.persistSession(conversationId, sessionId).catch((err) => {
|
|
3450
|
+
this.log({
|
|
3451
|
+
level: "warn",
|
|
3452
|
+
message: `Persisting the OpenCode session binding ${sessionId.slice(0, 8)} for conversation ${conversationId.slice(0, 8)} failed (best-effort, not retried) \u2014 the completion PATCH also carries opencode_session_id, so the binding is repaired when the turn finishes: ${err instanceof Error ? err.message : String(err)}`,
|
|
3453
|
+
conversation_id: conversationId
|
|
3454
|
+
});
|
|
3129
3455
|
});
|
|
3130
3456
|
return sessionId;
|
|
3131
3457
|
}
|
|
@@ -3324,7 +3650,10 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3324
3650
|
pausedOnPermission: false,
|
|
3325
3651
|
pausedClearConfirmed: false,
|
|
3326
3652
|
pausedInFlight: false,
|
|
3327
|
-
deliveryDeadlineAnchored: false
|
|
3653
|
+
deliveryDeadlineAnchored: false,
|
|
3654
|
+
b2PinnedSinceMs: 0,
|
|
3655
|
+
b2LastDescendantCheckMs: 0,
|
|
3656
|
+
b2AbandonedSignalled: false
|
|
3328
3657
|
});
|
|
3329
3658
|
}
|
|
3330
3659
|
/**
|
|
@@ -3399,7 +3728,10 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3399
3728
|
pausedOnPermission: false,
|
|
3400
3729
|
pausedClearConfirmed: false,
|
|
3401
3730
|
pausedInFlight: false,
|
|
3402
|
-
deliveryDeadlineAnchored: false
|
|
3731
|
+
deliveryDeadlineAnchored: false,
|
|
3732
|
+
b2PinnedSinceMs: 0,
|
|
3733
|
+
b2LastDescendantCheckMs: 0,
|
|
3734
|
+
b2AbandonedSignalled: false
|
|
3403
3735
|
});
|
|
3404
3736
|
}
|
|
3405
3737
|
/**
|
|
@@ -3561,58 +3893,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3561
3893
|
}
|
|
3562
3894
|
}
|
|
3563
3895
|
if (state === "done") {
|
|
3564
|
-
this.
|
|
3565
|
-
if (!inFlight.done) {
|
|
3566
|
-
this.log({
|
|
3567
|
-
level: "info",
|
|
3568
|
-
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
3569
|
-
conversation_id: conv.id,
|
|
3570
|
-
message_id: inFlight.evidentMessageId
|
|
3571
|
-
});
|
|
3572
|
-
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
3573
|
-
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3574
|
-
try {
|
|
3575
|
-
await this.markDone(
|
|
3576
|
-
conv.id,
|
|
3577
|
-
inFlight.evidentMessageId,
|
|
3578
|
-
sessionId,
|
|
3579
|
-
inFlight.opencodeMessageId,
|
|
3580
|
-
title,
|
|
3581
|
-
usage
|
|
3582
|
-
);
|
|
3583
|
-
} catch (err) {
|
|
3584
|
-
if (err instanceof ChannelAuthError) throw err;
|
|
3585
|
-
if (err instanceof ChannelTerminalError) {
|
|
3586
|
-
this.log({
|
|
3587
|
-
level: "warn",
|
|
3588
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
3589
|
-
conversation_id: conv.id,
|
|
3590
|
-
message_id: inFlight.evidentMessageId
|
|
3591
|
-
});
|
|
3592
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3593
|
-
return;
|
|
3594
|
-
}
|
|
3595
|
-
if (this.now() >= inFlight.deadline) {
|
|
3596
|
-
this.log({
|
|
3597
|
-
level: "warn",
|
|
3598
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done within the watch window \u2014 leaving for the cron safety net: ${err instanceof Error ? err.message : String(err)}`,
|
|
3599
|
-
conversation_id: conv.id,
|
|
3600
|
-
message_id: inFlight.evidentMessageId
|
|
3601
|
-
});
|
|
3602
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3603
|
-
return;
|
|
3604
|
-
}
|
|
3605
|
-
this.log({
|
|
3606
|
-
level: "warn",
|
|
3607
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
3608
|
-
conversation_id: conv.id,
|
|
3609
|
-
message_id: inFlight.evidentMessageId
|
|
3610
|
-
});
|
|
3611
|
-
return;
|
|
3612
|
-
}
|
|
3613
|
-
inFlight.done = true;
|
|
3614
|
-
}
|
|
3615
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3896
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3616
3897
|
return;
|
|
3617
3898
|
}
|
|
3618
3899
|
if (state === "failed") {
|
|
@@ -3626,8 +3907,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3626
3907
|
message_id: inFlight.evidentMessageId
|
|
3627
3908
|
});
|
|
3628
3909
|
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3910
|
+
const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
|
|
3629
3911
|
try {
|
|
3630
|
-
await this.markFailed(
|
|
3912
|
+
await this.markFailed(
|
|
3913
|
+
conv.id,
|
|
3914
|
+
inFlight.evidentMessageId,
|
|
3915
|
+
sessionId,
|
|
3916
|
+
error2,
|
|
3917
|
+
usage,
|
|
3918
|
+
failure
|
|
3919
|
+
);
|
|
3631
3920
|
} catch (err) {
|
|
3632
3921
|
if (err instanceof ChannelAuthError) throw err;
|
|
3633
3922
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3672,6 +3961,44 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3672
3961
|
});
|
|
3673
3962
|
}
|
|
3674
3963
|
const activelyRunning = state === "running" && !awaitingHuman;
|
|
3964
|
+
const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
|
|
3965
|
+
const snapshotReadable = messages != null && messages.length > 0;
|
|
3966
|
+
if (!pinnedNow) {
|
|
3967
|
+
if (snapshotReadable) {
|
|
3968
|
+
inFlight.b2PinnedSinceMs = 0;
|
|
3969
|
+
inFlight.b2LastDescendantCheckMs = 0;
|
|
3970
|
+
inFlight.b2AbandonedSignalled = false;
|
|
3971
|
+
}
|
|
3972
|
+
} else {
|
|
3973
|
+
if (inFlight.b2AbandonedSignalled) {
|
|
3974
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3975
|
+
return;
|
|
3976
|
+
}
|
|
3977
|
+
if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
|
|
3978
|
+
const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
|
|
3979
|
+
if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
|
|
3980
|
+
inFlight.b2LastDescendantCheckMs = this.now();
|
|
3981
|
+
const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
|
|
3982
|
+
if (isB2AbandonmentConfirmed({
|
|
3983
|
+
pinnedForMs,
|
|
3984
|
+
minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
|
|
3985
|
+
descendantOngoing
|
|
3986
|
+
})) {
|
|
3987
|
+
inFlight.b2AbandonedSignalled = true;
|
|
3988
|
+
this.log({
|
|
3989
|
+
level: "warn",
|
|
3990
|
+
message: `Message ${id.slice(0, 8)} b2-pinned for ${Math.round(pinnedForMs / 1e3)}s with no ongoing descendant sub-agent session (status-map confirmed) \u2014 treating the delegated/tool turn as abandoned, resolving done`,
|
|
3991
|
+
conversation_id: conv.id,
|
|
3992
|
+
message_id: id
|
|
3993
|
+
});
|
|
3994
|
+
void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
|
|
3995
|
+
watched_for_ms: pinnedForMs
|
|
3996
|
+
});
|
|
3997
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3998
|
+
return;
|
|
3999
|
+
}
|
|
4000
|
+
}
|
|
4001
|
+
}
|
|
3675
4002
|
if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
|
|
3676
4003
|
this.log({
|
|
3677
4004
|
level: "warn",
|
|
@@ -3740,6 +4067,70 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3740
4067
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3741
4068
|
}
|
|
3742
4069
|
}
|
|
4070
|
+
/**
|
|
4071
|
+
* Settle a message whose run-state has resolved `'done'` — extracted verbatim
|
|
4072
|
+
* (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
|
|
4073
|
+
* inline `state === 'done'` branch body, so a SECOND caller (the #721
|
|
4074
|
+
* b2-abandonment resolution) can reach the exact same completion behavior
|
|
4075
|
+
* (delivery-deadline anchoring, title resolution, usage extraction, and
|
|
4076
|
+
* `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
|
|
4077
|
+
* and risking the two copies silently drifting apart.
|
|
4078
|
+
*/
|
|
4079
|
+
async settleMessageDone(sessionId, watcher, inFlight, messages) {
|
|
4080
|
+
const conv = watcher.conv;
|
|
4081
|
+
this.anchorDeliveryDeadline(inFlight);
|
|
4082
|
+
if (!inFlight.done) {
|
|
4083
|
+
this.log({
|
|
4084
|
+
level: "info",
|
|
4085
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
4086
|
+
conversation_id: conv.id,
|
|
4087
|
+
message_id: inFlight.evidentMessageId
|
|
4088
|
+
});
|
|
4089
|
+
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
4090
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
4091
|
+
try {
|
|
4092
|
+
await this.markDone(
|
|
4093
|
+
conv.id,
|
|
4094
|
+
inFlight.evidentMessageId,
|
|
4095
|
+
sessionId,
|
|
4096
|
+
inFlight.opencodeMessageId,
|
|
4097
|
+
title,
|
|
4098
|
+
usage
|
|
4099
|
+
);
|
|
4100
|
+
} catch (err) {
|
|
4101
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
4102
|
+
if (err instanceof ChannelTerminalError) {
|
|
4103
|
+
this.log({
|
|
4104
|
+
level: "warn",
|
|
4105
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
4106
|
+
conversation_id: conv.id,
|
|
4107
|
+
message_id: inFlight.evidentMessageId
|
|
4108
|
+
});
|
|
4109
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4110
|
+
return;
|
|
4111
|
+
}
|
|
4112
|
+
if (this.now() >= inFlight.deadline) {
|
|
4113
|
+
this.log({
|
|
4114
|
+
level: "warn",
|
|
4115
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done within the watch window \u2014 leaving for the cron safety net: ${err instanceof Error ? err.message : String(err)}`,
|
|
4116
|
+
conversation_id: conv.id,
|
|
4117
|
+
message_id: inFlight.evidentMessageId
|
|
4118
|
+
});
|
|
4119
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4120
|
+
return;
|
|
4121
|
+
}
|
|
4122
|
+
this.log({
|
|
4123
|
+
level: "warn",
|
|
4124
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
4125
|
+
conversation_id: conv.id,
|
|
4126
|
+
message_id: inFlight.evidentMessageId
|
|
4127
|
+
});
|
|
4128
|
+
return;
|
|
4129
|
+
}
|
|
4130
|
+
inFlight.done = true;
|
|
4131
|
+
}
|
|
4132
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4133
|
+
}
|
|
3743
4134
|
// Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
|
|
3744
4135
|
/**
|
|
3745
4136
|
* Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
|
|
@@ -3906,6 +4297,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3906
4297
|
if (state === "failed") {
|
|
3907
4298
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
3908
4299
|
const usage = messageUsage(messages, ocId ?? "");
|
|
4300
|
+
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
3909
4301
|
this.log({
|
|
3910
4302
|
level: "error",
|
|
3911
4303
|
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -3913,7 +4305,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3913
4305
|
message_id: row.id
|
|
3914
4306
|
});
|
|
3915
4307
|
try {
|
|
3916
|
-
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
|
|
4308
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
|
|
3917
4309
|
} catch (err) {
|
|
3918
4310
|
if (err instanceof ChannelAuthError) throw err;
|
|
3919
4311
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -4319,6 +4711,47 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4319
4711
|
}
|
|
4320
4712
|
return false;
|
|
4321
4713
|
}
|
|
4714
|
+
/**
|
|
4715
|
+
* Tri-state variant of the upward parentID membership walk (#721), used ONLY
|
|
4716
|
+
* by `isAnyDescendantSessionOngoing`. Walks the SAME cached
|
|
4717
|
+
* `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
|
|
4718
|
+
* `sessionBelongsTo`, which deliberately collapses "confirmed not a
|
|
4719
|
+
* descendant" and "the walk's fetch failed" into the same `false` (safe for
|
|
4720
|
+
* its OTHER callers: interaction attribution and the recovery-path
|
|
4721
|
+
* `isAnyDescendantSessionAlive`, both of which just retry next tick with no
|
|
4722
|
+
* safety consequence either way) — this variant keeps those two outcomes
|
|
4723
|
+
* SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
|
|
4724
|
+
* (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
|
|
4725
|
+
* not ongoing".
|
|
4726
|
+
*
|
|
4727
|
+
* Return contract:
|
|
4728
|
+
* - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
|
|
4729
|
+
* - `false` → the walk reached a definitive, parent-less root session
|
|
4730
|
+
* WITHOUT ever matching `rootSessionId` — `sessionId` is
|
|
4731
|
+
* CONFIRMED NOT a descendant of it.
|
|
4732
|
+
* - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
|
|
4733
|
+
* through the walk (`resolveSessionParent` returned `undefined`),
|
|
4734
|
+
* or the depth cap (32) was hit without a definitive answer (a
|
|
4735
|
+
* pathological/cyclic chain proves nothing either way). NEVER
|
|
4736
|
+
* treat this the same as `false` — see `sessionBelongsTo`'s own
|
|
4737
|
+
* doc comment above for why that collapse is safe THERE but not
|
|
4738
|
+
* here.
|
|
4739
|
+
*
|
|
4740
|
+
* `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
|
|
4741
|
+
* to the live-path descendant check, not a modification of shared code used
|
|
4742
|
+
* by interaction attribution or the recovery path.
|
|
4743
|
+
*/
|
|
4744
|
+
async resolveSessionMembership(sessionId, rootSessionId) {
|
|
4745
|
+
let current = sessionId;
|
|
4746
|
+
for (let depth = 0; current && depth < 32; depth++) {
|
|
4747
|
+
if (current === rootSessionId) return true;
|
|
4748
|
+
const parent = await this.resolveSessionParent(current);
|
|
4749
|
+
if (parent === void 0) return null;
|
|
4750
|
+
if (parent === null) return false;
|
|
4751
|
+
current = parent;
|
|
4752
|
+
}
|
|
4753
|
+
return null;
|
|
4754
|
+
}
|
|
4322
4755
|
/**
|
|
4323
4756
|
* Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
|
|
4324
4757
|
* `null` for a root session (no parent) and `undefined` when opencode is
|
|
@@ -4509,6 +4942,84 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4509
4942
|
}
|
|
4510
4943
|
return false;
|
|
4511
4944
|
}
|
|
4945
|
+
/**
|
|
4946
|
+
* LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
|
|
4947
|
+
* sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
|
|
4948
|
+
* in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
|
|
4949
|
+
*
|
|
4950
|
+
* Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
|
|
4951
|
+
* cross-check above): that method judges liveness from the child's OWN
|
|
4952
|
+
* TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
|
|
4953
|
+
* on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
|
|
4954
|
+
* path the local opencode server IS running, so its in-memory status map is
|
|
4955
|
+
* live and authoritative — and per ADR-0047 §4a ("the child has its own entry
|
|
4956
|
+
* [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
|
|
4957
|
+
* ENTIRE turn (including any tool call it is itself executing), not a
|
|
4958
|
+
* per-message transcript snapshot. This sidesteps the "child's own tool is
|
|
4959
|
+
* executing, between its step's completion and the next generation step"
|
|
4960
|
+
* transcript gap that a transcript-based check would need a second,
|
|
4961
|
+
* sustained-window bound to guard against — it is simply not derived from
|
|
4962
|
+
* message timestamps at all.
|
|
4963
|
+
*
|
|
4964
|
+
* Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
|
|
4965
|
+
* status, as the recovery path does per §4a)? Because on the LIVE path the
|
|
4966
|
+
* root session can be shared: a SECOND, unrelated user message can land on the
|
|
4967
|
+
* SAME session (issue #721's own root cause) and keep the root `busy` for a
|
|
4968
|
+
* reason that has nothing to do with THIS message's delegation. A `task`
|
|
4969
|
+
* descendant session is spawned for exactly one delegated turn and never
|
|
4970
|
+
* reused, so its OWN status-map entry is unambiguous evidence about that one
|
|
4971
|
+
* delegation — which the root's status is not.
|
|
4972
|
+
*
|
|
4973
|
+
* Why membership is checked via `resolveSessionMembership`, NOT
|
|
4974
|
+
* `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
|
|
4975
|
+
* `GET /session/:id` fetch failure into "not a descendant", which would
|
|
4976
|
+
* silently drop a genuinely-live candidate from consideration on the one
|
|
4977
|
+
* unlucky tick its membership-walk fetch hiccups (#721).
|
|
4978
|
+
* `resolveSessionMembership` keeps that failure mode as a distinct `null`
|
|
4979
|
+
* (indeterminate) so it is folded into THIS method's own `indeterminate` flag
|
|
4980
|
+
* instead.
|
|
4981
|
+
*
|
|
4982
|
+
* Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
|
|
4983
|
+
* - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
|
|
4984
|
+
* - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
|
|
4985
|
+
* confirmed either way (`resolveSessionMembership` never
|
|
4986
|
+
* returned `null`), and every CONFIRMED descendant's status read
|
|
4987
|
+
* succeeded and is not ongoing (includes "no descendant session
|
|
4988
|
+
* exists at all" — e.g. a plain, non-`task` tool call).
|
|
4989
|
+
* - `null` → INDETERMINATE: `listSessions` failed, OR at least one
|
|
4990
|
+
* candidate's MEMBERSHIP could not be confirmed
|
|
4991
|
+
* (`resolveSessionMembership` returned `null` — a fetch failure
|
|
4992
|
+
* or pathological chain partway through the parent walk), OR at
|
|
4993
|
+
* least one CONFIRMED descendant's `isSessionOngoing` read
|
|
4994
|
+
* failed — and no OTHER candidate was already confirmed `true`.
|
|
4995
|
+
* The caller MUST NOT treat `null` the same as `false` here
|
|
4996
|
+
* (unlike the recovery cross-check's contract) — see
|
|
4997
|
+
* `isB2AbandonmentConfirmed`.
|
|
4998
|
+
*/
|
|
4999
|
+
async isAnyDescendantSessionOngoing(rootSessionId) {
|
|
5000
|
+
const sessions = await listSessions(this.port);
|
|
5001
|
+
if (!sessions) {
|
|
5002
|
+
this.log({
|
|
5003
|
+
level: "warn",
|
|
5004
|
+
message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
|
|
5005
|
+
});
|
|
5006
|
+
return null;
|
|
5007
|
+
}
|
|
5008
|
+
let indeterminate = false;
|
|
5009
|
+
for (const candidate of sessions) {
|
|
5010
|
+
if (!candidate?.id || candidate.id === rootSessionId) continue;
|
|
5011
|
+
const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
|
|
5012
|
+
if (membership === null) {
|
|
5013
|
+
indeterminate = true;
|
|
5014
|
+
continue;
|
|
5015
|
+
}
|
|
5016
|
+
if (membership === false) continue;
|
|
5017
|
+
const ongoing = await isSessionOngoing(this.port, candidate.id);
|
|
5018
|
+
if (ongoing === true) return true;
|
|
5019
|
+
if (ongoing === null) indeterminate = true;
|
|
5020
|
+
}
|
|
5021
|
+
return indeterminate ? null : false;
|
|
5022
|
+
}
|
|
4512
5023
|
/**
|
|
4513
5024
|
* Cheap decision-telemetry label for a running row's LAST correlated reply
|
|
4514
5025
|
* (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
|
|
@@ -4772,7 +5283,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4772
5283
|
* exists but is wedged, so the next attempt must get a fresh one
|
|
4773
5284
|
* instead of reusing it — see WI-1's server-side null-clearing PATCH).
|
|
4774
5285
|
*/
|
|
4775
|
-
async markFailed(conversationId, messageId, sessionId, error2, usage) {
|
|
5286
|
+
async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
|
|
4776
5287
|
const body = { status: "failed" };
|
|
4777
5288
|
if (sessionId === null) {
|
|
4778
5289
|
body.opencode_session_id = null;
|
|
@@ -4781,6 +5292,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4781
5292
|
}
|
|
4782
5293
|
if (error2 !== void 0) body.error = error2;
|
|
4783
5294
|
if (usage) Object.assign(body, usage);
|
|
5295
|
+
if (failure) {
|
|
5296
|
+
body.failure_kind = failure.kind;
|
|
5297
|
+
body.failure_provider_id = failure.providerId;
|
|
5298
|
+
body.failure_model_id = failure.modelId;
|
|
5299
|
+
body.failure_reason = failure.reason;
|
|
5300
|
+
}
|
|
4784
5301
|
await this.callWithRetry(
|
|
4785
5302
|
"marking message as failed",
|
|
4786
5303
|
() => this.fetchImpl(
|
|
@@ -4793,6 +5310,29 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4793
5310
|
)
|
|
4794
5311
|
);
|
|
4795
5312
|
}
|
|
5313
|
+
/**
|
|
5314
|
+
* Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
|
|
5315
|
+
*
|
|
5316
|
+
* `messageFailure` alone (structured OpenCode error → `model_auth`) covers
|
|
5317
|
+
* most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
|
|
5318
|
+
* to the P1-2b zero-provider check — one extra loopback call to
|
|
5319
|
+
* `hasAnyConfiguredProvider`, only reached when the structured classifier
|
|
5320
|
+
* couldn't place it. Fails open (never throws): a fallback probe failure
|
|
5321
|
+
* (`null`/indeterminate) leaves the classification `null`, which produces
|
|
5322
|
+
* today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
|
|
5323
|
+
*/
|
|
5324
|
+
async classifyModelAuthFailure(messages, userMessageId) {
|
|
5325
|
+
const classified = messageFailure(messages, userMessageId);
|
|
5326
|
+
if (classified != null) return classified;
|
|
5327
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5328
|
+
const hasProvider = await hasAnyConfiguredProvider(this.port);
|
|
5329
|
+
return applyZeroProviderFallback(
|
|
5330
|
+
classified,
|
|
5331
|
+
hasProvider,
|
|
5332
|
+
reply?.info?.providerID ?? null,
|
|
5333
|
+
reply?.info?.modelID ?? null
|
|
5334
|
+
);
|
|
5335
|
+
}
|
|
4796
5336
|
/**
|
|
4797
5337
|
* Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
|
|
4798
5338
|
* (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
|
|
@@ -4945,10 +5485,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4945
5485
|
import chalk5 from "chalk";
|
|
4946
5486
|
import ora2 from "ora";
|
|
4947
5487
|
import { select as select2 } from "@inquirer/prompts";
|
|
5488
|
+
var INTERACTIVE_START_TIMEOUT_MS = 3e4;
|
|
4948
5489
|
async function ensureOpenCodeRunning(ctx) {
|
|
4949
5490
|
const healthCheck = await checkOpenCodeHealth(ctx.port);
|
|
4950
5491
|
if (healthCheck.healthy) {
|
|
4951
|
-
return {
|
|
5492
|
+
return {
|
|
5493
|
+
port: ctx.port,
|
|
5494
|
+
process: null,
|
|
5495
|
+
version: healthCheck.version ?? null,
|
|
5496
|
+
notReadyReason: null
|
|
5497
|
+
};
|
|
4952
5498
|
}
|
|
4953
5499
|
const runningInstances = await findHealthyOpenCodeInstances();
|
|
4954
5500
|
if (runningInstances.length > 0) {
|
|
@@ -4969,7 +5515,7 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4969
5515
|
console.log(chalk5.yellow("Tip: Run with the correct port:"));
|
|
4970
5516
|
console.log(
|
|
4971
5517
|
chalk5.dim(
|
|
4972
|
-
` ${getCliName()} run --
|
|
5518
|
+
` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
|
|
4973
5519
|
)
|
|
4974
5520
|
);
|
|
4975
5521
|
}
|
|
@@ -4989,14 +5535,22 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4989
5535
|
if (!ctx.interactive) {
|
|
4990
5536
|
ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
|
|
4991
5537
|
const proc = await startOpenCode(ctx.port);
|
|
4992
|
-
const health = await waitForOpenCodeHealth(ctx.port,
|
|
5538
|
+
const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
|
|
4993
5539
|
if (!health.healthy) {
|
|
4994
|
-
|
|
4995
|
-
|
|
4996
|
-
|
|
5540
|
+
return {
|
|
5541
|
+
port: ctx.port,
|
|
5542
|
+
process: proc,
|
|
5543
|
+
version: null,
|
|
5544
|
+
notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
|
|
5545
|
+
};
|
|
4997
5546
|
}
|
|
4998
5547
|
ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
|
|
4999
|
-
return {
|
|
5548
|
+
return {
|
|
5549
|
+
port: ctx.port,
|
|
5550
|
+
process: proc,
|
|
5551
|
+
version: health.version ?? null,
|
|
5552
|
+
notReadyReason: null
|
|
5553
|
+
};
|
|
5000
5554
|
}
|
|
5001
5555
|
let port = ctx.port;
|
|
5002
5556
|
if (isPortInUse(port)) {
|
|
@@ -5049,15 +5603,15 @@ Port ${port} is already in use.`));
|
|
|
5049
5603
|
if (action === "start") {
|
|
5050
5604
|
const spinner = ora2("Starting OpenCode...").start();
|
|
5051
5605
|
const proc = await startOpenCode(port);
|
|
5052
|
-
const health = await waitForOpenCodeHealth(port,
|
|
5606
|
+
const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
|
|
5053
5607
|
if (!health.healthy) {
|
|
5054
5608
|
spinner.fail("Failed to start OpenCode");
|
|
5055
5609
|
throw new Error("OpenCode failed to start");
|
|
5056
5610
|
}
|
|
5057
5611
|
spinner.stop();
|
|
5058
|
-
return { port, process: proc, version: health.version ?? null };
|
|
5612
|
+
return { port, process: proc, version: health.version ?? null, notReadyReason: null };
|
|
5059
5613
|
}
|
|
5060
|
-
return { port, process: null, version: null };
|
|
5614
|
+
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
5061
5615
|
}
|
|
5062
5616
|
|
|
5063
5617
|
// src/commands/agent-lookup.ts
|
|
@@ -5099,7 +5653,7 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
5099
5653
|
return { agent_id: data.agent_id };
|
|
5100
5654
|
}
|
|
5101
5655
|
return {
|
|
5102
|
-
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --
|
|
5656
|
+
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
|
|
5103
5657
|
};
|
|
5104
5658
|
} catch (error2) {
|
|
5105
5659
|
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
@@ -5155,6 +5709,34 @@ async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
|
5155
5709
|
return { ok: false, error: describeBestEffortError(error2) };
|
|
5156
5710
|
}
|
|
5157
5711
|
}
|
|
5712
|
+
function toReportedWindow(window) {
|
|
5713
|
+
if (!window) return null;
|
|
5714
|
+
return { utilization: window.utilization, resets_at: window.resetsAt };
|
|
5715
|
+
}
|
|
5716
|
+
async function reportClaudeUsage(agentId, authHeader, snapshot) {
|
|
5717
|
+
try {
|
|
5718
|
+
const apiUrl = getApiUrlConfig();
|
|
5719
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/claude-usage`, {
|
|
5720
|
+
method: "POST",
|
|
5721
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5722
|
+
body: JSON.stringify({
|
|
5723
|
+
five_hour: toReportedWindow(snapshot.fiveHour),
|
|
5724
|
+
seven_day: toReportedWindow(snapshot.sevenDay)
|
|
5725
|
+
}),
|
|
5726
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5727
|
+
});
|
|
5728
|
+
if (!response.ok) {
|
|
5729
|
+
const serverMessage = await readErrorMessage(response);
|
|
5730
|
+
return {
|
|
5731
|
+
ok: false,
|
|
5732
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5733
|
+
};
|
|
5734
|
+
}
|
|
5735
|
+
return { ok: true };
|
|
5736
|
+
} catch (error2) {
|
|
5737
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5738
|
+
}
|
|
5739
|
+
}
|
|
5158
5740
|
async function getAgentInfo(agentId, authHeader) {
|
|
5159
5741
|
const apiUrl = getApiUrlConfig();
|
|
5160
5742
|
try {
|
|
@@ -5233,7 +5815,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
5233
5815
|
if (trimmed === "") {
|
|
5234
5816
|
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5235
5817
|
}
|
|
5236
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
5818
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join3(homeDir, trimmed.slice(2)) : trimmed;
|
|
5237
5819
|
if (!isAbsolute2(expanded)) {
|
|
5238
5820
|
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5239
5821
|
}
|
|
@@ -5254,6 +5836,35 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
5254
5836
|
}
|
|
5255
5837
|
return directories;
|
|
5256
5838
|
}
|
|
5839
|
+
var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
|
|
5840
|
+
var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
|
|
5841
|
+
var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
|
|
5842
|
+
function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
|
|
5843
|
+
const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
|
|
5844
|
+
let raw;
|
|
5845
|
+
let source;
|
|
5846
|
+
if (options.opencodeStartTimeout !== void 0) {
|
|
5847
|
+
raw = options.opencodeStartTimeout;
|
|
5848
|
+
source = "--opencode-start-timeout";
|
|
5849
|
+
} else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
|
|
5850
|
+
raw = env[OPENCODE_START_TIMEOUT_ENV];
|
|
5851
|
+
source = OPENCODE_START_TIMEOUT_ENV;
|
|
5852
|
+
} else {
|
|
5853
|
+
return { timeoutMs: defaultMs, warnings: [] };
|
|
5854
|
+
}
|
|
5855
|
+
const trimmed = raw.trim();
|
|
5856
|
+
const seconds = Number(trimmed);
|
|
5857
|
+
const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
|
|
5858
|
+
if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
|
|
5859
|
+
return {
|
|
5860
|
+
timeoutMs: defaultMs,
|
|
5861
|
+
warnings: [
|
|
5862
|
+
`Ignoring invalid ${source} "${raw}": expected a positive integer number of seconds (at most ${MAX_OPENCODE_START_TIMEOUT_SECONDS}); using the default ${DEFAULT_OPENCODE_START_TIMEOUT_SECONDS}s`
|
|
5863
|
+
]
|
|
5864
|
+
};
|
|
5865
|
+
}
|
|
5866
|
+
return { timeoutMs: seconds * 1e3, warnings: [] };
|
|
5867
|
+
}
|
|
5257
5868
|
function meetsThreshold(state, level) {
|
|
5258
5869
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
5259
5870
|
}
|
|
@@ -5275,6 +5886,10 @@ function log2(state, message, level = "info") {
|
|
|
5275
5886
|
function logActivity(state, entry) {
|
|
5276
5887
|
const level = entry.level ?? (entry.type === "error" ? "error" : "info");
|
|
5277
5888
|
if (!meetsThreshold(state, level)) return;
|
|
5889
|
+
forwardRunnerActivity(
|
|
5890
|
+
{ level, message: entry.message, error: entry.error },
|
|
5891
|
+
{ agentId: state.agentId, authHeader: state.authHeader }
|
|
5892
|
+
);
|
|
5278
5893
|
const fullEntry = {
|
|
5279
5894
|
...entry,
|
|
5280
5895
|
level,
|
|
@@ -5512,6 +6127,94 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
5512
6127
|
);
|
|
5513
6128
|
state.sessionCleanupTimers.push(interval, firstSweep);
|
|
5514
6129
|
}
|
|
6130
|
+
function scheduleClaudeUsageReporting(state, options) {
|
|
6131
|
+
const { mode, warnings } = resolveClaudeUsageReportingMode(
|
|
6132
|
+
options.claudeUsageReporting,
|
|
6133
|
+
process.env
|
|
6134
|
+
);
|
|
6135
|
+
for (const warning2 of warnings) {
|
|
6136
|
+
logActivity(state, {
|
|
6137
|
+
type: "info",
|
|
6138
|
+
level: "warn",
|
|
6139
|
+
message: `Claude usage reporting: ${warning2}`
|
|
6140
|
+
});
|
|
6141
|
+
}
|
|
6142
|
+
if (mode === "off") {
|
|
6143
|
+
logActivity(state, {
|
|
6144
|
+
type: "info",
|
|
6145
|
+
level: "debug",
|
|
6146
|
+
message: "Claude usage reporting is off (--claude-usage-reporting off)"
|
|
6147
|
+
});
|
|
6148
|
+
return;
|
|
6149
|
+
}
|
|
6150
|
+
let consecutiveFailures = 0;
|
|
6151
|
+
const scheduleNextTick = () => {
|
|
6152
|
+
state.claudeUsageTimer = setTimeout(() => void tick(false), nextReportDelayMs());
|
|
6153
|
+
};
|
|
6154
|
+
const tick = async (isFirst) => {
|
|
6155
|
+
try {
|
|
6156
|
+
const usage = await getClaudeUsage();
|
|
6157
|
+
const result = await reportClaudeUsage(state.agentId, state.authHeader, usage);
|
|
6158
|
+
if (result.ok) {
|
|
6159
|
+
if (consecutiveFailures > 0) {
|
|
6160
|
+
logActivity(state, {
|
|
6161
|
+
type: "info",
|
|
6162
|
+
level: "info",
|
|
6163
|
+
message: "Claude usage reporting recovered"
|
|
6164
|
+
});
|
|
6165
|
+
}
|
|
6166
|
+
consecutiveFailures = 0;
|
|
6167
|
+
logActivity(state, {
|
|
6168
|
+
type: "info",
|
|
6169
|
+
level: "debug",
|
|
6170
|
+
message: "Reported Claude usage to Evident"
|
|
6171
|
+
});
|
|
6172
|
+
} else {
|
|
6173
|
+
consecutiveFailures++;
|
|
6174
|
+
logActivity(state, {
|
|
6175
|
+
type: "info",
|
|
6176
|
+
level: consecutiveFailures === 1 ? "warn" : "debug",
|
|
6177
|
+
message: `Failed to report Claude usage: ${result.error}`
|
|
6178
|
+
});
|
|
6179
|
+
}
|
|
6180
|
+
scheduleNextTick();
|
|
6181
|
+
} catch (error2) {
|
|
6182
|
+
if (error2 instanceof ClaudeUsageError && isLocalCredentialProblem(error2)) {
|
|
6183
|
+
if (mode === "on") {
|
|
6184
|
+
logActivity(state, {
|
|
6185
|
+
type: "info",
|
|
6186
|
+
level: "warn",
|
|
6187
|
+
message: "Claude usage reporting is forced on but no usable Claude Code login was found \u2014 run `claude` to sign in; reporting will keep retrying"
|
|
6188
|
+
});
|
|
6189
|
+
scheduleNextTick();
|
|
6190
|
+
} else if (isFirst) {
|
|
6191
|
+
logActivity(state, {
|
|
6192
|
+
type: "info",
|
|
6193
|
+
level: "debug",
|
|
6194
|
+
message: `Claude usage reporting: ${error2.message}`
|
|
6195
|
+
});
|
|
6196
|
+
} else {
|
|
6197
|
+
logActivity(state, {
|
|
6198
|
+
type: "info",
|
|
6199
|
+
level: "debug",
|
|
6200
|
+
message: `Claude usage reporting: ${error2.message}`
|
|
6201
|
+
});
|
|
6202
|
+
scheduleNextTick();
|
|
6203
|
+
}
|
|
6204
|
+
} else {
|
|
6205
|
+
consecutiveFailures++;
|
|
6206
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
6207
|
+
logActivity(state, {
|
|
6208
|
+
type: "info",
|
|
6209
|
+
level: consecutiveFailures === 1 ? "warn" : "debug",
|
|
6210
|
+
message: `Claude usage reporting failed: ${message}`
|
|
6211
|
+
});
|
|
6212
|
+
scheduleNextTick();
|
|
6213
|
+
}
|
|
6214
|
+
}
|
|
6215
|
+
};
|
|
6216
|
+
state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
|
|
6217
|
+
}
|
|
5515
6218
|
async function notifyOffline(state) {
|
|
5516
6219
|
if (!state.agentId || !state.authHeader) return;
|
|
5517
6220
|
if (!state.connected) {
|
|
@@ -5547,6 +6250,10 @@ async function cleanup(state, opts = {}) {
|
|
|
5547
6250
|
clearTimeout(timer);
|
|
5548
6251
|
}
|
|
5549
6252
|
state.sessionCleanupTimers = [];
|
|
6253
|
+
if (state.claudeUsageTimer) {
|
|
6254
|
+
clearTimeout(state.claudeUsageTimer);
|
|
6255
|
+
state.claudeUsageTimer = null;
|
|
6256
|
+
}
|
|
5550
6257
|
if (opts.graceful && state.channelDriver) {
|
|
5551
6258
|
state.channelDriver.stop();
|
|
5552
6259
|
log2(state, "Draining in-flight channel work before shutdown...");
|
|
@@ -5594,7 +6301,7 @@ async function run(options) {
|
|
|
5594
6301
|
let fileSyncDirectories;
|
|
5595
6302
|
try {
|
|
5596
6303
|
logLevel = resolveLogLevel(options);
|
|
5597
|
-
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo,
|
|
6304
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
|
|
5598
6305
|
} catch (error2) {
|
|
5599
6306
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
5600
6307
|
if (options.json) {
|
|
@@ -5627,8 +6334,10 @@ async function run(options) {
|
|
|
5627
6334
|
messageCount: 0,
|
|
5628
6335
|
lastProxiedActivityAt: null,
|
|
5629
6336
|
sessionCleanupTimers: [],
|
|
6337
|
+
claudeUsageTimer: null,
|
|
5630
6338
|
authHeader: ""
|
|
5631
6339
|
};
|
|
6340
|
+
setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
|
|
5632
6341
|
if (fileSyncDirectories.length > 0) {
|
|
5633
6342
|
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
5634
6343
|
} else {
|
|
@@ -5817,40 +6526,52 @@ async function run(options) {
|
|
|
5817
6526
|
} else {
|
|
5818
6527
|
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
5819
6528
|
}
|
|
6529
|
+
const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
|
|
6530
|
+
for (const warning2 of opencodeStartTimeoutWarnings) {
|
|
6531
|
+
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
6532
|
+
}
|
|
5820
6533
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
5821
6534
|
try {
|
|
5822
6535
|
const oc = await ensureOpenCodeRunning({
|
|
5823
6536
|
port: state.port,
|
|
5824
6537
|
interactive: state.interactive,
|
|
5825
6538
|
agentId: state.agentId,
|
|
5826
|
-
log: (message) => log2(state, message)
|
|
6539
|
+
log: (message) => log2(state, message),
|
|
6540
|
+
startTimeoutMs: opencodeStartTimeoutMs
|
|
5827
6541
|
});
|
|
5828
6542
|
state.port = oc.port;
|
|
5829
6543
|
state.opencodeProcess = oc.process;
|
|
5830
6544
|
state.opencodeVersion = oc.version;
|
|
5831
|
-
state.opencodeConnected = oc.
|
|
6545
|
+
state.opencodeConnected = oc.notReadyReason === null;
|
|
5832
6546
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
5833
6547
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
5834
|
-
|
|
5835
|
-
|
|
5836
|
-
|
|
5837
|
-
|
|
5838
|
-
|
|
6548
|
+
if (!state.interactive && oc.notReadyReason !== null) {
|
|
6549
|
+
const message = `OpenCode is not ready on port ${state.port}: ${oc.notReadyReason}. The runner will still come online, but messages will fail until opencode answers \u2014 raise the wait with --opencode-start-timeout <seconds> (env ${OPENCODE_START_TIMEOUT_ENV}).`;
|
|
6550
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6551
|
+
} else {
|
|
6552
|
+
const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
|
|
6553
|
+
if (versionWarning) {
|
|
6554
|
+
log2(state, versionWarning, "warn");
|
|
6555
|
+
if (state.interactive && !state.json) {
|
|
6556
|
+
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
6557
|
+
}
|
|
5839
6558
|
}
|
|
5840
|
-
|
|
5841
|
-
|
|
5842
|
-
|
|
5843
|
-
|
|
5844
|
-
|
|
5845
|
-
|
|
5846
|
-
|
|
5847
|
-
|
|
5848
|
-
|
|
5849
|
-
|
|
5850
|
-
|
|
5851
|
-
|
|
5852
|
-
|
|
5853
|
-
|
|
6559
|
+
const noProviderWarning = buildNoProviderWarning(
|
|
6560
|
+
await hasAnyConfiguredProvider(state.port)
|
|
6561
|
+
);
|
|
6562
|
+
if (noProviderWarning) {
|
|
6563
|
+
log2(state, noProviderWarning, "warn");
|
|
6564
|
+
if (state.interactive && !state.json) {
|
|
6565
|
+
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
6566
|
+
blank();
|
|
6567
|
+
console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
6568
|
+
console.log(
|
|
6569
|
+
chalk6.dim(
|
|
6570
|
+
`Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
6571
|
+
)
|
|
6572
|
+
);
|
|
6573
|
+
blank();
|
|
6574
|
+
}
|
|
5854
6575
|
}
|
|
5855
6576
|
}
|
|
5856
6577
|
} catch (error2) {
|
|
@@ -5868,7 +6589,7 @@ async function run(options) {
|
|
|
5868
6589
|
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
5869
6590
|
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
5870
6591
|
fileSyncDirectories,
|
|
5871
|
-
homeDir:
|
|
6592
|
+
homeDir: homedir3(),
|
|
5872
6593
|
log: (entry) => (
|
|
5873
6594
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
5874
6595
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -5895,6 +6616,18 @@ async function run(options) {
|
|
|
5895
6616
|
type: "info",
|
|
5896
6617
|
message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
|
|
5897
6618
|
});
|
|
6619
|
+
if (options.tunnelReadyFile) {
|
|
6620
|
+
const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
|
|
6621
|
+
if (marker.ok) {
|
|
6622
|
+
log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
|
|
6623
|
+
} else {
|
|
6624
|
+
log2(
|
|
6625
|
+
state,
|
|
6626
|
+
`Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
|
|
6627
|
+
"error"
|
|
6628
|
+
);
|
|
6629
|
+
}
|
|
6630
|
+
}
|
|
5898
6631
|
emitAgentConnected(state.agentId, {
|
|
5899
6632
|
port: state.port,
|
|
5900
6633
|
cli_version: getCliVersion(),
|
|
@@ -5985,6 +6718,7 @@ async function run(options) {
|
|
|
5985
6718
|
throw error2;
|
|
5986
6719
|
}
|
|
5987
6720
|
scheduleSessionCleanup(state, channelDriver, options);
|
|
6721
|
+
scheduleClaudeUsageReporting(state, options);
|
|
5988
6722
|
if (!interactive || state.json) {
|
|
5989
6723
|
log2(state, "Driving channel messages...");
|
|
5990
6724
|
}
|
|
@@ -6039,13 +6773,17 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
6039
6773
|
program.command("login").description("Authenticate with Evident").option("--token", "Use token-based authentication (for CI/CD)").option("--no-browser", "Do not open the browser automatically").action(login);
|
|
6040
6774
|
program.command("logout").description("Remove stored credentials for the current endpoint").option("--all", "Remove stored credentials for all endpoints").action((options) => logout({ all: options.all }));
|
|
6041
6775
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
6776
|
+
program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);
|
|
6042
6777
|
program.command("run").description("Connect to Evident and process messages").option("--runner [id]", "Runner ID to connect to (optional when EVIDENT_RUNNER_KEY is set)").option(
|
|
6043
6778
|
"-a, --agent [id]",
|
|
6044
6779
|
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
6045
6780
|
).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
6046
6781
|
"--log-level <level>",
|
|
6047
6782
|
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
6048
|
-
).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(
|
|
6783
|
+
).option("-v, --verbose", "Alias for --log-level debug (ignored if --log-level is set)").option("-c, --conversation <id>", "Process only this specific conversation").option("--idle-timeout <seconds>", "Exit after N seconds idle").option(
|
|
6784
|
+
"--opencode-start-timeout <seconds>",
|
|
6785
|
+
"Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
|
|
6786
|
+
).option("--json", "Output in JSON format").option(
|
|
6049
6787
|
"--session-cleanup-max-age <duration>",
|
|
6050
6788
|
"Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
|
|
6051
6789
|
).option(
|
|
@@ -6054,11 +6792,17 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
6054
6792
|
).option(
|
|
6055
6793
|
"--session-cleanup-interval <duration>",
|
|
6056
6794
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
6795
|
+
).option(
|
|
6796
|
+
"--claude-usage-reporting <mode>",
|
|
6797
|
+
"Report Claude subscription usage to Evident: auto | on | off (default: auto). Env: EVIDENT_CLAUDE_USAGE_REPORTING"
|
|
6057
6798
|
).option(
|
|
6058
6799
|
"--enable-file-sync-to <dir>",
|
|
6059
6800
|
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
6060
6801
|
(value, previous) => previous.concat([value]),
|
|
6061
6802
|
[]
|
|
6803
|
+
).option(
|
|
6804
|
+
"--tunnel-ready-file <path>",
|
|
6805
|
+
"Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
|
|
6062
6806
|
).action(
|
|
6063
6807
|
(options) => {
|
|
6064
6808
|
run({
|
|
@@ -6071,14 +6815,21 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
6071
6815
|
verbose: options.verbose,
|
|
6072
6816
|
conversation: options.conversation,
|
|
6073
6817
|
idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
|
|
6818
|
+
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
6819
|
+
// resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
|
|
6820
|
+
opencodeStartTimeout: options.opencodeStartTimeout,
|
|
6074
6821
|
json: options.json,
|
|
6075
6822
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
6076
6823
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
6077
6824
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
6078
6825
|
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
6826
|
+
// Raw string — the resolver in run.ts single-sources parsing
|
|
6827
|
+
// (resolveClaudeUsageReportingMode).
|
|
6828
|
+
claudeUsageReporting: options.claudeUsageReporting,
|
|
6079
6829
|
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
6080
6830
|
// resolveFileSyncDirectories.
|
|
6081
|
-
enableFileSyncTo: options.enableFileSyncTo
|
|
6831
|
+
enableFileSyncTo: options.enableFileSyncTo,
|
|
6832
|
+
tunnelReadyFile: options.tunnelReadyFile
|
|
6082
6833
|
});
|
|
6083
6834
|
}
|
|
6084
6835
|
);
|