@evident-ai/cli 3.1.1-dev.5a3c6a5 → 3.1.1-dev.5d5a3d3
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 +1095 -161
- 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,132 @@ 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 normalizeResetsAt(value) {
|
|
586
|
+
const ms = Date.parse(value);
|
|
587
|
+
return Number.isNaN(ms) ? null : new Date(ms).toISOString();
|
|
588
|
+
}
|
|
589
|
+
function toWindow(value) {
|
|
590
|
+
if (!value || typeof value !== "object") {
|
|
591
|
+
return null;
|
|
592
|
+
}
|
|
593
|
+
const window = value;
|
|
594
|
+
if (typeof window.utilization !== "number" || typeof window.resets_at !== "string") {
|
|
595
|
+
return null;
|
|
596
|
+
}
|
|
597
|
+
const resetsAt = normalizeResetsAt(window.resets_at);
|
|
598
|
+
if (resetsAt === null) {
|
|
599
|
+
return null;
|
|
600
|
+
}
|
|
601
|
+
return { utilization: window.utilization, resetsAt };
|
|
602
|
+
}
|
|
603
|
+
async function getClaudeUsage() {
|
|
604
|
+
const credentials2 = readClaudeCliCredentials();
|
|
605
|
+
if (!credentials2) {
|
|
606
|
+
throw new ClaudeUsageError(
|
|
607
|
+
"No local Claude Code login found. Run `claude` once to sign in with your Claude subscription.",
|
|
608
|
+
"no_credentials"
|
|
609
|
+
);
|
|
610
|
+
}
|
|
611
|
+
if (credentials2.expiresAt < Date.now()) {
|
|
612
|
+
throw new ClaudeUsageError(
|
|
613
|
+
"Claude Code credentials have expired. Run `claude` to refresh them.",
|
|
614
|
+
"credentials_expired"
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
const res = await fetch(CLAUDE_USAGE_URL, {
|
|
618
|
+
headers: {
|
|
619
|
+
Authorization: `Bearer ${credentials2.accessToken}`,
|
|
620
|
+
"Content-Type": "application/json",
|
|
621
|
+
"anthropic-version": "2023-06-01"
|
|
622
|
+
}
|
|
623
|
+
});
|
|
624
|
+
if (!res.ok) {
|
|
625
|
+
throw new ClaudeUsageError(`Claude usage request failed: HTTP ${res.status}`, "request_failed");
|
|
626
|
+
}
|
|
627
|
+
const body = await res.json();
|
|
628
|
+
return {
|
|
629
|
+
fiveHour: toWindow(body.five_hour),
|
|
630
|
+
sevenDay: toWindow(body.seven_day)
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// src/commands/claude-usage.ts
|
|
635
|
+
function formatWindow(label, window) {
|
|
636
|
+
if (!window) {
|
|
637
|
+
return keyValue(label, "not available for this plan");
|
|
638
|
+
}
|
|
639
|
+
const resetsAt = new Date(window.resetsAt);
|
|
640
|
+
return keyValue(label, `${window.utilization}% used, resets ${resetsAt.toLocaleString()}`);
|
|
641
|
+
}
|
|
642
|
+
async function claudeUsage() {
|
|
643
|
+
try {
|
|
644
|
+
const usage = await getClaudeUsage();
|
|
645
|
+
blank();
|
|
646
|
+
console.log(formatWindow("5-hour session", usage.fiveHour));
|
|
647
|
+
console.log(formatWindow("7-day", usage.sevenDay));
|
|
648
|
+
blank();
|
|
649
|
+
} catch (err) {
|
|
650
|
+
if (err instanceof ClaudeUsageError) {
|
|
651
|
+
printError(err.message);
|
|
652
|
+
process.exit(1);
|
|
653
|
+
}
|
|
654
|
+
throw err;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
501
658
|
// src/commands/run.ts
|
|
502
|
-
import { homedir as
|
|
503
|
-
import { isAbsolute as isAbsolute2, join as
|
|
659
|
+
import { homedir as homedir3 } from "os";
|
|
660
|
+
import { isAbsolute as isAbsolute2, join as join3, parse, resolve as resolvePath } from "path";
|
|
504
661
|
import chalk6 from "chalk";
|
|
505
662
|
|
|
506
663
|
// ../../packages/types/src/telemetry/index.ts
|
|
@@ -510,7 +667,10 @@ var TelemetryEventTypes = {
|
|
|
510
667
|
AGENT_DISCONNECTED: "agent.disconnected",
|
|
511
668
|
AGENT_MESSAGE_PROCESSING: "agent.message_processing",
|
|
512
669
|
AGENT_MESSAGE_DONE: "agent.message_done",
|
|
513
|
-
AGENT_MESSAGE_FAILED: "agent.message_failed"
|
|
670
|
+
AGENT_MESSAGE_FAILED: "agent.message_failed",
|
|
671
|
+
// A `warn`/`error` runner-side log line forwarded server-side for
|
|
672
|
+
// observability (issue #916) — see `apps/cli/src/lib/runner-activity-telemetry.ts`.
|
|
673
|
+
RUNNER_ACTIVITY: "runner.activity"
|
|
514
674
|
};
|
|
515
675
|
|
|
516
676
|
// ../../packages/types/src/tunnel/index.ts
|
|
@@ -565,6 +725,13 @@ var isShuttingDown = false;
|
|
|
565
725
|
var FLUSH_INTERVAL_MS = 5e3;
|
|
566
726
|
var MAX_BUFFER_SIZE = 50;
|
|
567
727
|
var FLUSH_TIMEOUT_MS = 3e3;
|
|
728
|
+
var authProvider = null;
|
|
729
|
+
function setTelemetryAuthProvider(provider) {
|
|
730
|
+
authProvider = provider;
|
|
731
|
+
}
|
|
732
|
+
var FLUSH_FAILURE_LOG_INTERVAL_MS = 6e4;
|
|
733
|
+
var lastFlushFailureLoggedAt = 0;
|
|
734
|
+
var suppressedFlushFailureCount = 0;
|
|
568
735
|
function logEvent(eventType, options = {}) {
|
|
569
736
|
const event = {
|
|
570
737
|
event_type: eventType,
|
|
@@ -599,9 +766,16 @@ async function flushEvents() {
|
|
|
599
766
|
flushTimeout = null;
|
|
600
767
|
}
|
|
601
768
|
try {
|
|
602
|
-
const
|
|
603
|
-
|
|
604
|
-
|
|
769
|
+
const providerContext = authProvider?.();
|
|
770
|
+
let authHeader;
|
|
771
|
+
if (providerContext?.authHeader) {
|
|
772
|
+
authHeader = providerContext.authHeader;
|
|
773
|
+
} else {
|
|
774
|
+
const credentials2 = await getToken();
|
|
775
|
+
if (!credentials2) {
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
authHeader = `Bearer ${credentials2.token}`;
|
|
605
779
|
}
|
|
606
780
|
const apiUrl = getApiUrlConfig();
|
|
607
781
|
const controller = new AbortController();
|
|
@@ -616,7 +790,7 @@ async function flushEvents() {
|
|
|
616
790
|
method: "POST",
|
|
617
791
|
headers: {
|
|
618
792
|
"Content-Type": "application/json",
|
|
619
|
-
Authorization:
|
|
793
|
+
Authorization: authHeader
|
|
620
794
|
},
|
|
621
795
|
body: JSON.stringify(request),
|
|
622
796
|
signal: controller.signal
|
|
@@ -628,8 +802,15 @@ async function flushEvents() {
|
|
|
628
802
|
clearTimeout(timeout);
|
|
629
803
|
}
|
|
630
804
|
} catch (error2) {
|
|
631
|
-
|
|
632
|
-
|
|
805
|
+
const now = Date.now();
|
|
806
|
+
if (now - lastFlushFailureLoggedAt >= FLUSH_FAILURE_LOG_INTERVAL_MS) {
|
|
807
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
808
|
+
const suffix = suppressedFlushFailureCount > 0 ? ` (${suppressedFlushFailureCount} more suppressed in the last ${FLUSH_FAILURE_LOG_INTERVAL_MS / 1e3}s)` : "";
|
|
809
|
+
console.error(`Telemetry flush error: ${message}${suffix}`);
|
|
810
|
+
lastFlushFailureLoggedAt = now;
|
|
811
|
+
suppressedFlushFailureCount = 0;
|
|
812
|
+
} else {
|
|
813
|
+
suppressedFlushFailureCount++;
|
|
633
814
|
}
|
|
634
815
|
}
|
|
635
816
|
}
|
|
@@ -698,6 +879,69 @@ var EventTypes = {
|
|
|
698
879
|
DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
|
|
699
880
|
};
|
|
700
881
|
|
|
882
|
+
// src/lib/runner-activity-telemetry.ts
|
|
883
|
+
var FORWARDED_LEVELS = /* @__PURE__ */ new Set(["warn", "error"]);
|
|
884
|
+
var SEVERITY_BY_LEVEL = {
|
|
885
|
+
warn: "warning",
|
|
886
|
+
error: "error"
|
|
887
|
+
};
|
|
888
|
+
var MAX_MESSAGE_LENGTH = 500;
|
|
889
|
+
var TRUNCATION_MARKER = "\u2026";
|
|
890
|
+
function redact(message) {
|
|
891
|
+
return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
|
|
892
|
+
}
|
|
893
|
+
function truncate(message) {
|
|
894
|
+
if (message.length <= MAX_MESSAGE_LENGTH) return message;
|
|
895
|
+
return message.slice(0, MAX_MESSAGE_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
|
|
896
|
+
}
|
|
897
|
+
var RATE_LIMIT_WINDOW_MS = 6e4;
|
|
898
|
+
var RATE_LIMIT_MAX_EVENTS = 30;
|
|
899
|
+
var windowStartedAt = 0;
|
|
900
|
+
var windowCount = 0;
|
|
901
|
+
var windowDroppedCount = 0;
|
|
902
|
+
function admitUnderRateLimit(now) {
|
|
903
|
+
if (now - windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
|
|
904
|
+
if (windowDroppedCount > 0) {
|
|
905
|
+
console.error(
|
|
906
|
+
`[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)`
|
|
907
|
+
);
|
|
908
|
+
}
|
|
909
|
+
windowStartedAt = now;
|
|
910
|
+
windowCount = 0;
|
|
911
|
+
windowDroppedCount = 0;
|
|
912
|
+
}
|
|
913
|
+
if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
|
|
914
|
+
windowDroppedCount++;
|
|
915
|
+
if (windowDroppedCount === 1) {
|
|
916
|
+
console.error(
|
|
917
|
+
`[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
|
|
918
|
+
);
|
|
919
|
+
}
|
|
920
|
+
return false;
|
|
921
|
+
}
|
|
922
|
+
windowCount++;
|
|
923
|
+
return true;
|
|
924
|
+
}
|
|
925
|
+
function forwardRunnerActivity(entry, context) {
|
|
926
|
+
try {
|
|
927
|
+
if (!FORWARDED_LEVELS.has(entry.level)) return;
|
|
928
|
+
if (!context.agentId || !context.authHeader) return;
|
|
929
|
+
if (!admitUnderRateLimit(Date.now())) return;
|
|
930
|
+
const rawMessage = entry.error ?? entry.message ?? "";
|
|
931
|
+
const message = truncate(redact(rawMessage));
|
|
932
|
+
logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
|
|
933
|
+
severity: SEVERITY_BY_LEVEL[entry.level],
|
|
934
|
+
message,
|
|
935
|
+
metadata: { source: "cli.run" },
|
|
936
|
+
agentId: context.agentId
|
|
937
|
+
});
|
|
938
|
+
} catch (err) {
|
|
939
|
+
console.error(
|
|
940
|
+
`[runner-activity-telemetry] failed to forward runner activity: ${err instanceof Error ? err.message : String(err)}`
|
|
941
|
+
);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
701
945
|
// src/lib/auth.ts
|
|
702
946
|
async function getAuthCredentials() {
|
|
703
947
|
const runnerKey = process.env.EVIDENT_RUNNER_KEY;
|
|
@@ -1532,6 +1776,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
|
|
|
1532
1776
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1533
1777
|
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
1534
1778
|
}
|
|
1779
|
+
function isB2AbandonmentConfirmed(params) {
|
|
1780
|
+
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
|
|
1781
|
+
}
|
|
1535
1782
|
function messageError(messages, userMessageId) {
|
|
1536
1783
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1537
1784
|
const error2 = errorOf(reply);
|
|
@@ -1545,6 +1792,42 @@ function messageError(messages, userMessageId) {
|
|
|
1545
1792
|
}
|
|
1546
1793
|
return "The agent run failed.";
|
|
1547
1794
|
}
|
|
1795
|
+
function messageFailure(messages, userMessageId) {
|
|
1796
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1797
|
+
const error2 = errorOf(reply);
|
|
1798
|
+
if (error2 == null || typeof error2 !== "object") return null;
|
|
1799
|
+
const e = error2;
|
|
1800
|
+
const replyProviderId = reply?.info?.providerID ?? null;
|
|
1801
|
+
const replyModelId = reply?.info?.modelID ?? null;
|
|
1802
|
+
if (e.name === "ProviderAuthError") {
|
|
1803
|
+
const data = e.data;
|
|
1804
|
+
const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
|
|
1805
|
+
return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
|
|
1806
|
+
}
|
|
1807
|
+
if (e.name === "APIError") {
|
|
1808
|
+
const data = e.data;
|
|
1809
|
+
const statusCode = data?.statusCode;
|
|
1810
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
1811
|
+
return {
|
|
1812
|
+
kind: "model_auth",
|
|
1813
|
+
providerId: replyProviderId,
|
|
1814
|
+
modelId: replyModelId,
|
|
1815
|
+
reason: "rejected"
|
|
1816
|
+
};
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
return null;
|
|
1820
|
+
}
|
|
1821
|
+
function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
|
|
1822
|
+
if (classified != null) return classified;
|
|
1823
|
+
if (hasConfiguredProvider !== false) return null;
|
|
1824
|
+
return {
|
|
1825
|
+
kind: "model_auth",
|
|
1826
|
+
providerId: replyProviderId,
|
|
1827
|
+
modelId: replyModelId,
|
|
1828
|
+
reason: "missing"
|
|
1829
|
+
};
|
|
1830
|
+
}
|
|
1548
1831
|
function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
1549
1832
|
if (!messages || messages.length === 0) return false;
|
|
1550
1833
|
return messages.some(
|
|
@@ -2073,13 +2356,52 @@ var RunnerConnection = class {
|
|
|
2073
2356
|
}
|
|
2074
2357
|
};
|
|
2075
2358
|
|
|
2359
|
+
// src/lib/tunnel/ready-marker.ts
|
|
2360
|
+
import { writeFileSync } from "fs";
|
|
2361
|
+
function writeTunnelReadyMarker(path, agentId) {
|
|
2362
|
+
try {
|
|
2363
|
+
writeFileSync(path, `${agentId}
|
|
2364
|
+
`);
|
|
2365
|
+
return { ok: true };
|
|
2366
|
+
} catch (error2) {
|
|
2367
|
+
return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
|
|
2371
|
+
// src/lib/claude-usage-reporting.ts
|
|
2372
|
+
var VALID_MODES = ["auto", "on", "off"];
|
|
2373
|
+
function resolveClaudeUsageReportingMode(flagValue, env) {
|
|
2374
|
+
const raw = flagValue ?? env.EVIDENT_CLAUDE_USAGE_REPORTING;
|
|
2375
|
+
if (raw === void 0 || raw === "") {
|
|
2376
|
+
return { mode: "auto", warnings: [] };
|
|
2377
|
+
}
|
|
2378
|
+
const normalized = raw.trim().toLowerCase();
|
|
2379
|
+
if (VALID_MODES.includes(normalized)) {
|
|
2380
|
+
return { mode: normalized, warnings: [] };
|
|
2381
|
+
}
|
|
2382
|
+
const source = flagValue !== void 0 ? "--claude-usage-reporting" : "EVIDENT_CLAUDE_USAGE_REPORTING";
|
|
2383
|
+
return {
|
|
2384
|
+
mode: "auto",
|
|
2385
|
+
warnings: [
|
|
2386
|
+
`Ignoring invalid ${source} "${raw}": expected one of ${VALID_MODES.join(", ")}; using auto`
|
|
2387
|
+
]
|
|
2388
|
+
};
|
|
2389
|
+
}
|
|
2390
|
+
var BASE_REPORT_DELAY_MS = 10 * 6e4;
|
|
2391
|
+
var REPORT_DELAY_JITTER_FRACTION = 0.2;
|
|
2392
|
+
function nextReportDelayMs(random = Math.random) {
|
|
2393
|
+
const jitterRangeMs = BASE_REPORT_DELAY_MS * REPORT_DELAY_JITTER_FRACTION;
|
|
2394
|
+
return BASE_REPORT_DELAY_MS - jitterRangeMs + random() * (2 * jitterRangeMs);
|
|
2395
|
+
}
|
|
2396
|
+
var FIRST_REPORT_DELAY_MS = 5e3 + Math.random() * 1e4;
|
|
2397
|
+
|
|
2076
2398
|
// src/lib/channels/driver.ts
|
|
2077
|
-
import { homedir } from "os";
|
|
2399
|
+
import { homedir as homedir2 } from "os";
|
|
2078
2400
|
|
|
2079
2401
|
// src/lib/file-push.ts
|
|
2080
2402
|
import { randomUUID } from "crypto";
|
|
2081
2403
|
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";
|
|
2404
|
+
import { basename, dirname as dirname2, isAbsolute, join as join2, relative, resolve as resolve2, sep } from "path";
|
|
2083
2405
|
var FILE_MODE = 384;
|
|
2084
2406
|
var DIRECTORY_MODE = 448;
|
|
2085
2407
|
async function writePushedFile(request) {
|
|
@@ -2112,7 +2434,7 @@ async function writePushedFile(request) {
|
|
|
2112
2434
|
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2113
2435
|
dirname2(candidate)
|
|
2114
2436
|
);
|
|
2115
|
-
const realTarget =
|
|
2437
|
+
const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
|
|
2116
2438
|
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2117
2439
|
if (allowedDirectory === null) {
|
|
2118
2440
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
@@ -2148,7 +2470,7 @@ function expandAndValidate(requestedPath, homeDir) {
|
|
|
2148
2470
|
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2149
2471
|
return null;
|
|
2150
2472
|
}
|
|
2151
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
2473
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join2(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2152
2474
|
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2153
2475
|
return null;
|
|
2154
2476
|
}
|
|
@@ -2221,13 +2543,13 @@ function contains(realDirectory, realTarget) {
|
|
|
2221
2543
|
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2222
2544
|
let current = existingAncestor;
|
|
2223
2545
|
for (const segment of missingSegments) {
|
|
2224
|
-
current =
|
|
2546
|
+
current = join2(current, segment);
|
|
2225
2547
|
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2226
2548
|
await chmod(current, DIRECTORY_MODE);
|
|
2227
2549
|
}
|
|
2228
2550
|
}
|
|
2229
2551
|
async function writeAtomically(realTarget, content) {
|
|
2230
|
-
const temporaryPath =
|
|
2552
|
+
const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2231
2553
|
let handle;
|
|
2232
2554
|
try {
|
|
2233
2555
|
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
@@ -2499,6 +2821,8 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
|
2499
2821
|
var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
2500
2822
|
var HEARTBEAT_MS = 6e4;
|
|
2501
2823
|
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
2824
|
+
var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
|
|
2825
|
+
var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
|
|
2502
2826
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2503
2827
|
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
2504
2828
|
var ChannelAuthError = class extends Error {
|
|
@@ -2724,23 +3048,23 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2724
3048
|
* and stops opencode.
|
|
2725
3049
|
*/
|
|
2726
3050
|
stopped = false;
|
|
2727
|
-
constructor(
|
|
2728
|
-
this.agentId =
|
|
2729
|
-
this.port =
|
|
2730
|
-
this.apiUrl =
|
|
2731
|
-
this.getAuthHeader =
|
|
2732
|
-
this.conversationFilter =
|
|
2733
|
-
this.retry = { ...DEFAULT_RETRY_POLICY, ...
|
|
2734
|
-
this.log =
|
|
3051
|
+
constructor(config) {
|
|
3052
|
+
this.agentId = config.agentId;
|
|
3053
|
+
this.port = config.port;
|
|
3054
|
+
this.apiUrl = config.apiUrl.replace(/\/$/, "");
|
|
3055
|
+
this.getAuthHeader = config.getAuthHeader;
|
|
3056
|
+
this.conversationFilter = config.conversationFilter ?? null;
|
|
3057
|
+
this.retry = { ...DEFAULT_RETRY_POLICY, ...config.retry };
|
|
3058
|
+
this.log = config.log ?? (() => {
|
|
2735
3059
|
});
|
|
2736
|
-
this.fetchImpl =
|
|
2737
|
-
this.sleep =
|
|
2738
|
-
this.pausedPollIntervalMs =
|
|
2739
|
-
this.pausedMaxWaitMs =
|
|
2740
|
-
this.stuckQueuedMs =
|
|
2741
|
-
this.now =
|
|
2742
|
-
this.fileSyncDirectories =
|
|
2743
|
-
this.homeDir =
|
|
3060
|
+
this.fetchImpl = config.fetchImpl ?? fetch;
|
|
3061
|
+
this.sleep = config.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
3062
|
+
this.pausedPollIntervalMs = config.pausedPollIntervalMs ?? DEFAULT_PAUSED_POLL_INTERVAL_MS;
|
|
3063
|
+
this.pausedMaxWaitMs = config.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
3064
|
+
this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
3065
|
+
this.now = config.now ?? (() => Date.now());
|
|
3066
|
+
this.fileSyncDirectories = config.fileSyncDirectories ?? [];
|
|
3067
|
+
this.homeDir = config.homeDir ?? homedir2();
|
|
2744
3068
|
}
|
|
2745
3069
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2746
3070
|
get opencodeBase() {
|
|
@@ -3125,7 +3449,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3125
3449
|
const directory = await this.resolveOpenCodeDirectory();
|
|
3126
3450
|
const sessionId = await createOpenCodeSession(this.port, directory);
|
|
3127
3451
|
this.sessions.set(conversationId, sessionId);
|
|
3128
|
-
await this.persistSession(conversationId, sessionId).catch(() => {
|
|
3452
|
+
await this.persistSession(conversationId, sessionId).catch((err) => {
|
|
3453
|
+
this.log({
|
|
3454
|
+
level: "warn",
|
|
3455
|
+
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)}`,
|
|
3456
|
+
conversation_id: conversationId
|
|
3457
|
+
});
|
|
3129
3458
|
});
|
|
3130
3459
|
return sessionId;
|
|
3131
3460
|
}
|
|
@@ -3317,12 +3646,17 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3317
3646
|
stuckReported: false,
|
|
3318
3647
|
lastAliveAt: 0,
|
|
3319
3648
|
aliveInFlight: false,
|
|
3649
|
+
titleSynced: false,
|
|
3650
|
+
titleSyncInFlight: false,
|
|
3320
3651
|
awaitingHumanLatched: false,
|
|
3321
3652
|
pausedOnQuestion: false,
|
|
3322
3653
|
pausedOnPermission: false,
|
|
3323
3654
|
pausedClearConfirmed: false,
|
|
3324
3655
|
pausedInFlight: false,
|
|
3325
|
-
deliveryDeadlineAnchored: false
|
|
3656
|
+
deliveryDeadlineAnchored: false,
|
|
3657
|
+
b2PinnedSinceMs: 0,
|
|
3658
|
+
b2LastDescendantCheckMs: 0,
|
|
3659
|
+
b2AbandonedSignalled: false
|
|
3326
3660
|
});
|
|
3327
3661
|
}
|
|
3328
3662
|
/**
|
|
@@ -3390,12 +3724,17 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3390
3724
|
// with no extra `re_adopted` signal needed (folds old WI-6).
|
|
3391
3725
|
lastAliveAt: 0,
|
|
3392
3726
|
aliveInFlight: false,
|
|
3727
|
+
titleSynced: false,
|
|
3728
|
+
titleSyncInFlight: false,
|
|
3393
3729
|
awaitingHumanLatched: false,
|
|
3394
3730
|
pausedOnQuestion: false,
|
|
3395
3731
|
pausedOnPermission: false,
|
|
3396
3732
|
pausedClearConfirmed: false,
|
|
3397
3733
|
pausedInFlight: false,
|
|
3398
|
-
deliveryDeadlineAnchored: false
|
|
3734
|
+
deliveryDeadlineAnchored: false,
|
|
3735
|
+
b2PinnedSinceMs: 0,
|
|
3736
|
+
b2LastDescendantCheckMs: 0,
|
|
3737
|
+
b2AbandonedSignalled: false
|
|
3399
3738
|
});
|
|
3400
3739
|
}
|
|
3401
3740
|
/**
|
|
@@ -3557,58 +3896,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3557
3896
|
}
|
|
3558
3897
|
}
|
|
3559
3898
|
if (state === "done") {
|
|
3560
|
-
this.
|
|
3561
|
-
if (!inFlight.done) {
|
|
3562
|
-
this.log({
|
|
3563
|
-
level: "info",
|
|
3564
|
-
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
3565
|
-
conversation_id: conv.id,
|
|
3566
|
-
message_id: inFlight.evidentMessageId
|
|
3567
|
-
});
|
|
3568
|
-
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
3569
|
-
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3570
|
-
try {
|
|
3571
|
-
await this.markDone(
|
|
3572
|
-
conv.id,
|
|
3573
|
-
inFlight.evidentMessageId,
|
|
3574
|
-
sessionId,
|
|
3575
|
-
inFlight.opencodeMessageId,
|
|
3576
|
-
title,
|
|
3577
|
-
usage
|
|
3578
|
-
);
|
|
3579
|
-
} catch (err) {
|
|
3580
|
-
if (err instanceof ChannelAuthError) throw err;
|
|
3581
|
-
if (err instanceof ChannelTerminalError) {
|
|
3582
|
-
this.log({
|
|
3583
|
-
level: "warn",
|
|
3584
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
3585
|
-
conversation_id: conv.id,
|
|
3586
|
-
message_id: inFlight.evidentMessageId
|
|
3587
|
-
});
|
|
3588
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3589
|
-
return;
|
|
3590
|
-
}
|
|
3591
|
-
if (this.now() >= inFlight.deadline) {
|
|
3592
|
-
this.log({
|
|
3593
|
-
level: "warn",
|
|
3594
|
-
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)}`,
|
|
3595
|
-
conversation_id: conv.id,
|
|
3596
|
-
message_id: inFlight.evidentMessageId
|
|
3597
|
-
});
|
|
3598
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3599
|
-
return;
|
|
3600
|
-
}
|
|
3601
|
-
this.log({
|
|
3602
|
-
level: "warn",
|
|
3603
|
-
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
3604
|
-
conversation_id: conv.id,
|
|
3605
|
-
message_id: inFlight.evidentMessageId
|
|
3606
|
-
});
|
|
3607
|
-
return;
|
|
3608
|
-
}
|
|
3609
|
-
inFlight.done = true;
|
|
3610
|
-
}
|
|
3611
|
-
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3899
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3612
3900
|
return;
|
|
3613
3901
|
}
|
|
3614
3902
|
if (state === "failed") {
|
|
@@ -3622,8 +3910,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3622
3910
|
message_id: inFlight.evidentMessageId
|
|
3623
3911
|
});
|
|
3624
3912
|
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3913
|
+
const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
|
|
3625
3914
|
try {
|
|
3626
|
-
await this.markFailed(
|
|
3915
|
+
await this.markFailed(
|
|
3916
|
+
conv.id,
|
|
3917
|
+
inFlight.evidentMessageId,
|
|
3918
|
+
sessionId,
|
|
3919
|
+
error2,
|
|
3920
|
+
usage,
|
|
3921
|
+
failure
|
|
3922
|
+
);
|
|
3627
3923
|
} catch (err) {
|
|
3628
3924
|
if (err instanceof ChannelAuthError) throw err;
|
|
3629
3925
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3668,6 +3964,44 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3668
3964
|
});
|
|
3669
3965
|
}
|
|
3670
3966
|
const activelyRunning = state === "running" && !awaitingHuman;
|
|
3967
|
+
const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
|
|
3968
|
+
const snapshotReadable = messages != null && messages.length > 0;
|
|
3969
|
+
if (!pinnedNow) {
|
|
3970
|
+
if (snapshotReadable) {
|
|
3971
|
+
inFlight.b2PinnedSinceMs = 0;
|
|
3972
|
+
inFlight.b2LastDescendantCheckMs = 0;
|
|
3973
|
+
inFlight.b2AbandonedSignalled = false;
|
|
3974
|
+
}
|
|
3975
|
+
} else {
|
|
3976
|
+
if (inFlight.b2AbandonedSignalled) {
|
|
3977
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3978
|
+
return;
|
|
3979
|
+
}
|
|
3980
|
+
if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
|
|
3981
|
+
const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
|
|
3982
|
+
if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
|
|
3983
|
+
inFlight.b2LastDescendantCheckMs = this.now();
|
|
3984
|
+
const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
|
|
3985
|
+
if (isB2AbandonmentConfirmed({
|
|
3986
|
+
pinnedForMs,
|
|
3987
|
+
minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
|
|
3988
|
+
descendantOngoing
|
|
3989
|
+
})) {
|
|
3990
|
+
inFlight.b2AbandonedSignalled = true;
|
|
3991
|
+
this.log({
|
|
3992
|
+
level: "warn",
|
|
3993
|
+
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`,
|
|
3994
|
+
conversation_id: conv.id,
|
|
3995
|
+
message_id: id
|
|
3996
|
+
});
|
|
3997
|
+
void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
|
|
3998
|
+
watched_for_ms: pinnedForMs
|
|
3999
|
+
});
|
|
4000
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
4001
|
+
return;
|
|
4002
|
+
}
|
|
4003
|
+
}
|
|
4004
|
+
}
|
|
3671
4005
|
if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
|
|
3672
4006
|
this.log({
|
|
3673
4007
|
level: "warn",
|
|
@@ -3687,6 +4021,18 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3687
4021
|
inFlight.aliveInFlight = false;
|
|
3688
4022
|
if (ok) inFlight.lastAliveAt = this.now();
|
|
3689
4023
|
});
|
|
4024
|
+
if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
|
|
4025
|
+
inFlight.titleSyncInFlight = true;
|
|
4026
|
+
void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
|
|
4027
|
+
if (!title) {
|
|
4028
|
+
inFlight.titleSyncInFlight = false;
|
|
4029
|
+
return;
|
|
4030
|
+
}
|
|
4031
|
+
const ok = await this.patchConversationTitle(conv.id, title);
|
|
4032
|
+
inFlight.titleSyncInFlight = false;
|
|
4033
|
+
if (ok) inFlight.titleSynced = true;
|
|
4034
|
+
});
|
|
4035
|
+
}
|
|
3690
4036
|
}
|
|
3691
4037
|
if (awaitingHuman) {
|
|
3692
4038
|
if (!inFlight.awaitingHumanLatched) {
|
|
@@ -3724,6 +4070,70 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3724
4070
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3725
4071
|
}
|
|
3726
4072
|
}
|
|
4073
|
+
/**
|
|
4074
|
+
* Settle a message whose run-state has resolved `'done'` — extracted verbatim
|
|
4075
|
+
* (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
|
|
4076
|
+
* inline `state === 'done'` branch body, so a SECOND caller (the #721
|
|
4077
|
+
* b2-abandonment resolution) can reach the exact same completion behavior
|
|
4078
|
+
* (delivery-deadline anchoring, title resolution, usage extraction, and
|
|
4079
|
+
* `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
|
|
4080
|
+
* and risking the two copies silently drifting apart.
|
|
4081
|
+
*/
|
|
4082
|
+
async settleMessageDone(sessionId, watcher, inFlight, messages) {
|
|
4083
|
+
const conv = watcher.conv;
|
|
4084
|
+
this.anchorDeliveryDeadline(inFlight);
|
|
4085
|
+
if (!inFlight.done) {
|
|
4086
|
+
this.log({
|
|
4087
|
+
level: "info",
|
|
4088
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
4089
|
+
conversation_id: conv.id,
|
|
4090
|
+
message_id: inFlight.evidentMessageId
|
|
4091
|
+
});
|
|
4092
|
+
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
4093
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
4094
|
+
try {
|
|
4095
|
+
await this.markDone(
|
|
4096
|
+
conv.id,
|
|
4097
|
+
inFlight.evidentMessageId,
|
|
4098
|
+
sessionId,
|
|
4099
|
+
inFlight.opencodeMessageId,
|
|
4100
|
+
title,
|
|
4101
|
+
usage
|
|
4102
|
+
);
|
|
4103
|
+
} catch (err) {
|
|
4104
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
4105
|
+
if (err instanceof ChannelTerminalError) {
|
|
4106
|
+
this.log({
|
|
4107
|
+
level: "warn",
|
|
4108
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
4109
|
+
conversation_id: conv.id,
|
|
4110
|
+
message_id: inFlight.evidentMessageId
|
|
4111
|
+
});
|
|
4112
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4113
|
+
return;
|
|
4114
|
+
}
|
|
4115
|
+
if (this.now() >= inFlight.deadline) {
|
|
4116
|
+
this.log({
|
|
4117
|
+
level: "warn",
|
|
4118
|
+
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)}`,
|
|
4119
|
+
conversation_id: conv.id,
|
|
4120
|
+
message_id: inFlight.evidentMessageId
|
|
4121
|
+
});
|
|
4122
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4123
|
+
return;
|
|
4124
|
+
}
|
|
4125
|
+
this.log({
|
|
4126
|
+
level: "warn",
|
|
4127
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
4128
|
+
conversation_id: conv.id,
|
|
4129
|
+
message_id: inFlight.evidentMessageId
|
|
4130
|
+
});
|
|
4131
|
+
return;
|
|
4132
|
+
}
|
|
4133
|
+
inFlight.done = true;
|
|
4134
|
+
}
|
|
4135
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4136
|
+
}
|
|
3727
4137
|
// Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
|
|
3728
4138
|
/**
|
|
3729
4139
|
* Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
|
|
@@ -3890,6 +4300,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3890
4300
|
if (state === "failed") {
|
|
3891
4301
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
3892
4302
|
const usage = messageUsage(messages, ocId ?? "");
|
|
4303
|
+
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
3893
4304
|
this.log({
|
|
3894
4305
|
level: "error",
|
|
3895
4306
|
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -3897,7 +4308,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3897
4308
|
message_id: row.id
|
|
3898
4309
|
});
|
|
3899
4310
|
try {
|
|
3900
|
-
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
|
|
4311
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
|
|
3901
4312
|
} catch (err) {
|
|
3902
4313
|
if (err instanceof ChannelAuthError) throw err;
|
|
3903
4314
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -4303,6 +4714,47 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4303
4714
|
}
|
|
4304
4715
|
return false;
|
|
4305
4716
|
}
|
|
4717
|
+
/**
|
|
4718
|
+
* Tri-state variant of the upward parentID membership walk (#721), used ONLY
|
|
4719
|
+
* by `isAnyDescendantSessionOngoing`. Walks the SAME cached
|
|
4720
|
+
* `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
|
|
4721
|
+
* `sessionBelongsTo`, which deliberately collapses "confirmed not a
|
|
4722
|
+
* descendant" and "the walk's fetch failed" into the same `false` (safe for
|
|
4723
|
+
* its OTHER callers: interaction attribution and the recovery-path
|
|
4724
|
+
* `isAnyDescendantSessionAlive`, both of which just retry next tick with no
|
|
4725
|
+
* safety consequence either way) — this variant keeps those two outcomes
|
|
4726
|
+
* SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
|
|
4727
|
+
* (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
|
|
4728
|
+
* not ongoing".
|
|
4729
|
+
*
|
|
4730
|
+
* Return contract:
|
|
4731
|
+
* - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
|
|
4732
|
+
* - `false` → the walk reached a definitive, parent-less root session
|
|
4733
|
+
* WITHOUT ever matching `rootSessionId` — `sessionId` is
|
|
4734
|
+
* CONFIRMED NOT a descendant of it.
|
|
4735
|
+
* - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
|
|
4736
|
+
* through the walk (`resolveSessionParent` returned `undefined`),
|
|
4737
|
+
* or the depth cap (32) was hit without a definitive answer (a
|
|
4738
|
+
* pathological/cyclic chain proves nothing either way). NEVER
|
|
4739
|
+
* treat this the same as `false` — see `sessionBelongsTo`'s own
|
|
4740
|
+
* doc comment above for why that collapse is safe THERE but not
|
|
4741
|
+
* here.
|
|
4742
|
+
*
|
|
4743
|
+
* `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
|
|
4744
|
+
* to the live-path descendant check, not a modification of shared code used
|
|
4745
|
+
* by interaction attribution or the recovery path.
|
|
4746
|
+
*/
|
|
4747
|
+
async resolveSessionMembership(sessionId, rootSessionId) {
|
|
4748
|
+
let current = sessionId;
|
|
4749
|
+
for (let depth = 0; current && depth < 32; depth++) {
|
|
4750
|
+
if (current === rootSessionId) return true;
|
|
4751
|
+
const parent = await this.resolveSessionParent(current);
|
|
4752
|
+
if (parent === void 0) return null;
|
|
4753
|
+
if (parent === null) return false;
|
|
4754
|
+
current = parent;
|
|
4755
|
+
}
|
|
4756
|
+
return null;
|
|
4757
|
+
}
|
|
4306
4758
|
/**
|
|
4307
4759
|
* Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
|
|
4308
4760
|
* `null` for a root session (no parent) and `undefined` when opencode is
|
|
@@ -4387,6 +4839,54 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4387
4839
|
}
|
|
4388
4840
|
return null;
|
|
4389
4841
|
}
|
|
4842
|
+
/**
|
|
4843
|
+
* Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
|
|
4844
|
+
* session title onto the conversation via the PLAIN conversation-update
|
|
4845
|
+
* endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
|
|
4846
|
+
* message-status endpoint `markProcessing`/`markDone` use. Deliberately a
|
|
4847
|
+
* separate, lighter call: it carries no `status`, so it cannot re-trigger the
|
|
4848
|
+
* `processing`/`done` transition side effects (Slack notices, activity-log
|
|
4849
|
+
* rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
|
|
4850
|
+
* ever touches `conversations.title`. That route (`routes/conversations.ts`)
|
|
4851
|
+
* skips a title write matching the stored value, so a redundant call with the
|
|
4852
|
+
* same title is a real no-op — it does not bump `updated_at`, which the
|
|
4853
|
+
* conversation list sorts and paginates on. (Note this is a DIFFERENT guard
|
|
4854
|
+
* from `threads.ts`'s "non-empty AND changed" one, which only covers the
|
|
4855
|
+
* message-status PATCH; the non-empty half is enforced here instead, by
|
|
4856
|
+
* `resolveSessionTitle` never returning an empty/placeholder title.)
|
|
4857
|
+
*
|
|
4858
|
+
* Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
|
|
4859
|
+
* is logged and the title is simply retried on the next heartbeat tick (the
|
|
4860
|
+
* caller only latches `titleSynced` on `true`).
|
|
4861
|
+
*/
|
|
4862
|
+
async patchConversationTitle(conversationId, title) {
|
|
4863
|
+
try {
|
|
4864
|
+
const res = await this.fetchImpl(
|
|
4865
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
|
|
4866
|
+
{
|
|
4867
|
+
method: "PATCH",
|
|
4868
|
+
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
4869
|
+
body: JSON.stringify({ title })
|
|
4870
|
+
}
|
|
4871
|
+
);
|
|
4872
|
+
if (!res.ok) {
|
|
4873
|
+
this.log({
|
|
4874
|
+
level: "debug",
|
|
4875
|
+
message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
|
|
4876
|
+
conversation_id: conversationId
|
|
4877
|
+
});
|
|
4878
|
+
return false;
|
|
4879
|
+
}
|
|
4880
|
+
return true;
|
|
4881
|
+
} catch (err) {
|
|
4882
|
+
this.log({
|
|
4883
|
+
level: "debug",
|
|
4884
|
+
message: `Best-effort mid-turn title sync PATCH failed for conversation ${conversationId.slice(0, 8)} (will retry next heartbeat): ${err instanceof Error ? err.message : String(err)}`,
|
|
4885
|
+
conversation_id: conversationId
|
|
4886
|
+
});
|
|
4887
|
+
return false;
|
|
4888
|
+
}
|
|
4889
|
+
}
|
|
4390
4890
|
/**
|
|
4391
4891
|
* DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
|
|
4392
4892
|
* (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
|
|
@@ -4445,6 +4945,84 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4445
4945
|
}
|
|
4446
4946
|
return false;
|
|
4447
4947
|
}
|
|
4948
|
+
/**
|
|
4949
|
+
* LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
|
|
4950
|
+
* sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
|
|
4951
|
+
* in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
|
|
4952
|
+
*
|
|
4953
|
+
* Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
|
|
4954
|
+
* cross-check above): that method judges liveness from the child's OWN
|
|
4955
|
+
* TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
|
|
4956
|
+
* on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
|
|
4957
|
+
* path the local opencode server IS running, so its in-memory status map is
|
|
4958
|
+
* live and authoritative — and per ADR-0047 §4a ("the child has its own entry
|
|
4959
|
+
* [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
|
|
4960
|
+
* ENTIRE turn (including any tool call it is itself executing), not a
|
|
4961
|
+
* per-message transcript snapshot. This sidesteps the "child's own tool is
|
|
4962
|
+
* executing, between its step's completion and the next generation step"
|
|
4963
|
+
* transcript gap that a transcript-based check would need a second,
|
|
4964
|
+
* sustained-window bound to guard against — it is simply not derived from
|
|
4965
|
+
* message timestamps at all.
|
|
4966
|
+
*
|
|
4967
|
+
* Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
|
|
4968
|
+
* status, as the recovery path does per §4a)? Because on the LIVE path the
|
|
4969
|
+
* root session can be shared: a SECOND, unrelated user message can land on the
|
|
4970
|
+
* SAME session (issue #721's own root cause) and keep the root `busy` for a
|
|
4971
|
+
* reason that has nothing to do with THIS message's delegation. A `task`
|
|
4972
|
+
* descendant session is spawned for exactly one delegated turn and never
|
|
4973
|
+
* reused, so its OWN status-map entry is unambiguous evidence about that one
|
|
4974
|
+
* delegation — which the root's status is not.
|
|
4975
|
+
*
|
|
4976
|
+
* Why membership is checked via `resolveSessionMembership`, NOT
|
|
4977
|
+
* `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
|
|
4978
|
+
* `GET /session/:id` fetch failure into "not a descendant", which would
|
|
4979
|
+
* silently drop a genuinely-live candidate from consideration on the one
|
|
4980
|
+
* unlucky tick its membership-walk fetch hiccups (#721).
|
|
4981
|
+
* `resolveSessionMembership` keeps that failure mode as a distinct `null`
|
|
4982
|
+
* (indeterminate) so it is folded into THIS method's own `indeterminate` flag
|
|
4983
|
+
* instead.
|
|
4984
|
+
*
|
|
4985
|
+
* Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
|
|
4986
|
+
* - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
|
|
4987
|
+
* - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
|
|
4988
|
+
* confirmed either way (`resolveSessionMembership` never
|
|
4989
|
+
* returned `null`), and every CONFIRMED descendant's status read
|
|
4990
|
+
* succeeded and is not ongoing (includes "no descendant session
|
|
4991
|
+
* exists at all" — e.g. a plain, non-`task` tool call).
|
|
4992
|
+
* - `null` → INDETERMINATE: `listSessions` failed, OR at least one
|
|
4993
|
+
* candidate's MEMBERSHIP could not be confirmed
|
|
4994
|
+
* (`resolveSessionMembership` returned `null` — a fetch failure
|
|
4995
|
+
* or pathological chain partway through the parent walk), OR at
|
|
4996
|
+
* least one CONFIRMED descendant's `isSessionOngoing` read
|
|
4997
|
+
* failed — and no OTHER candidate was already confirmed `true`.
|
|
4998
|
+
* The caller MUST NOT treat `null` the same as `false` here
|
|
4999
|
+
* (unlike the recovery cross-check's contract) — see
|
|
5000
|
+
* `isB2AbandonmentConfirmed`.
|
|
5001
|
+
*/
|
|
5002
|
+
async isAnyDescendantSessionOngoing(rootSessionId) {
|
|
5003
|
+
const sessions = await listSessions(this.port);
|
|
5004
|
+
if (!sessions) {
|
|
5005
|
+
this.log({
|
|
5006
|
+
level: "warn",
|
|
5007
|
+
message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
|
|
5008
|
+
});
|
|
5009
|
+
return null;
|
|
5010
|
+
}
|
|
5011
|
+
let indeterminate = false;
|
|
5012
|
+
for (const candidate of sessions) {
|
|
5013
|
+
if (!candidate?.id || candidate.id === rootSessionId) continue;
|
|
5014
|
+
const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
|
|
5015
|
+
if (membership === null) {
|
|
5016
|
+
indeterminate = true;
|
|
5017
|
+
continue;
|
|
5018
|
+
}
|
|
5019
|
+
if (membership === false) continue;
|
|
5020
|
+
const ongoing = await isSessionOngoing(this.port, candidate.id);
|
|
5021
|
+
if (ongoing === true) return true;
|
|
5022
|
+
if (ongoing === null) indeterminate = true;
|
|
5023
|
+
}
|
|
5024
|
+
return indeterminate ? null : false;
|
|
5025
|
+
}
|
|
4448
5026
|
/**
|
|
4449
5027
|
* Cheap decision-telemetry label for a running row's LAST correlated reply
|
|
4450
5028
|
* (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
|
|
@@ -4708,7 +5286,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4708
5286
|
* exists but is wedged, so the next attempt must get a fresh one
|
|
4709
5287
|
* instead of reusing it — see WI-1's server-side null-clearing PATCH).
|
|
4710
5288
|
*/
|
|
4711
|
-
async markFailed(conversationId, messageId, sessionId, error2, usage) {
|
|
5289
|
+
async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
|
|
4712
5290
|
const body = { status: "failed" };
|
|
4713
5291
|
if (sessionId === null) {
|
|
4714
5292
|
body.opencode_session_id = null;
|
|
@@ -4717,6 +5295,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4717
5295
|
}
|
|
4718
5296
|
if (error2 !== void 0) body.error = error2;
|
|
4719
5297
|
if (usage) Object.assign(body, usage);
|
|
5298
|
+
if (failure) {
|
|
5299
|
+
body.failure_kind = failure.kind;
|
|
5300
|
+
body.failure_provider_id = failure.providerId;
|
|
5301
|
+
body.failure_model_id = failure.modelId;
|
|
5302
|
+
body.failure_reason = failure.reason;
|
|
5303
|
+
}
|
|
4720
5304
|
await this.callWithRetry(
|
|
4721
5305
|
"marking message as failed",
|
|
4722
5306
|
() => this.fetchImpl(
|
|
@@ -4729,6 +5313,29 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4729
5313
|
)
|
|
4730
5314
|
);
|
|
4731
5315
|
}
|
|
5316
|
+
/**
|
|
5317
|
+
* Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
|
|
5318
|
+
*
|
|
5319
|
+
* `messageFailure` alone (structured OpenCode error → `model_auth`) covers
|
|
5320
|
+
* most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
|
|
5321
|
+
* to the P1-2b zero-provider check — one extra loopback call to
|
|
5322
|
+
* `hasAnyConfiguredProvider`, only reached when the structured classifier
|
|
5323
|
+
* couldn't place it. Fails open (never throws): a fallback probe failure
|
|
5324
|
+
* (`null`/indeterminate) leaves the classification `null`, which produces
|
|
5325
|
+
* today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
|
|
5326
|
+
*/
|
|
5327
|
+
async classifyModelAuthFailure(messages, userMessageId) {
|
|
5328
|
+
const classified = messageFailure(messages, userMessageId);
|
|
5329
|
+
if (classified != null) return classified;
|
|
5330
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5331
|
+
const hasProvider = await hasAnyConfiguredProvider(this.port);
|
|
5332
|
+
return applyZeroProviderFallback(
|
|
5333
|
+
classified,
|
|
5334
|
+
hasProvider,
|
|
5335
|
+
reply?.info?.providerID ?? null,
|
|
5336
|
+
reply?.info?.modelID ?? null
|
|
5337
|
+
);
|
|
5338
|
+
}
|
|
4732
5339
|
/**
|
|
4733
5340
|
* Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
|
|
4734
5341
|
* (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
|
|
@@ -4881,10 +5488,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4881
5488
|
import chalk5 from "chalk";
|
|
4882
5489
|
import ora2 from "ora";
|
|
4883
5490
|
import { select as select2 } from "@inquirer/prompts";
|
|
5491
|
+
var INTERACTIVE_START_TIMEOUT_MS = 3e4;
|
|
4884
5492
|
async function ensureOpenCodeRunning(ctx) {
|
|
4885
5493
|
const healthCheck = await checkOpenCodeHealth(ctx.port);
|
|
4886
5494
|
if (healthCheck.healthy) {
|
|
4887
|
-
return {
|
|
5495
|
+
return {
|
|
5496
|
+
port: ctx.port,
|
|
5497
|
+
process: null,
|
|
5498
|
+
version: healthCheck.version ?? null,
|
|
5499
|
+
notReadyReason: null
|
|
5500
|
+
};
|
|
4888
5501
|
}
|
|
4889
5502
|
const runningInstances = await findHealthyOpenCodeInstances();
|
|
4890
5503
|
if (runningInstances.length > 0) {
|
|
@@ -4905,7 +5518,7 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4905
5518
|
console.log(chalk5.yellow("Tip: Run with the correct port:"));
|
|
4906
5519
|
console.log(
|
|
4907
5520
|
chalk5.dim(
|
|
4908
|
-
` ${getCliName()} run --
|
|
5521
|
+
` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
|
|
4909
5522
|
)
|
|
4910
5523
|
);
|
|
4911
5524
|
}
|
|
@@ -4925,14 +5538,22 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4925
5538
|
if (!ctx.interactive) {
|
|
4926
5539
|
ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
|
|
4927
5540
|
const proc = await startOpenCode(ctx.port);
|
|
4928
|
-
const health = await waitForOpenCodeHealth(ctx.port,
|
|
5541
|
+
const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
|
|
4929
5542
|
if (!health.healthy) {
|
|
4930
|
-
|
|
4931
|
-
|
|
4932
|
-
|
|
5543
|
+
return {
|
|
5544
|
+
port: ctx.port,
|
|
5545
|
+
process: proc,
|
|
5546
|
+
version: null,
|
|
5547
|
+
notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
|
|
5548
|
+
};
|
|
4933
5549
|
}
|
|
4934
5550
|
ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
|
|
4935
|
-
return {
|
|
5551
|
+
return {
|
|
5552
|
+
port: ctx.port,
|
|
5553
|
+
process: proc,
|
|
5554
|
+
version: health.version ?? null,
|
|
5555
|
+
notReadyReason: null
|
|
5556
|
+
};
|
|
4936
5557
|
}
|
|
4937
5558
|
let port = ctx.port;
|
|
4938
5559
|
if (isPortInUse(port)) {
|
|
@@ -4985,15 +5606,15 @@ Port ${port} is already in use.`));
|
|
|
4985
5606
|
if (action === "start") {
|
|
4986
5607
|
const spinner = ora2("Starting OpenCode...").start();
|
|
4987
5608
|
const proc = await startOpenCode(port);
|
|
4988
|
-
const health = await waitForOpenCodeHealth(port,
|
|
5609
|
+
const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
|
|
4989
5610
|
if (!health.healthy) {
|
|
4990
5611
|
spinner.fail("Failed to start OpenCode");
|
|
4991
5612
|
throw new Error("OpenCode failed to start");
|
|
4992
5613
|
}
|
|
4993
5614
|
spinner.stop();
|
|
4994
|
-
return { port, process: proc, version: health.version ?? null };
|
|
5615
|
+
return { port, process: proc, version: health.version ?? null, notReadyReason: null };
|
|
4995
5616
|
}
|
|
4996
|
-
return { port, process: null, version: null };
|
|
5617
|
+
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
4997
5618
|
}
|
|
4998
5619
|
|
|
4999
5620
|
// src/commands/agent-lookup.ts
|
|
@@ -5035,19 +5656,21 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
5035
5656
|
return { agent_id: data.agent_id };
|
|
5036
5657
|
}
|
|
5037
5658
|
return {
|
|
5038
|
-
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --
|
|
5659
|
+
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
|
|
5039
5660
|
};
|
|
5040
5661
|
} catch (error2) {
|
|
5041
5662
|
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
5042
5663
|
return { error: `Failed to resolve runner from key: ${message}` };
|
|
5043
5664
|
}
|
|
5044
5665
|
}
|
|
5666
|
+
var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
|
|
5045
5667
|
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
5046
5668
|
const apiUrl = getApiUrlConfig();
|
|
5047
5669
|
try {
|
|
5048
5670
|
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
5049
5671
|
method: "POST",
|
|
5050
|
-
headers: { Authorization: authHeader }
|
|
5672
|
+
headers: { Authorization: authHeader },
|
|
5673
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5051
5674
|
});
|
|
5052
5675
|
if (!response.ok) {
|
|
5053
5676
|
const serverMessage = await readErrorMessage(response);
|
|
@@ -5058,7 +5681,63 @@ async function notifyAgentDisconnected(agentId, authHeader) {
|
|
|
5058
5681
|
}
|
|
5059
5682
|
return { ok: true };
|
|
5060
5683
|
} catch (error2) {
|
|
5061
|
-
return { ok: false, error:
|
|
5684
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5685
|
+
}
|
|
5686
|
+
}
|
|
5687
|
+
function describeBestEffortError(error2) {
|
|
5688
|
+
const name = error2?.name;
|
|
5689
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
5690
|
+
return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
|
|
5691
|
+
}
|
|
5692
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
5693
|
+
}
|
|
5694
|
+
async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
5695
|
+
try {
|
|
5696
|
+
const apiUrl = getApiUrlConfig();
|
|
5697
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
|
|
5698
|
+
method: "POST",
|
|
5699
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5700
|
+
body: JSON.stringify({ microvm_id: microvmId }),
|
|
5701
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5702
|
+
});
|
|
5703
|
+
if (!response.ok) {
|
|
5704
|
+
const serverMessage = await readErrorMessage(response);
|
|
5705
|
+
return {
|
|
5706
|
+
ok: false,
|
|
5707
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5708
|
+
};
|
|
5709
|
+
}
|
|
5710
|
+
return { ok: true };
|
|
5711
|
+
} catch (error2) {
|
|
5712
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5713
|
+
}
|
|
5714
|
+
}
|
|
5715
|
+
function toReportedWindow(window) {
|
|
5716
|
+
if (!window) return null;
|
|
5717
|
+
return { utilization: window.utilization, resets_at: window.resetsAt };
|
|
5718
|
+
}
|
|
5719
|
+
async function reportClaudeUsage(agentId, authHeader, snapshot) {
|
|
5720
|
+
try {
|
|
5721
|
+
const apiUrl = getApiUrlConfig();
|
|
5722
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/claude-usage`, {
|
|
5723
|
+
method: "POST",
|
|
5724
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5725
|
+
body: JSON.stringify({
|
|
5726
|
+
five_hour: toReportedWindow(snapshot.fiveHour),
|
|
5727
|
+
seven_day: toReportedWindow(snapshot.sevenDay)
|
|
5728
|
+
}),
|
|
5729
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5730
|
+
});
|
|
5731
|
+
if (!response.ok) {
|
|
5732
|
+
const serverMessage = await readErrorMessage(response);
|
|
5733
|
+
return {
|
|
5734
|
+
ok: false,
|
|
5735
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5736
|
+
};
|
|
5737
|
+
}
|
|
5738
|
+
return { ok: true };
|
|
5739
|
+
} catch (error2) {
|
|
5740
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5062
5741
|
}
|
|
5063
5742
|
}
|
|
5064
5743
|
async function getAgentInfo(agentId, authHeader) {
|
|
@@ -5108,6 +5787,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
|
5108
5787
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
5109
5788
|
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
5110
5789
|
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
5790
|
+
var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
5111
5791
|
function resolveLogLevel(options) {
|
|
5112
5792
|
const accepted = Object.keys(LOG_LEVELS);
|
|
5113
5793
|
const validate = (value, source) => {
|
|
@@ -5138,7 +5818,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
5138
5818
|
if (trimmed === "") {
|
|
5139
5819
|
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5140
5820
|
}
|
|
5141
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
5821
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join3(homeDir, trimmed.slice(2)) : trimmed;
|
|
5142
5822
|
if (!isAbsolute2(expanded)) {
|
|
5143
5823
|
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5144
5824
|
}
|
|
@@ -5159,6 +5839,35 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
5159
5839
|
}
|
|
5160
5840
|
return directories;
|
|
5161
5841
|
}
|
|
5842
|
+
var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
|
|
5843
|
+
var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
|
|
5844
|
+
var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
|
|
5845
|
+
function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
|
|
5846
|
+
const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
|
|
5847
|
+
let raw;
|
|
5848
|
+
let source;
|
|
5849
|
+
if (options.opencodeStartTimeout !== void 0) {
|
|
5850
|
+
raw = options.opencodeStartTimeout;
|
|
5851
|
+
source = "--opencode-start-timeout";
|
|
5852
|
+
} else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
|
|
5853
|
+
raw = env[OPENCODE_START_TIMEOUT_ENV];
|
|
5854
|
+
source = OPENCODE_START_TIMEOUT_ENV;
|
|
5855
|
+
} else {
|
|
5856
|
+
return { timeoutMs: defaultMs, warnings: [] };
|
|
5857
|
+
}
|
|
5858
|
+
const trimmed = raw.trim();
|
|
5859
|
+
const seconds = Number(trimmed);
|
|
5860
|
+
const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
|
|
5861
|
+
if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
|
|
5862
|
+
return {
|
|
5863
|
+
timeoutMs: defaultMs,
|
|
5864
|
+
warnings: [
|
|
5865
|
+
`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`
|
|
5866
|
+
]
|
|
5867
|
+
};
|
|
5868
|
+
}
|
|
5869
|
+
return { timeoutMs: seconds * 1e3, warnings: [] };
|
|
5870
|
+
}
|
|
5162
5871
|
function meetsThreshold(state, level) {
|
|
5163
5872
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
5164
5873
|
}
|
|
@@ -5180,6 +5889,10 @@ function log2(state, message, level = "info") {
|
|
|
5180
5889
|
function logActivity(state, entry) {
|
|
5181
5890
|
const level = entry.level ?? (entry.type === "error" ? "error" : "info");
|
|
5182
5891
|
if (!meetsThreshold(state, level)) return;
|
|
5892
|
+
forwardRunnerActivity(
|
|
5893
|
+
{ level, message: entry.message, error: entry.error },
|
|
5894
|
+
{ agentId: state.agentId, authHeader: state.authHeader }
|
|
5895
|
+
);
|
|
5183
5896
|
const fullEntry = {
|
|
5184
5897
|
...entry,
|
|
5185
5898
|
level,
|
|
@@ -5279,6 +5992,7 @@ async function handleAuthError(state, error2) {
|
|
|
5279
5992
|
}
|
|
5280
5993
|
async function driveChannels(state, driver) {
|
|
5281
5994
|
let idlePolls = 0;
|
|
5995
|
+
let consecutiveDrainFailures = 0;
|
|
5282
5996
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
5283
5997
|
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
5284
5998
|
while (state.running) {
|
|
@@ -5296,6 +6010,7 @@ async function driveChannels(state, driver) {
|
|
|
5296
6010
|
);
|
|
5297
6011
|
try {
|
|
5298
6012
|
const processed = await driver.drainPending();
|
|
6013
|
+
consecutiveDrainFailures = 0;
|
|
5299
6014
|
state.messageCount += processed;
|
|
5300
6015
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
5301
6016
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
@@ -5330,8 +6045,32 @@ async function driveChannels(state, driver) {
|
|
|
5330
6045
|
const errorMessage = error2 instanceof Error ? error2.message : String(error2);
|
|
5331
6046
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
5332
6047
|
if (state.interactive) displayStatus(state);
|
|
6048
|
+
if (driver.hasInFlightWatchers()) {
|
|
6049
|
+
consecutiveDrainFailures = 0;
|
|
6050
|
+
} else if (state.idleTimeout !== null) {
|
|
6051
|
+
consecutiveDrainFailures++;
|
|
6052
|
+
if (consecutiveDrainFailures === 1) {
|
|
6053
|
+
logActivity(state, {
|
|
6054
|
+
type: "info",
|
|
6055
|
+
message: `Cannot reach Evident, will exit if this persists past the idle timeout (timeout: ${state.idleTimeout}s)...`
|
|
6056
|
+
});
|
|
6057
|
+
if (state.interactive) displayStatus(state);
|
|
6058
|
+
}
|
|
6059
|
+
}
|
|
5333
6060
|
}
|
|
5334
6061
|
await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
|
|
6062
|
+
if (state.idleTimeout !== null && consecutiveDrainFailures >= 2) {
|
|
6063
|
+
const unreachableMs = consecutiveDrainFailures * CHANNEL_POLL_INTERVAL_MS;
|
|
6064
|
+
if (unreachableMs > state.idleTimeout * 1e3) {
|
|
6065
|
+
logActivity(state, {
|
|
6066
|
+
type: "info",
|
|
6067
|
+
level: "warn",
|
|
6068
|
+
message: `Exiting: could not reach Evident for ${consecutiveDrainFailures} consecutive polls (${Math.round(unreachableMs / 1e3)}s)`
|
|
6069
|
+
});
|
|
6070
|
+
if (state.interactive) displayStatus(state);
|
|
6071
|
+
break;
|
|
6072
|
+
}
|
|
6073
|
+
}
|
|
5335
6074
|
if (state.idleTimeout !== null && idlePolls >= 2) {
|
|
5336
6075
|
const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
|
|
5337
6076
|
if (idleMs > state.idleTimeout * 1e3) {
|
|
@@ -5343,8 +6082,8 @@ async function driveChannels(state, driver) {
|
|
|
5343
6082
|
}
|
|
5344
6083
|
}
|
|
5345
6084
|
var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
|
|
5346
|
-
async function runSweep(state, driver,
|
|
5347
|
-
const mode = `age=${
|
|
6085
|
+
async function runSweep(state, driver, config) {
|
|
6086
|
+
const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
|
|
5348
6087
|
try {
|
|
5349
6088
|
const sessions = await listSessions(state.port);
|
|
5350
6089
|
if (sessions === null) {
|
|
@@ -5357,8 +6096,8 @@ async function runSweep(state, driver, config2) {
|
|
|
5357
6096
|
const toDelete = selectSessionsToDelete(
|
|
5358
6097
|
sessions.map((s) => ({ id: s.id, lastActivityMs: sessionLastActivityMs(s) })),
|
|
5359
6098
|
{
|
|
5360
|
-
maxAgeMs:
|
|
5361
|
-
maxCount:
|
|
6099
|
+
maxAgeMs: config.maxAgeMs,
|
|
6100
|
+
maxCount: config.maxCount,
|
|
5362
6101
|
nowMs: Date.now(),
|
|
5363
6102
|
protectedIds: driver.protectedSessionIds()
|
|
5364
6103
|
}
|
|
@@ -5394,7 +6133,7 @@ async function runSweep(state, driver, config2) {
|
|
|
5394
6133
|
}
|
|
5395
6134
|
}
|
|
5396
6135
|
function scheduleSessionCleanup(state, driver, options) {
|
|
5397
|
-
const
|
|
6136
|
+
const config = resolveSessionCleanupConfig(
|
|
5398
6137
|
{
|
|
5399
6138
|
maxAge: options.sessionCleanupMaxAge,
|
|
5400
6139
|
maxCount: options.sessionCleanupMaxCount,
|
|
@@ -5402,21 +6141,109 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
5402
6141
|
},
|
|
5403
6142
|
process.env
|
|
5404
6143
|
);
|
|
5405
|
-
for (const warning2 of
|
|
6144
|
+
for (const warning2 of config.warnings) {
|
|
5406
6145
|
logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
|
|
5407
6146
|
}
|
|
5408
|
-
if (!
|
|
6147
|
+
if (!config.enabled) return;
|
|
5409
6148
|
logActivity(state, {
|
|
5410
6149
|
type: "info",
|
|
5411
|
-
message: `Session cleanup enabled (age=${
|
|
6150
|
+
message: `Session cleanup enabled (age=${config.maxAgeMs ?? "\u2014"}, count=${config.maxCount ?? "\u2014"}, interval=${config.intervalMs}ms)`
|
|
5412
6151
|
});
|
|
5413
|
-
const interval = setInterval(() => void runSweep(state, driver,
|
|
6152
|
+
const interval = setInterval(() => void runSweep(state, driver, config), config.intervalMs);
|
|
5414
6153
|
const firstSweep = setTimeout(
|
|
5415
|
-
() => void runSweep(state, driver,
|
|
6154
|
+
() => void runSweep(state, driver, config),
|
|
5416
6155
|
SESSION_CLEANUP_FIRST_SWEEP_MS
|
|
5417
6156
|
);
|
|
5418
6157
|
state.sessionCleanupTimers.push(interval, firstSweep);
|
|
5419
6158
|
}
|
|
6159
|
+
function scheduleClaudeUsageReporting(state, options) {
|
|
6160
|
+
const { mode, warnings } = resolveClaudeUsageReportingMode(
|
|
6161
|
+
options.claudeUsageReporting,
|
|
6162
|
+
process.env
|
|
6163
|
+
);
|
|
6164
|
+
for (const warning2 of warnings) {
|
|
6165
|
+
logActivity(state, {
|
|
6166
|
+
type: "info",
|
|
6167
|
+
level: "warn",
|
|
6168
|
+
message: `Claude usage reporting: ${warning2}`
|
|
6169
|
+
});
|
|
6170
|
+
}
|
|
6171
|
+
if (mode === "off") {
|
|
6172
|
+
logActivity(state, {
|
|
6173
|
+
type: "info",
|
|
6174
|
+
level: "debug",
|
|
6175
|
+
message: "Claude usage reporting is off (--claude-usage-reporting off)"
|
|
6176
|
+
});
|
|
6177
|
+
return;
|
|
6178
|
+
}
|
|
6179
|
+
let consecutiveFailures = 0;
|
|
6180
|
+
const scheduleNextTick = () => {
|
|
6181
|
+
state.claudeUsageTimer = setTimeout(() => void tick(false), nextReportDelayMs());
|
|
6182
|
+
};
|
|
6183
|
+
const tick = async (isFirst) => {
|
|
6184
|
+
try {
|
|
6185
|
+
const usage = await getClaudeUsage();
|
|
6186
|
+
const result = await reportClaudeUsage(state.agentId, state.authHeader, usage);
|
|
6187
|
+
if (result.ok) {
|
|
6188
|
+
if (consecutiveFailures > 0) {
|
|
6189
|
+
logActivity(state, {
|
|
6190
|
+
type: "info",
|
|
6191
|
+
level: "info",
|
|
6192
|
+
message: "Claude usage reporting recovered"
|
|
6193
|
+
});
|
|
6194
|
+
}
|
|
6195
|
+
consecutiveFailures = 0;
|
|
6196
|
+
logActivity(state, {
|
|
6197
|
+
type: "info",
|
|
6198
|
+
level: "debug",
|
|
6199
|
+
message: "Reported Claude usage to Evident"
|
|
6200
|
+
});
|
|
6201
|
+
} else {
|
|
6202
|
+
consecutiveFailures++;
|
|
6203
|
+
logActivity(state, {
|
|
6204
|
+
type: "info",
|
|
6205
|
+
level: consecutiveFailures === 1 ? "warn" : "debug",
|
|
6206
|
+
message: `Failed to report Claude usage: ${result.error}`
|
|
6207
|
+
});
|
|
6208
|
+
}
|
|
6209
|
+
scheduleNextTick();
|
|
6210
|
+
} catch (error2) {
|
|
6211
|
+
if (error2 instanceof ClaudeUsageError && isLocalCredentialProblem(error2)) {
|
|
6212
|
+
if (mode === "on") {
|
|
6213
|
+
logActivity(state, {
|
|
6214
|
+
type: "info",
|
|
6215
|
+
level: "warn",
|
|
6216
|
+
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"
|
|
6217
|
+
});
|
|
6218
|
+
scheduleNextTick();
|
|
6219
|
+
} else if (isFirst) {
|
|
6220
|
+
logActivity(state, {
|
|
6221
|
+
type: "info",
|
|
6222
|
+
level: "debug",
|
|
6223
|
+
message: `Claude usage reporting: ${error2.message}`
|
|
6224
|
+
});
|
|
6225
|
+
} else {
|
|
6226
|
+
logActivity(state, {
|
|
6227
|
+
type: "info",
|
|
6228
|
+
level: "debug",
|
|
6229
|
+
message: `Claude usage reporting: ${error2.message}`
|
|
6230
|
+
});
|
|
6231
|
+
scheduleNextTick();
|
|
6232
|
+
}
|
|
6233
|
+
} else {
|
|
6234
|
+
consecutiveFailures++;
|
|
6235
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
6236
|
+
logActivity(state, {
|
|
6237
|
+
type: "info",
|
|
6238
|
+
level: consecutiveFailures === 1 ? "warn" : "debug",
|
|
6239
|
+
message: `Claude usage reporting failed: ${message}`
|
|
6240
|
+
});
|
|
6241
|
+
scheduleNextTick();
|
|
6242
|
+
}
|
|
6243
|
+
}
|
|
6244
|
+
};
|
|
6245
|
+
state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
|
|
6246
|
+
}
|
|
5420
6247
|
async function notifyOffline(state) {
|
|
5421
6248
|
if (!state.agentId || !state.authHeader) return;
|
|
5422
6249
|
if (!state.connected) {
|
|
@@ -5434,13 +6261,28 @@ async function notifyOffline(state) {
|
|
|
5434
6261
|
if (state.interactive) displayStatus(state);
|
|
5435
6262
|
}
|
|
5436
6263
|
}
|
|
6264
|
+
async function timeShutdownPhase(state, durations, name, run2) {
|
|
6265
|
+
const startedAt = Date.now();
|
|
6266
|
+
try {
|
|
6267
|
+
return await run2();
|
|
6268
|
+
} finally {
|
|
6269
|
+
const elapsedMs = Date.now() - startedAt;
|
|
6270
|
+
durations[name] = elapsedMs;
|
|
6271
|
+
log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
|
|
6272
|
+
}
|
|
6273
|
+
}
|
|
5437
6274
|
async function cleanup(state, opts = {}) {
|
|
6275
|
+
const durations = {};
|
|
5438
6276
|
state.running = false;
|
|
5439
6277
|
for (const timer of state.sessionCleanupTimers) {
|
|
5440
6278
|
clearInterval(timer);
|
|
5441
6279
|
clearTimeout(timer);
|
|
5442
6280
|
}
|
|
5443
6281
|
state.sessionCleanupTimers = [];
|
|
6282
|
+
if (state.claudeUsageTimer) {
|
|
6283
|
+
clearTimeout(state.claudeUsageTimer);
|
|
6284
|
+
state.claudeUsageTimer = null;
|
|
6285
|
+
}
|
|
5444
6286
|
if (opts.graceful && state.channelDriver) {
|
|
5445
6287
|
state.channelDriver.stop();
|
|
5446
6288
|
log2(state, "Draining in-flight channel work before shutdown...");
|
|
@@ -5448,7 +6290,13 @@ async function cleanup(state, opts = {}) {
|
|
|
5448
6290
|
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
5449
6291
|
displayStatus(state);
|
|
5450
6292
|
}
|
|
5451
|
-
const
|
|
6293
|
+
const driver = state.channelDriver;
|
|
6294
|
+
const settled = await timeShutdownPhase(
|
|
6295
|
+
state,
|
|
6296
|
+
durations,
|
|
6297
|
+
"drain",
|
|
6298
|
+
() => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
|
|
6299
|
+
);
|
|
5452
6300
|
if (!settled) {
|
|
5453
6301
|
logActivity(state, {
|
|
5454
6302
|
type: "info",
|
|
@@ -5457,13 +6305,15 @@ async function cleanup(state, opts = {}) {
|
|
|
5457
6305
|
if (state.interactive) displayStatus(state);
|
|
5458
6306
|
}
|
|
5459
6307
|
}
|
|
5460
|
-
await notifyOffline(state);
|
|
6308
|
+
await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
|
|
5461
6309
|
if (state.connection) {
|
|
5462
|
-
state.connection
|
|
6310
|
+
const connection = state.connection;
|
|
6311
|
+
await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
|
|
5463
6312
|
state.connection = null;
|
|
5464
6313
|
}
|
|
5465
6314
|
if (state.opencodeProcess) {
|
|
5466
|
-
|
|
6315
|
+
const opencodeProcess = state.opencodeProcess;
|
|
6316
|
+
await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
|
|
5467
6317
|
if (state.interactive) {
|
|
5468
6318
|
logActivity(state, { type: "info", message: "Stopped OpenCode process" });
|
|
5469
6319
|
displayStatus(state);
|
|
@@ -5472,6 +6322,7 @@ async function cleanup(state, opts = {}) {
|
|
|
5472
6322
|
}
|
|
5473
6323
|
state.opencodeProcess = null;
|
|
5474
6324
|
}
|
|
6325
|
+
return durations;
|
|
5475
6326
|
}
|
|
5476
6327
|
async function run(options) {
|
|
5477
6328
|
const interactive = isInteractive(options.json);
|
|
@@ -5479,7 +6330,7 @@ async function run(options) {
|
|
|
5479
6330
|
let fileSyncDirectories;
|
|
5480
6331
|
try {
|
|
5481
6332
|
logLevel = resolveLogLevel(options);
|
|
5482
|
-
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo,
|
|
6333
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
|
|
5483
6334
|
} catch (error2) {
|
|
5484
6335
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
5485
6336
|
if (options.json) {
|
|
@@ -5512,8 +6363,10 @@ async function run(options) {
|
|
|
5512
6363
|
messageCount: 0,
|
|
5513
6364
|
lastProxiedActivityAt: null,
|
|
5514
6365
|
sessionCleanupTimers: [],
|
|
6366
|
+
claudeUsageTimer: null,
|
|
5515
6367
|
authHeader: ""
|
|
5516
6368
|
};
|
|
6369
|
+
setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
|
|
5517
6370
|
if (fileSyncDirectories.length > 0) {
|
|
5518
6371
|
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
5519
6372
|
} else {
|
|
@@ -5542,14 +6395,38 @@ async function run(options) {
|
|
|
5542
6395
|
const handleSignal = async () => {
|
|
5543
6396
|
if (state.shuttingDown) return;
|
|
5544
6397
|
state.shuttingDown = true;
|
|
6398
|
+
const shutdownStartedAt = Date.now();
|
|
5545
6399
|
if (state.interactive) {
|
|
5546
6400
|
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
5547
6401
|
displayStatus(state);
|
|
5548
6402
|
} else {
|
|
5549
6403
|
log2(state, "Shutting down...");
|
|
5550
6404
|
}
|
|
5551
|
-
await cleanup(state, { graceful: true });
|
|
5552
|
-
|
|
6405
|
+
const durations = await cleanup(state, { graceful: true });
|
|
6406
|
+
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
6407
|
+
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
6408
|
+
let timer;
|
|
6409
|
+
const flushed = shutdownTelemetry().then(
|
|
6410
|
+
() => true,
|
|
6411
|
+
(error2) => {
|
|
6412
|
+
log2(
|
|
6413
|
+
state,
|
|
6414
|
+
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
6415
|
+
"warn"
|
|
6416
|
+
);
|
|
6417
|
+
return true;
|
|
6418
|
+
}
|
|
6419
|
+
);
|
|
6420
|
+
const timedOut = new Promise((resolve3) => {
|
|
6421
|
+
timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
|
|
6422
|
+
});
|
|
6423
|
+
if (!await Promise.race([flushed, timedOut])) {
|
|
6424
|
+
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
6425
|
+
}
|
|
6426
|
+
clearTimeout(timer);
|
|
6427
|
+
});
|
|
6428
|
+
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
6429
|
+
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
5553
6430
|
process.exit(0);
|
|
5554
6431
|
};
|
|
5555
6432
|
process.on("SIGINT", handleSignal);
|
|
@@ -5663,40 +6540,67 @@ async function run(options) {
|
|
|
5663
6540
|
}
|
|
5664
6541
|
spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
|
|
5665
6542
|
state.agentName = validation.agent.name;
|
|
6543
|
+
const microvmId = process.env.MICROVM_ID?.trim();
|
|
6544
|
+
if (microvmId) {
|
|
6545
|
+
const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
|
|
6546
|
+
if (reported.ok) {
|
|
6547
|
+
log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
|
|
6548
|
+
} else {
|
|
6549
|
+
const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
|
|
6550
|
+
log2(state, message, "warn");
|
|
6551
|
+
if (state.interactive && !state.json) {
|
|
6552
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6553
|
+
}
|
|
6554
|
+
}
|
|
6555
|
+
} else {
|
|
6556
|
+
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
6557
|
+
}
|
|
6558
|
+
const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
|
|
6559
|
+
for (const warning2 of opencodeStartTimeoutWarnings) {
|
|
6560
|
+
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
6561
|
+
}
|
|
5666
6562
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
5667
6563
|
try {
|
|
5668
6564
|
const oc = await ensureOpenCodeRunning({
|
|
5669
6565
|
port: state.port,
|
|
5670
6566
|
interactive: state.interactive,
|
|
5671
6567
|
agentId: state.agentId,
|
|
5672
|
-
log: (message) => log2(state, message)
|
|
6568
|
+
log: (message) => log2(state, message),
|
|
6569
|
+
startTimeoutMs: opencodeStartTimeoutMs
|
|
5673
6570
|
});
|
|
5674
6571
|
state.port = oc.port;
|
|
5675
6572
|
state.opencodeProcess = oc.process;
|
|
5676
6573
|
state.opencodeVersion = oc.version;
|
|
5677
|
-
state.opencodeConnected = oc.
|
|
6574
|
+
state.opencodeConnected = oc.notReadyReason === null;
|
|
5678
6575
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
5679
6576
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
5680
|
-
|
|
5681
|
-
|
|
5682
|
-
|
|
5683
|
-
|
|
5684
|
-
|
|
6577
|
+
if (!state.interactive && oc.notReadyReason !== null) {
|
|
6578
|
+
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}).`;
|
|
6579
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6580
|
+
} else {
|
|
6581
|
+
const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
|
|
6582
|
+
if (versionWarning) {
|
|
6583
|
+
log2(state, versionWarning, "warn");
|
|
6584
|
+
if (state.interactive && !state.json) {
|
|
6585
|
+
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
6586
|
+
}
|
|
5685
6587
|
}
|
|
5686
|
-
|
|
5687
|
-
|
|
5688
|
-
|
|
5689
|
-
|
|
5690
|
-
|
|
5691
|
-
|
|
5692
|
-
|
|
5693
|
-
|
|
5694
|
-
|
|
5695
|
-
|
|
5696
|
-
|
|
5697
|
-
|
|
5698
|
-
|
|
5699
|
-
|
|
6588
|
+
const noProviderWarning = buildNoProviderWarning(
|
|
6589
|
+
await hasAnyConfiguredProvider(state.port)
|
|
6590
|
+
);
|
|
6591
|
+
if (noProviderWarning) {
|
|
6592
|
+
log2(state, noProviderWarning, "warn");
|
|
6593
|
+
if (state.interactive && !state.json) {
|
|
6594
|
+
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
6595
|
+
blank();
|
|
6596
|
+
console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
6597
|
+
console.log(
|
|
6598
|
+
chalk6.dim(
|
|
6599
|
+
`Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
6600
|
+
)
|
|
6601
|
+
);
|
|
6602
|
+
blank();
|
|
6603
|
+
}
|
|
5700
6604
|
}
|
|
5701
6605
|
}
|
|
5702
6606
|
} catch (error2) {
|
|
@@ -5714,7 +6618,7 @@ async function run(options) {
|
|
|
5714
6618
|
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
5715
6619
|
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
5716
6620
|
fileSyncDirectories,
|
|
5717
|
-
homeDir:
|
|
6621
|
+
homeDir: homedir3(),
|
|
5718
6622
|
log: (entry) => (
|
|
5719
6623
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
5720
6624
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -5741,6 +6645,18 @@ async function run(options) {
|
|
|
5741
6645
|
type: "info",
|
|
5742
6646
|
message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
|
|
5743
6647
|
});
|
|
6648
|
+
if (options.tunnelReadyFile) {
|
|
6649
|
+
const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
|
|
6650
|
+
if (marker.ok) {
|
|
6651
|
+
log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
|
|
6652
|
+
} else {
|
|
6653
|
+
log2(
|
|
6654
|
+
state,
|
|
6655
|
+
`Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
|
|
6656
|
+
"error"
|
|
6657
|
+
);
|
|
6658
|
+
}
|
|
6659
|
+
}
|
|
5744
6660
|
emitAgentConnected(state.agentId, {
|
|
5745
6661
|
port: state.port,
|
|
5746
6662
|
cli_version: getCliVersion(),
|
|
@@ -5831,6 +6747,7 @@ async function run(options) {
|
|
|
5831
6747
|
throw error2;
|
|
5832
6748
|
}
|
|
5833
6749
|
scheduleSessionCleanup(state, channelDriver, options);
|
|
6750
|
+
scheduleClaudeUsageReporting(state, options);
|
|
5834
6751
|
if (!interactive || state.json) {
|
|
5835
6752
|
log2(state, "Driving channel messages...");
|
|
5836
6753
|
}
|
|
@@ -5885,13 +6802,17 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
5885
6802
|
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);
|
|
5886
6803
|
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 }));
|
|
5887
6804
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
6805
|
+
program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);
|
|
5888
6806
|
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(
|
|
5889
6807
|
"-a, --agent [id]",
|
|
5890
6808
|
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
5891
6809
|
).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
5892
6810
|
"--log-level <level>",
|
|
5893
6811
|
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
5894
|
-
).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(
|
|
6812
|
+
).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(
|
|
6813
|
+
"--opencode-start-timeout <seconds>",
|
|
6814
|
+
"Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
|
|
6815
|
+
).option("--json", "Output in JSON format").option(
|
|
5895
6816
|
"--session-cleanup-max-age <duration>",
|
|
5896
6817
|
"Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
|
|
5897
6818
|
).option(
|
|
@@ -5900,11 +6821,17 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5900
6821
|
).option(
|
|
5901
6822
|
"--session-cleanup-interval <duration>",
|
|
5902
6823
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
6824
|
+
).option(
|
|
6825
|
+
"--claude-usage-reporting <mode>",
|
|
6826
|
+
"Report Claude subscription usage to Evident: auto | on | off (default: auto). Env: EVIDENT_CLAUDE_USAGE_REPORTING"
|
|
5903
6827
|
).option(
|
|
5904
6828
|
"--enable-file-sync-to <dir>",
|
|
5905
6829
|
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
5906
6830
|
(value, previous) => previous.concat([value]),
|
|
5907
6831
|
[]
|
|
6832
|
+
).option(
|
|
6833
|
+
"--tunnel-ready-file <path>",
|
|
6834
|
+
"Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
|
|
5908
6835
|
).action(
|
|
5909
6836
|
(options) => {
|
|
5910
6837
|
run({
|
|
@@ -5917,14 +6844,21 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5917
6844
|
verbose: options.verbose,
|
|
5918
6845
|
conversation: options.conversation,
|
|
5919
6846
|
idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
|
|
6847
|
+
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
6848
|
+
// resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
|
|
6849
|
+
opencodeStartTimeout: options.opencodeStartTimeout,
|
|
5920
6850
|
json: options.json,
|
|
5921
6851
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
5922
6852
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
5923
6853
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
5924
6854
|
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
6855
|
+
// Raw string — the resolver in run.ts single-sources parsing
|
|
6856
|
+
// (resolveClaudeUsageReportingMode).
|
|
6857
|
+
claudeUsageReporting: options.claudeUsageReporting,
|
|
5925
6858
|
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
5926
6859
|
// resolveFileSyncDirectories.
|
|
5927
|
-
enableFileSyncTo: options.enableFileSyncTo
|
|
6860
|
+
enableFileSyncTo: options.enableFileSyncTo,
|
|
6861
|
+
tunnelReadyFile: options.tunnelReadyFile
|
|
5928
6862
|
});
|
|
5929
6863
|
}
|
|
5930
6864
|
);
|