@evident-ai/cli 3.1.1-dev.1e66164 → 3.1.1-dev.201318e
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/dist/index.js +1067 -257
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -532,6 +532,353 @@ async function whoami() {
|
|
|
532
532
|
blank();
|
|
533
533
|
}
|
|
534
534
|
|
|
535
|
+
// src/lib/auth.ts
|
|
536
|
+
async function getAuthCredentials() {
|
|
537
|
+
const runnerKey = process.env.EVIDENT_RUNNER_KEY;
|
|
538
|
+
const agentKey = process.env.EVIDENT_AGENT_KEY;
|
|
539
|
+
if (runnerKey) {
|
|
540
|
+
return {
|
|
541
|
+
token: runnerKey,
|
|
542
|
+
authType: "agent_key",
|
|
543
|
+
keySource: "runner_key",
|
|
544
|
+
notice: agentKey ? "Both EVIDENT_RUNNER_KEY and EVIDENT_AGENT_KEY are set; using EVIDENT_RUNNER_KEY." : void 0
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
if (agentKey) {
|
|
548
|
+
return { token: agentKey, authType: "agent_key", keySource: "agent_key" };
|
|
549
|
+
}
|
|
550
|
+
const userToken = process.env.EVIDENT_TOKEN;
|
|
551
|
+
if (userToken) {
|
|
552
|
+
return { token: userToken, authType: "bearer" };
|
|
553
|
+
}
|
|
554
|
+
const keychainCreds = await getToken();
|
|
555
|
+
if (keychainCreds) {
|
|
556
|
+
return {
|
|
557
|
+
token: keychainCreds.token,
|
|
558
|
+
authType: "bearer",
|
|
559
|
+
user: keychainCreds.user
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
return null;
|
|
563
|
+
}
|
|
564
|
+
function getAuthHeader(credentials2) {
|
|
565
|
+
if (credentials2.authType === "agent_key") {
|
|
566
|
+
return `SandboxKey ${credentials2.token}`;
|
|
567
|
+
}
|
|
568
|
+
return `Bearer ${credentials2.token}`;
|
|
569
|
+
}
|
|
570
|
+
function isInteractive(jsonOutput) {
|
|
571
|
+
if (jsonOutput) return false;
|
|
572
|
+
if (process.env.CI) return false;
|
|
573
|
+
if (process.env.GITHUB_ACTIONS) return false;
|
|
574
|
+
if (!process.stdin.isTTY) return false;
|
|
575
|
+
return true;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// src/commands/agent-lookup.ts
|
|
579
|
+
async function readErrorMessage(response) {
|
|
580
|
+
const text = await response.text().catch(() => "");
|
|
581
|
+
if (!text) return response.statusText || void 0;
|
|
582
|
+
try {
|
|
583
|
+
const data = JSON.parse(text);
|
|
584
|
+
const message = data.message ?? data.error;
|
|
585
|
+
if (typeof message === "string" && message.trim()) {
|
|
586
|
+
return message;
|
|
587
|
+
}
|
|
588
|
+
} catch {
|
|
589
|
+
}
|
|
590
|
+
return text.trim() || response.statusText || void 0;
|
|
591
|
+
}
|
|
592
|
+
function authFailureHint(apiUrl, serverMessage) {
|
|
593
|
+
const reason = serverMessage ? `: ${serverMessage}` : "";
|
|
594
|
+
return `Authentication failed${reason}. Your credentials were rejected by ${apiUrl}. This usually means you logged in against a different environment, or your session expired \u2014 log in again pointing at this endpoint and retry.`;
|
|
595
|
+
}
|
|
596
|
+
async function resolveAgentIdFromKey(authHeader) {
|
|
597
|
+
const apiUrl = getApiUrlConfig();
|
|
598
|
+
try {
|
|
599
|
+
const response = await fetch(`${apiUrl}/me`, {
|
|
600
|
+
headers: { Authorization: authHeader }
|
|
601
|
+
});
|
|
602
|
+
if (response.status === 401) {
|
|
603
|
+
const serverMessage = await readErrorMessage(response);
|
|
604
|
+
return { error: authFailureHint(apiUrl, serverMessage), authFailed: true };
|
|
605
|
+
}
|
|
606
|
+
if (!response.ok) {
|
|
607
|
+
const serverMessage = await readErrorMessage(response);
|
|
608
|
+
return {
|
|
609
|
+
error: `Failed to resolve runner from key (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
const data = await response.json();
|
|
613
|
+
if (data.auth_type === "agent_key" && data.agent_id) {
|
|
614
|
+
return { agent_id: data.agent_id };
|
|
615
|
+
}
|
|
616
|
+
return {
|
|
617
|
+
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
|
|
618
|
+
};
|
|
619
|
+
} catch (error2) {
|
|
620
|
+
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
621
|
+
return { error: `Failed to resolve runner from key: ${message}` };
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
|
|
625
|
+
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
626
|
+
const apiUrl = getApiUrlConfig();
|
|
627
|
+
try {
|
|
628
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
629
|
+
method: "POST",
|
|
630
|
+
headers: { Authorization: authHeader },
|
|
631
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
632
|
+
});
|
|
633
|
+
if (!response.ok) {
|
|
634
|
+
const serverMessage = await readErrorMessage(response);
|
|
635
|
+
return {
|
|
636
|
+
ok: false,
|
|
637
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
return { ok: true };
|
|
641
|
+
} catch (error2) {
|
|
642
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
function describeBestEffortError(error2) {
|
|
646
|
+
const name = error2?.name;
|
|
647
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
648
|
+
return `timed out after ${BEST_EFFORT_NOTIFY_TIMEOUT_MS}ms`;
|
|
649
|
+
}
|
|
650
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
651
|
+
}
|
|
652
|
+
async function reportMicrovmId(agentId, authHeader, microvmId) {
|
|
653
|
+
try {
|
|
654
|
+
const apiUrl = getApiUrlConfig();
|
|
655
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/microvm`, {
|
|
656
|
+
method: "POST",
|
|
657
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
658
|
+
body: JSON.stringify({ microvm_id: microvmId }),
|
|
659
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
660
|
+
});
|
|
661
|
+
if (!response.ok) {
|
|
662
|
+
const serverMessage = await readErrorMessage(response);
|
|
663
|
+
return {
|
|
664
|
+
ok: false,
|
|
665
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
return { ok: true };
|
|
669
|
+
} catch (error2) {
|
|
670
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
function toReportedWindow(window) {
|
|
674
|
+
if (!window) return null;
|
|
675
|
+
return { utilization: window.utilization, resets_at: window.resetsAt };
|
|
676
|
+
}
|
|
677
|
+
async function reportClaudeUsage(agentId, authHeader, snapshot) {
|
|
678
|
+
try {
|
|
679
|
+
const apiUrl = getApiUrlConfig();
|
|
680
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/claude-usage`, {
|
|
681
|
+
method: "POST",
|
|
682
|
+
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
|
683
|
+
body: JSON.stringify({
|
|
684
|
+
five_hour: toReportedWindow(snapshot.fiveHour),
|
|
685
|
+
seven_day: toReportedWindow(snapshot.sevenDay)
|
|
686
|
+
}),
|
|
687
|
+
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
688
|
+
});
|
|
689
|
+
if (!response.ok) {
|
|
690
|
+
const serverMessage = await readErrorMessage(response);
|
|
691
|
+
return {
|
|
692
|
+
ok: false,
|
|
693
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
return { ok: true };
|
|
697
|
+
} catch (error2) {
|
|
698
|
+
return { ok: false, error: describeBestEffortError(error2) };
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
async function getAgentInfo(agentId, authHeader) {
|
|
702
|
+
const apiUrl = getApiUrlConfig();
|
|
703
|
+
try {
|
|
704
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}`, {
|
|
705
|
+
headers: { Authorization: authHeader }
|
|
706
|
+
});
|
|
707
|
+
if (response.status === 401) {
|
|
708
|
+
const serverMessage = await readErrorMessage(response);
|
|
709
|
+
return { valid: false, error: authFailureHint(apiUrl, serverMessage), authFailed: true };
|
|
710
|
+
}
|
|
711
|
+
if (response.status === 403) {
|
|
712
|
+
const serverMessage = await readErrorMessage(response);
|
|
713
|
+
return {
|
|
714
|
+
valid: false,
|
|
715
|
+
error: serverMessage ?? "You do not have access to this runner (it may belong to a different team or organization)."
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
if (response.status === 404) {
|
|
719
|
+
const serverMessage = await readErrorMessage(response);
|
|
720
|
+
return { valid: false, error: serverMessage ?? `Runner ${agentId} not found` };
|
|
721
|
+
}
|
|
722
|
+
if (!response.ok) {
|
|
723
|
+
const serverMessage = await readErrorMessage(response);
|
|
724
|
+
return {
|
|
725
|
+
valid: false,
|
|
726
|
+
error: `API error (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
const agent = await response.json();
|
|
730
|
+
if (agent.agent_type !== "local") {
|
|
731
|
+
return {
|
|
732
|
+
valid: false,
|
|
733
|
+
error: `Runner is type '${agent.agent_type}', must be 'local' for CLI connection`
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
return { valid: true, agent };
|
|
737
|
+
} catch (error2) {
|
|
738
|
+
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
739
|
+
return { valid: false, error: `Failed to validate runner: ${message}` };
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// src/commands/status.ts
|
|
744
|
+
var STATUS_TIMEOUT_MS = 1e4;
|
|
745
|
+
function authLabelFor(credentials2) {
|
|
746
|
+
if (credentials2.authType === "agent_key") {
|
|
747
|
+
return credentials2.keySource === "agent_key" ? "runner key (EVIDENT_AGENT_KEY)" : "runner key (EVIDENT_RUNNER_KEY)";
|
|
748
|
+
}
|
|
749
|
+
return "user token";
|
|
750
|
+
}
|
|
751
|
+
function describeFetchError(error2) {
|
|
752
|
+
const name = error2?.name;
|
|
753
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
754
|
+
return `timed out after ${STATUS_TIMEOUT_MS}ms waiting for a response`;
|
|
755
|
+
}
|
|
756
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
757
|
+
}
|
|
758
|
+
async function checkStatus(jsonMode) {
|
|
759
|
+
const apiUrl = getApiUrlConfig();
|
|
760
|
+
const credentials2 = await getAuthCredentials();
|
|
761
|
+
if (!credentials2) {
|
|
762
|
+
return {
|
|
763
|
+
ok: false,
|
|
764
|
+
endpoint: apiUrl,
|
|
765
|
+
reason: "no_credentials",
|
|
766
|
+
error: "No credentials configured. Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY), or EVIDENT_TOKEN, or run `evident login`.",
|
|
767
|
+
exitCode: 1
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
if (credentials2.notice && !jsonMode) {
|
|
771
|
+
printWarning(credentials2.notice);
|
|
772
|
+
}
|
|
773
|
+
let response;
|
|
774
|
+
try {
|
|
775
|
+
response = await fetch(`${apiUrl}/me`, {
|
|
776
|
+
headers: { Authorization: getAuthHeader(credentials2) },
|
|
777
|
+
signal: AbortSignal.timeout(STATUS_TIMEOUT_MS)
|
|
778
|
+
});
|
|
779
|
+
} catch (error2) {
|
|
780
|
+
return {
|
|
781
|
+
ok: false,
|
|
782
|
+
endpoint: apiUrl,
|
|
783
|
+
authLabel: authLabelFor(credentials2),
|
|
784
|
+
reason: "unreachable",
|
|
785
|
+
error: `Could not reach ${apiUrl}: ${describeFetchError(error2)}. The credentials were NOT validated.`,
|
|
786
|
+
exitCode: 75
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
if (response.status === 401) {
|
|
790
|
+
const serverMessage = await readErrorMessage(response);
|
|
791
|
+
return {
|
|
792
|
+
ok: false,
|
|
793
|
+
endpoint: apiUrl,
|
|
794
|
+
authLabel: authLabelFor(credentials2),
|
|
795
|
+
reason: "unauthorized",
|
|
796
|
+
error: authFailureHint(apiUrl, serverMessage),
|
|
797
|
+
exitCode: 1
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
if (response.status === 404) {
|
|
801
|
+
return {
|
|
802
|
+
ok: false,
|
|
803
|
+
endpoint: apiUrl,
|
|
804
|
+
authLabel: authLabelFor(credentials2),
|
|
805
|
+
reason: "endpoint_not_found",
|
|
806
|
+
error: `${apiUrl}/me returned HTTP 404 \u2014 that endpoint has no /me route, so it is probably missing the /v1 prefix. The credentials were NOT validated.`,
|
|
807
|
+
exitCode: 75
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
if (response.status >= 500) {
|
|
811
|
+
const serverMessage = await readErrorMessage(response);
|
|
812
|
+
return {
|
|
813
|
+
ok: false,
|
|
814
|
+
endpoint: apiUrl,
|
|
815
|
+
authLabel: authLabelFor(credentials2),
|
|
816
|
+
reason: "unreachable",
|
|
817
|
+
error: `${apiUrl} returned HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}. The credentials were NOT validated.`,
|
|
818
|
+
exitCode: 75
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
if (!response.ok) {
|
|
822
|
+
const serverMessage = await readErrorMessage(response);
|
|
823
|
+
return {
|
|
824
|
+
ok: false,
|
|
825
|
+
endpoint: apiUrl,
|
|
826
|
+
authLabel: authLabelFor(credentials2),
|
|
827
|
+
reason: "http_error",
|
|
828
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`,
|
|
829
|
+
exitCode: 1
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
const data = await response.json();
|
|
833
|
+
return {
|
|
834
|
+
ok: true,
|
|
835
|
+
endpoint: apiUrl,
|
|
836
|
+
authType: data.auth_type,
|
|
837
|
+
authLabel: authLabelFor(credentials2),
|
|
838
|
+
runnerId: data.auth_type === "agent_key" ? data.agent_id : void 0,
|
|
839
|
+
reason: "ok",
|
|
840
|
+
exitCode: 0
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
function printJson(result) {
|
|
844
|
+
const payload = {
|
|
845
|
+
ok: result.ok,
|
|
846
|
+
endpoint: result.endpoint
|
|
847
|
+
};
|
|
848
|
+
if (result.authType) payload.auth_type = result.authType;
|
|
849
|
+
if (result.runnerId) payload.runner_id = result.runnerId;
|
|
850
|
+
if (result.reason) payload.reason = result.reason;
|
|
851
|
+
if (result.error) payload.error = result.error;
|
|
852
|
+
console.log(JSON.stringify(payload));
|
|
853
|
+
}
|
|
854
|
+
function printHuman(result) {
|
|
855
|
+
blank();
|
|
856
|
+
console.log(keyValue("Endpoint", result.endpoint));
|
|
857
|
+
if (result.ok) {
|
|
858
|
+
console.log(keyValue("Auth", result.authLabel ?? "\u2014"));
|
|
859
|
+
if (result.runnerId) {
|
|
860
|
+
console.log(keyValue("Runner", result.runnerId));
|
|
861
|
+
}
|
|
862
|
+
console.log(keyValue("Status", "OK \u2014 credentials accepted"));
|
|
863
|
+
blank();
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
if (result.authLabel) {
|
|
867
|
+
console.log(keyValue("Auth", result.authLabel));
|
|
868
|
+
}
|
|
869
|
+
blank();
|
|
870
|
+
printError(result.error ?? "Unknown error");
|
|
871
|
+
}
|
|
872
|
+
async function status(options = {}) {
|
|
873
|
+
const result = await checkStatus(Boolean(options.json));
|
|
874
|
+
if (options.json) {
|
|
875
|
+
printJson(result);
|
|
876
|
+
} else {
|
|
877
|
+
printHuman(result);
|
|
878
|
+
}
|
|
879
|
+
process.exit(result.exitCode);
|
|
880
|
+
}
|
|
881
|
+
|
|
535
882
|
// src/lib/claude-usage.ts
|
|
536
883
|
import { execFileSync } from "child_process";
|
|
537
884
|
import { readFileSync } from "fs";
|
|
@@ -582,6 +929,10 @@ var ClaudeUsageError = class extends Error {
|
|
|
582
929
|
function isLocalCredentialProblem(err) {
|
|
583
930
|
return err instanceof ClaudeUsageError && (err.reason === "no_credentials" || err.reason === "credentials_expired");
|
|
584
931
|
}
|
|
932
|
+
function normalizeResetsAt(value) {
|
|
933
|
+
const ms = Date.parse(value);
|
|
934
|
+
return Number.isNaN(ms) ? null : new Date(ms).toISOString();
|
|
935
|
+
}
|
|
585
936
|
function toWindow(value) {
|
|
586
937
|
if (!value || typeof value !== "object") {
|
|
587
938
|
return null;
|
|
@@ -590,7 +941,11 @@ function toWindow(value) {
|
|
|
590
941
|
if (typeof window.utilization !== "number" || typeof window.resets_at !== "string") {
|
|
591
942
|
return null;
|
|
592
943
|
}
|
|
593
|
-
|
|
944
|
+
const resetsAt = normalizeResetsAt(window.resets_at);
|
|
945
|
+
if (resetsAt === null) {
|
|
946
|
+
return null;
|
|
947
|
+
}
|
|
948
|
+
return { utilization: window.utilization, resetsAt };
|
|
594
949
|
}
|
|
595
950
|
async function getClaudeUsage() {
|
|
596
951
|
const credentials2 = readClaudeCliCredentials();
|
|
@@ -652,6 +1007,9 @@ import { homedir as homedir3 } from "os";
|
|
|
652
1007
|
import { isAbsolute as isAbsolute2, join as join3, parse, resolve as resolvePath } from "path";
|
|
653
1008
|
import chalk6 from "chalk";
|
|
654
1009
|
|
|
1010
|
+
// ../../packages/types/src/agents/index.ts
|
|
1011
|
+
var MICROVM_MAX_LIFETIME_MS = 8 * 60 * 6e4;
|
|
1012
|
+
|
|
655
1013
|
// ../../packages/types/src/telemetry/index.ts
|
|
656
1014
|
var TelemetryEventTypes = {
|
|
657
1015
|
// Agent activity events (shown in web UI activity log)
|
|
@@ -934,49 +1292,6 @@ function forwardRunnerActivity(entry, context) {
|
|
|
934
1292
|
}
|
|
935
1293
|
}
|
|
936
1294
|
|
|
937
|
-
// src/lib/auth.ts
|
|
938
|
-
async function getAuthCredentials() {
|
|
939
|
-
const runnerKey = process.env.EVIDENT_RUNNER_KEY;
|
|
940
|
-
const agentKey = process.env.EVIDENT_AGENT_KEY;
|
|
941
|
-
if (runnerKey) {
|
|
942
|
-
return {
|
|
943
|
-
token: runnerKey,
|
|
944
|
-
authType: "agent_key",
|
|
945
|
-
keySource: "runner_key",
|
|
946
|
-
notice: agentKey ? "Both EVIDENT_RUNNER_KEY and EVIDENT_AGENT_KEY are set; using EVIDENT_RUNNER_KEY." : void 0
|
|
947
|
-
};
|
|
948
|
-
}
|
|
949
|
-
if (agentKey) {
|
|
950
|
-
return { token: agentKey, authType: "agent_key", keySource: "agent_key" };
|
|
951
|
-
}
|
|
952
|
-
const userToken = process.env.EVIDENT_TOKEN;
|
|
953
|
-
if (userToken) {
|
|
954
|
-
return { token: userToken, authType: "bearer" };
|
|
955
|
-
}
|
|
956
|
-
const keychainCreds = await getToken();
|
|
957
|
-
if (keychainCreds) {
|
|
958
|
-
return {
|
|
959
|
-
token: keychainCreds.token,
|
|
960
|
-
authType: "bearer",
|
|
961
|
-
user: keychainCreds.user
|
|
962
|
-
};
|
|
963
|
-
}
|
|
964
|
-
return null;
|
|
965
|
-
}
|
|
966
|
-
function getAuthHeader(credentials2) {
|
|
967
|
-
if (credentials2.authType === "agent_key") {
|
|
968
|
-
return `SandboxKey ${credentials2.token}`;
|
|
969
|
-
}
|
|
970
|
-
return `Bearer ${credentials2.token}`;
|
|
971
|
-
}
|
|
972
|
-
function isInteractive(jsonOutput) {
|
|
973
|
-
if (jsonOutput) return false;
|
|
974
|
-
if (process.env.CI) return false;
|
|
975
|
-
if (process.env.GITHUB_ACTIONS) return false;
|
|
976
|
-
if (!process.stdin.isTTY) return false;
|
|
977
|
-
return true;
|
|
978
|
-
}
|
|
979
|
-
|
|
980
1295
|
// src/lib/opencode/health.ts
|
|
981
1296
|
async function checkOpenCodeHealth(port) {
|
|
982
1297
|
try {
|
|
@@ -1784,6 +2099,21 @@ function messageError(messages, userMessageId) {
|
|
|
1784
2099
|
}
|
|
1785
2100
|
return "The agent run failed.";
|
|
1786
2101
|
}
|
|
2102
|
+
function isAbortedTerminalReply(messages, userMessageId) {
|
|
2103
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
2104
|
+
const error2 = errorOf(reply);
|
|
2105
|
+
if (error2 == null) return false;
|
|
2106
|
+
if (typeof error2 === "string") return error2.trim() === "Aborted";
|
|
2107
|
+
if (typeof error2 === "object") {
|
|
2108
|
+
const e = error2;
|
|
2109
|
+
if (e.name === "MessageAbortedError") return true;
|
|
2110
|
+
if (e.name === "AbortError") return true;
|
|
2111
|
+
const dataMessage = e.data?.message;
|
|
2112
|
+
const rendered = typeof dataMessage === "string" ? dataMessage : typeof e.message === "string" ? e.message : null;
|
|
2113
|
+
return rendered != null && rendered.trim() === "Aborted";
|
|
2114
|
+
}
|
|
2115
|
+
return false;
|
|
2116
|
+
}
|
|
1787
2117
|
function messageFailure(messages, userMessageId) {
|
|
1788
2118
|
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1789
2119
|
const error2 = errorOf(reply);
|
|
@@ -2386,6 +2716,10 @@ function nextReportDelayMs(random = Math.random) {
|
|
|
2386
2716
|
return BASE_REPORT_DELAY_MS - jitterRangeMs + random() * (2 * jitterRangeMs);
|
|
2387
2717
|
}
|
|
2388
2718
|
var FIRST_REPORT_DELAY_MS = 5e3 + Math.random() * 1e4;
|
|
2719
|
+
var CLAUDE_USAGE_FAILURE_REESCALATION_TICKS = 6;
|
|
2720
|
+
function claudeUsageFailureLogLevel(consecutiveFailures) {
|
|
2721
|
+
return consecutiveFailures === 1 || consecutiveFailures % CLAUDE_USAGE_FAILURE_REESCALATION_TICKS === 0 ? "warn" : "debug";
|
|
2722
|
+
}
|
|
2389
2723
|
|
|
2390
2724
|
// src/lib/channels/driver.ts
|
|
2391
2725
|
import { homedir as homedir2 } from "os";
|
|
@@ -2708,8 +3042,8 @@ async function applyOne(options, file) {
|
|
|
2708
3042
|
await ack(options, file, "applied");
|
|
2709
3043
|
return true;
|
|
2710
3044
|
}
|
|
2711
|
-
function durableDownloadCode(
|
|
2712
|
-
return
|
|
3045
|
+
function durableDownloadCode(status2) {
|
|
3046
|
+
return status2 === 413 ? "file_too_large" : "write_failed";
|
|
2713
3047
|
}
|
|
2714
3048
|
async function downloadContent(options, file, label) {
|
|
2715
3049
|
try {
|
|
@@ -2742,8 +3076,8 @@ async function downloadContent(options, file, label) {
|
|
|
2742
3076
|
return { ok: false, terminal: false };
|
|
2743
3077
|
}
|
|
2744
3078
|
}
|
|
2745
|
-
async function ack(options, file,
|
|
2746
|
-
const outcome = `${
|
|
3079
|
+
async function ack(options, file, status2, reason) {
|
|
3080
|
+
const outcome = `${status2}${reason ? ` (${reason})` : ""}`;
|
|
2747
3081
|
try {
|
|
2748
3082
|
const res = await options.fetchImpl(
|
|
2749
3083
|
`${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
|
|
@@ -2753,7 +3087,7 @@ async function ack(options, file, status, reason) {
|
|
|
2753
3087
|
Authorization: options.getAuthHeader(),
|
|
2754
3088
|
"Content-Type": "application/json"
|
|
2755
3089
|
},
|
|
2756
|
-
body: JSON.stringify(reason ? { status, reason } : { status })
|
|
3090
|
+
body: JSON.stringify(reason ? { status: status2, reason } : { status: status2 })
|
|
2757
3091
|
}
|
|
2758
3092
|
);
|
|
2759
3093
|
if (!res.ok) {
|
|
@@ -2817,6 +3151,7 @@ var B2_ABANDONMENT_MIN_PINNED_MS = 3 * 6e4;
|
|
|
2817
3151
|
var B2_ABANDONMENT_RECHECK_MS = HEARTBEAT_MS;
|
|
2818
3152
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2819
3153
|
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
3154
|
+
var MAX_IDENTICAL_REDRIVE_POLL_FAILURES = 5;
|
|
2820
3155
|
var ChannelAuthError = class extends Error {
|
|
2821
3156
|
constructor(message) {
|
|
2822
3157
|
super(message);
|
|
@@ -2825,10 +3160,10 @@ var ChannelAuthError = class extends Error {
|
|
|
2825
3160
|
};
|
|
2826
3161
|
var ChannelTerminalError = class extends Error {
|
|
2827
3162
|
status;
|
|
2828
|
-
constructor(message,
|
|
3163
|
+
constructor(message, status2) {
|
|
2829
3164
|
super(message);
|
|
2830
3165
|
this.name = "ChannelTerminalError";
|
|
2831
|
-
this.status =
|
|
3166
|
+
this.status = status2;
|
|
2832
3167
|
}
|
|
2833
3168
|
};
|
|
2834
3169
|
function backoffDelay(attempt, policy) {
|
|
@@ -2836,8 +3171,12 @@ function backoffDelay(attempt, policy) {
|
|
|
2836
3171
|
const capped = Math.min(policy.maxDelayMs, exp);
|
|
2837
3172
|
return Math.floor(Math.random() * capped);
|
|
2838
3173
|
}
|
|
2839
|
-
function isRetryableStatus(
|
|
2840
|
-
return
|
|
3174
|
+
function isRetryableStatus(status2) {
|
|
3175
|
+
return status2 === 429 || status2 >= 500 && status2 <= 599;
|
|
3176
|
+
}
|
|
3177
|
+
var VOLATILE_BODY_FIELD_PATTERN = /("(?:ref|requestId|request_id|traceId|trace_id)"\s*:\s*)"[^"]*"/gi;
|
|
3178
|
+
function normalizeRedrivePollFailureBody(body) {
|
|
3179
|
+
return body.replace(VOLATILE_BODY_FIELD_PATTERN, '$1"<redacted>"').replace(/\s+/g, " ").trim().slice(0, 200);
|
|
2841
3180
|
}
|
|
2842
3181
|
var ChannelDriver = class _ChannelDriver {
|
|
2843
3182
|
agentId;
|
|
@@ -2952,6 +3291,75 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
2952
3291
|
* processing list, exactly like `dontRedispatch`/`doneUndeliverable`.
|
|
2953
3292
|
*/
|
|
2954
3293
|
readoptPollUnresolvedSignalled = /* @__PURE__ */ new Set();
|
|
3294
|
+
/**
|
|
3295
|
+
* "Already emitted `redrive_unresolved` for this row" (#965). Mirrors
|
|
3296
|
+
* `readoptPollUnresolvedSignalled`: `resolveRedrive`'s `unresolved` leaf recurs
|
|
3297
|
+
* every ~2s drain until opencode's status becomes readable, but the
|
|
3298
|
+
* server-visible signal is an OUTCOME, so it fires at most once per row. Cleared
|
|
3299
|
+
* on any non-`unresolved` outcome so the set cannot grow beyond the currently
|
|
3300
|
+
* unresolvable rows.
|
|
3301
|
+
*/
|
|
3302
|
+
redriveUnresolvedSignalled = /* @__PURE__ */ new Set();
|
|
3303
|
+
/**
|
|
3304
|
+
* First `now()` a `pending` row's re-drive was observed `unresolved` (#965). A
|
|
3305
|
+
* `pending` row is invisible to every cron arm (all require `status =
|
|
3306
|
+
* 'processing'`), so an indefinitely-`unresolved` row would be stranded with
|
|
3307
|
+
* nothing driving it. Once `now - since >= pausedMaxWaitMs`, `resolveRedrive`
|
|
3308
|
+
* takes `dispatch` instead of `unresolved` (reusing the existing knob — see
|
|
3309
|
+
* ADR-0047's own "unreachable ⇒ bounded" rule). Cleared on any other outcome.
|
|
3310
|
+
*/
|
|
3311
|
+
redriveUnresolvedSince = /* @__PURE__ */ new Map();
|
|
3312
|
+
/**
|
|
3313
|
+
* Consecutive-identical-poll-failure streak for the re-drive fence (#1348),
|
|
3314
|
+
* keyed by Evident **message id** (not session) so `clearRedriveUnresolved`
|
|
3315
|
+
* can drop it with the other two trackers and it cannot leak. `sessionId` is
|
|
3316
|
+
* carried inside the entry, not the key: a session change is a different
|
|
3317
|
+
* situation and resets the streak, which gives the `(sessionId, message.id)`
|
|
3318
|
+
* pairing #1348 asks for without a composite map key.
|
|
3319
|
+
*/
|
|
3320
|
+
redrivePollFailures = /* @__PURE__ */ new Map();
|
|
3321
|
+
/**
|
|
3322
|
+
* "Already emitted `redrive_outcome_unreported` for THIS (message, outcome)
|
|
3323
|
+
* streak" (Class B, #1340: the runner DECIDED reattach/settle/fail_permanent
|
|
3324
|
+
* but its own PATCH to record it failed — distinct from Class A's
|
|
3325
|
+
* `redrive_poll_failed`, where opencode itself can't be observed). Keyed by
|
|
3326
|
+
* message id, valued by the outcome currently failing to report, so a
|
|
3327
|
+
* change of outcome starts a fresh signal. Cleared by
|
|
3328
|
+
* `clearRedriveUnresolved` the instant either PATCH succeeds.
|
|
3329
|
+
*/
|
|
3330
|
+
redriveOutcomeUnreportedSignalled = /* @__PURE__ */ new Map();
|
|
3331
|
+
/**
|
|
3332
|
+
* First `now()` a Class B outcome PATCH (reattach/settle/fail_permanent) was
|
|
3333
|
+
* observed to fail for this message (#1366's failure-window trip arm,
|
|
3334
|
+
* `boundRedriveOutcome`). Duration, not a tick count — bounded by the
|
|
3335
|
+
* existing `pausedMaxWaitMs` window (reusing the knob, not a new constant).
|
|
3336
|
+
* Cleared by `clearRedriveUnresolved` the instant the original PATCH
|
|
3337
|
+
* succeeds.
|
|
3338
|
+
*/
|
|
3339
|
+
redriveOutcomeFailingSince = /* @__PURE__ */ new Map();
|
|
3340
|
+
/**
|
|
3341
|
+
* "Already posted `redrive_outcome_abandoned` with `reported: false` for this
|
|
3342
|
+
* row" (#1366) — the bound tripped but the terminal `markFailed` fallback ALSO
|
|
3343
|
+
* failed (the route-level fault of G2), so every following tick re-attempts
|
|
3344
|
+
* the same terminal PATCH. Guards that quiet retry from re-signalling on
|
|
3345
|
+
* every tick. Cleared by `clearRedriveUnresolved`.
|
|
3346
|
+
*/
|
|
3347
|
+
redriveOutcomeAbandonedSignalled = /* @__PURE__ */ new Set();
|
|
3348
|
+
/**
|
|
3349
|
+
* Consecutive-UNCONFIRMED-dispatch streak for a `pending` row with NO stored
|
|
3350
|
+
* `opencode_message_id` yet — i.e. one that has never even reached the
|
|
3351
|
+
* re-drive fence above. `sendPromptAsync`'s POST may 2xx, but its own
|
|
3352
|
+
* read-back retries can never confirm the assigned id when the session's
|
|
3353
|
+
* message list is PERMANENTLY unreadable (e.g. a corrupted local opencode
|
|
3354
|
+
* SQLite DB, #1345/#1348's exact fault, just hit BEFORE the row is ever
|
|
3355
|
+
* dispatched instead of after). Unlike an already-dispatched row, THIS row has
|
|
3356
|
+
* no other safety net at all: the lifecycle cron only reclaims `status =
|
|
3357
|
+
* 'processing'` rows, and a row stuck here never reaches `processing`. Keyed
|
|
3358
|
+
* by message id, carrying `sessionId` so a session change (a fresh one bound
|
|
3359
|
+
* after abandonment) starts a new streak rather than inheriting the old
|
|
3360
|
+
* session's count — same shape as `redrivePollFailures` above.
|
|
3361
|
+
*/
|
|
3362
|
+
unconfirmedDispatchFailures = /* @__PURE__ */ new Map();
|
|
2955
3363
|
/**
|
|
2956
3364
|
* "A null-id re-adopt re-dispatch is in flight, awaiting its read-back" (WI-5
|
|
2957
3365
|
* Task 5.4, High-2). Since we no longer send a caller-supplied id, a re-dispatch
|
|
@@ -3276,7 +3684,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3276
3684
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
3277
3685
|
*/
|
|
3278
3686
|
async processConversation(conv) {
|
|
3279
|
-
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
3687
|
+
const { sessionId, refusedSessionId, created: sessionCreated } = await this.ensureSession(conv);
|
|
3280
3688
|
const messages = await this.getPendingMessages(conv.id);
|
|
3281
3689
|
let dispatched = 0;
|
|
3282
3690
|
let skippedAlreadyDispatched = 0;
|
|
@@ -3291,6 +3699,15 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3291
3699
|
skippedAlreadyDispatched += 1;
|
|
3292
3700
|
continue;
|
|
3293
3701
|
}
|
|
3702
|
+
if (message.opencode_message_id) {
|
|
3703
|
+
const outcome = await this.resolveRedrive(conv, sessionId, message, sessionCreated);
|
|
3704
|
+
if (outcome === "abandoned") {
|
|
3705
|
+
continue;
|
|
3706
|
+
}
|
|
3707
|
+
if (outcome !== "dispatch") {
|
|
3708
|
+
break;
|
|
3709
|
+
}
|
|
3710
|
+
}
|
|
3294
3711
|
const options = {
|
|
3295
3712
|
agent: message.opencode_agent ?? void 0,
|
|
3296
3713
|
model: message.opencode_model ?? void 0
|
|
@@ -3357,28 +3774,476 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3357
3774
|
break;
|
|
3358
3775
|
}
|
|
3359
3776
|
if (opencodeMessageId === null) {
|
|
3777
|
+
const streak = this.recordUnconfirmedDispatch(message.id, sessionId);
|
|
3778
|
+
if (streak < MAX_IDENTICAL_REDRIVE_POLL_FAILURES) {
|
|
3779
|
+
this.log({
|
|
3780
|
+
level: "warn",
|
|
3781
|
+
message: `Message ${message.id.slice(0, 8)} dispatched but its opencode id could not be read back (${streak}/${MAX_IDENTICAL_REDRIVE_POLL_FAILURES}) \u2014 leaving un-tracked to retry next tick`,
|
|
3782
|
+
conversation_id: conv.id,
|
|
3783
|
+
message_id: message.id
|
|
3784
|
+
});
|
|
3785
|
+
continue;
|
|
3786
|
+
}
|
|
3787
|
+
this.unconfirmedDispatchFailures.delete(message.id);
|
|
3788
|
+
this.sessions.delete(conv.id);
|
|
3789
|
+
this.supersede(conv.id, sessionId);
|
|
3790
|
+
const errorMessage = `OpenCode accepted this message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
|
|
3360
3791
|
this.log({
|
|
3361
|
-
level: "
|
|
3362
|
-
message:
|
|
3792
|
+
level: "error",
|
|
3793
|
+
message: errorMessage,
|
|
3363
3794
|
conversation_id: conv.id,
|
|
3364
3795
|
message_id: message.id
|
|
3365
3796
|
});
|
|
3366
|
-
|
|
3797
|
+
await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
|
|
3798
|
+
this.log({
|
|
3799
|
+
level: "warn",
|
|
3800
|
+
message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
|
|
3801
|
+
conversation_id: conv.id,
|
|
3802
|
+
message_id: message.id
|
|
3803
|
+
});
|
|
3804
|
+
});
|
|
3805
|
+
break;
|
|
3367
3806
|
}
|
|
3807
|
+
this.unconfirmedDispatchFailures.delete(message.id);
|
|
3368
3808
|
this.dispatched.add(message.id);
|
|
3369
3809
|
this.registerInFlight(conv, sessionId, message, opencodeMessageId);
|
|
3370
3810
|
dispatched += 1;
|
|
3371
3811
|
void this.postSignal(conv.id, message.id, "dispatched");
|
|
3372
3812
|
}
|
|
3373
|
-
if (messages.length > 0 && dispatched === 0 && skippedAlreadyDispatched === messages.length) {
|
|
3813
|
+
if (messages.length > 0 && dispatched === 0 && skippedAlreadyDispatched === messages.length) {
|
|
3814
|
+
this.log({
|
|
3815
|
+
level: "warn",
|
|
3816
|
+
message: `Conversation ${conv.id.slice(0, 8)} has ${messages.length} pending message(s) but ALL are already marked dispatched locally (in-flight set: ${this.dispatched.size}) \u2014 none sent to OpenCode this tick. If this repeats, a message may be stuck acknowledged-but-never-dispatched (its watcher never settled).`,
|
|
3817
|
+
conversation_id: conv.id
|
|
3818
|
+
});
|
|
3819
|
+
}
|
|
3820
|
+
this.ensureWatcherRunning(sessionId);
|
|
3821
|
+
return dispatched;
|
|
3822
|
+
}
|
|
3823
|
+
/**
|
|
3824
|
+
* Poll a session's message list for the re-drive fence (#965), via the
|
|
3825
|
+
* INJECTED `fetchImpl` — NOT the imported `getSessionMessages` helper, which
|
|
3826
|
+
* hits the global `fetch` and would bypass the same override every other
|
|
3827
|
+
* opencode poll in this file respects. Mirrors `readoptProcessing`'s own
|
|
3828
|
+
* snapshot fetch (`:3081-3111`).
|
|
3829
|
+
*
|
|
3830
|
+
* Returns `{ ok: true, messages }` on a readable snapshot, or
|
|
3831
|
+
* `{ ok: false, signature }` on failure — `signature` is a string that
|
|
3832
|
+
* repeats across attempts for the SAME underlying fault (used by the
|
|
3833
|
+
* consecutive-identical-failure bound, #1348), or `null` for a thrown
|
|
3834
|
+
* exception, which is NOT countable toward that bound (a network blip / an
|
|
3835
|
+
* opencode restart also throws identically every tick, and must keep
|
|
3836
|
+
* retrying unbounded rather than ever being treated as permanent).
|
|
3837
|
+
*/
|
|
3838
|
+
async pollSessionMessagesForRedrive(conv, message, sessionId) {
|
|
3839
|
+
try {
|
|
3840
|
+
const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
|
|
3841
|
+
if (!res.ok) {
|
|
3842
|
+
const rawBody = await res.text();
|
|
3843
|
+
const normalized = normalizeRedrivePollFailureBody(rawBody);
|
|
3844
|
+
this.log({
|
|
3845
|
+
level: "warn",
|
|
3846
|
+
message: `Re-drive: polling session ${sessionId.slice(0, 8)} for message ${message.id.slice(0, 8)} returned HTTP ${res.status}${normalized ? `: ${normalized}` : ""} \u2014 treating as unreadable this tick`,
|
|
3847
|
+
conversation_id: conv.id,
|
|
3848
|
+
message_id: message.id
|
|
3849
|
+
});
|
|
3850
|
+
return { ok: false, signature: `HTTP ${res.status}${normalized ? `: ${normalized}` : ""}` };
|
|
3851
|
+
}
|
|
3852
|
+
const body = await res.json();
|
|
3853
|
+
if (!Array.isArray(body)) {
|
|
3854
|
+
this.log({
|
|
3855
|
+
level: "warn",
|
|
3856
|
+
message: `Re-drive: polling session ${sessionId.slice(0, 8)} for message ${message.id.slice(0, 8)} returned a non-array message body \u2014 treating as unreadable this tick`,
|
|
3857
|
+
conversation_id: conv.id,
|
|
3858
|
+
message_id: message.id
|
|
3859
|
+
});
|
|
3860
|
+
return { ok: false, signature: "non-array message body" };
|
|
3861
|
+
}
|
|
3862
|
+
return { ok: true, messages: body };
|
|
3863
|
+
} catch (err) {
|
|
3864
|
+
this.log({
|
|
3865
|
+
level: "warn",
|
|
3866
|
+
message: `Re-drive: failed to poll session ${sessionId.slice(0, 8)} for message ${message.id.slice(0, 8)} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
|
|
3867
|
+
conversation_id: conv.id,
|
|
3868
|
+
message_id: message.id
|
|
3869
|
+
});
|
|
3870
|
+
return { ok: false, signature: null };
|
|
3871
|
+
}
|
|
3872
|
+
}
|
|
3873
|
+
/**
|
|
3874
|
+
* The re-drive fence for a `pending` row that already carries a stored
|
|
3875
|
+
* `opencode_message_id` (#965) — i.e. it has already been handed to opencode at
|
|
3876
|
+
* least once (see the invariant at `QueuedMessage.opencode_message_id`'s doc).
|
|
3877
|
+
* The lifecycle cron can falsely reclaim a `processing` row back to `pending`
|
|
3878
|
+
* mid-turn (a 5-minute liveness-staleness check racing a still-running turn);
|
|
3879
|
+
* without this fence the drain loop would re-`prompt_async` the SAME turn a
|
|
3880
|
+
* second time against live GitHub state. Mirrors `readoptOne`'s job for the
|
|
3881
|
+
* `processing` re-adopt path, but simpler: no b1/b2 preamble cross-check is
|
|
3882
|
+
* needed here because `sessionCreated` already handles the cases (a #553
|
|
3883
|
+
* abandoned session, a #190 vanished one) that path exists for.
|
|
3884
|
+
*
|
|
3885
|
+
* Only `ChannelAuthError` propagates. A poll that fails identically
|
|
3886
|
+
* `MAX_IDENTICAL_REDRIVE_POLL_FAILURES` times in a row reports the message
|
|
3887
|
+
* failed instead of retrying it (#1348) — SEPARATE from, not a replacement
|
|
3888
|
+
* for, `resolveRedriveUnresolved`'s own `pausedMaxWaitMs` bound below. Every
|
|
3889
|
+
* other failure resolves to `unresolved` and is retried whole on the next
|
|
3890
|
+
* ~2s drain tick.
|
|
3891
|
+
*/
|
|
3892
|
+
async resolveRedrive(conv, sessionId, message, sessionCreated) {
|
|
3893
|
+
const ocId = message.opencode_message_id ?? null;
|
|
3894
|
+
if (sessionCreated) {
|
|
3895
|
+
this.clearRedriveUnresolved(message.id);
|
|
3896
|
+
void this.postSignal(conv.id, message.id, "redrive_redispatched");
|
|
3897
|
+
return "dispatch";
|
|
3898
|
+
}
|
|
3899
|
+
const polled = await this.pollSessionMessagesForRedrive(conv, message, sessionId);
|
|
3900
|
+
if (!polled.ok) {
|
|
3901
|
+
const streak = this.recordRedrivePollFailure(message.id, sessionId, polled.signature);
|
|
3902
|
+
if (streak >= MAX_IDENTICAL_REDRIVE_POLL_FAILURES && polled.signature !== null) {
|
|
3903
|
+
return this.failRedrivePollPermanent(conv, sessionId, message, polled.signature, streak);
|
|
3904
|
+
}
|
|
3905
|
+
return this.resolveRedriveUnresolved(conv, message);
|
|
3906
|
+
}
|
|
3907
|
+
this.redrivePollFailures.delete(message.id);
|
|
3908
|
+
const messages = polled.messages;
|
|
3909
|
+
if (messages.length === 0) {
|
|
3910
|
+
return this.resolveRedriveUnresolved(conv, message);
|
|
3911
|
+
}
|
|
3912
|
+
const state = messageRunState(messages, ocId ?? "");
|
|
3913
|
+
if (state === "failed" && isAbortedTerminalReply(messages, ocId ?? "")) {
|
|
3914
|
+
const ongoing = await isSessionOngoing(this.port, sessionId);
|
|
3915
|
+
if (ongoing === false) {
|
|
3916
|
+
this.log({
|
|
3917
|
+
level: "info",
|
|
3918
|
+
message: `Re-drive: message ${message.id.slice(0, 8)} carries an abort-shaped terminal error and session ${sessionId.slice(0, 8)} is not-ongoing per GET /session/status \u2014 restart orphan, re-dispatching instead of marking it permanently failed`,
|
|
3919
|
+
conversation_id: conv.id,
|
|
3920
|
+
message_id: message.id
|
|
3921
|
+
});
|
|
3922
|
+
this.clearRedriveUnresolved(message.id);
|
|
3923
|
+
void this.postSignal(conv.id, message.id, "redrive_redispatched");
|
|
3924
|
+
return "dispatch";
|
|
3925
|
+
}
|
|
3926
|
+
}
|
|
3927
|
+
if (state === "done" || state === "failed") {
|
|
3928
|
+
return this.settleRedrive(conv, sessionId, message, ocId, messages, state);
|
|
3929
|
+
}
|
|
3930
|
+
if (state === "running" || state === "queued") {
|
|
3931
|
+
const ongoing = await isSessionOngoing(this.port, sessionId);
|
|
3932
|
+
if (ongoing === true) {
|
|
3933
|
+
return this.reattachRedrive(conv, sessionId, message, ocId);
|
|
3934
|
+
}
|
|
3935
|
+
if (ongoing === false) {
|
|
3936
|
+
this.clearRedriveUnresolved(message.id);
|
|
3937
|
+
void this.postSignal(conv.id, message.id, "redrive_redispatched");
|
|
3938
|
+
return "dispatch";
|
|
3939
|
+
}
|
|
3940
|
+
return this.resolveRedriveUnresolved(conv, message);
|
|
3941
|
+
}
|
|
3942
|
+
this.clearRedriveUnresolved(message.id);
|
|
3943
|
+
void this.postSignal(conv.id, message.id, "redrive_redispatched");
|
|
3944
|
+
return "dispatch";
|
|
3945
|
+
}
|
|
3946
|
+
/**
|
|
3947
|
+
* The `reattached` outcome (Task 3.3): the prior turn is STILL ONGOING per
|
|
3948
|
+
* opencode's own status map — undo the false reclaim instead of starting a
|
|
3949
|
+
* second turn.
|
|
3950
|
+
*/
|
|
3951
|
+
async reattachRedrive(conv, sessionId, message, ocId) {
|
|
3952
|
+
let anchorMs;
|
|
3953
|
+
const parsed = message.processing_started_at ? Date.parse(message.processing_started_at) : NaN;
|
|
3954
|
+
if (!Number.isNaN(parsed)) {
|
|
3955
|
+
anchorMs = parsed;
|
|
3956
|
+
} else {
|
|
3957
|
+
anchorMs = this.now();
|
|
3958
|
+
this.log({
|
|
3959
|
+
level: "error",
|
|
3960
|
+
message: `Re-drive: message ${message.id.slice(0, 8)} has null/unparseable processing_started_at (${String(message.processing_started_at)}) \u2014 anchoring the watcher's absolute-age ceiling to now (defensive)`,
|
|
3961
|
+
conversation_id: conv.id,
|
|
3962
|
+
message_id: message.id
|
|
3963
|
+
});
|
|
3964
|
+
}
|
|
3965
|
+
const title = await this.resolveSessionTitle(sessionId, conv.id);
|
|
3966
|
+
try {
|
|
3967
|
+
await this.markProcessing(conv.id, message.id, sessionId, ocId, title);
|
|
3968
|
+
} catch (err) {
|
|
3969
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
3970
|
+
this.log({
|
|
3971
|
+
level: "warn",
|
|
3972
|
+
message: `Re-drive: failed to restore message ${message.id.slice(0, 8)} to processing (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
|
|
3973
|
+
conversation_id: conv.id,
|
|
3974
|
+
message_id: message.id
|
|
3975
|
+
});
|
|
3976
|
+
const bound = await this.boundRedriveOutcome(conv, message, "reattach");
|
|
3977
|
+
return bound === "abandoned" ? "abandoned" : "unresolved";
|
|
3978
|
+
}
|
|
3979
|
+
this.clearRedriveUnresolved(message.id);
|
|
3980
|
+
this.registerReadopted(conv, sessionId, message, ocId ?? "", anchorMs);
|
|
3981
|
+
this.dispatched.add(message.id);
|
|
3982
|
+
this.readopted.add(message.id);
|
|
3983
|
+
this.ensureWatcherRunning(sessionId);
|
|
3984
|
+
const watchedForMs = this.now() - anchorMs;
|
|
3985
|
+
void this.postSignal(conv.id, message.id, "redrive_reattached", {
|
|
3986
|
+
watched_for_ms: watchedForMs
|
|
3987
|
+
});
|
|
3988
|
+
this.log({
|
|
3989
|
+
level: "warn",
|
|
3990
|
+
message: `Re-drive: message ${message.id.slice(0, 8)} (session ${sessionId.slice(0, 8)}) was wrongly reclaimed to pending while its turn was still running (watched ${watchedForMs}ms) \u2014 restored to processing instead of re-dispatching`,
|
|
3991
|
+
conversation_id: conv.id,
|
|
3992
|
+
message_id: message.id
|
|
3993
|
+
});
|
|
3994
|
+
return "reattached";
|
|
3995
|
+
}
|
|
3996
|
+
/**
|
|
3997
|
+
* The `settled` outcome (Task 3.2): the prior turn already finished (or
|
|
3998
|
+
* errored) while nobody was watching — deliver/report it instead of re-running.
|
|
3999
|
+
* Mirrors `readoptOne`'s `done`/`failed` branches' error discipline, simplified
|
|
4000
|
+
* (no `doneUndeliverable` park: a terminal PATCH failure here just retries next
|
|
4001
|
+
* drain, same as any other non-auth failure). The restart-abort carve-out that
|
|
4002
|
+
* keeps the two in step for `failed` lives in the caller (`resolveRedrive`, #1310),
|
|
4003
|
+
* so a row reaching this `failed` branch is a GENUINE failure.
|
|
4004
|
+
*/
|
|
4005
|
+
async settleRedrive(conv, sessionId, message, ocId, messages, state) {
|
|
4006
|
+
try {
|
|
4007
|
+
if (state === "done") {
|
|
4008
|
+
const title = await this.resolveSessionTitle(sessionId, conv.id);
|
|
4009
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
4010
|
+
this.log({
|
|
4011
|
+
level: "info",
|
|
4012
|
+
message: `Re-drive: message ${message.id.slice(0, 8)} completed while its row was wrongly reclaimed to pending \u2014 marking done instead of re-dispatching`,
|
|
4013
|
+
conversation_id: conv.id,
|
|
4014
|
+
message_id: message.id
|
|
4015
|
+
});
|
|
4016
|
+
await this.markDone(conv.id, message.id, sessionId, ocId, title, usage);
|
|
4017
|
+
} else {
|
|
4018
|
+
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
4019
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
4020
|
+
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
4021
|
+
this.log({
|
|
4022
|
+
level: "error",
|
|
4023
|
+
message: `Re-drive: message ${message.id.slice(0, 8)} errored while its row was wrongly reclaimed to pending \u2014 marking failed instead of re-dispatching: ${error2 ?? "(no error text)"}`,
|
|
4024
|
+
conversation_id: conv.id,
|
|
4025
|
+
message_id: message.id
|
|
4026
|
+
});
|
|
4027
|
+
await this.markFailed(conv.id, message.id, sessionId, error2, usage, failure);
|
|
4028
|
+
}
|
|
4029
|
+
} catch (err) {
|
|
4030
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
4031
|
+
this.log({
|
|
4032
|
+
level: "warn",
|
|
4033
|
+
message: `Re-drive: failed to report message ${message.id.slice(0, 8)} ${state} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
|
|
4034
|
+
conversation_id: conv.id,
|
|
4035
|
+
message_id: message.id
|
|
4036
|
+
});
|
|
4037
|
+
const bound = await this.boundRedriveOutcome(conv, message, "settle");
|
|
4038
|
+
return bound === "abandoned" ? "abandoned" : "unresolved";
|
|
4039
|
+
}
|
|
4040
|
+
this.clearRedriveUnresolved(message.id);
|
|
4041
|
+
void this.postSignal(conv.id, message.id, "redrive_settled");
|
|
4042
|
+
return "settled";
|
|
4043
|
+
}
|
|
4044
|
+
/**
|
|
4045
|
+
* The permanent-failure outcome (#1348): the fence's own poll of this session
|
|
4046
|
+
* failed with the SAME opencode-answered signature
|
|
4047
|
+
* `MAX_IDENTICAL_REDRIVE_POLL_FAILURES` times in a row — a transient blip
|
|
4048
|
+
* would have varied or eventually cleared (see `pollSessionMessagesForRedrive`
|
|
4049
|
+
* and `recordRedrivePollFailure`), so this is a durable fault (e.g. #1345's
|
|
4050
|
+
* corrupted opencode session) rather than something worth retrying forever.
|
|
4051
|
+
* Mirrors `settleRedrive`'s error discipline: no `usage`/`failure` args to
|
|
4052
|
+
* `markFailed` (no opencode snapshot to extract them from — this poll never
|
|
4053
|
+
* got a readable one).
|
|
4054
|
+
*/
|
|
4055
|
+
async failRedrivePollPermanent(conv, sessionId, message, signature, streak) {
|
|
4056
|
+
this.log({
|
|
4057
|
+
level: "error",
|
|
4058
|
+
message: `Re-drive: message ${message.id.slice(0, 8)} (session ${sessionId.slice(0, 8)}) failed to poll with the identical signature "${signature}" ${streak} times in a row \u2014 reporting the message failed instead of retrying forever`,
|
|
4059
|
+
conversation_id: conv.id,
|
|
4060
|
+
message_id: message.id
|
|
4061
|
+
});
|
|
4062
|
+
try {
|
|
4063
|
+
await this.markFailed(
|
|
4064
|
+
conv.id,
|
|
4065
|
+
message.id,
|
|
4066
|
+
sessionId,
|
|
4067
|
+
`The runner could not read this conversation's state from OpenCode (${signature}). The same failure repeated ${streak} times in a row, so the message was not retried further.`
|
|
4068
|
+
);
|
|
4069
|
+
} catch (err) {
|
|
4070
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
4071
|
+
this.log({
|
|
4072
|
+
level: "warn",
|
|
4073
|
+
message: `Re-drive: failed to report message ${message.id.slice(0, 8)} permanently failed (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
|
|
4074
|
+
conversation_id: conv.id,
|
|
4075
|
+
message_id: message.id
|
|
4076
|
+
});
|
|
4077
|
+
const bound = await this.boundRedriveOutcome(conv, message, "fail_permanent");
|
|
4078
|
+
return bound === "abandoned" ? "abandoned" : "unresolved";
|
|
4079
|
+
}
|
|
4080
|
+
this.clearRedriveUnresolved(message.id);
|
|
4081
|
+
void this.postSignal(conv.id, message.id, "redrive_poll_failed");
|
|
4082
|
+
return "settled";
|
|
4083
|
+
}
|
|
4084
|
+
/**
|
|
4085
|
+
* The bounded `unresolved` outcome (Task 3.4): opencode's state could not be
|
|
4086
|
+
* observed (snapshot unreadable/empty, or `isSessionOngoing` returned `null`).
|
|
4087
|
+
* A `pending` row is swept by the server's own `PENDING_MAX_AGE_MS` (24h,
|
|
4088
|
+
* #1368) cron arm, but that is a day-scale backstop — this local bound acts
|
|
4089
|
+
* in minutes so the row (and the conversation it starves, per the ordering
|
|
4090
|
+
* invariant below) isn't left stranded for that long. Bound to the existing
|
|
4091
|
+
* `pausedMaxWaitMs` window (reusing the knob, not a new constant); takes
|
|
4092
|
+
* `dispatch` once elapsed.
|
|
4093
|
+
*/
|
|
4094
|
+
resolveRedriveUnresolved(conv, message) {
|
|
4095
|
+
const now = this.now();
|
|
4096
|
+
const since = this.redriveUnresolvedSince.get(message.id);
|
|
4097
|
+
if (since !== void 0 && now - since >= this.pausedMaxWaitMs) {
|
|
4098
|
+
this.clearRedriveUnresolved(message.id);
|
|
4099
|
+
void this.postSignal(conv.id, message.id, "redrive_redispatched");
|
|
4100
|
+
return "dispatch";
|
|
4101
|
+
}
|
|
4102
|
+
if (since === void 0) {
|
|
4103
|
+
this.redriveUnresolvedSince.set(message.id, now);
|
|
4104
|
+
}
|
|
4105
|
+
if (!this.redriveUnresolvedSignalled.has(message.id)) {
|
|
4106
|
+
this.redriveUnresolvedSignalled.add(message.id);
|
|
4107
|
+
void this.postSignal(conv.id, message.id, "redrive_unresolved");
|
|
4108
|
+
}
|
|
4109
|
+
return "unresolved";
|
|
4110
|
+
}
|
|
4111
|
+
/** Clear all `unresolved`/failure-streak trackers for a row (any non-`unresolved` outcome). */
|
|
4112
|
+
clearRedriveUnresolved(messageId) {
|
|
4113
|
+
this.redriveUnresolvedSince.delete(messageId);
|
|
4114
|
+
this.redriveUnresolvedSignalled.delete(messageId);
|
|
4115
|
+
this.redrivePollFailures.delete(messageId);
|
|
4116
|
+
this.redriveOutcomeUnreportedSignalled.delete(messageId);
|
|
4117
|
+
this.redriveOutcomeFailingSince.delete(messageId);
|
|
4118
|
+
this.redriveOutcomeAbandonedSignalled.delete(messageId);
|
|
4119
|
+
}
|
|
4120
|
+
/**
|
|
4121
|
+
* Class B (#1340): the runner DECIDED an outcome (reattach/settle/fail_permanent)
|
|
4122
|
+
* but its own PATCH to record it failed. Fires at most once per (message,
|
|
4123
|
+
* outcome) streak, and only while `boundRedriveOutcome` has not yet tripped —
|
|
4124
|
+
* once it trips, `redrive_outcome_abandoned` takes over reporting for the row
|
|
4125
|
+
* (#1366).
|
|
4126
|
+
*/
|
|
4127
|
+
signalRedriveOutcomeUnreported(conv, message, outcome) {
|
|
4128
|
+
if (this.redriveOutcomeUnreportedSignalled.get(message.id) === outcome) return;
|
|
4129
|
+
this.redriveOutcomeUnreportedSignalled.set(message.id, outcome);
|
|
4130
|
+
void this.postSignal(conv.id, message.id, "redrive_outcome_unreported", {
|
|
4131
|
+
attempted_outcome: outcome
|
|
4132
|
+
});
|
|
4133
|
+
}
|
|
4134
|
+
/**
|
|
4135
|
+
* The runner-authored, honest error text for the terminal fallback a tripped
|
|
4136
|
+
* `boundRedriveOutcome` sends. Distinguishable per outcome and truthful about
|
|
4137
|
+
* what actually happened — the `settle`/done case must say the turn finished
|
|
4138
|
+
* but its result could not be recorded, never that the runner stopped
|
|
4139
|
+
* responding (that would be a lie for this shape, see #1366's "why this ships").
|
|
4140
|
+
*/
|
|
4141
|
+
static REDRIVE_ABANDON_ERROR = {
|
|
4142
|
+
reattach: "your runner could not record that this message had started, so it was given up on",
|
|
4143
|
+
settle: "your runner finished this message but could not record the result, so the reply could not be delivered",
|
|
4144
|
+
fail_permanent: "the runner could not read this conversation's state from OpenCode, and could not record that failure either, so the message was given up on"
|
|
4145
|
+
};
|
|
4146
|
+
/**
|
|
4147
|
+
* Bound for Class B (#1340, #1366): the runner DECIDED an outcome but its own
|
|
4148
|
+
* PATCH to record it failed. Two independent trip arms (either sufficient):
|
|
4149
|
+
* (1) this failure streak has lasted `pausedMaxWaitMs` — DURATION, not a tick
|
|
4150
|
+
* count, reusing the knob `resolveRedriveUnresolved` already established; (2)
|
|
4151
|
+
* the turn's `processing_started_at` age has crossed
|
|
4152
|
+
* `ABSOLUTE_MAX_PROCESSING_MS` — durable and restart-surviving, since arm (1)'s
|
|
4153
|
+
* in-memory streak resets on a scale-to-zero restart.
|
|
4154
|
+
*
|
|
4155
|
+
* INVARIANT — a tripped bound never suppresses the original outcome attempt;
|
|
4156
|
+
* it only adds a fallback after that attempt has failed again. This is only
|
|
4157
|
+
* ever reached from inside the catch of the ORIGINAL outcome PATCH, which is
|
|
4158
|
+
* attempted first on every tick whether or not this bound tripped before —
|
|
4159
|
+
* there is no give-up latch that would short-circuit it. That is what lets a
|
|
4160
|
+
* route-level fault that heals later still deliver the turn's real
|
|
4161
|
+
* `done`/`failed` payload: once the original PATCH succeeds again, this
|
|
4162
|
+
* helper is never entered and the row settles with its real result.
|
|
4163
|
+
*/
|
|
4164
|
+
async boundRedriveOutcome(conv, message, outcome) {
|
|
4165
|
+
const now = this.now();
|
|
4166
|
+
const since = this.redriveOutcomeFailingSince.get(message.id);
|
|
4167
|
+
if (since === void 0) this.redriveOutcomeFailingSince.set(message.id, now);
|
|
4168
|
+
const durationTripped = now - (since ?? now) >= this.pausedMaxWaitMs;
|
|
4169
|
+
const parsed = message.processing_started_at ? Date.parse(message.processing_started_at) : NaN;
|
|
4170
|
+
const absoluteAgeTripped = !Number.isNaN(parsed) && now - parsed >= ABSOLUTE_MAX_PROCESSING_MS;
|
|
4171
|
+
if (!durationTripped && !absoluteAgeTripped) {
|
|
4172
|
+
this.signalRedriveOutcomeUnreported(conv, message, outcome);
|
|
4173
|
+
return "retry";
|
|
4174
|
+
}
|
|
4175
|
+
const arm = durationTripped ? "failure_window" : "absolute_age";
|
|
4176
|
+
try {
|
|
4177
|
+
await this.markFailed(
|
|
4178
|
+
conv.id,
|
|
4179
|
+
message.id,
|
|
4180
|
+
void 0,
|
|
4181
|
+
_ChannelDriver.REDRIVE_ABANDON_ERROR[outcome]
|
|
4182
|
+
);
|
|
4183
|
+
} catch (err) {
|
|
4184
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
3374
4185
|
this.log({
|
|
3375
4186
|
level: "warn",
|
|
3376
|
-
message: `
|
|
3377
|
-
conversation_id: conv.id
|
|
4187
|
+
message: `Re-drive bound: fallback markFailed for message ${message.id.slice(0, 8)} also failed (arm ${arm}, will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
|
|
4188
|
+
conversation_id: conv.id,
|
|
4189
|
+
message_id: message.id
|
|
3378
4190
|
});
|
|
4191
|
+
if (!this.redriveOutcomeAbandonedSignalled.has(message.id)) {
|
|
4192
|
+
this.redriveOutcomeAbandonedSignalled.add(message.id);
|
|
4193
|
+
void this.postSignal(conv.id, message.id, "redrive_outcome_abandoned", {
|
|
4194
|
+
attempted_outcome: outcome,
|
|
4195
|
+
reported: false,
|
|
4196
|
+
arm
|
|
4197
|
+
});
|
|
4198
|
+
}
|
|
4199
|
+
return "retry";
|
|
3379
4200
|
}
|
|
3380
|
-
this.
|
|
3381
|
-
|
|
4201
|
+
this.clearRedriveUnresolved(message.id);
|
|
4202
|
+
void this.postSignal(conv.id, message.id, "redrive_outcome_abandoned", {
|
|
4203
|
+
attempted_outcome: outcome,
|
|
4204
|
+
reported: true,
|
|
4205
|
+
arm
|
|
4206
|
+
});
|
|
4207
|
+
return "abandoned";
|
|
4208
|
+
}
|
|
4209
|
+
/**
|
|
4210
|
+
* Record one poll outcome toward the re-drive fence's consecutive-identical-
|
|
4211
|
+
* failure streak (#1348) and return the resulting count. `signature === null`
|
|
4212
|
+
* (a thrown exception, H1) always clears the streak and returns `0` — it is
|
|
4213
|
+
* never countable. Otherwise the streak continues only when BOTH the session
|
|
4214
|
+
* and the signature match the previous failure; anything else (a different
|
|
4215
|
+
* session, or the same session failing a DIFFERENT way) starts a fresh streak
|
|
4216
|
+
* at `1`.
|
|
4217
|
+
*/
|
|
4218
|
+
recordRedrivePollFailure(messageId, sessionId, signature) {
|
|
4219
|
+
if (signature === null) {
|
|
4220
|
+
this.redrivePollFailures.delete(messageId);
|
|
4221
|
+
return 0;
|
|
4222
|
+
}
|
|
4223
|
+
const existing = this.redrivePollFailures.get(messageId);
|
|
4224
|
+
if (existing && existing.sessionId === sessionId && existing.signature === signature) {
|
|
4225
|
+
existing.count += 1;
|
|
4226
|
+
return existing.count;
|
|
4227
|
+
}
|
|
4228
|
+
this.redrivePollFailures.set(messageId, { sessionId, signature, count: 1 });
|
|
4229
|
+
return 1;
|
|
4230
|
+
}
|
|
4231
|
+
/**
|
|
4232
|
+
* Record one UNCONFIRMED-dispatch outcome (a `pending` row with no stored
|
|
4233
|
+
* `opencode_message_id` whose `sendPromptAsync` returned `null`) toward the
|
|
4234
|
+
* bound in `processConversation`'s dispatch loop, and return the resulting
|
|
4235
|
+
* count. Mirrors `recordRedrivePollFailure`'s session-scoping: a session
|
|
4236
|
+
* change starts a fresh streak at `1` rather than inheriting the old one's
|
|
4237
|
+
* count, since a new session is a genuinely different attempt.
|
|
4238
|
+
*/
|
|
4239
|
+
recordUnconfirmedDispatch(messageId, sessionId) {
|
|
4240
|
+
const existing = this.unconfirmedDispatchFailures.get(messageId);
|
|
4241
|
+
if (existing && existing.sessionId === sessionId) {
|
|
4242
|
+
existing.count += 1;
|
|
4243
|
+
return existing.count;
|
|
4244
|
+
}
|
|
4245
|
+
this.unconfirmedDispatchFailures.set(messageId, { sessionId, count: 1 });
|
|
4246
|
+
return 1;
|
|
3382
4247
|
}
|
|
3383
4248
|
/**
|
|
3384
4249
|
* Record that `sessionId` is no longer a valid binding for `conversationId`
|
|
@@ -3404,6 +4269,13 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3404
4269
|
* `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
|
|
3405
4270
|
* binding was an id this runner had abandoned, so a resurrection genuinely
|
|
3406
4271
|
* happened and a fresh session was bound instead. The caller reports it.
|
|
4272
|
+
*
|
|
4273
|
+
* `created` says the returned session was made JUST NOW, so it provably holds
|
|
4274
|
+
* no prior turn. The re-drive fence needs that as CONTRARY evidence ("nothing
|
|
4275
|
+
* to reconcile against") — distinct from the ambiguous "I polled and saw an
|
|
4276
|
+
* empty transcript", which stays a deferral. Keep it separate from
|
|
4277
|
+
* `refusedSessionId`: only the latter means a #553 resurrection happened, and
|
|
4278
|
+
* only it may drive the `session_superseded` signal.
|
|
3407
4279
|
*/
|
|
3408
4280
|
async ensureSession(conv) {
|
|
3409
4281
|
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
@@ -3414,7 +4286,11 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3414
4286
|
conversation_id: conv.id
|
|
3415
4287
|
});
|
|
3416
4288
|
this.sessions.delete(conv.id);
|
|
3417
|
-
return {
|
|
4289
|
+
return {
|
|
4290
|
+
sessionId: await this.createAndBindSession(conv.id),
|
|
4291
|
+
refusedSessionId: bound,
|
|
4292
|
+
created: true
|
|
4293
|
+
};
|
|
3418
4294
|
}
|
|
3419
4295
|
if (bound) {
|
|
3420
4296
|
const exists = await sessionExists(this.port, bound);
|
|
@@ -3425,12 +4301,12 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3425
4301
|
conversation_id: conv.id
|
|
3426
4302
|
});
|
|
3427
4303
|
this.sessions.delete(conv.id);
|
|
3428
|
-
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
4304
|
+
return { sessionId: await this.createAndBindSession(conv.id), created: true };
|
|
3429
4305
|
}
|
|
3430
4306
|
this.sessions.set(conv.id, bound);
|
|
3431
|
-
return { sessionId: bound };
|
|
4307
|
+
return { sessionId: bound, created: false };
|
|
3432
4308
|
}
|
|
3433
|
-
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
4309
|
+
return { sessionId: await this.createAndBindSession(conv.id), created: true };
|
|
3434
4310
|
}
|
|
3435
4311
|
/**
|
|
3436
4312
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -3663,9 +4539,10 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
3663
4539
|
* opencode reports ACTIVELY `running` is watched to completion (its liveness
|
|
3664
4540
|
* heartbeat keeps the cron off its row), while a re-adopted turn that is paused
|
|
3665
4541
|
* awaiting a human — or queued/unreachable — is still bounded by `deadline` and
|
|
3666
|
-
* handed to the cron.
|
|
3667
|
-
*
|
|
3668
|
-
*
|
|
4542
|
+
* handed to the cron. Real invariant (#965): the cron MAY reclaim a row this
|
|
4543
|
+
* runner still holds; a reclaimed row that already ran is never re-dispatched
|
|
4544
|
+
* while opencode reports its turn ongoing (readopt's own gate here, and the
|
|
4545
|
+
* `pending`-row re-drive fence, `resolveRedrive`). `dispatchedAt` stays `now`
|
|
3669
4546
|
* (only the appear-guard uses it).
|
|
3670
4547
|
*
|
|
3671
4548
|
* `evidentMessageId` addresses the SERVER row (for markProcessing/markDone);
|
|
@@ -4225,7 +5102,10 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4225
5102
|
* re-dispatched (at most once, see `forceReadoptRun`):
|
|
4226
5103
|
* - `done` → `markDone` now (guarded like the watcher's done branch);
|
|
4227
5104
|
* - `failed` → `markFailed` with the surfaced error (issue #182), so an
|
|
4228
|
-
* errored turn is reported failed on restart, NOT re-dispatched
|
|
5105
|
+
* errored turn is reported failed on restart, NOT re-dispatched —
|
|
5106
|
+
* EXCEPT a restart-ABORTED turn under a not-ongoing session,
|
|
5107
|
+
* which is a restart orphan wearing a terminal error and is
|
|
5108
|
+
* re-dispatched instead (issue #1310, see the branch below);
|
|
4229
5109
|
* - `running`/`queued` → re-attach a watcher via `registerReadopted` (no re-dispatch),
|
|
4230
5110
|
* tracking the stored id so the reply correlates by it;
|
|
4231
5111
|
* - `unknown`/null id → re-dispatch (opencode assigns a fresh id) + attach a watcher.
|
|
@@ -4289,7 +5169,16 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4289
5169
|
void this.postSignal(row.conversation_id, row.id, "readopt_done");
|
|
4290
5170
|
return;
|
|
4291
5171
|
}
|
|
4292
|
-
|
|
5172
|
+
const restartAborted = state === "failed" && sessionOngoing === false && isAbortedTerminalReply(messages, ocId ?? "");
|
|
5173
|
+
if (restartAborted) {
|
|
5174
|
+
this.log({
|
|
5175
|
+
level: "info",
|
|
5176
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} carries an abort-shaped terminal error and session ${sessionId.slice(0, 8)} is not-ongoing per GET /session/status \u2014 restart orphan, re-dispatching instead of marking it permanently failed`,
|
|
5177
|
+
conversation_id: row.conversation_id,
|
|
5178
|
+
message_id: row.id
|
|
5179
|
+
});
|
|
5180
|
+
}
|
|
5181
|
+
if (state === "failed" && !restartAborted) {
|
|
4293
5182
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
4294
5183
|
const usage = messageUsage(messages, ocId ?? "");
|
|
4295
5184
|
const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
|
|
@@ -4503,15 +5392,39 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4503
5392
|
}
|
|
4504
5393
|
if (ocId === null) {
|
|
4505
5394
|
this.awaitingReadopt.delete(row.id);
|
|
5395
|
+
const streak = this.recordUnconfirmedDispatch(row.id, sessionId);
|
|
5396
|
+
if (streak >= MAX_IDENTICAL_REDRIVE_POLL_FAILURES) {
|
|
5397
|
+
this.unconfirmedDispatchFailures.delete(row.id);
|
|
5398
|
+
this.sessions.delete(readoptConv.id);
|
|
5399
|
+
this.supersede(readoptConv.id, sessionId);
|
|
5400
|
+
const errorMessage = `OpenCode accepted this re-dispatched message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
|
|
5401
|
+
this.log({
|
|
5402
|
+
level: "error",
|
|
5403
|
+
message: errorMessage,
|
|
5404
|
+
conversation_id: row.conversation_id,
|
|
5405
|
+
message_id: row.id
|
|
5406
|
+
});
|
|
5407
|
+
await this.markFailed(row.conversation_id, row.id, null, errorMessage).catch((markErr) => {
|
|
5408
|
+
this.log({
|
|
5409
|
+
level: "warn",
|
|
5410
|
+
message: `markFailed PATCH for message ${row.id.slice(0, 8)} (conversation ${row.conversation_id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
|
|
5411
|
+
conversation_id: row.conversation_id,
|
|
5412
|
+
message_id: row.id
|
|
5413
|
+
});
|
|
5414
|
+
});
|
|
5415
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
|
|
5416
|
+
return;
|
|
5417
|
+
}
|
|
4506
5418
|
this.log({
|
|
4507
5419
|
level: "warn",
|
|
4508
|
-
message: `Re-adopt: message ${row.id.slice(0, 8)} re-dispatched but its opencode id could not be read back \u2014 leaving un-tracked to retry next drain`,
|
|
5420
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} re-dispatched but its opencode id could not be read back (${streak}/${MAX_IDENTICAL_REDRIVE_POLL_FAILURES}) \u2014 leaving un-tracked to retry next drain`,
|
|
4509
5421
|
conversation_id: row.conversation_id,
|
|
4510
5422
|
message_id: row.id
|
|
4511
5423
|
});
|
|
4512
5424
|
void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
|
|
4513
5425
|
return;
|
|
4514
5426
|
}
|
|
5427
|
+
this.unconfirmedDispatchFailures.delete(row.id);
|
|
4515
5428
|
this.registerReadopted(readoptConv, sessionId, readoptMessage, ocId, this.processedAtMs(row));
|
|
4516
5429
|
this.dispatched.add(row.id);
|
|
4517
5430
|
this.readopted.add(row.id);
|
|
@@ -4567,7 +5480,8 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
4567
5480
|
opencode_model: row.opencode_model,
|
|
4568
5481
|
source_message_id: row.source_message_id,
|
|
4569
5482
|
slack_user_id: row.slack_user_id,
|
|
4570
|
-
attachments: row.attachments ?? null
|
|
5483
|
+
attachments: row.attachments ?? null,
|
|
5484
|
+
opencode_message_id: row.opencode_message_id
|
|
4571
5485
|
};
|
|
4572
5486
|
}
|
|
4573
5487
|
/**
|
|
@@ -5159,11 +6073,11 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
5159
6073
|
* `ensureSession` guard, not this suppression, is what makes the self-heal
|
|
5160
6074
|
* stick.
|
|
5161
6075
|
*/
|
|
5162
|
-
sessionIdBody(sessionId, conversationId, messageId,
|
|
6076
|
+
sessionIdBody(sessionId, conversationId, messageId, status2) {
|
|
5163
6077
|
if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
|
|
5164
6078
|
this.log({
|
|
5165
6079
|
level: "debug",
|
|
5166
|
-
message: `Omitting the abandoned OpenCode session ${sessionId.slice(0, 8)} from the '${
|
|
6080
|
+
message: `Omitting the abandoned OpenCode session ${sessionId.slice(0, 8)} from the '${status2}' update for message ${messageId.slice(0, 8)} so it is not re-bound to conversation ${conversationId.slice(0, 8)}`,
|
|
5167
6081
|
conversation_id: conversationId,
|
|
5168
6082
|
message_id: messageId
|
|
5169
6083
|
});
|
|
@@ -5609,171 +6523,6 @@ Port ${port} is already in use.`));
|
|
|
5609
6523
|
return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
|
|
5610
6524
|
}
|
|
5611
6525
|
|
|
5612
|
-
// src/commands/agent-lookup.ts
|
|
5613
|
-
async function readErrorMessage(response) {
|
|
5614
|
-
const text = await response.text().catch(() => "");
|
|
5615
|
-
if (!text) return response.statusText || void 0;
|
|
5616
|
-
try {
|
|
5617
|
-
const data = JSON.parse(text);
|
|
5618
|
-
const message = data.message ?? data.error;
|
|
5619
|
-
if (typeof message === "string" && message.trim()) {
|
|
5620
|
-
return message;
|
|
5621
|
-
}
|
|
5622
|
-
} catch {
|
|
5623
|
-
}
|
|
5624
|
-
return text.trim() || response.statusText || void 0;
|
|
5625
|
-
}
|
|
5626
|
-
function authFailureHint(apiUrl, serverMessage) {
|
|
5627
|
-
const reason = serverMessage ? `: ${serverMessage}` : "";
|
|
5628
|
-
return `Authentication failed${reason}. Your credentials were rejected by ${apiUrl}. This usually means you logged in against a different environment, or your session expired \u2014 log in again pointing at this endpoint and retry.`;
|
|
5629
|
-
}
|
|
5630
|
-
async function resolveAgentIdFromKey(authHeader) {
|
|
5631
|
-
const apiUrl = getApiUrlConfig();
|
|
5632
|
-
try {
|
|
5633
|
-
const response = await fetch(`${apiUrl}/me`, {
|
|
5634
|
-
headers: { Authorization: authHeader }
|
|
5635
|
-
});
|
|
5636
|
-
if (response.status === 401) {
|
|
5637
|
-
const serverMessage = await readErrorMessage(response);
|
|
5638
|
-
return { error: authFailureHint(apiUrl, serverMessage), authFailed: true };
|
|
5639
|
-
}
|
|
5640
|
-
if (!response.ok) {
|
|
5641
|
-
const serverMessage = await readErrorMessage(response);
|
|
5642
|
-
return {
|
|
5643
|
-
error: `Failed to resolve runner from key (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5644
|
-
};
|
|
5645
|
-
}
|
|
5646
|
-
const data = await response.json();
|
|
5647
|
-
if (data.auth_type === "agent_key" && data.agent_id) {
|
|
5648
|
-
return { agent_id: data.agent_id };
|
|
5649
|
-
}
|
|
5650
|
-
return {
|
|
5651
|
-
error: "Cannot resolve runner ID: auth type is not agent_key. Please provide --runner explicitly."
|
|
5652
|
-
};
|
|
5653
|
-
} catch (error2) {
|
|
5654
|
-
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
5655
|
-
return { error: `Failed to resolve runner from key: ${message}` };
|
|
5656
|
-
}
|
|
5657
|
-
}
|
|
5658
|
-
var BEST_EFFORT_NOTIFY_TIMEOUT_MS = 2e3;
|
|
5659
|
-
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
5660
|
-
const apiUrl = getApiUrlConfig();
|
|
5661
|
-
try {
|
|
5662
|
-
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
5663
|
-
method: "POST",
|
|
5664
|
-
headers: { Authorization: authHeader },
|
|
5665
|
-
signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
|
|
5666
|
-
});
|
|
5667
|
-
if (!response.ok) {
|
|
5668
|
-
const serverMessage = await readErrorMessage(response);
|
|
5669
|
-
return {
|
|
5670
|
-
ok: false,
|
|
5671
|
-
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5672
|
-
};
|
|
5673
|
-
}
|
|
5674
|
-
return { ok: true };
|
|
5675
|
-
} catch (error2) {
|
|
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) };
|
|
5733
|
-
}
|
|
5734
|
-
}
|
|
5735
|
-
async function getAgentInfo(agentId, authHeader) {
|
|
5736
|
-
const apiUrl = getApiUrlConfig();
|
|
5737
|
-
try {
|
|
5738
|
-
const response = await fetch(`${apiUrl}/runners/${agentId}`, {
|
|
5739
|
-
headers: { Authorization: authHeader }
|
|
5740
|
-
});
|
|
5741
|
-
if (response.status === 401) {
|
|
5742
|
-
const serverMessage = await readErrorMessage(response);
|
|
5743
|
-
return { valid: false, error: authFailureHint(apiUrl, serverMessage), authFailed: true };
|
|
5744
|
-
}
|
|
5745
|
-
if (response.status === 403) {
|
|
5746
|
-
const serverMessage = await readErrorMessage(response);
|
|
5747
|
-
return {
|
|
5748
|
-
valid: false,
|
|
5749
|
-
error: serverMessage ?? "You do not have access to this runner (it may belong to a different team or organization)."
|
|
5750
|
-
};
|
|
5751
|
-
}
|
|
5752
|
-
if (response.status === 404) {
|
|
5753
|
-
const serverMessage = await readErrorMessage(response);
|
|
5754
|
-
return { valid: false, error: serverMessage ?? `Runner ${agentId} not found` };
|
|
5755
|
-
}
|
|
5756
|
-
if (!response.ok) {
|
|
5757
|
-
const serverMessage = await readErrorMessage(response);
|
|
5758
|
-
return {
|
|
5759
|
-
valid: false,
|
|
5760
|
-
error: `API error (HTTP ${response.status})${serverMessage ? `: ${serverMessage}` : ""}`
|
|
5761
|
-
};
|
|
5762
|
-
}
|
|
5763
|
-
const agent = await response.json();
|
|
5764
|
-
if (agent.agent_type !== "local") {
|
|
5765
|
-
return {
|
|
5766
|
-
valid: false,
|
|
5767
|
-
error: `Runner is type '${agent.agent_type}', must be 'local' for CLI connection`
|
|
5768
|
-
};
|
|
5769
|
-
}
|
|
5770
|
-
return { valid: true, agent };
|
|
5771
|
-
} catch (error2) {
|
|
5772
|
-
const message = error2 instanceof Error ? error2.message : "Unknown error";
|
|
5773
|
-
return { valid: false, error: `Failed to validate runner: ${message}` };
|
|
5774
|
-
}
|
|
5775
|
-
}
|
|
5776
|
-
|
|
5777
6526
|
// src/commands/run.ts
|
|
5778
6527
|
var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
5779
6528
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
@@ -5984,9 +6733,15 @@ async function handleAuthError(state, error2) {
|
|
|
5984
6733
|
}
|
|
5985
6734
|
async function driveChannels(state, driver) {
|
|
5986
6735
|
let idlePolls = 0;
|
|
6736
|
+
let idleMs = 0;
|
|
6737
|
+
let consecutiveDrainFailures = 0;
|
|
6738
|
+
let unreachableMs = 0;
|
|
5987
6739
|
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
5988
6740
|
let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
5989
6741
|
while (state.running) {
|
|
6742
|
+
const cycleStartedAtMs = performance.now();
|
|
6743
|
+
let idleThisCycle = false;
|
|
6744
|
+
let unreachableThisCycle = false;
|
|
5990
6745
|
if (state.connection?.reconnecting && state.connection.reconnectPromise) {
|
|
5991
6746
|
logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
|
|
5992
6747
|
if (state.interactive) displayStatus(state);
|
|
@@ -6001,17 +6756,23 @@ async function driveChannels(state, driver) {
|
|
|
6001
6756
|
);
|
|
6002
6757
|
try {
|
|
6003
6758
|
const processed = await driver.drainPending();
|
|
6759
|
+
consecutiveDrainFailures = 0;
|
|
6760
|
+
unreachableMs = 0;
|
|
6004
6761
|
state.messageCount += processed;
|
|
6005
6762
|
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
6006
6763
|
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
6007
6764
|
const appliedFiles = driver.fileSyncActivity().appliedFiles;
|
|
6008
|
-
const
|
|
6765
|
+
const filesApplied = appliedFiles !== lastSeenAppliedFiles;
|
|
6766
|
+
const fileActivity = carriedOverFileSync || filesApplied;
|
|
6009
6767
|
lastSeenAppliedFiles = appliedFiles;
|
|
6768
|
+
if (filesApplied) state.claudeUsageRearm?.();
|
|
6010
6769
|
if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
|
|
6011
6770
|
idlePolls = 0;
|
|
6771
|
+
idleMs = 0;
|
|
6012
6772
|
if (processed > 0 && state.interactive) displayStatus(state);
|
|
6013
6773
|
} else if (state.idleTimeout !== null) {
|
|
6014
6774
|
idlePolls++;
|
|
6775
|
+
idleThisCycle = true;
|
|
6015
6776
|
if (idlePolls === 1) {
|
|
6016
6777
|
logActivity(state, {
|
|
6017
6778
|
type: "info",
|
|
@@ -6035,15 +6796,38 @@ async function driveChannels(state, driver) {
|
|
|
6035
6796
|
const errorMessage = error2 instanceof Error ? error2.message : String(error2);
|
|
6036
6797
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
6037
6798
|
if (state.interactive) displayStatus(state);
|
|
6799
|
+
if (driver.hasInFlightWatchers()) {
|
|
6800
|
+
consecutiveDrainFailures = 0;
|
|
6801
|
+
unreachableMs = 0;
|
|
6802
|
+
} else if (state.idleTimeout !== null) {
|
|
6803
|
+
consecutiveDrainFailures++;
|
|
6804
|
+
unreachableThisCycle = true;
|
|
6805
|
+
if (consecutiveDrainFailures === 1) {
|
|
6806
|
+
logActivity(state, {
|
|
6807
|
+
type: "info",
|
|
6808
|
+
message: `Cannot reach Evident, will exit if this persists past the idle timeout (timeout: ${state.idleTimeout}s)...`
|
|
6809
|
+
});
|
|
6810
|
+
if (state.interactive) displayStatus(state);
|
|
6811
|
+
}
|
|
6812
|
+
}
|
|
6038
6813
|
}
|
|
6039
6814
|
await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
|
|
6040
|
-
|
|
6041
|
-
|
|
6042
|
-
|
|
6043
|
-
|
|
6044
|
-
|
|
6045
|
-
|
|
6046
|
-
|
|
6815
|
+
const cycleMs = performance.now() - cycleStartedAtMs;
|
|
6816
|
+
if (idleThisCycle) idleMs += cycleMs;
|
|
6817
|
+
if (unreachableThisCycle) unreachableMs += cycleMs;
|
|
6818
|
+
if (state.idleTimeout !== null && consecutiveDrainFailures >= 2 && unreachableMs > state.idleTimeout * 1e3) {
|
|
6819
|
+
logActivity(state, {
|
|
6820
|
+
type: "info",
|
|
6821
|
+
level: "warn",
|
|
6822
|
+
message: `Exiting: could not reach Evident for ${consecutiveDrainFailures} consecutive polls (${Math.round(unreachableMs / 1e3)}s)`
|
|
6823
|
+
});
|
|
6824
|
+
if (state.interactive) displayStatus(state);
|
|
6825
|
+
break;
|
|
6826
|
+
}
|
|
6827
|
+
if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3) {
|
|
6828
|
+
logActivity(state, { type: "info", message: "Idle timeout reached" });
|
|
6829
|
+
if (state.interactive) displayStatus(state);
|
|
6830
|
+
break;
|
|
6047
6831
|
}
|
|
6048
6832
|
}
|
|
6049
6833
|
}
|
|
@@ -6122,6 +6906,9 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
6122
6906
|
);
|
|
6123
6907
|
state.sessionCleanupTimers.push(interval, firstSweep);
|
|
6124
6908
|
}
|
|
6909
|
+
function claudeUsageFailureStreakSuffix(consecutiveFailures) {
|
|
6910
|
+
return consecutiveFailures > 1 ? ` (${consecutiveFailures} consecutive failures)` : "";
|
|
6911
|
+
}
|
|
6125
6912
|
function scheduleClaudeUsageReporting(state, options) {
|
|
6126
6913
|
const { mode, warnings } = resolveClaudeUsageReportingMode(
|
|
6127
6914
|
options.claudeUsageReporting,
|
|
@@ -6140,13 +6927,26 @@ function scheduleClaudeUsageReporting(state, options) {
|
|
|
6140
6927
|
level: "debug",
|
|
6141
6928
|
message: "Claude usage reporting is off (--claude-usage-reporting off)"
|
|
6142
6929
|
});
|
|
6143
|
-
return;
|
|
6930
|
+
return null;
|
|
6144
6931
|
}
|
|
6145
6932
|
let consecutiveFailures = 0;
|
|
6933
|
+
let armed = false;
|
|
6934
|
+
let rearmRequested = false;
|
|
6146
6935
|
const scheduleNextTick = () => {
|
|
6936
|
+
armed = true;
|
|
6937
|
+
rearmRequested = false;
|
|
6147
6938
|
state.claudeUsageTimer = setTimeout(() => void tick(false), nextReportDelayMs());
|
|
6148
6939
|
};
|
|
6149
|
-
const
|
|
6940
|
+
const rearm = () => {
|
|
6941
|
+
if (armed) {
|
|
6942
|
+
rearmRequested = true;
|
|
6943
|
+
return;
|
|
6944
|
+
}
|
|
6945
|
+
rearmRequested = false;
|
|
6946
|
+
armed = true;
|
|
6947
|
+
state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
|
|
6948
|
+
};
|
|
6949
|
+
const tick = async (isProbe) => {
|
|
6150
6950
|
try {
|
|
6151
6951
|
const usage = await getClaudeUsage();
|
|
6152
6952
|
const result = await reportClaudeUsage(state.agentId, state.authHeader, usage);
|
|
@@ -6168,8 +6968,8 @@ function scheduleClaudeUsageReporting(state, options) {
|
|
|
6168
6968
|
consecutiveFailures++;
|
|
6169
6969
|
logActivity(state, {
|
|
6170
6970
|
type: "info",
|
|
6171
|
-
level: consecutiveFailures
|
|
6172
|
-
message: `Failed to report Claude usage: ${result.error}`
|
|
6971
|
+
level: claudeUsageFailureLogLevel(consecutiveFailures),
|
|
6972
|
+
message: `Failed to report Claude usage: ${result.error}${claudeUsageFailureStreakSuffix(consecutiveFailures)}`
|
|
6173
6973
|
});
|
|
6174
6974
|
}
|
|
6175
6975
|
scheduleNextTick();
|
|
@@ -6182,12 +6982,14 @@ function scheduleClaudeUsageReporting(state, options) {
|
|
|
6182
6982
|
message: "Claude usage reporting is forced on but no usable Claude Code login was found \u2014 run `claude` to sign in; reporting will keep retrying"
|
|
6183
6983
|
});
|
|
6184
6984
|
scheduleNextTick();
|
|
6185
|
-
} else if (
|
|
6985
|
+
} else if (isProbe) {
|
|
6186
6986
|
logActivity(state, {
|
|
6187
6987
|
type: "info",
|
|
6188
6988
|
level: "debug",
|
|
6189
6989
|
message: `Claude usage reporting: ${error2.message}`
|
|
6190
6990
|
});
|
|
6991
|
+
armed = false;
|
|
6992
|
+
if (rearmRequested) rearm();
|
|
6191
6993
|
} else {
|
|
6192
6994
|
logActivity(state, {
|
|
6193
6995
|
type: "info",
|
|
@@ -6201,14 +7003,16 @@ function scheduleClaudeUsageReporting(state, options) {
|
|
|
6201
7003
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
6202
7004
|
logActivity(state, {
|
|
6203
7005
|
type: "info",
|
|
6204
|
-
level: consecutiveFailures
|
|
6205
|
-
message: `Claude usage reporting failed: ${message}`
|
|
7006
|
+
level: claudeUsageFailureLogLevel(consecutiveFailures),
|
|
7007
|
+
message: `Claude usage reporting failed: ${message}${claudeUsageFailureStreakSuffix(consecutiveFailures)}`
|
|
6206
7008
|
});
|
|
6207
7009
|
scheduleNextTick();
|
|
6208
7010
|
}
|
|
6209
7011
|
}
|
|
6210
7012
|
};
|
|
7013
|
+
armed = true;
|
|
6211
7014
|
state.claudeUsageTimer = setTimeout(() => void tick(true), FIRST_REPORT_DELAY_MS);
|
|
7015
|
+
return rearm;
|
|
6212
7016
|
}
|
|
6213
7017
|
async function notifyOffline(state) {
|
|
6214
7018
|
if (!state.agentId || !state.authHeader) return;
|
|
@@ -6249,6 +7053,7 @@ async function cleanup(state, opts = {}) {
|
|
|
6249
7053
|
clearTimeout(state.claudeUsageTimer);
|
|
6250
7054
|
state.claudeUsageTimer = null;
|
|
6251
7055
|
}
|
|
7056
|
+
state.claudeUsageRearm = null;
|
|
6252
7057
|
if (opts.graceful && state.channelDriver) {
|
|
6253
7058
|
state.channelDriver.stop();
|
|
6254
7059
|
log2(state, "Draining in-flight channel work before shutdown...");
|
|
@@ -6330,6 +7135,7 @@ async function run(options) {
|
|
|
6330
7135
|
lastProxiedActivityAt: null,
|
|
6331
7136
|
sessionCleanupTimers: [],
|
|
6332
7137
|
claudeUsageTimer: null,
|
|
7138
|
+
claudeUsageRearm: null,
|
|
6333
7139
|
authHeader: ""
|
|
6334
7140
|
};
|
|
6335
7141
|
setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
|
|
@@ -6409,6 +7215,7 @@ async function run(options) {
|
|
|
6409
7215
|
console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
|
|
6410
7216
|
blank();
|
|
6411
7217
|
process.exit(1);
|
|
7218
|
+
return;
|
|
6412
7219
|
}
|
|
6413
7220
|
blank();
|
|
6414
7221
|
console.log(chalk6.yellow("You are not logged in to Evident."));
|
|
@@ -6453,6 +7260,7 @@ async function run(options) {
|
|
|
6453
7260
|
} else {
|
|
6454
7261
|
printError(resolved.error || "Failed to resolve runner ID from key");
|
|
6455
7262
|
process.exit(1);
|
|
7263
|
+
return;
|
|
6456
7264
|
}
|
|
6457
7265
|
} else {
|
|
6458
7266
|
printError(
|
|
@@ -6466,6 +7274,7 @@ async function run(options) {
|
|
|
6466
7274
|
);
|
|
6467
7275
|
blank();
|
|
6468
7276
|
process.exit(1);
|
|
7277
|
+
return;
|
|
6469
7278
|
}
|
|
6470
7279
|
}
|
|
6471
7280
|
telemetry.info(
|
|
@@ -6713,7 +7522,7 @@ async function run(options) {
|
|
|
6713
7522
|
throw error2;
|
|
6714
7523
|
}
|
|
6715
7524
|
scheduleSessionCleanup(state, channelDriver, options);
|
|
6716
|
-
scheduleClaudeUsageReporting(state, options);
|
|
7525
|
+
state.claudeUsageRearm = scheduleClaudeUsageReporting(state, options);
|
|
6717
7526
|
if (!interactive || state.json) {
|
|
6718
7527
|
log2(state, "Driving channel messages...");
|
|
6719
7528
|
}
|
|
@@ -6768,6 +7577,7 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
6768
7577
|
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);
|
|
6769
7578
|
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 }));
|
|
6770
7579
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
7580
|
+
program.command("status").description("Check whether the configured credentials can reach Evident").option("--json", "Output in JSON format").action((options) => status({ json: options.json }));
|
|
6771
7581
|
program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);
|
|
6772
7582
|
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(
|
|
6773
7583
|
"-a, --agent [id]",
|
|
@@ -6797,7 +7607,7 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
6797
7607
|
[]
|
|
6798
7608
|
).option(
|
|
6799
7609
|
"--tunnel-ready-file <path>",
|
|
6800
|
-
"Path to write once the tunnel is connected (
|
|
7610
|
+
"Path to write once the tunnel is connected (opt-in; unused unless an operator/image sets it)"
|
|
6801
7611
|
).action(
|
|
6802
7612
|
(options) => {
|
|
6803
7613
|
run({
|