Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AntigravityTurnOutcome.ts

194 lines7.8 KB

1// @effect-diagnostics nodeBuiltinImport:off -- node:sqlite and lstat read the native session log.
2import * as NodeFSP from "node:fs/promises";
3import * as NodePath from "node:path";
4import * as NodeSqlite from "node:sqlite";
5​
6import type { OrchestrationV2ProviderFailure } from "@t3tools/contracts";
7import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import type * as EffectAcpSchema from "effect-acp/compat";
12​
13import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts";
14​
15// CORTEX_STEP_TYPE_ERROR_MESSAGE in the native trajectory.
16const ERROR_STEP_TYPE = 17;
17// The harness error text leads the payload; a Go stack trace follows it.
18const MAX_ERROR_PAYLOAD_BYTES = 16_384;
19// The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it.
20const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s;
21const QUOTA_EXHAUSTED = /\breason:QUOTA_EXHAUSTED\b/;
22const RESET_TIMESTAMP = /\bquotaResetTimeStamp:([^\s\]]+)/;
23const RESET_DELAY = /\bquotaResetDelay:((?:\d+(?:\.\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\s\]])/;
24const GO_DURATION_PART = /(\d+(?:\.\d+)?)(ns|us|µs|μs|ms|h|m|s)/g;
25const GO_DURATION_UNIT_MS: Record<string, number> = {
26 ns: 1e-6,
27 us: 1e-3,
28 µs: 1e-3,
29 μs: 1e-3,
30 ms: 1,
31 s: 1_000,
32 m: 60_000,
33 h: 3_600_000,
34};
35const NATIVE_SESSION_ID = /^[\w-]+$/;
36​
37interface LastStep {
38 readonly type: number;
39 readonly payload: Uint8Array | null;
41​
42const readSteps = <A>(file: string, read: (database: NodeSqlite.DatabaseSync) => A) =>
43 Effect.try(() => {
44 const database = new NodeSqlite.DatabaseSync(file, { readOnly: true });
45 try {
46 database.exec("PRAGMA busy_timeout = 100");
47 const hasSteps =
48 database
49 .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'")
50 .get() !== undefined;
51 return hasSteps ? read(database) : undefined;
52 } finally {
53 database.close();
54 }
55 });
56​
57const lastStepIndex = (database: NodeSqlite.DatabaseSync) => {
58 const index = database.prepare("SELECT max(idx) AS idx FROM steps").get()?.idx;
59 return typeof index === "number" ? index : -1;
60};
61​
62const lastStepAfter =
63 (index: number) =>
64 (database: NodeSqlite.DatabaseSync): LastStep | undefined => {
65 const row = database
66 .prepare(
67 `SELECT step_type AS type, substr(step_payload, 1, ?) AS payload
68 FROM steps WHERE idx > ? ORDER BY idx DESC LIMIT 1`,
69 )
70 .get(MAX_ERROR_PAYLOAD_BYTES, index);
71 if (typeof row?.type !== "number") return undefined;
72 return { type: row.type, payload: row.payload instanceof Uint8Array ? row.payload : null };
73 };
74​
75function resetAtFrom(text: string, now: DateTime.Utc): string | undefined {
76 // makeProviderFailure drops a timestamp that does not parse, so fall back to the delay.
77 const timestamp = RESET_TIMESTAMP.exec(text)?.[1];
78 if (timestamp !== undefined && Option.isSome(DateTime.make(timestamp))) return timestamp;
79 const delay = RESET_DELAY.exec(text)?.[1];
80 if (delay === undefined) return undefined;
81 let delayMs = 0;
82 for (const [, amount, unit] of delay.matchAll(GO_DURATION_PART)) {
83 delayMs += Number(amount) * (GO_DURATION_UNIT_MS[unit!] ?? 0);
84 }
85 return delayMs > 0 ? DateTime.formatIso(DateTime.add(now, { milliseconds: delayMs })) : undefined;
87​
88function turnFailure(
89 stopReason: EffectAcpSchema.StopReason,
90 step: LastStep | undefined,
91 now: DateTime.Utc,
92): OrchestrationV2ProviderFailure | undefined {
93 const errorText =
94 step?.type === ERROR_STEP_TYPE
95 ? new TextDecoder().decode(step.payload ?? new Uint8Array())
96 : undefined;
97 // The agent maps only the SDK's QUOTA_EXHAUSTED stop reason to `refusal`.
98 if (errorText === undefined && stopReason !== "refusal") return undefined;
99 const text = errorText ?? "";
100 const apiError = API_ERROR.exec(text);
101 if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) {
102 return makeProviderFailure({
103 class: "usage_limit",
104 message: "You have reached your Antigravity quota for this period.",
105 code: apiError?.[3] ?? "QUOTA_EXHAUSTED",
106 retryable: true,
107 resetAt: resetAtFrom(text, now) ?? null,
108 });
109 }
110 if (apiError === null) {
111 return makeProviderFailure({
112 class: "provider_error",
113 message: "Antigravity stopped this turn because of an error.",
114 });
115 }
116 const [, httpStatus, message, status] = apiError;
117 const rateLimited = httpStatus === "429" || status === "RESOURCE_EXHAUSTED";
118 return makeProviderFailure({
119 class: rateLimited ? "usage_limit" : "provider_error",
120 message: message!.trim(),
121 code: status ?? null,
122 retryable: rateLimited || Number(httpStatus) >= 500,
123 });
125​
126const conversationSegments = ["antigravity-acp", "conversations"];
127​
128/**
129 * Antigravity reports an upstream API failure as a chat message and `end_turn`. Its
130 * session log ends that turn with an error step, so the check reads only steps the
131 * current prompt added, read-only, from this session's own unlinked database. Without
132 * that evidence a typed `refusal` still fails the turn.
133 */
134export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.watch")(function* (
135 profileDirectory: string,
136 sessionId: string,
137) {
138 const typedOnly = (result: EffectAcpSchema.PromptResponse) =>
139 DateTime.now.pipe(Effect.map((now) => turnFailure(result.stopReason, undefined, now)));
140 if (!NATIVE_SESSION_ID.test(sessionId)) return typedOnly;
141 const segments = [...conversationSegments, `${sessionId}.db`];
142 const before = yield* Effect.tryPromise(async () => {
143 const root = await antigravityProfileRoot(profileDirectory);
144 if (root === undefined) return undefined;
145 if ((await antigravityManagedPath(root, conversationSegments, "directory")) === undefined) {
146 return undefined;
147 }
148 const database = await antigravityManagedPath(root, segments, "file");
149 // A path that exists but fails the proof is a link or other foreign entry.
150 if (database === undefined) {
151 const present = await NodeFSP.lstat(NodePath.join(root, ...segments)).then(
152 () => true,
153 () => false,
154 );
155 return present ? undefined : { root, identity: undefined, startIndex: -1 };
156 }
157 return { root, identity: database.info, startIndex: undefined };
158 }).pipe(Effect.orElseSucceed(() => undefined));
159 if (before === undefined) {
160 yield* Effect.logWarning("The Antigravity session log is not this session's own file.");
161 return typedOnly;
162 }
163 const startIndex =
164 before.startIndex ??
165 (yield* readSteps(NodePath.join(before.root, ...segments), lastStepIndex).pipe(
166 Effect.map((index) => index ?? -1),
167 Effect.orElseSucceed(() => undefined),
168 ));
169 if (startIndex === undefined) {
170 yield* Effect.logWarning("Could not read the Antigravity session log before the prompt.");
171 return typedOnly;
172 }
173 return Effect.fn("AntigravityTurnOutcome.check")(function* (
174 result: EffectAcpSchema.PromptResponse,
175 ) {
176 // The same file as before the prompt, or one this prompt created, still unlinked.
177 const after = yield* Effect.tryPromise(() =>
178 antigravityManagedPath(before.root, segments, "file"),
179 ).pipe(Effect.orElseSucceed(() => undefined));
180 const sameFile =
181 after !== undefined &&
182 (before.identity === undefined ||
183 (after.info.dev === before.identity.dev && after.info.ino === before.identity.ino));
184 const step = sameFile
185 ? yield* readSteps(after.path, lastStepAfter(startIndex)).pipe(
186 Effect.tapError(() =>
187 Effect.logWarning("Could not read the Antigravity session log after the prompt."),
188 ),
189 Effect.orElseSucceed(() => undefined),
190 )
191 : undefined;
192 return turnFailure(result.stopReason, step, yield* DateTime.now);
193 });
194});