@evident-ai/cli 3.1.1-dev.5a3c6a5 → 3.1.1-dev.5ca1c14
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 +1087 -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,124 @@ async function whoami() {
|
|
|
498
532
|
blank();
|
|
499
533
|
}
|
|
500
534
|
|
|
535
|
+
// src/lib/claude-usage.ts
|
|
536
|
+
import { execFileSync } from "child_process";
|
|
537
|
+
import { readFileSync } from "fs";
|
|
538
|
+
import { homedir } from "os";
|
|
539
|
+
import { join } from "path";
|
|
540
|
+
var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
541
|
+
var KEYCHAIN_SERVICE = "Claude Code-credentials";
|
|
542
|
+
function parseClaudeCliCredentials(raw) {
|
|
543
|
+
let parsed;
|
|
544
|
+
try {
|
|
545
|
+
parsed = JSON.parse(raw);
|
|
546
|
+
} catch {
|
|
547
|
+
return null;
|
|
548
|
+
}
|
|
549
|
+
const data = parsed.claudeAiOauth ?? parsed;
|
|
550
|
+
const creds = data;
|
|
551
|
+
if (typeof creds.accessToken !== "string" || typeof creds.expiresAt !== "number") {
|
|
552
|
+
return null;
|
|
553
|
+
}
|
|
554
|
+
return { accessToken: creds.accessToken, expiresAt: creds.expiresAt };
|
|
555
|
+
}
|
|
556
|
+
function readClaudeCliCredentials() {
|
|
557
|
+
if (process.platform === "darwin") {
|
|
558
|
+
try {
|
|
559
|
+
const raw = execFileSync(
|
|
560
|
+
"/usr/bin/security",
|
|
561
|
+
["find-generic-password", "-s", KEYCHAIN_SERVICE, "-w"],
|
|
562
|
+
{ encoding: "utf-8", timeout: 2e3, stdio: ["pipe", "pipe", "ignore"] }
|
|
563
|
+
);
|
|
564
|
+
return parseClaudeCliCredentials(raw);
|
|
565
|
+
} catch {
|
|
566
|
+
return null;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
try {
|
|
570
|
+
const raw = readFileSync(join(homedir(), ".claude", ".credentials.json"), "utf-8");
|
|
571
|
+
return parseClaudeCliCredentials(raw);
|
|
572
|
+
} catch {
|
|
573
|
+
return null;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
var ClaudeUsageError = class extends Error {
|
|
577
|
+
constructor(message, reason) {
|
|
578
|
+
super(message);
|
|
579
|
+
this.reason = reason;
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
function isLocalCredentialProblem(err) {
|
|
583
|
+
return err instanceof ClaudeUsageError && (err.reason === "no_credentials" || err.reason === "credentials_expired");
|
|
584
|
+
}
|
|
585
|
+
function toWindow(value) {
|
|
586
|
+
if (!value || typeof value !== "object") {
|
|
587
|
+
return null;
|
|
588
|
+
}
|
|
589
|
+
const window = value;
|
|
590
|
+
if (typeof window.utilization !== "number" || typeof window.resets_at !== "string") {
|
|
591
|
+
return null;
|
|
592
|
+
}
|
|
593
|
+
return { utilization: window.utilization, resetsAt: window.resets_at };
|
|
594
|
+
}
|
|
595
|
+
async function getClaudeUsage() {
|
|
596
|
+
const credentials2 = readClaudeCliCredentials();
|
|
597
|
+
if (!credentials2) {
|
|
598
|
+
throw new ClaudeUsageError(
|
|
599
|
+
"No local Claude Code login found. Run `claude` once to sign in with your Claude subscription.",
|
|
600
|
+
"no_credentials"
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
if (credentials2.expiresAt < Date.now()) {
|
|
604
|
+
throw new ClaudeUsageError(
|
|
605
|
+
"Claude Code credentials have expired. Run `claude` to refresh them.",
|
|
606
|
+
"credentials_expired"
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
const res = await fetch(CLAUDE_USAGE_URL, {
|
|
610
|
+
headers: {
|
|
611
|
+
Authorization: `Bearer ${credentials2.accessToken}`,
|
|
612
|
+
"Content-Type": "application/json",
|
|
613
|
+
"anthropic-version": "2023-06-01"
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
if (!res.ok) {
|
|
617
|
+
throw new ClaudeUsageError(`Claude usage request failed: HTTP ${res.status}`, "request_failed");
|
|
618
|
+
}
|
|
619
|
+
const body = await res.json();
|
|
620
|
+
return {
|
|
621
|
+
fiveHour: toWindow(body.five_hour),
|
|
622
|
+
sevenDay: toWindow(body.seven_day)
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
// src/commands/claude-usage.ts
|
|
627
|
+
function formatWindow(label, window) {
|
|
628
|
+
if (!window) {
|
|
629
|
+
return keyValue(label, "not available for this plan");
|
|
630
|
+
}
|
|
631
|
+
const resetsAt = new Date(window.resetsAt);
|
|
632
|
+
return keyValue(label, `${window.utilization}% used, resets ${resetsAt.toLocaleString()}`);
|
|
633
|
+
}
|
|
634
|
+
async function claudeUsage() {
|
|
635
|
+
try {
|
|
636
|
+
const usage = await getClaudeUsage();
|
|
637
|
+
blank();
|
|
638
|
+
console.log(formatWindow("5-hour session", usage.fiveHour));
|
|
639
|
+
console.log(formatWindow("7-day", usage.sevenDay));
|
|
640
|
+
blank();
|
|
641
|
+
} catch (err) {
|
|
642
|
+
if (err instanceof ClaudeUsageError) {
|
|
643
|
+
printError(err.message);
|
|
644
|
+
process.exit(1);
|
|
645
|
+
}
|
|
646
|
+
throw err;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
501
650
|
// src/commands/run.ts
|
|
502
|
-
import { homedir as
|
|
503
|
-
import { isAbsolute as isAbsolute2, join as
|
|
651
|
+
import { homedir as homedir3 } from "os";
|
|
652
|
+
import { isAbsolute as isAbsolute2, join as join3, parse, resolve as resolvePath } from "path";
|
|
504
653
|
import chalk6 from "chalk";
|
|
505
654
|
|
|
506
655
|
// ../../packages/types/src/telemetry/index.ts
|
|
@@ -510,7 +659,10 @@ var TelemetryEventTypes = {
|
|
|
510
659
|
AGENT_DISCONNECTED: "agent.disconnected",
|
|
511
660
|
AGENT_MESSAGE_PROCESSING: "agent.message_processing",
|
|
512
661
|
AGENT_MESSAGE_DONE: "agent.message_done",
|
|
513
|
-
AGENT_MESSAGE_FAILED: "agent.message_failed"
|
|
662
|
+
AGENT_MESSAGE_FAILED: "agent.message_failed",
|
|
663
|
+
// A `warn`/`error` runner-side log line forwarded server-side for
|
|
664
|
+
// observability (issue #916) — see `apps/cli/src/lib/runner-activity-telemetry.ts`.
|
|
665
|
+
RUNNER_ACTIVITY: "runner.activity"
|
|
514
666
|
};
|
|
515
667
|
|
|
516
668
|
// ../../packages/types/src/tunnel/index.ts
|
|
@@ -565,6 +717,13 @@ var isShuttingDown = false;
|
|
|
565
717
|
var FLUSH_INTERVAL_MS = 5e3;
|
|
566
718
|
var MAX_BUFFER_SIZE = 50;
|
|
567
719
|
var FLUSH_TIMEOUT_MS = 3e3;
|
|
720
|
+
var authProvider = null;
|
|
721
|
+
function setTelemetryAuthProvider(provider) {
|
|
722
|
+
authProvider = provider;
|
|
723
|
+
}
|
|
724
|
+
var FLUSH_FAILURE_LOG_INTERVAL_MS = 6e4;
|
|
725
|
+
var lastFlushFailureLoggedAt = 0;
|
|
726
|
+
var suppressedFlushFailureCount = 0;
|
|
568
727
|
function logEvent(eventType, options = {}) {
|
|
569
728
|
const event = {
|
|
570
729
|
event_type: eventType,
|
|
@@ -599,9 +758,16 @@ async function flushEvents() {
|
|
|
599
758
|
flushTimeout = null;
|
|
600
759
|
}
|
|
601
760
|
try {
|
|
602
|
-
const
|
|
603
|
-
|
|
604
|
-
|
|
761
|
+
const providerContext = authProvider?.();
|
|
762
|
+
let authHeader;
|
|
763
|
+
if (providerContext?.authHeader) {
|
|
764
|
+
authHeader = providerContext.authHeader;
|
|
765
|
+
} else {
|
|
766
|
+
const credentials2 = await getToken();
|
|
767
|
+
if (!credentials2) {
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
authHeader = `Bearer ${credentials2.token}`;
|
|
605
771
|
}
|
|
606
772
|
const apiUrl = getApiUrlConfig();
|
|
607
773
|
const controller = new AbortController();
|
|
@@ -616,7 +782,7 @@ async function flushEvents() {
|
|
|
616
782
|
method: "POST",
|
|
617
783
|
headers: {
|
|
618
784
|
"Content-Type": "application/json",
|
|
619
|
-
Authorization:
|
|
785
|
+
Authorization: authHeader
|
|
620
786
|
},
|
|
621
787
|
body: JSON.stringify(request),
|
|
622
788
|
signal: controller.signal
|
|
@@ -628,8 +794,15 @@ async function flushEvents() {
|
|
|
628
794
|
clearTimeout(timeout);
|
|
629
795
|
}
|
|
630
796
|
} catch (error2) {
|
|
631
|
-
|
|
632
|
-
|
|
797
|
+
const now = Date.now();
|
|
798
|
+
if (now - lastFlushFailureLoggedAt >= FLUSH_FAILURE_LOG_INTERVAL_MS) {
|
|
799
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
800
|
+
const suffix = suppressedFlushFailureCount > 0 ? ` (${suppressedFlushFailureCount} more suppressed in the last ${FLUSH_FAILURE_LOG_INTERVAL_MS / 1e3}s)` : "";
|
|
801
|
+
console.error(`Telemetry flush error: ${message}${suffix}`);
|
|
802
|
+
lastFlushFailureLoggedAt = now;
|
|
803
|
+
suppressedFlushFailureCount = 0;
|
|
804
|
+
} else {
|
|
805
|
+
suppressedFlushFailureCount++;
|
|
633
806
|
}
|
|
634
807
|
}
|
|
635
808
|
}
|
|
@@ -698,6 +871,69 @@ var EventTypes = {
|
|
|
698
871
|
DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
|
|
699
872
|
};
|
|
700
873
|
|
|
874
|
+
// src/lib/runner-activity-telemetry.ts
|
|
875
|
+
var FORWARDED_LEVELS = /* @__PURE__ */ new Set(["warn", "error"]);
|
|
876
|
+
var SEVERITY_BY_LEVEL = {
|
|
877
|
+
warn: "warning",
|
|
878
|
+
error: "error"
|
|
879
|
+
};
|
|
880
|
+
var MAX_MESSAGE_LENGTH = 500;
|
|
881
|
+
var TRUNCATION_MARKER = "\u2026";
|
|
882
|
+
function redact(message) {
|
|
883
|
+
return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
|
|
884
|
+
}
|
|
885
|
+
function truncate(message) {
|
|
886
|
+
if (message.length <= MAX_MESSAGE_LENGTH) return message;
|
|
887
|
+
return message.slice(0, MAX_MESSAGE_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
|
|
888
|
+
}
|
|
889
|
+
var RATE_LIMIT_WINDOW_MS = 6e4;
|
|
890
|
+
var RATE_LIMIT_MAX_EVENTS = 30;
|
|
891
|
+
var windowStartedAt = 0;
|
|
892
|
+
var windowCount = 0;
|
|
893
|
+
var windowDroppedCount = 0;
|
|
894
|
+
function admitUnderRateLimit(now) {
|
|
895
|
+
if (now - windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
|
|
896
|
+
if (windowDroppedCount > 0) {
|
|
897
|
+
console.error(
|
|
898
|
+
`[runner-activity-telemetry] rate cap reached: dropped ${windowDroppedCount} ${windowDroppedCount === 1 ? "entry" : "entries"} in the last ${RATE_LIMIT_WINDOW_MS / 1e3}s (cap ${RATE_LIMIT_MAX_EVENTS}/min)`
|
|
899
|
+
);
|
|
900
|
+
}
|
|
901
|
+
windowStartedAt = now;
|
|
902
|
+
windowCount = 0;
|
|
903
|
+
windowDroppedCount = 0;
|
|
904
|
+
}
|
|
905
|
+
if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
|
|
906
|
+
windowDroppedCount++;
|
|
907
|
+
if (windowDroppedCount === 1) {
|
|
908
|
+
console.error(
|
|
909
|
+
`[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
return false;
|
|
913
|
+
}
|
|
914
|
+
windowCount++;
|
|
915
|
+
return true;
|
|
916
|
+
}
|
|
917
|
+
function forwardRunnerActivity(entry, context) {
|
|
918
|
+
try {
|
|
919
|
+
if (!FORWARDED_LEVELS.has(entry.level)) return;
|
|
920
|
+
if (!context.agentId || !context.authHeader) return;
|
|
921
|
+
if (!admitUnderRateLimit(Date.now())) return;
|
|
922
|
+
const rawMessage = entry.error ?? entry.message ?? "";
|
|
923
|
+
const message = truncate(redact(rawMessage));
|
|
924
|
+
logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
|
|
925
|
+
severity: SEVERITY_BY_LEVEL[entry.level],
|
|
926
|
+
message,
|
|
927
|
+
metadata: { source: "cli.run" },
|
|
928
|
+
agentId: context.agentId
|
|
929
|
+
});
|
|
930
|
+
} catch (err) {
|
|
931
|
+
console.error(
|
|
932
|
+
`[runner-activity-telemetry] failed to forward runner activity: ${err instanceof Error ? err.message : String(err)}`
|
|
933
|
+
);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
701
937
|
// src/lib/auth.ts
|
|
702
938
|
async function getAuthCredentials() {
|
|
703
939
|
const runnerKey = process.env.EVIDENT_RUNNER_KEY;
|
|
@@ -1532,6 +1768,9 @@ function isPreamblePinnedRunning(messages, userMessageId) {
|
|
|
1532
1768
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1533
1769
|
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
1534
1770
|
}
|
|
1771
|
+
function isB2AbandonmentConfirmed(params) {
|
|
1772
|
+
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
|
|
1773
|
+
}
|
|
1535
1774
|
function messageError(messages, userMessageId) {
|
|
1536
1775
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1537
1776
|
const error2 = errorOf(reply);
|
|
@@ -1545,6 +1784,42 @@ function messageError(messages, userMessageId) {
|
|
|
1545
1784
|
}
|
|
1546
1785
|
return "The agent run failed.";
|
|
1547
1786
|
}
|
|
1787
|
+
function messageFailure(messages, userMessageId) {
|
|
1788
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1789
|
+
const error2 = errorOf(reply);
|
|
1790
|
+
if (error2 == null || typeof error2 !== "object") return null;
|
|
1791
|
+
const e = error2;
|
|
1792
|
+
const replyProviderId = reply?.info?.providerID ?? null;
|
|
1793
|
+
const replyModelId = reply?.info?.modelID ?? null;
|
|
1794
|
+
if (e.name === "ProviderAuthError") {
|
|
1795
|
+
const data = e.data;
|
|
1796
|
+
const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
|
|
1797
|
+
return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
|
|
1798
|
+
}
|
|
1799
|
+
if (e.name === "APIError") {
|
|
1800
|
+
const data = e.data;
|
|
1801
|
+
const statusCode = data?.statusCode;
|
|
1802
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
1803
|
+
return {
|
|
1804
|
+
kind: "model_auth",
|
|
1805
|
+
providerId: replyProviderId,
|
|
1806
|
+
modelId: replyModelId,
|
|
1807
|
+
reason: "rejected"
|
|
1808
|
+
};
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
return null;
|
|
1812
|
+
}
|
|
1813
|
+
function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
|
|
1814
|
+
if (classified != null) return classified;
|
|
1815
|
+
if (hasConfiguredProvider !== false) return null;
|
|
1816
|
+
return {
|
|
1817
|
+
kind: "model_auth",
|
|
1818
|
+
providerId: replyProviderId,
|
|
1819
|
+
modelId: replyModelId,
|
|
1820
|
+
reason: "missing"
|
|
1821
|
+
};
|
|
1822
|
+
}
|
|
1548
1823
|
function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
1549
1824
|
if (!messages || messages.length === 0) return false;
|
|
1550
1825
|
return messages.some(
|
|
@@ -2073,13 +2348,52 @@ var RunnerConnection = class {
|
|
|
2073
2348
|
}
|
|
2074
2349
|
};
|
|
2075
2350
|
|
|
2351
|
+
// src/lib/tunnel/ready-marker.ts
|
|
2352
|
+
import { writeFileSync } from "fs";
|
|
2353
|
+
function writeTunnelReadyMarker(path, agentId) {
|
|
2354
|
+
try {
|
|
2355
|
+
writeFileSync(path, `${agentId}
|
|
2356
|
+
`);
|
|
2357
|
+
return { ok: true };
|
|
2358
|
+
} catch (error2) {
|
|
2359
|
+
return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
|
|
2363
|
+
// src/lib/claude-usage-reporting.ts
|
|
2364
|
+
var VALID_MODES = ["auto", "on", "off"];
|
|
2365
|
+
function resolveClaudeUsageReportingMode(flagValue, env) {
|
|
2366
|
+
const raw = flagValue ?? env.EVIDENT_CLAUDE_USAGE_REPORTING;
|
|
2367
|
+
if (raw === void 0 || raw === "") {
|
|
2368
|
+
return { mode: "auto", warnings: [] };
|
|
2369
|
+
}
|
|
2370
|
+
const normalized = raw.trim().toLowerCase();
|
|
2371
|
+
if (VALID_MODES.includes(normalized)) {
|
|
2372
|
+
return { mode: normalized, warnings: [] };
|
|
2373
|
+
}
|
|
2374
|
+
const source = flagValue !== void 0 ? "--claude-usage-reporting" : "EVIDENT_CLAUDE_USAGE_REPORTING";
|
|
2375
|
+
return {
|
|
2376
|
+
mode: "auto",
|
|
2377
|
+
warnings: [
|
|
2378
|
+
`Ignoring invalid ${source} "${raw}": expected one of ${VALID_MODES.join(", ")}; using auto`
|
|
2379
|
+
]
|
|
2380
|
+
};
|
|
2381
|
+
}
|
|
2382
|
+
var BASE_REPORT_DELAY_MS = 10 * 6e4;
|
|
2383
|
+
var REPORT_DELAY_JITTER_FRACTION = 0.2;
|
|
2384
|
+
function nextReportDelayMs(random = Math.random) {
|
|
2385
|
+
const jitterRangeMs = BASE_REPORT_DELAY_MS * REPORT_DELAY_JITTER_FRACTION;
|
|
2386
|
+
return BASE_REPORT_DELAY_MS - jitterRangeMs + random() * (2 * jitterRangeMs);
|
|
2387
|
+
}
|
|
2388
|
+
var FIRST_REPORT_DELAY_MS = 5e3 + Math.random() * 1e4;
|
|
2389
|
+
|
|
2076
2390
|
// src/lib/channels/driver.ts
|
|
2077
|
-
import { homedir } from "os";
|
|
2391
|
+
import { homedir as homedir2 } from "os";
|
|
2078
2392
|
|
|
2079
2393
|
// src/lib/file-push.ts
|
|
2080
2394
|
import { randomUUID } from "crypto";
|
|
2081
2395
|
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";
|
|
2396
|
+
import { basename, dirname as dirname2, isAbsolute, join as join2, relative, resolve as resolve2, sep } from "path";
|
|
2083
2397
|
var FILE_MODE = 384;
|
|
2084
2398
|
var DIRECTORY_MODE = 448;
|
|
2085
2399
|
async function writePushedFile(request) {
|
|
@@ -2112,7 +2426,7 @@ async function writePushedFile(request) {
|
|
|
2112
2426
|
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
2113
2427
|
dirname2(candidate)
|
|
2114
2428
|
);
|
|
2115
|
-
const realTarget =
|
|
2429
|
+
const realTarget = join2(existingAncestor, ...missingSegments, basename(candidate));
|
|
2116
2430
|
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
|
|
2117
2431
|
if (allowedDirectory === null) {
|
|
2118
2432
|
return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
@@ -2148,7 +2462,7 @@ function expandAndValidate(requestedPath, homeDir) {
|
|
|
2148
2462
|
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
2149
2463
|
return null;
|
|
2150
2464
|
}
|
|
2151
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
2465
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join2(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
2152
2466
|
if (expanded.split(/[/\\]/).includes("..")) {
|
|
2153
2467
|
return null;
|
|
2154
2468
|
}
|
|
@@ -2221,13 +2535,13 @@ function contains(realDirectory, realTarget) {
|
|
|
2221
2535
|
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
2222
2536
|
let current = existingAncestor;
|
|
2223
2537
|
for (const segment of missingSegments) {
|
|
2224
|
-
current =
|
|
2538
|
+
current = join2(current, segment);
|
|
2225
2539
|
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
2226
2540
|
await chmod(current, DIRECTORY_MODE);
|
|
2227
2541
|
}
|
|
2228
2542
|
}
|
|
2229
2543
|
async function writeAtomically(realTarget, content) {
|
|
2230
|
-
const temporaryPath =
|
|
2544
|
+
const temporaryPath = join2(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
2231
2545
|
let handle;
|
|
2232
2546
|
try {
|
|
2233
2547
|
handle = await open2(temporaryPath, "wx", FILE_MODE);
|
|
@@ -2499,6 +2813,8 @@ var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
|
2499
2813
|
var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
2500
2814
|
var HEARTBEAT_MS = 6e4;
|
|
2501
2815
|
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
2816
|
+
var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
|
|
2817
|
+
var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
|
|
2502
2818
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2503
2819
|
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
2504
2820
|
var ChannelAuthError = class extends Error {
|
|
@@ -2724,23 +3040,23 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2724
3040
|
* and stops opencode.
|
|
2725
3041
|
*/
|
|
2726
3042
|
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 =
|
|
3043
|
+
constructor(config) {
|
|
3044
|
+
this.agentId = config.agentId;
|
|
3045
|
+
this.port = config.port;
|
|
3046
|
+
this.apiUrl = config.apiUrl.replace(/\/$/, "");
|
|
3047
|
+
this.getAuthHeader = config.getAuthHeader;
|
|
3048
|
+
this.conversationFilter = config.conversationFilter ?? null;
|
|
3049
|
+
this.retry = { ...DEFAULT_RETRY_POLICY, ...config.retry };
|
|
3050
|
+
this.log = config.log ?? (() => {
|
|
2735
3051
|
});
|
|
2736
|
-
this.fetchImpl =
|
|
2737
|
-
this.sleep =
|
|
2738
|
-
this.pausedPollIntervalMs =
|
|
2739
|
-
this.pausedMaxWaitMs =
|
|
2740
|
-
this.stuckQueuedMs =
|
|
2741
|
-
this.now =
|
|
2742
|
-
this.fileSyncDirectories =
|
|
2743
|
-
this.homeDir =
|
|
3052
|
+
this.fetchImpl = config.fetchImpl ?? fetch;
|
|
3053
|
+
this.sleep = config.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
3054
|
+
this.pausedPollIntervalMs = config.pausedPollIntervalMs ?? DEFAULT_PAUSED_POLL_INTERVAL_MS;
|
|
3055
|
+
this.pausedMaxWaitMs = config.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
3056
|
+
this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
3057
|
+
this.now = config.now ?? (() => Date.now());
|
|
3058
|
+
this.fileSyncDirectories = config.fileSyncDirectories ?? [];
|
|
3059
|
+
this.homeDir = config.homeDir ?? homedir2();
|
|
2744
3060
|
}
|
|
2745
3061
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
2746
3062
|
get opencodeBase() {
|
|
@@ -3125,7 +3441,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3125
3441
|
const directory = await this.resolveOpenCodeDirectory();
|
|
3126
3442
|
const sessionId = await createOpenCodeSession(this.port, directory);
|
|
3127
3443
|
this.sessions.set(conversationId, sessionId);
|
|
3128
|
-
await this.persistSession(conversationId, sessionId).catch(() => {
|
|
3444
|
+
await this.persistSession(conversationId, sessionId).catch((err) => {
|
|
3445
|
+
this.log({
|
|
3446
|
+
level: "warn",
|
|
3447
|
+
message: `Persisting the OpenCode session binding ${sessionId.slice(0, 8)} for conversation ${conversationId.slice(0, 8)} failed (best-effort, not retried) \u2014 the completion PATCH also carries opencode_session_id, so the binding is repaired when the turn finishes: ${err instanceof Error ? err.message : String(err)}`,
|
|
3448
|
+
conversation_id: conversationId
|
|
3449
|
+
});
|
|
3129
3450
|
});
|
|
3130
3451
|
return sessionId;
|
|
3131
3452
|
}
|
|
@@ -3317,12 +3638,17 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3317
3638
|
stuckReported: false,
|
|
3318
3639
|
lastAliveAt: 0,
|
|
3319
3640
|
aliveInFlight: false,
|
|
3641
|
+
titleSynced: false,
|
|
3642
|
+
titleSyncInFlight: false,
|
|
3320
3643
|
awaitingHumanLatched: false,
|
|
3321
3644
|
pausedOnQuestion: false,
|
|
3322
3645
|
pausedOnPermission: false,
|
|
3323
3646
|
pausedClearConfirmed: false,
|
|
3324
3647
|
pausedInFlight: false,
|
|
3325
|
-
deliveryDeadlineAnchored: false
|
|
3648
|
+
deliveryDeadlineAnchored: false,
|
|
3649
|
+
b2PinnedSinceMs: 0,
|
|
3650
|
+
b2LastDescendantCheckMs: 0,
|
|
3651
|
+
b2AbandonedSignalled: false
|
|
3326
3652
|
});
|
|
3327
3653
|
}
|
|
3328
3654
|
/**
|
|
@@ -3390,12 +3716,17 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3390
3716
|
// with no extra `re_adopted` signal needed (folds old WI-6).
|
|
3391
3717
|
lastAliveAt: 0,
|
|
3392
3718
|
aliveInFlight: false,
|
|
3719
|
+
titleSynced: false,
|
|
3720
|
+
titleSyncInFlight: false,
|
|
3393
3721
|
awaitingHumanLatched: false,
|
|
3394
3722
|
pausedOnQuestion: false,
|
|
3395
3723
|
pausedOnPermission: false,
|
|
3396
3724
|
pausedClearConfirmed: false,
|
|
3397
3725
|
pausedInFlight: false,
|
|
3398
|
-
deliveryDeadlineAnchored: false
|
|
3726
|
+
deliveryDeadlineAnchored: false,
|
|
3727
|
+
b2PinnedSinceMs: 0,
|
|
3728
|
+
b2LastDescendantCheckMs: 0,
|
|
3729
|
+
b2AbandonedSignalled: false
|
|
3399
3730
|
});
|
|
3400
3731
|
}
|
|
3401
3732
|
/**
|
|
@@ -3557,58 +3888,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3557
3888
|
}
|
|
3558
3889
|
}
|
|
3559
3890
|
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);
|
|
3891
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3612
3892
|
return;
|
|
3613
3893
|
}
|
|
3614
3894
|
if (state === "failed") {
|
|
@@ -3622,8 +3902,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3622
3902
|
message_id: inFlight.evidentMessageId
|
|
3623
3903
|
});
|
|
3624
3904
|
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
3905
|
+
const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
|
|
3625
3906
|
try {
|
|
3626
|
-
await this.markFailed(
|
|
3907
|
+
await this.markFailed(
|
|
3908
|
+
conv.id,
|
|
3909
|
+
inFlight.evidentMessageId,
|
|
3910
|
+
sessionId,
|
|
3911
|
+
error2,
|
|
3912
|
+
usage,
|
|
3913
|
+
failure
|
|
3914
|
+
);
|
|
3627
3915
|
} catch (err) {
|
|
3628
3916
|
if (err instanceof ChannelAuthError) throw err;
|
|
3629
3917
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3668,6 +3956,44 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3668
3956
|
});
|
|
3669
3957
|
}
|
|
3670
3958
|
const activelyRunning = state === "running" && !awaitingHuman;
|
|
3959
|
+
const pinnedNow = activelyRunning && isPreamblePinnedRunning(messages, inFlight.opencodeMessageId);
|
|
3960
|
+
const snapshotReadable = messages != null && messages.length > 0;
|
|
3961
|
+
if (!pinnedNow) {
|
|
3962
|
+
if (snapshotReadable) {
|
|
3963
|
+
inFlight.b2PinnedSinceMs = 0;
|
|
3964
|
+
inFlight.b2LastDescendantCheckMs = 0;
|
|
3965
|
+
inFlight.b2AbandonedSignalled = false;
|
|
3966
|
+
}
|
|
3967
|
+
} else {
|
|
3968
|
+
if (inFlight.b2AbandonedSignalled) {
|
|
3969
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3970
|
+
return;
|
|
3971
|
+
}
|
|
3972
|
+
if (inFlight.b2PinnedSinceMs === 0) inFlight.b2PinnedSinceMs = this.now();
|
|
3973
|
+
const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
|
|
3974
|
+
if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
|
|
3975
|
+
inFlight.b2LastDescendantCheckMs = this.now();
|
|
3976
|
+
const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
|
|
3977
|
+
if (isB2AbandonmentConfirmed({
|
|
3978
|
+
pinnedForMs,
|
|
3979
|
+
minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
|
|
3980
|
+
descendantOngoing
|
|
3981
|
+
})) {
|
|
3982
|
+
inFlight.b2AbandonedSignalled = true;
|
|
3983
|
+
this.log({
|
|
3984
|
+
level: "warn",
|
|
3985
|
+
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`,
|
|
3986
|
+
conversation_id: conv.id,
|
|
3987
|
+
message_id: id
|
|
3988
|
+
});
|
|
3989
|
+
void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
|
|
3990
|
+
watched_for_ms: pinnedForMs
|
|
3991
|
+
});
|
|
3992
|
+
await this.settleMessageDone(sessionId, watcher, inFlight, messages);
|
|
3993
|
+
return;
|
|
3994
|
+
}
|
|
3995
|
+
}
|
|
3996
|
+
}
|
|
3671
3997
|
if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
|
|
3672
3998
|
this.log({
|
|
3673
3999
|
level: "warn",
|
|
@@ -3687,6 +4013,18 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3687
4013
|
inFlight.aliveInFlight = false;
|
|
3688
4014
|
if (ok) inFlight.lastAliveAt = this.now();
|
|
3689
4015
|
});
|
|
4016
|
+
if (!inFlight.titleSynced && !inFlight.titleSyncInFlight) {
|
|
4017
|
+
inFlight.titleSyncInFlight = true;
|
|
4018
|
+
void this.resolveSessionTitle(sessionId, conv.id).then(async (title) => {
|
|
4019
|
+
if (!title) {
|
|
4020
|
+
inFlight.titleSyncInFlight = false;
|
|
4021
|
+
return;
|
|
4022
|
+
}
|
|
4023
|
+
const ok = await this.patchConversationTitle(conv.id, title);
|
|
4024
|
+
inFlight.titleSyncInFlight = false;
|
|
4025
|
+
if (ok) inFlight.titleSynced = true;
|
|
4026
|
+
});
|
|
4027
|
+
}
|
|
3690
4028
|
}
|
|
3691
4029
|
if (awaitingHuman) {
|
|
3692
4030
|
if (!inFlight.awaitingHumanLatched) {
|
|
@@ -3724,6 +4062,70 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3724
4062
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
3725
4063
|
}
|
|
3726
4064
|
}
|
|
4065
|
+
/**
|
|
4066
|
+
* Settle a message whose run-state has resolved `'done'` — extracted verbatim
|
|
4067
|
+
* (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
|
|
4068
|
+
* inline `state === 'done'` branch body, so a SECOND caller (the #721
|
|
4069
|
+
* b2-abandonment resolution) can reach the exact same completion behavior
|
|
4070
|
+
* (delivery-deadline anchoring, title resolution, usage extraction, and
|
|
4071
|
+
* `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
|
|
4072
|
+
* and risking the two copies silently drifting apart.
|
|
4073
|
+
*/
|
|
4074
|
+
async settleMessageDone(sessionId, watcher, inFlight, messages) {
|
|
4075
|
+
const conv = watcher.conv;
|
|
4076
|
+
this.anchorDeliveryDeadline(inFlight);
|
|
4077
|
+
if (!inFlight.done) {
|
|
4078
|
+
this.log({
|
|
4079
|
+
level: "info",
|
|
4080
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} completed \u2014 marking done`,
|
|
4081
|
+
conversation_id: conv.id,
|
|
4082
|
+
message_id: inFlight.evidentMessageId
|
|
4083
|
+
});
|
|
4084
|
+
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
4085
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
4086
|
+
try {
|
|
4087
|
+
await this.markDone(
|
|
4088
|
+
conv.id,
|
|
4089
|
+
inFlight.evidentMessageId,
|
|
4090
|
+
sessionId,
|
|
4091
|
+
inFlight.opencodeMessageId,
|
|
4092
|
+
title,
|
|
4093
|
+
usage
|
|
4094
|
+
);
|
|
4095
|
+
} catch (err) {
|
|
4096
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
4097
|
+
if (err instanceof ChannelTerminalError) {
|
|
4098
|
+
this.log({
|
|
4099
|
+
level: "warn",
|
|
4100
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
4101
|
+
conversation_id: conv.id,
|
|
4102
|
+
message_id: inFlight.evidentMessageId
|
|
4103
|
+
});
|
|
4104
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4105
|
+
return;
|
|
4106
|
+
}
|
|
4107
|
+
if (this.now() >= inFlight.deadline) {
|
|
4108
|
+
this.log({
|
|
4109
|
+
level: "warn",
|
|
4110
|
+
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)}`,
|
|
4111
|
+
conversation_id: conv.id,
|
|
4112
|
+
message_id: inFlight.evidentMessageId
|
|
4113
|
+
});
|
|
4114
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4115
|
+
return;
|
|
4116
|
+
}
|
|
4117
|
+
this.log({
|
|
4118
|
+
level: "warn",
|
|
4119
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
4120
|
+
conversation_id: conv.id,
|
|
4121
|
+
message_id: inFlight.evidentMessageId
|
|
4122
|
+
});
|
|
4123
|
+
return;
|
|
4124
|
+
}
|
|
4125
|
+
inFlight.done = true;
|
|
4126
|
+
}
|
|
4127
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
4128
|
+
}
|
|
3727
4129
|
// Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
|
|
3728
4130
|
/**
|
|
3729
4131
|
* Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
|
|
@@ -3890,6 +4292,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3890
4292
|
if (state === "failed") {
|
|
3891
4293
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
3892
4294
|
const usage = messageUsage(messages, ocId ?? "");
|
|
4295
|
+
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
3893
4296
|
this.log({
|
|
3894
4297
|
level: "error",
|
|
3895
4298
|
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -3897,7 +4300,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3897
4300
|
message_id: row.id
|
|
3898
4301
|
});
|
|
3899
4302
|
try {
|
|
3900
|
-
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
|
|
4303
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
|
|
3901
4304
|
} catch (err) {
|
|
3902
4305
|
if (err instanceof ChannelAuthError) throw err;
|
|
3903
4306
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -4303,6 +4706,47 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4303
4706
|
}
|
|
4304
4707
|
return false;
|
|
4305
4708
|
}
|
|
4709
|
+
/**
|
|
4710
|
+
* Tri-state variant of the upward parentID membership walk (#721), used ONLY
|
|
4711
|
+
* by `isAnyDescendantSessionOngoing`. Walks the SAME cached
|
|
4712
|
+
* `resolveSessionParent` chain `sessionBelongsTo` uses above, but — unlike
|
|
4713
|
+
* `sessionBelongsTo`, which deliberately collapses "confirmed not a
|
|
4714
|
+
* descendant" and "the walk's fetch failed" into the same `false` (safe for
|
|
4715
|
+
* its OTHER callers: interaction attribution and the recovery-path
|
|
4716
|
+
* `isAnyDescendantSessionAlive`, both of which just retry next tick with no
|
|
4717
|
+
* safety consequence either way) — this variant keeps those two outcomes
|
|
4718
|
+
* SEPARATE, because `isAnyDescendantSessionOngoing`'s caller
|
|
4719
|
+
* (`isB2AbandonmentConfirmed`) must never treat "couldn't tell" as "confirmed
|
|
4720
|
+
* not ongoing".
|
|
4721
|
+
*
|
|
4722
|
+
* Return contract:
|
|
4723
|
+
* - `true` → the walk reached `rootSessionId` — `sessionId` IS a descendant.
|
|
4724
|
+
* - `false` → the walk reached a definitive, parent-less root session
|
|
4725
|
+
* WITHOUT ever matching `rootSessionId` — `sessionId` is
|
|
4726
|
+
* CONFIRMED NOT a descendant of it.
|
|
4727
|
+
* - `null` → INDETERMINATE: a `GET /session/:id` fetch failed partway
|
|
4728
|
+
* through the walk (`resolveSessionParent` returned `undefined`),
|
|
4729
|
+
* or the depth cap (32) was hit without a definitive answer (a
|
|
4730
|
+
* pathological/cyclic chain proves nothing either way). NEVER
|
|
4731
|
+
* treat this the same as `false` — see `sessionBelongsTo`'s own
|
|
4732
|
+
* doc comment above for why that collapse is safe THERE but not
|
|
4733
|
+
* here.
|
|
4734
|
+
*
|
|
4735
|
+
* `sessionBelongsTo` itself is UNCHANGED — this is an additive helper scoped
|
|
4736
|
+
* to the live-path descendant check, not a modification of shared code used
|
|
4737
|
+
* by interaction attribution or the recovery path.
|
|
4738
|
+
*/
|
|
4739
|
+
async resolveSessionMembership(sessionId, rootSessionId) {
|
|
4740
|
+
let current = sessionId;
|
|
4741
|
+
for (let depth = 0; current && depth < 32; depth++) {
|
|
4742
|
+
if (current === rootSessionId) return true;
|
|
4743
|
+
const parent = await this.resolveSessionParent(current);
|
|
4744
|
+
if (parent === void 0) return null;
|
|
4745
|
+
if (parent === null) return false;
|
|
4746
|
+
current = parent;
|
|
4747
|
+
}
|
|
4748
|
+
return null;
|
|
4749
|
+
}
|
|
4306
4750
|
/**
|
|
4307
4751
|
* Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
|
|
4308
4752
|
* `null` for a root session (no parent) and `undefined` when opencode is
|
|
@@ -4387,6 +4831,54 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4387
4831
|
}
|
|
4388
4832
|
return null;
|
|
4389
4833
|
}
|
|
4834
|
+
/**
|
|
4835
|
+
* Best-effort mid-turn title sync (#711 follow-up): PATCH a resolved OpenCode
|
|
4836
|
+
* session title onto the conversation via the PLAIN conversation-update
|
|
4837
|
+
* endpoint (`PATCH /runners/:agentId/conversations/:conversationId`) — NOT the
|
|
4838
|
+
* message-status endpoint `markProcessing`/`markDone` use. Deliberately a
|
|
4839
|
+
* separate, lighter call: it carries no `status`, so it cannot re-trigger the
|
|
4840
|
+
* `processing`/`done` transition side effects (Slack notices, activity-log
|
|
4841
|
+
* rows, delivery jobs) those PATCHes gate on `transitioned` — this call only
|
|
4842
|
+
* ever touches `conversations.title`. That route (`routes/conversations.ts`)
|
|
4843
|
+
* skips a title write matching the stored value, so a redundant call with the
|
|
4844
|
+
* same title is a real no-op — it does not bump `updated_at`, which the
|
|
4845
|
+
* conversation list sorts and paginates on. (Note this is a DIFFERENT guard
|
|
4846
|
+
* from `threads.ts`'s "non-empty AND changed" one, which only covers the
|
|
4847
|
+
* message-status PATCH; the non-empty half is enforced here instead, by
|
|
4848
|
+
* `resolveSessionTitle` never returning an empty/placeholder title.)
|
|
4849
|
+
*
|
|
4850
|
+
* Telemetry-only / never blocks the caller, mirroring `postSignal`: a failure
|
|
4851
|
+
* is logged and the title is simply retried on the next heartbeat tick (the
|
|
4852
|
+
* caller only latches `titleSynced` on `true`).
|
|
4853
|
+
*/
|
|
4854
|
+
async patchConversationTitle(conversationId, title) {
|
|
4855
|
+
try {
|
|
4856
|
+
const res = await this.fetchImpl(
|
|
4857
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/${conversationId}`,
|
|
4858
|
+
{
|
|
4859
|
+
method: "PATCH",
|
|
4860
|
+
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
4861
|
+
body: JSON.stringify({ title })
|
|
4862
|
+
}
|
|
4863
|
+
);
|
|
4864
|
+
if (!res.ok) {
|
|
4865
|
+
this.log({
|
|
4866
|
+
level: "debug",
|
|
4867
|
+
message: `Mid-turn title sync PATCH for conversation ${conversationId.slice(0, 8)} returned HTTP ${res.status} (best-effort, will retry next heartbeat)`,
|
|
4868
|
+
conversation_id: conversationId
|
|
4869
|
+
});
|
|
4870
|
+
return false;
|
|
4871
|
+
}
|
|
4872
|
+
return true;
|
|
4873
|
+
} catch (err) {
|
|
4874
|
+
this.log({
|
|
4875
|
+
level: "debug",
|
|
4876
|
+
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)}`,
|
|
4877
|
+
conversation_id: conversationId
|
|
4878
|
+
});
|
|
4879
|
+
return false;
|
|
4880
|
+
}
|
|
4881
|
+
}
|
|
4390
4882
|
/**
|
|
4391
4883
|
* DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
|
|
4392
4884
|
* (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
|
|
@@ -4445,6 +4937,84 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4445
4937
|
}
|
|
4446
4938
|
return false;
|
|
4447
4939
|
}
|
|
4940
|
+
/**
|
|
4941
|
+
* LIVE-PATH descendant-liveness check (#721): is any descendant (`task`
|
|
4942
|
+
* sub-agent) session under `rootSessionId` currently ONGOING per OpenCode's own
|
|
4943
|
+
* in-memory status map (`isSessionOngoing` — `busy`/`retry`)?
|
|
4944
|
+
*
|
|
4945
|
+
* Deliberately NOT `isAnyDescendantSessionAlive` (the RECOVERY-path
|
|
4946
|
+
* cross-check above): that method judges liveness from the child's OWN
|
|
4947
|
+
* TRANSCRIPT (`isSessionActivelyGenerating`), which is the right (only) option
|
|
4948
|
+
* on the recovery path because a restart WIPES `SessionStatus`. On the LIVE
|
|
4949
|
+
* path the local opencode server IS running, so its in-memory status map is
|
|
4950
|
+
* live and authoritative — and per ADR-0047 §4a ("the child has its own entry
|
|
4951
|
+
* [in the map]"), a `task` descendant's OWN busy/retry entry reflects its
|
|
4952
|
+
* ENTIRE turn (including any tool call it is itself executing), not a
|
|
4953
|
+
* per-message transcript snapshot. This sidesteps the "child's own tool is
|
|
4954
|
+
* executing, between its step's completion and the next generation step"
|
|
4955
|
+
* transcript gap that a transcript-based check would need a second,
|
|
4956
|
+
* sustained-window bound to guard against — it is simply not derived from
|
|
4957
|
+
* message timestamps at all.
|
|
4958
|
+
*
|
|
4959
|
+
* Why not just check `isSessionOngoing(port, rootSessionId)` (the ROOT's own
|
|
4960
|
+
* status, as the recovery path does per §4a)? Because on the LIVE path the
|
|
4961
|
+
* root session can be shared: a SECOND, unrelated user message can land on the
|
|
4962
|
+
* SAME session (issue #721's own root cause) and keep the root `busy` for a
|
|
4963
|
+
* reason that has nothing to do with THIS message's delegation. A `task`
|
|
4964
|
+
* descendant session is spawned for exactly one delegated turn and never
|
|
4965
|
+
* reused, so its OWN status-map entry is unambiguous evidence about that one
|
|
4966
|
+
* delegation — which the root's status is not.
|
|
4967
|
+
*
|
|
4968
|
+
* Why membership is checked via `resolveSessionMembership`, NOT
|
|
4969
|
+
* `sessionBelongsTo`: `sessionBelongsTo` collapses a transient
|
|
4970
|
+
* `GET /session/:id` fetch failure into "not a descendant", which would
|
|
4971
|
+
* silently drop a genuinely-live candidate from consideration on the one
|
|
4972
|
+
* unlucky tick its membership-walk fetch hiccups (#721).
|
|
4973
|
+
* `resolveSessionMembership` keeps that failure mode as a distinct `null`
|
|
4974
|
+
* (indeterminate) so it is folded into THIS method's own `indeterminate` flag
|
|
4975
|
+
* instead.
|
|
4976
|
+
*
|
|
4977
|
+
* Return contract (note the DIFFERENT judge vs. `isAnyDescendantSessionAlive`):
|
|
4978
|
+
* - `true` → some descendant session is `busy`/`retry` (genuinely ongoing).
|
|
4979
|
+
* - `false` → enumeration succeeded, EVERY candidate's MEMBERSHIP was
|
|
4980
|
+
* confirmed either way (`resolveSessionMembership` never
|
|
4981
|
+
* returned `null`), and every CONFIRMED descendant's status read
|
|
4982
|
+
* succeeded and is not ongoing (includes "no descendant session
|
|
4983
|
+
* exists at all" — e.g. a plain, non-`task` tool call).
|
|
4984
|
+
* - `null` → INDETERMINATE: `listSessions` failed, OR at least one
|
|
4985
|
+
* candidate's MEMBERSHIP could not be confirmed
|
|
4986
|
+
* (`resolveSessionMembership` returned `null` — a fetch failure
|
|
4987
|
+
* or pathological chain partway through the parent walk), OR at
|
|
4988
|
+
* least one CONFIRMED descendant's `isSessionOngoing` read
|
|
4989
|
+
* failed — and no OTHER candidate was already confirmed `true`.
|
|
4990
|
+
* The caller MUST NOT treat `null` the same as `false` here
|
|
4991
|
+
* (unlike the recovery cross-check's contract) — see
|
|
4992
|
+
* `isB2AbandonmentConfirmed`.
|
|
4993
|
+
*/
|
|
4994
|
+
async isAnyDescendantSessionOngoing(rootSessionId) {
|
|
4995
|
+
const sessions = await listSessions(this.port);
|
|
4996
|
+
if (!sessions) {
|
|
4997
|
+
this.log({
|
|
4998
|
+
level: "warn",
|
|
4999
|
+
message: `Could not enumerate sessions to check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating descendant liveness as indeterminate`
|
|
5000
|
+
});
|
|
5001
|
+
return null;
|
|
5002
|
+
}
|
|
5003
|
+
let indeterminate = false;
|
|
5004
|
+
for (const candidate of sessions) {
|
|
5005
|
+
if (!candidate?.id || candidate.id === rootSessionId) continue;
|
|
5006
|
+
const membership = await this.resolveSessionMembership(candidate.id, rootSessionId);
|
|
5007
|
+
if (membership === null) {
|
|
5008
|
+
indeterminate = true;
|
|
5009
|
+
continue;
|
|
5010
|
+
}
|
|
5011
|
+
if (membership === false) continue;
|
|
5012
|
+
const ongoing = await isSessionOngoing(this.port, candidate.id);
|
|
5013
|
+
if (ongoing === true) return true;
|
|
5014
|
+
if (ongoing === null) indeterminate = true;
|
|
5015
|
+
}
|
|
5016
|
+
return indeterminate ? null : false;
|
|
5017
|
+
}
|
|
4448
5018
|
/**
|
|
4449
5019
|
* Cheap decision-telemetry label for a running row's LAST correlated reply
|
|
4450
5020
|
* (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
|
|
@@ -4708,7 +5278,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4708
5278
|
* exists but is wedged, so the next attempt must get a fresh one
|
|
4709
5279
|
* instead of reusing it — see WI-1's server-side null-clearing PATCH).
|
|
4710
5280
|
*/
|
|
4711
|
-
async markFailed(conversationId, messageId, sessionId, error2, usage) {
|
|
5281
|
+
async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
|
|
4712
5282
|
const body = { status: "failed" };
|
|
4713
5283
|
if (sessionId === null) {
|
|
4714
5284
|
body.opencode_session_id = null;
|
|
@@ -4717,6 +5287,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4717
5287
|
}
|
|
4718
5288
|
if (error2 !== void 0) body.error = error2;
|
|
4719
5289
|
if (usage) Object.assign(body, usage);
|
|
5290
|
+
if (failure) {
|
|
5291
|
+
body.failure_kind = failure.kind;
|
|
5292
|
+
body.failure_provider_id = failure.providerId;
|
|
5293
|
+
body.failure_model_id = failure.modelId;
|
|
5294
|
+
body.failure_reason = failure.reason;
|
|
5295
|
+
}
|
|
4720
5296
|
await this.callWithRetry(
|
|
4721
5297
|
"marking message as failed",
|
|
4722
5298
|
() => this.fetchImpl(
|
|
@@ -4729,6 +5305,29 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4729
5305
|
)
|
|
4730
5306
|
);
|
|
4731
5307
|
}
|
|
5308
|
+
/**
|
|
5309
|
+
* Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
|
|
5310
|
+
*
|
|
5311
|
+
* `messageFailure` alone (structured OpenCode error → `model_auth`) covers
|
|
5312
|
+
* most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
|
|
5313
|
+
* to the P1-2b zero-provider check — one extra loopback call to
|
|
5314
|
+
* `hasAnyConfiguredProvider`, only reached when the structured classifier
|
|
5315
|
+
* couldn't place it. Fails open (never throws): a fallback probe failure
|
|
5316
|
+
* (`null`/indeterminate) leaves the classification `null`, which produces
|
|
5317
|
+
* today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
|
|
5318
|
+
*/
|
|
5319
|
+
async classifyModelAuthFailure(messages, userMessageId) {
|
|
5320
|
+
const classified = messageFailure(messages, userMessageId);
|
|
5321
|
+
if (classified != null) return classified;
|
|
5322
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5323
|
+
const hasProvider = await hasAnyConfiguredProvider(this.port);
|
|
5324
|
+
return applyZeroProviderFallback(
|
|
5325
|
+
classified,
|
|
5326
|
+
hasProvider,
|
|
5327
|
+
reply?.info?.providerID ?? null,
|
|
5328
|
+
reply?.info?.modelID ?? null
|
|
5329
|
+
);
|
|
5330
|
+
}
|
|
4732
5331
|
/**
|
|
4733
5332
|
* Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
|
|
4734
5333
|
* (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
|
|
@@ -4881,10 +5480,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4881
5480
|
import chalk5 from "chalk";
|
|
4882
5481
|
import ora2 from "ora";
|
|
4883
5482
|
import { select as select2 } from "@inquirer/prompts";
|
|
5483
|
+
var INTERACTIVE_START_TIMEOUT_MS = 3e4;
|
|
4884
5484
|
async function ensureOpenCodeRunning(ctx) {
|
|
4885
5485
|
const healthCheck = await checkOpenCodeHealth(ctx.port);
|
|
4886
5486
|
if (healthCheck.healthy) {
|
|
4887
|
-
return {
|
|
5487
|
+
return {
|
|
5488
|
+
port: ctx.port,
|
|
5489
|
+
process: null,
|
|
5490
|
+
version: healthCheck.version ?? null,
|
|
5491
|
+
notReadyReason: null
|
|
5492
|
+
};
|
|
4888
5493
|
}
|
|
4889
5494
|
const runningInstances = await findHealthyOpenCodeInstances();
|
|
4890
5495
|
if (runningInstances.length > 0) {
|
|
@@ -4905,7 +5510,7 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4905
5510
|
console.log(chalk5.yellow("Tip: Run with the correct port:"));
|
|
4906
5511
|
console.log(
|
|
4907
5512
|
chalk5.dim(
|
|
4908
|
-
` ${getCliName()} run --
|
|
5513
|
+
` ${getCliName()} run --runner ${ctx.agentId} --port ${runningInstances[0].port}`
|
|
4909
5514
|
)
|
|
4910
5515
|
);
|
|
4911
5516
|
}
|
|
@@ -4925,14 +5530,22 @@ async function ensureOpenCodeRunning(ctx) {
|
|
|
4925
5530
|
if (!ctx.interactive) {
|
|
4926
5531
|
ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
|
|
4927
5532
|
const proc = await startOpenCode(ctx.port);
|
|
4928
|
-
const health = await waitForOpenCodeHealth(ctx.port,
|
|
5533
|
+
const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
|
|
4929
5534
|
if (!health.healthy) {
|
|
4930
|
-
|
|
4931
|
-
|
|
4932
|
-
|
|
5535
|
+
return {
|
|
5536
|
+
port: ctx.port,
|
|
5537
|
+
process: proc,
|
|
5538
|
+
version: null,
|
|
5539
|
+
notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
|
|
5540
|
+
};
|
|
4933
5541
|
}
|
|
4934
5542
|
ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
|
|
4935
|
-
return {
|
|
5543
|
+
return {
|
|
5544
|
+
port: ctx.port,
|
|
5545
|
+
process: proc,
|
|
5546
|
+
version: health.version ?? null,
|
|
5547
|
+
notReadyReason: null
|
|
5548
|
+
};
|
|
4936
5549
|
}
|
|
4937
5550
|
let port = ctx.port;
|
|
4938
5551
|
if (isPortInUse(port)) {
|
|
@@ -4985,15 +5598,15 @@ Port ${port} is already in use.`));
|
|
|
4985
5598
|
if (action === "start") {
|
|
4986
5599
|
const spinner = ora2("Starting OpenCode...").start();
|
|
4987
5600
|
const proc = await startOpenCode(port);
|
|
4988
|
-
const health = await waitForOpenCodeHealth(port,
|
|
5601
|
+
const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
|
|
4989
5602
|
if (!health.healthy) {
|
|
4990
5603
|
spinner.fail("Failed to start OpenCode");
|
|
4991
5604
|
throw new Error("OpenCode failed to start");
|
|
4992
5605
|
}
|
|
4993
5606
|
spinner.stop();
|
|
4994
|
-
return { port, process: proc, version: health.version ?? null };
|
|
5607
|
+
return { port, process: proc, version: health.version ?? null, notReadyReason: null };
|
|
4995
5608
|
}
|
|
4996
|
-
return { port, process: null, version: null };
|
|
5609
|
+
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
4997
5610
|
}
|
|
4998
5611
|
|
|
4999
5612
|
// src/commands/agent-lookup.ts
|
|
@@ -5035,19 +5648,21 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
5035
5648
|
return { agent_id: data.agent_id };
|
|
5036
5649
|
}
|
|
5037
5650
|
return {
|
|
5038
|
-
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --
|
|
5651
|
+
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
|
|
5039
5652
|
};
|
|
5040
5653
|
} catch (error2) {
|
|
5041
5654
|
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
5042
5655
|
return { error: `Failed to resolve runner from key: ${message}` };
|
|
5043
5656
|
}
|
|
5044
5657
|
}
|
|
5658
|
+
var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
|
|
5045
5659
|
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
5046
5660
|
const apiUrl = getApiUrlConfig();
|
|
5047
5661
|
try {
|
|
5048
5662
|
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
5049
5663
|
method: "POST",
|
|
5050
|
-
headers: { Authorization: authHeader }
|
|
5664
|
+
headers: { Authorization: authHeader },
|
|
5665
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5051
5666
|
});
|
|
5052
5667
|
if (!response.ok) {
|
|
5053
5668
|
const serverMessage = await readErrorMessage(response);
|
|
@@ -5058,7 +5673,63 @@ async function notifyAgentDisconnected(agentId, authHeader) {
|
|
|
5058
5673
|
}
|
|
5059
5674
|
return { ok: true };
|
|
5060
5675
|
} catch (error2) {
|
|
5061
|
-
return { ok: false, error:
|
|
5676
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5677
|
+
}
|
|
5678
|
+
}
|
|
5679
|
+
function describeBestEffortError(error2) {
|
|
5680
|
+
const name = error2?.name;
|
|
5681
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
5682
|
+
return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
|
|
5683
|
+
}
|
|
5684
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
5685
|
+
}
|
|
5686
|
+
async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
5687
|
+
try {
|
|
5688
|
+
const apiUrl = getApiUrlConfig();
|
|
5689
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
|
|
5690
|
+
method: "POST",
|
|
5691
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5692
|
+
body: JSON.stringify({ microvm_id: microvmId }),
|
|
5693
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5694
|
+
});
|
|
5695
|
+
if (!response.ok) {
|
|
5696
|
+
const serverMessage = await readErrorMessage(response);
|
|
5697
|
+
return {
|
|
5698
|
+
ok: false,
|
|
5699
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5700
|
+
};
|
|
5701
|
+
}
|
|
5702
|
+
return { ok: true };
|
|
5703
|
+
} catch (error2) {
|
|
5704
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5705
|
+
}
|
|
5706
|
+
}
|
|
5707
|
+
function toReportedWindow(window) {
|
|
5708
|
+
if (!window) return null;
|
|
5709
|
+
return { utilization: window.utilization, resets_at: window.resetsAt };
|
|
5710
|
+
}
|
|
5711
|
+
async function reportClaudeUsage(agentId, authHeader, snapshot) {
|
|
5712
|
+
try {
|
|
5713
|
+
const apiUrl = getApiUrlConfig();
|
|
5714
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/claude-usage`, {
|
|
5715
|
+
method: "POST",
|
|
5716
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
5717
|
+
body: JSON.stringify({
|
|
5718
|
+
five_hour: toReportedWindow(snapshot.fiveHour),
|
|
5719
|
+
seven_day: toReportedWindow(snapshot.sevenDay)
|
|
5720
|
+
}),
|
|
5721
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5722
|
+
});
|
|
5723
|
+
if (!response.ok) {
|
|
5724
|
+
const serverMessage = await readErrorMessage(response);
|
|
5725
|
+
return {
|
|
5726
|
+
ok: false,
|
|
5727
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5728
|
+
};
|
|
5729
|
+
}
|
|
5730
|
+
return { ok: true };
|
|
5731
|
+
} catch (error2) {
|
|
5732
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
5062
5733
|
}
|
|
5063
5734
|
}
|
|
5064
5735
|
async function getAgentInfo(agentId, authHeader) {
|
|
@@ -5108,6 +5779,7 @@ var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
|
5108
5779
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
5109
5780
|
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
5110
5781
|
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
5782
|
+
var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
5111
5783
|
function resolveLogLevel(options) {
|
|
5112
5784
|
const accepted = Object.keys(LOG_LEVELS);
|
|
5113
5785
|
const validate = (value, source) => {
|
|
@@ -5138,7 +5810,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
5138
5810
|
if (trimmed === "") {
|
|
5139
5811
|
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
5140
5812
|
}
|
|
5141
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
5813
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join3(homeDir, trimmed.slice(2)) : trimmed;
|
|
5142
5814
|
if (!isAbsolute2(expanded)) {
|
|
5143
5815
|
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
5144
5816
|
}
|
|
@@ -5159,6 +5831,35 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
5159
5831
|
}
|
|
5160
5832
|
return directories;
|
|
5161
5833
|
}
|
|
5834
|
+
var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
|
|
5835
|
+
var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
|
|
5836
|
+
var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
|
|
5837
|
+
function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
|
|
5838
|
+
const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
|
|
5839
|
+
let raw;
|
|
5840
|
+
let source;
|
|
5841
|
+
if (options.opencodeStartTimeout !== void 0) {
|
|
5842
|
+
raw = options.opencodeStartTimeout;
|
|
5843
|
+
source = "--opencode-start-timeout";
|
|
5844
|
+
} else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
|
|
5845
|
+
raw = env[OPENCODE_START_TIMEOUT_ENV];
|
|
5846
|
+
source = OPENCODE_START_TIMEOUT_ENV;
|
|
5847
|
+
} else {
|
|
5848
|
+
return { timeoutMs: defaultMs, warnings: [] };
|
|
5849
|
+
}
|
|
5850
|
+
const trimmed = raw.trim();
|
|
5851
|
+
const seconds = Number(trimmed);
|
|
5852
|
+
const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
|
|
5853
|
+
if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
|
|
5854
|
+
return {
|
|
5855
|
+
timeoutMs: defaultMs,
|
|
5856
|
+
warnings: [
|
|
5857
|
+
`Ignoring invalid ${source} "${raw}": expected a positive integer number of seconds (at most ${MAX_OPENCODE_START_TIMEOUT_SECONDS}); using the default ${DEFAULT_OPENCODE_START_TIMEOUT_SECONDS}s`
|
|
5858
|
+
]
|
|
5859
|
+
};
|
|
5860
|
+
}
|
|
5861
|
+
return { timeoutMs: seconds * 1e3, warnings: [] };
|
|
5862
|
+
}
|
|
5162
5863
|
function meetsThreshold(state, level) {
|
|
5163
5864
|
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
5164
5865
|
}
|
|
@@ -5180,6 +5881,10 @@ function log2(state, message, level = "info") {
|
|
|
5180
5881
|
function logActivity(state, entry) {
|
|
5181
5882
|
const level = entry.level ?? (entry.type === "error" ? "error" : "info");
|
|
5182
5883
|
if (!meetsThreshold(state, level)) return;
|
|
5884
|
+
forwardRunnerActivity(
|
|
5885
|
+
{ level, message: entry.message, error: entry.error },
|
|
5886
|
+
{ agentId: state.agentId, authHeader: state.authHeader }
|
|
5887
|
+
);
|
|
5183
5888
|
const fullEntry = {
|
|
5184
5889
|
...entry,
|
|
5185
5890
|
level,
|
|
@@ -5279,6 +5984,7 @@ async function handleAuthError(state, error2) {
|
|
|
5279
5984
|
}
|
|
5280
5985
|
async function driveChannels(state, driver) {
|
|
5281
5986
|
let idlePolls = 0;
|
|
5987
|
+
let consecutiveDrainFailures = 0;
|
|
5282
5988
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
5283
5989
|
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
5284
5990
|
while (state.running) {
|
|
@@ -5296,6 +6002,7 @@ async function driveChannels(state, driver) {
|
|
|
5296
6002
|
);
|
|
5297
6003
|
try {
|
|
5298
6004
|
const processed = await driver.drainPending();
|
|
6005
|
+
consecutiveDrainFailures = 0;
|
|
5299
6006
|
state.messageCount += processed;
|
|
5300
6007
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
5301
6008
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
@@ -5330,8 +6037,32 @@ async function driveChannels(state, driver) {
|
|
|
5330
6037
|
const errorMessage = error2 instanceof Error ? error2.message : String(error2);
|
|
5331
6038
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
5332
6039
|
if (state.interactive) displayStatus(state);
|
|
6040
|
+
if (driver.hasInFlightWatchers()) {
|
|
6041
|
+
consecutiveDrainFailures = 0;
|
|
6042
|
+
} else if (state.idleTimeout !== null) {
|
|
6043
|
+
consecutiveDrainFailures++;
|
|
6044
|
+
if (consecutiveDrainFailures === 1) {
|
|
6045
|
+
logActivity(state, {
|
|
6046
|
+
type: "info",
|
|
6047
|
+
message: `Cannot reach Evident, will exit if this persists past the idle timeout (timeout: ${state.idleTimeout}s)...`
|
|
6048
|
+
});
|
|
6049
|
+
if (state.interactive) displayStatus(state);
|
|
6050
|
+
}
|
|
6051
|
+
}
|
|
5333
6052
|
}
|
|
5334
6053
|
await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
|
|
6054
|
+
if (state.idleTimeout !== null && consecutiveDrainFailures >= 2) {
|
|
6055
|
+
const unreachableMs = consecutiveDrainFailures * CHANNEL_POLL_INTERVAL_MS;
|
|
6056
|
+
if (unreachableMs > state.idleTimeout * 1e3) {
|
|
6057
|
+
logActivity(state, {
|
|
6058
|
+
type: "info",
|
|
6059
|
+
level: "warn",
|
|
6060
|
+
message: `Exiting: could not reach Evident for ${consecutiveDrainFailures} consecutive polls (${Math.round(unreachableMs / 1e3)}s)`
|
|
6061
|
+
});
|
|
6062
|
+
if (state.interactive) displayStatus(state);
|
|
6063
|
+
break;
|
|
6064
|
+
}
|
|
6065
|
+
}
|
|
5335
6066
|
if (state.idleTimeout !== null && idlePolls >= 2) {
|
|
5336
6067
|
const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
|
|
5337
6068
|
if (idleMs > state.idleTimeout * 1e3) {
|
|
@@ -5343,8 +6074,8 @@ async function driveChannels(state, driver) {
|
|
|
5343
6074
|
}
|
|
5344
6075
|
}
|
|
5345
6076
|
var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
|
|
5346
|
-
async function runSweep(state, driver,
|
|
5347
|
-
const mode = `age=${
|
|
6077
|
+
async function runSweep(state, driver, config) {
|
|
6078
|
+
const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
|
|
5348
6079
|
try {
|
|
5349
6080
|
const sessions = await listSessions(state.port);
|
|
5350
6081
|
if (sessions === null) {
|
|
@@ -5357,8 +6088,8 @@ async function runSweep(state, driver, config2) {
|
|
|
5357
6088
|
const toDelete = selectSessionsToDelete(
|
|
5358
6089
|
sessions.map((s) => ({ id: s.id, lastActivityMs: sessionLastActivityMs(s) })),
|
|
5359
6090
|
{
|
|
5360
|
-
maxAgeMs:
|
|
5361
|
-
maxCount:
|
|
6091
|
+
maxAgeMs: config.maxAgeMs,
|
|
6092
|
+
maxCount: config.maxCount,
|
|
5362
6093
|
nowMs: Date.now(),
|
|
5363
6094
|
protectedIds: driver.protectedSessionIds()
|
|
5364
6095
|
}
|
|
@@ -5394,7 +6125,7 @@ async function runSweep(state, driver, config2) {
|
|
|
5394
6125
|
}
|
|
5395
6126
|
}
|
|
5396
6127
|
function scheduleSessionCleanup(state, driver, options) {
|
|
5397
|
-
const
|
|
6128
|
+
const config = resolveSessionCleanupConfig(
|
|
5398
6129
|
{
|
|
5399
6130
|
maxAge: options.sessionCleanupMaxAge,
|
|
5400
6131
|
maxCount: options.sessionCleanupMaxCount,
|
|
@@ -5402,21 +6133,109 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
5402
6133
|
},
|
|
5403
6134
|
process.env
|
|
5404
6135
|
);
|
|
5405
|
-
for (const warning2 of
|
|
6136
|
+
for (const warning2 of config.warnings) {
|
|
5406
6137
|
logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
|
|
5407
6138
|
}
|
|
5408
|
-
if (!
|
|
6139
|
+
if (!config.enabled) return;
|
|
5409
6140
|
logActivity(state, {
|
|
5410
6141
|
type: "info",
|
|
5411
|
-
message: `Session cleanup enabled (age=${
|
|
6142
|
+
message: `Session cleanup enabled (age=${config.maxAgeMs ?? "\u2014"}, count=${config.maxCount ?? "\u2014"}, interval=${config.intervalMs}ms)`
|
|
5412
6143
|
});
|
|
5413
|
-
const interval = setInterval(() => void runSweep(state, driver,
|
|
6144
|
+
const interval = setInterval(() => void runSweep(state, driver, config), config.intervalMs);
|
|
5414
6145
|
const firstSweep = setTimeout(
|
|
5415
|
-
() => void runSweep(state, driver,
|
|
6146
|
+
() => void runSweep(state, driver, config),
|
|
5416
6147
|
SESSION_CLEANUP_FIRST_SWEEP_MS
|
|
5417
6148
|
);
|
|
5418
6149
|
state.sessionCleanupTimers.push(interval, firstSweep);
|
|
5419
6150
|
}
|
|
6151
|
+
function scheduleClaudeUsageReporting(state, options) {
|
|
6152
|
+
const { mode, warnings } = resolveClaudeUsageReportingMode(
|
|
6153
|
+
options.claudeUsageReporting,
|
|
6154
|
+
process.env
|
|
6155
|
+
);
|
|
6156
|
+
for (const warning2 of warnings) {
|
|
6157
|
+
logActivity(state, {
|
|
6158
|
+
type: "info",
|
|
6159
|
+
level: "warn",
|
|
6160
|
+
message: `Claude usage reporting: ${warning2}`
|
|
6161
|
+
});
|
|
6162
|
+
}
|
|
6163
|
+
if (mode === "off") {
|
|
6164
|
+
logActivity(state, {
|
|
6165
|
+
type: "info",
|
|
6166
|
+
level: "debug",
|
|
6167
|
+
message: "Claude usage reporting is off (--claude-usage-reporting off)"
|
|
6168
|
+
});
|
|
6169
|
+
return;
|
|
6170
|
+
}
|
|
6171
|
+
let consecutiveFailures = 0;
|
|
6172
|
+
const scheduleNextTick = () => {
|
|
6173
|
+
state.claudeUsageTimer = setTimeout(() => void tick(false), nextReportDelayMs());
|
|
6174
|
+
};
|
|
6175
|
+
const tick = async (isFirst) => {
|
|
6176
|
+
try {
|
|
6177
|
+
const usage = await getClaudeUsage();
|
|
6178
|
+
const result = await reportClaudeUsage(state.agentId, state.authHeader, usage);
|
|
6179
|
+
if (result.ok) {
|
|
6180
|
+
if (consecutiveFailures > 0) {
|
|
6181
|
+
logActivity(state, {
|
|
6182
|
+
type: "info",
|
|
6183
|
+
level: "info",
|
|
6184
|
+
message: "Claude usage reporting recovered"
|
|
6185
|
+
});
|
|
6186
|
+
}
|
|
6187
|
+
consecutiveFailures = 0;
|
|
6188
|
+
logActivity(state, {
|
|
6189
|
+
type: "info",
|
|
6190
|
+
level: "debug",
|
|
6191
|
+
message: "Reported Claude usage to Evident"
|
|
6192
|
+
});
|
|
6193
|
+
} else {
|
|
6194
|
+
consecutiveFailures++;
|
|
6195
|
+
logActivity(state, {
|
|
6196
|
+
type: "info",
|
|
6197
|
+
level: consecutiveFailures === 1 ? "warn" : "debug",
|
|
6198
|
+
message: `Failed to report Claude usage: ${result.error}`
|
|
6199
|
+
});
|
|
6200
|
+
}
|
|
6201
|
+
scheduleNextTick();
|
|
6202
|
+
} catch (error2) {
|
|
6203
|
+
if (error2 instanceof ClaudeUsageError && isLocalCredentialProblem(error2)) {
|
|
6204
|
+
if (mode === "on") {
|
|
6205
|
+
logActivity(state, {
|
|
6206
|
+
type: "info",
|
|
6207
|
+
level: "warn",
|
|
6208
|
+
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"
|
|
6209
|
+
});
|
|
6210
|
+
scheduleNextTick();
|
|
6211
|
+
} else if (isFirst) {
|
|
6212
|
+
logActivity(state, {
|
|
6213
|
+
type: "info",
|
|
6214
|
+
level: "debug",
|
|
6215
|
+
message: `Claude usage reporting: ${error2.message}`
|
|
6216
|
+
});
|
|
6217
|
+
} else {
|
|
6218
|
+
logActivity(state, {
|
|
6219
|
+
type: "info",
|
|
6220
|
+
level: "debug",
|
|
6221
|
+
message: `Claude usage reporting: ${error2.message}`
|
|
6222
|
+
});
|
|
6223
|
+
scheduleNextTick();
|
|
6224
|
+
}
|
|
6225
|
+
} else {
|
|
6226
|
+
consecutiveFailures++;
|
|
6227
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
6228
|
+
logActivity(state, {
|
|
6229
|
+
type: "info",
|
|
6230
|
+
level: consecutiveFailures === 1 ? "warn" : "debug",
|
|
6231
|
+
message: `Claude usage reporting failed: ${message}`
|
|
6232
|
+
});
|
|
6233
|
+
scheduleNextTick();
|
|
6234
|
+
}
|
|
6235
|
+
}
|
|
6236
|
+
};
|
|
6237
|
+
state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
|
|
6238
|
+
}
|
|
5420
6239
|
async function notifyOffline(state) {
|
|
5421
6240
|
if (!state.agentId || !state.authHeader) return;
|
|
5422
6241
|
if (!state.connected) {
|
|
@@ -5434,13 +6253,28 @@ async function notifyOffline(state) {
|
|
|
5434
6253
|
if (state.interactive) displayStatus(state);
|
|
5435
6254
|
}
|
|
5436
6255
|
}
|
|
6256
|
+
async function timeShutdownPhase(state, durations, name, run2) {
|
|
6257
|
+
const startedAt = Date.now();
|
|
6258
|
+
try {
|
|
6259
|
+
return await run2();
|
|
6260
|
+
} finally {
|
|
6261
|
+
const elapsedMs = Date.now() - startedAt;
|
|
6262
|
+
durations[name] = elapsedMs;
|
|
6263
|
+
log2(state, `Shutdown phase ${name}: ${elapsedMs}ms`);
|
|
6264
|
+
}
|
|
6265
|
+
}
|
|
5437
6266
|
async function cleanup(state, opts = {}) {
|
|
6267
|
+
const durations = {};
|
|
5438
6268
|
state.running = false;
|
|
5439
6269
|
for (const timer of state.sessionCleanupTimers) {
|
|
5440
6270
|
clearInterval(timer);
|
|
5441
6271
|
clearTimeout(timer);
|
|
5442
6272
|
}
|
|
5443
6273
|
state.sessionCleanupTimers = [];
|
|
6274
|
+
if (state.claudeUsageTimer) {
|
|
6275
|
+
clearTimeout(state.claudeUsageTimer);
|
|
6276
|
+
state.claudeUsageTimer = null;
|
|
6277
|
+
}
|
|
5444
6278
|
if (opts.graceful && state.channelDriver) {
|
|
5445
6279
|
state.channelDriver.stop();
|
|
5446
6280
|
log2(state, "Draining in-flight channel work before shutdown...");
|
|
@@ -5448,7 +6282,13 @@ async function cleanup(state, opts = {}) {
|
|
|
5448
6282
|
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
5449
6283
|
displayStatus(state);
|
|
5450
6284
|
}
|
|
5451
|
-
const
|
|
6285
|
+
const driver = state.channelDriver;
|
|
6286
|
+
const settled = await timeShutdownPhase(
|
|
6287
|
+
state,
|
|
6288
|
+
durations,
|
|
6289
|
+
"drain",
|
|
6290
|
+
() => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
|
|
6291
|
+
);
|
|
5452
6292
|
if (!settled) {
|
|
5453
6293
|
logActivity(state, {
|
|
5454
6294
|
type: "info",
|
|
@@ -5457,13 +6297,15 @@ async function cleanup(state, opts = {}) {
|
|
|
5457
6297
|
if (state.interactive) displayStatus(state);
|
|
5458
6298
|
}
|
|
5459
6299
|
}
|
|
5460
|
-
await notifyOffline(state);
|
|
6300
|
+
await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
|
|
5461
6301
|
if (state.connection) {
|
|
5462
|
-
state.connection
|
|
6302
|
+
const connection = state.connection;
|
|
6303
|
+
await timeShutdownPhase(state, durations, "tunnel_close", () => connection.close());
|
|
5463
6304
|
state.connection = null;
|
|
5464
6305
|
}
|
|
5465
6306
|
if (state.opencodeProcess) {
|
|
5466
|
-
|
|
6307
|
+
const opencodeProcess = state.opencodeProcess;
|
|
6308
|
+
await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
|
|
5467
6309
|
if (state.interactive) {
|
|
5468
6310
|
logActivity(state, { type: "info", message: "Stopped OpenCode process" });
|
|
5469
6311
|
displayStatus(state);
|
|
@@ -5472,6 +6314,7 @@ async function cleanup(state, opts = {}) {
|
|
|
5472
6314
|
}
|
|
5473
6315
|
state.opencodeProcess = null;
|
|
5474
6316
|
}
|
|
6317
|
+
return durations;
|
|
5475
6318
|
}
|
|
5476
6319
|
async function run(options) {
|
|
5477
6320
|
const interactive = isInteractive(options.json);
|
|
@@ -5479,7 +6322,7 @@ async function run(options) {
|
|
|
5479
6322
|
let fileSyncDirectories;
|
|
5480
6323
|
try {
|
|
5481
6324
|
logLevel = resolveLogLevel(options);
|
|
5482
|
-
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo,
|
|
6325
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir3());
|
|
5483
6326
|
} catch (error2) {
|
|
5484
6327
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
5485
6328
|
if (options.json) {
|
|
@@ -5512,8 +6355,10 @@ async function run(options) {
|
|
|
5512
6355
|
messageCount: 0,
|
|
5513
6356
|
lastProxiedActivityAt: null,
|
|
5514
6357
|
sessionCleanupTimers: [],
|
|
6358
|
+
claudeUsageTimer: null,
|
|
5515
6359
|
authHeader: ""
|
|
5516
6360
|
};
|
|
6361
|
+
setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
|
|
5517
6362
|
if (fileSyncDirectories.length > 0) {
|
|
5518
6363
|
log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
|
|
5519
6364
|
} else {
|
|
@@ -5542,14 +6387,38 @@ async function run(options) {
|
|
|
5542
6387
|
const handleSignal = async () => {
|
|
5543
6388
|
if (state.shuttingDown) return;
|
|
5544
6389
|
state.shuttingDown = true;
|
|
6390
|
+
const shutdownStartedAt = Date.now();
|
|
5545
6391
|
if (state.interactive) {
|
|
5546
6392
|
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
5547
6393
|
displayStatus(state);
|
|
5548
6394
|
} else {
|
|
5549
6395
|
log2(state, "Shutting down...");
|
|
5550
6396
|
}
|
|
5551
|
-
await cleanup(state, { graceful: true });
|
|
5552
|
-
|
|
6397
|
+
const durations = await cleanup(state, { graceful: true });
|
|
6398
|
+
const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
|
|
6399
|
+
await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
|
|
6400
|
+
let timer;
|
|
6401
|
+
const flushed = shutdownTelemetry().then(
|
|
6402
|
+
() => true,
|
|
6403
|
+
(error2) => {
|
|
6404
|
+
log2(
|
|
6405
|
+
state,
|
|
6406
|
+
`Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
6407
|
+
"warn"
|
|
6408
|
+
);
|
|
6409
|
+
return true;
|
|
6410
|
+
}
|
|
6411
|
+
);
|
|
6412
|
+
const timedOut = new Promise((resolve3) => {
|
|
6413
|
+
timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
|
|
6414
|
+
});
|
|
6415
|
+
if (!await Promise.race([flushed, timedOut])) {
|
|
6416
|
+
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
6417
|
+
}
|
|
6418
|
+
clearTimeout(timer);
|
|
6419
|
+
});
|
|
6420
|
+
const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
|
|
6421
|
+
log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
|
|
5553
6422
|
process.exit(0);
|
|
5554
6423
|
};
|
|
5555
6424
|
process.on("SIGINT", handleSignal);
|
|
@@ -5663,40 +6532,67 @@ async function run(options) {
|
|
|
5663
6532
|
}
|
|
5664
6533
|
spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
|
|
5665
6534
|
state.agentName = validation.agent.name;
|
|
6535
|
+
const microvmId = process.env.MICROVM_ID?.trim();
|
|
6536
|
+
if (microvmId) {
|
|
6537
|
+
const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
|
|
6538
|
+
if (reported.ok) {
|
|
6539
|
+
log2(state, "Reported MicroVM identity so this runner can be resumed rather than restarted");
|
|
6540
|
+
} else {
|
|
6541
|
+
const message = `Could not report MicroVM identity (future wakes will cold-start): ${reported.error}`;
|
|
6542
|
+
log2(state, message, "warn");
|
|
6543
|
+
if (state.interactive && !state.json) {
|
|
6544
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6545
|
+
}
|
|
6546
|
+
}
|
|
6547
|
+
} else {
|
|
6548
|
+
log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
|
|
6549
|
+
}
|
|
6550
|
+
const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
|
|
6551
|
+
for (const warning2 of opencodeStartTimeoutWarnings) {
|
|
6552
|
+
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
6553
|
+
}
|
|
5666
6554
|
const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
|
|
5667
6555
|
try {
|
|
5668
6556
|
const oc = await ensureOpenCodeRunning({
|
|
5669
6557
|
port: state.port,
|
|
5670
6558
|
interactive: state.interactive,
|
|
5671
6559
|
agentId: state.agentId,
|
|
5672
|
-
log: (message) => log2(state, message)
|
|
6560
|
+
log: (message) => log2(state, message),
|
|
6561
|
+
startTimeoutMs: opencodeStartTimeoutMs
|
|
5673
6562
|
});
|
|
5674
6563
|
state.port = oc.port;
|
|
5675
6564
|
state.opencodeProcess = oc.process;
|
|
5676
6565
|
state.opencodeVersion = oc.version;
|
|
5677
|
-
state.opencodeConnected = oc.
|
|
6566
|
+
state.opencodeConnected = oc.notReadyReason === null;
|
|
5678
6567
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
5679
6568
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
5680
|
-
|
|
5681
|
-
|
|
5682
|
-
|
|
5683
|
-
|
|
5684
|
-
|
|
6569
|
+
if (!state.interactive && oc.notReadyReason !== null) {
|
|
6570
|
+
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}).`;
|
|
6571
|
+
logActivity(state, { type: "info", level: "warn", message });
|
|
6572
|
+
} else {
|
|
6573
|
+
const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
|
|
6574
|
+
if (versionWarning) {
|
|
6575
|
+
log2(state, versionWarning, "warn");
|
|
6576
|
+
if (state.interactive && !state.json) {
|
|
6577
|
+
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
6578
|
+
}
|
|
5685
6579
|
}
|
|
5686
|
-
|
|
5687
|
-
|
|
5688
|
-
|
|
5689
|
-
|
|
5690
|
-
|
|
5691
|
-
|
|
5692
|
-
|
|
5693
|
-
|
|
5694
|
-
|
|
5695
|
-
|
|
5696
|
-
|
|
5697
|
-
|
|
5698
|
-
|
|
5699
|
-
|
|
6580
|
+
const noProviderWarning = buildNoProviderWarning(
|
|
6581
|
+
await hasAnyConfiguredProvider(state.port)
|
|
6582
|
+
);
|
|
6583
|
+
if (noProviderWarning) {
|
|
6584
|
+
log2(state, noProviderWarning, "warn");
|
|
6585
|
+
if (state.interactive && !state.json) {
|
|
6586
|
+
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
6587
|
+
blank();
|
|
6588
|
+
console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
6589
|
+
console.log(
|
|
6590
|
+
chalk6.dim(
|
|
6591
|
+
`Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
6592
|
+
)
|
|
6593
|
+
);
|
|
6594
|
+
blank();
|
|
6595
|
+
}
|
|
5700
6596
|
}
|
|
5701
6597
|
}
|
|
5702
6598
|
} catch (error2) {
|
|
@@ -5714,7 +6610,7 @@ async function run(options) {
|
|
|
5714
6610
|
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
5715
6611
|
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
5716
6612
|
fileSyncDirectories,
|
|
5717
|
-
homeDir:
|
|
6613
|
+
homeDir: homedir3(),
|
|
5718
6614
|
log: (entry) => (
|
|
5719
6615
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
5720
6616
|
// survive the sink filter (they no longer collapse to info). `type`
|
|
@@ -5741,6 +6637,18 @@ async function run(options) {
|
|
|
5741
6637
|
type: "info",
|
|
5742
6638
|
message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
|
|
5743
6639
|
});
|
|
6640
|
+
if (options.tunnelReadyFile) {
|
|
6641
|
+
const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
|
|
6642
|
+
if (marker.ok) {
|
|
6643
|
+
log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
|
|
6644
|
+
} else {
|
|
6645
|
+
log2(
|
|
6646
|
+
state,
|
|
6647
|
+
`Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
|
|
6648
|
+
"error"
|
|
6649
|
+
);
|
|
6650
|
+
}
|
|
6651
|
+
}
|
|
5744
6652
|
emitAgentConnected(state.agentId, {
|
|
5745
6653
|
port: state.port,
|
|
5746
6654
|
cli_version: getCliVersion(),
|
|
@@ -5831,6 +6739,7 @@ async function run(options) {
|
|
|
5831
6739
|
throw error2;
|
|
5832
6740
|
}
|
|
5833
6741
|
scheduleSessionCleanup(state, channelDriver, options);
|
|
6742
|
+
scheduleClaudeUsageReporting(state, options);
|
|
5834
6743
|
if (!interactive || state.json) {
|
|
5835
6744
|
log2(state, "Driving channel messages...");
|
|
5836
6745
|
}
|
|
@@ -5885,13 +6794,17 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
5885
6794
|
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
6795
|
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
6796
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
6797
|
+
program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);
|
|
5888
6798
|
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
6799
|
"-a, --agent [id]",
|
|
5890
6800
|
"Deprecated alias for --runner (still supported; --runner wins if both are given)"
|
|
5891
6801
|
).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
5892
6802
|
"--log-level <level>",
|
|
5893
6803
|
"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(
|
|
6804
|
+
).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(
|
|
6805
|
+
"--opencode-start-timeout <seconds>",
|
|
6806
|
+
"Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
|
|
6807
|
+
).option("--json", "Output in JSON format").option(
|
|
5895
6808
|
"--session-cleanup-max-age <duration>",
|
|
5896
6809
|
"Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
|
|
5897
6810
|
).option(
|
|
@@ -5900,11 +6813,17 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5900
6813
|
).option(
|
|
5901
6814
|
"--session-cleanup-interval <duration>",
|
|
5902
6815
|
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
6816
|
+
).option(
|
|
6817
|
+
"--claude-usage-reporting <mode>",
|
|
6818
|
+
"Report Claude subscription usage to Evident: auto | on | off (default: auto). Env: EVIDENT_CLAUDE_USAGE_REPORTING"
|
|
5903
6819
|
).option(
|
|
5904
6820
|
"--enable-file-sync-to <dir>",
|
|
5905
6821
|
"Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
|
|
5906
6822
|
(value, previous) => previous.concat([value]),
|
|
5907
6823
|
[]
|
|
6824
|
+
).option(
|
|
6825
|
+
"--tunnel-ready-file <path>",
|
|
6826
|
+
"Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
|
|
5908
6827
|
).action(
|
|
5909
6828
|
(options) => {
|
|
5910
6829
|
run({
|
|
@@ -5917,14 +6836,21 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
5917
6836
|
verbose: options.verbose,
|
|
5918
6837
|
conversation: options.conversation,
|
|
5919
6838
|
idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
|
|
6839
|
+
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
6840
|
+
// resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
|
|
6841
|
+
opencodeStartTimeout: options.opencodeStartTimeout,
|
|
5920
6842
|
json: options.json,
|
|
5921
6843
|
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
5922
6844
|
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
5923
6845
|
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
5924
6846
|
sessionCleanupInterval: options.sessionCleanupInterval,
|
|
6847
|
+
// Raw string — the resolver in run.ts single-sources parsing
|
|
6848
|
+
// (resolveClaudeUsageReportingMode).
|
|
6849
|
+
claudeUsageReporting: options.claudeUsageReporting,
|
|
5925
6850
|
// Raw values — expansion/validation is single-sourced in run.ts's
|
|
5926
6851
|
// resolveFileSyncDirectories.
|
|
5927
|
-
enableFileSyncTo: options.enableFileSyncTo
|
|
6852
|
+
enableFileSyncTo: options.enableFileSyncTo,
|
|
6853
|
+
tunnelReadyFile: options.tunnelReadyFile
|
|
5928
6854
|
});
|
|
5929
6855
|
}
|
|
5930
6856
|
);
|