@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 268 lines 10.7 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off -- node:sqlite and lstat read the native session log.
2 import * as NodeFSP from "node:fs/promises";
3 import * as NodePath from "node:path";
4 import * as NodeSqlite from "node:sqlite";
5
6 import type { OrchestrationV2ProviderFailure } from "@t3tools/contracts";
7 import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
8 import * as DateTime from "effect/DateTime";
9 import * as Effect from "effect/Effect";
10 import * as Option from "effect/Option";
11 import * as Schema from "effect/Schema";
12 import type * as EffectAcpSchema from "effect-acp/compat";
13
14 import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts";
15
16 // CORTEX_STEP_TYPE_ERROR_MESSAGE in the native trajectory.
17 const ERROR_STEP_TYPE = 17;
18 // CORTEX_STEP_TYPE_PLANNER_RESPONSE: the model answered within this turn.
19 const PLANNER_RESPONSE_STEP_TYPE = 15;
20 // The harness error text leads the payload; a Go stack trace follows it.
21 const MAX_ERROR_PAYLOAD_BYTES = 16_384;
22 // The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it.
23 const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s;
24 // Antigravity 1.5 with a Google account writes "STATUS (code NNN): message".
25 const STATUS_ERROR = /(?<![A-Z_])([A-Z_]+) \(code (\d{3})\): (\P{Cc}+)/u;
26 const QUOTA_EXHAUSTED = /\breason:QUOTA_EXHAUSTED\b/;
27 // Claude rejects a saved thinking block without a valid signature. It sits in the native
28 // history, so every later prompt to that session fails the same way.
29 const INVALID_THINKING_SIGNATURE =
30 /\bmessages\.\d+\.content\.\d+(?:\.thinking\.signature: Field required|: Invalid `signature` in `thinking` block)/;
31 const RESET_TIMESTAMP = /\bquotaResetTimeStamp:([^\s\]]+)/;
32 const RESET_DELAY = /\bquotaResetDelay:((?:\d+(?:\.\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\s\]])/;
33 // google.rpc.RetryInfo, which plain rate limits carry instead of a quota reset.
34 const RETRY_DELAY = /\bretryDelay:((?:\d+(?:\.\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\s\]])/;
35 const GO_DURATION_PART = /(\d+(?:\.\d+)?)(ns|us|µs|μs|ms|h|m|s)/g;
36 const GO_DURATION_UNIT_MS: Record<string, number> = {
37 ns: 1e-6,
38 us: 1e-3,
39 µs: 1e-3,
40 μs: 1e-3,
41 ms: 1,
42 s: 1_000,
43 m: 60_000,
44 h: 3_600_000,
45 };
46 const NATIVE_SESSION_ID = /^[\w-]+$/;
47
48 interface LastStep {
49 readonly type: number;
50 readonly payload: Uint8Array | null;
51 readonly reachedModel: boolean;
52 }
53
54 class AntigravitySessionLogError extends Schema.TaggedError<AntigravitySessionLogError>()(
55 "AntigravitySessionLogError",
56 { cause: Schema.Defect() },
57 ) {
58 override get message(): string {
59 return "Could not read the Antigravity session log.";
60 }
61 }
62
63 const sessionLogError = (cause: unknown) => new AntigravitySessionLogError({ cause });
64
65 const readSteps = <A>(file: string, read: (database: NodeSqlite.DatabaseSync) => A) =>
66 Effect.try({
67 try: () => {
68 const database = new NodeSqlite.DatabaseSync(file, { readOnly: true });
69 try {
70 database.exec("PRAGMA busy_timeout = 100");
71 const hasSteps =
72 database
73 .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'")
74 .get() !== undefined;
75 return hasSteps ? read(database) : undefined;
76 } finally {
77 database.close();
78 }
79 },
80 catch: sessionLogError,
81 });
82
83 const lastStepIndex = (database: NodeSqlite.DatabaseSync) => {
84 const index = database.prepare("SELECT max(idx) AS idx FROM steps").get()?.idx;
85 return typeof index === "number" ? index : -1;
86 };
87
88 const lastStepAfter =
89 (index: number) =>
90 (database: NodeSqlite.DatabaseSync): LastStep | undefined => {
91 const row = database
92 .prepare(
93 `SELECT step_type AS type, substr(step_payload, 1, ?) AS payload
94 FROM steps WHERE idx > ? ORDER BY idx DESC LIMIT 1`,
95 )
96 .get(MAX_ERROR_PAYLOAD_BYTES, index);
97 if (typeof row?.type !== "number") return undefined;
98 const reachedModel =
99 database
100 .prepare("SELECT 1 FROM steps WHERE idx > ? AND step_type = ? LIMIT 1")
101 .get(index, PLANNER_RESPONSE_STEP_TYPE) !== undefined;
102 return {
103 type: row.type,
104 payload: row.payload instanceof Uint8Array ? row.payload : null,
105 reachedModel,
106 };
107 };
108
109 function resetAtFrom(text: string, now: DateTime.Utc): string | undefined {
110 // makeProviderFailure drops a timestamp that does not parse, so fall back to the delay.
111 const timestamp = RESET_TIMESTAMP.exec(text)?.[1];
112 if (timestamp !== undefined && Option.isSome(DateTime.make(timestamp))) return timestamp;
113 const delay = RESET_DELAY.exec(text)?.[1] ?? RETRY_DELAY.exec(text)?.[1];
114 if (delay === undefined) return undefined;
115 let delayMs = 0;
116 for (const [, amount, unit] of delay.matchAll(GO_DURATION_PART)) {
117 delayMs += Number(amount) * (GO_DURATION_UNIT_MS[unit!] ?? 0);
118 }
119 return delayMs > 0 ? DateTime.formatIso(DateTime.add(now, { milliseconds: delayMs })) : undefined;
120 }
121
122 // Reorders STATUS_ERROR's groups to API_ERROR's: HTTP status, message, status name.
123 function statusError(text: string) {
124 const match = STATUS_ERROR.exec(text);
125 return match === null ? null : ([match[0], match[2], match[3], match[1]] as const);
126 }
127
128 function turnFailure(
129 stopReason: EffectAcpSchema.StopReason,
130 step: LastStep | undefined,
131 now: DateTime.Utc,
132 ):
133 | {
134 readonly failure: OrchestrationV2ProviderFailure;
135 readonly threadDisposition: "reusable" | "broken";
136 readonly resumeWith?: string;
137 }
138 | undefined {
139 const errorText =
140 step?.type === ERROR_STEP_TYPE
141 ? new TextDecoder().decode(step.payload ?? new Uint8Array())
142 : undefined;
143 // The agent maps only the SDK's QUOTA_EXHAUSTED stop reason to `refusal`.
144 if (errorText === undefined && stopReason !== "refusal") return undefined;
145 const text = errorText ?? "";
146 const apiError = API_ERROR.exec(text) ?? statusError(text);
147 const reusable = (failure: OrchestrationV2ProviderFailure) =>
148 ({ failure, threadDisposition: "reusable" }) as const;
149 if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) {
150 return reusable(
151 makeProviderFailure({
152 class: "usage_limit",
153 message: "You have reached your Antigravity quota for this period.",
154 code: apiError?.[3] ?? "QUOTA_EXHAUSTED",
155 retryable: true,
156 resetAt: resetAtFrom(text, now) ?? null,
157 }),
158 );
159 }
160 if (INVALID_THINKING_SIGNATURE.test(text)) {
161 return {
162 failure: makeProviderFailure({
163 class: "provider_error",
164 message:
165 "Antigravity's saved conversation can no longer be sent to the model. The next message starts a fresh Antigravity session with this thread's context.",
166 code: "INVALID_THINKING_SIGNATURE",
167 retryable: true,
168 }),
169 threadDisposition: "broken",
170 };
171 }
172 if (apiError === null) {
173 return reusable(
174 makeProviderFailure({
175 class: "provider_error",
176 message: "Antigravity stopped this turn because of an error.",
177 }),
178 );
179 }
180 const [, httpStatus, message, status] = apiError;
181 const rateLimited = httpStatus === "429" || status === "RESOURCE_EXHAUSTED";
182 // A 404 before the model answered is an unknown or unentitled model; after, a transient edge error.
183 const transientNotFound = httpStatus === "404" && step?.reachedModel === true;
184 const failure = makeProviderFailure({
185 class: rateLimited ? "usage_limit" : "provider_error",
186 message: message!.trim(),
187 code: status ?? null,
188 retryable: rateLimited || transientNotFound || Number(httpStatus) >= 500,
189 resetAt: resetAtFrom(text, now) ?? null,
190 });
191 return transientNotFound
192 ? { failure, threadDisposition: "reusable", resumeWith: "continue" }
193 : reusable(failure);
194 }
195
196 const conversationSegments = ["antigravity-acp", "conversations"];
197
198 /**
199 * Antigravity reports an upstream API failure as a chat message and `end_turn`. Its
200 * session log ends that turn with an error step, so the check reads only steps the
201 * current prompt added, read-only, from this session's own unlinked database. Without
202 * that evidence a typed `refusal` still fails the turn.
203 */
204 export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.watch")(function* (
205 profileDirectory: string,
206 sessionId: string,
207 ) {
208 const typedOnly = (result: EffectAcpSchema.PromptResponse) =>
209 DateTime.now.pipe(Effect.map((now) => turnFailure(result.stopReason, undefined, now)));
210 if (!NATIVE_SESSION_ID.test(sessionId)) return typedOnly;
211 const segments = [...conversationSegments, `${sessionId}.db`];
212 const before = yield* Effect.tryPromise({
213 try: async () => {
214 const root = await antigravityProfileRoot(profileDirectory);
215 if (root === undefined) return undefined;
216 if ((await antigravityManagedPath(root, conversationSegments, "directory")) === undefined) {
217 return undefined;
218 }
219 const database = await antigravityManagedPath(root, segments, "file");
220 // A path that exists but fails the proof is a link or other foreign entry.
221 if (database === undefined) {
222 const present = await NodeFSP.lstat(NodePath.join(root, ...segments)).then(
223 () => true,
224 () => false,
225 );
226 return present ? undefined : { root, identity: undefined, startIndex: -1 };
227 }
228 return { root, identity: database.info, startIndex: undefined };
229 },
230 catch: sessionLogError,
231 }).pipe(Effect.orElseSucceed(() => undefined));
232 if (before === undefined) {
233 yield* Effect.logWarning("The Antigravity session log is not this session's own file.");
234 return typedOnly;
235 }
236 const startIndex =
237 before.startIndex ??
238 (yield* readSteps(NodePath.join(before.root, ...segments), lastStepIndex).pipe(
239 Effect.map((index) => index ?? -1),
240 Effect.orElseSucceed(() => undefined),
241 ));
242 if (startIndex === undefined) {
243 yield* Effect.logWarning("Could not read the Antigravity session log before the prompt.");
244 return typedOnly;
245 }
246 return Effect.fn("AntigravityTurnOutcome.check")(function* (
247 result: EffectAcpSchema.PromptResponse,
248 ) {
249 // The same file as before the prompt, or one this prompt created, still unlinked.
250 const after = yield* Effect.tryPromise({
251 try: () => antigravityManagedPath(before.root, segments, "file"),
252 catch: sessionLogError,
253 }).pipe(Effect.orElseSucceed(() => undefined));
254 const sameFile =
255 after !== undefined &&
256 (before.identity === undefined ||
257 (after.info.dev === before.identity.dev && after.info.ino === before.identity.ino));
258 const step = sameFile
259 ? yield* readSteps(after.path, lastStepAfter(startIndex)).pipe(
260 Effect.tapError(() =>
261 Effect.logWarning("Could not read the Antigravity session log after the prompt."),
262 ),
263 Effect.orElseSucceed(() => undefined),
264 )
265 : undefined;
266 return turnFailure(result.stopReason, step, yield* DateTime.now);
267 });
268 });