@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 201 lines 7.21 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off -- node:sqlite reads the native session database read-only.
2 import * as NodeSqlite from "node:sqlite";
3 import * as NodeURL from "node:url";
4
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Path from "effect/Path";
8 import * as Schema from "effect/Schema";
9
10 import { protoFields } from "./AntigravityChildWork.ts";
11 import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts";
12
13 const isNativeSessionId = Schema.is(Schema.String.check(Schema.isUUID(4)));
14 const decodeSessionMetadata = Schema.decodeEffect(
15 Schema.fromJsonString(Schema.Struct({ cwd: Schema.String })),
16 );
17
18 // Field numbers from the runtime's TrajectoryMetadata proto in trajectory_metadata_blob.
19 const TRAJECTORY_WORKSPACES = 1;
20 const WORKSPACE_URI = 1;
21 const TRAJECTORY_SESSION_ID = 6;
22 const TRAJECTORY_WORKSPACE_URIS = 7;
23 const MAX_METADATA_BLOB_BYTES = 1024 * 1024;
24
25 const utf8Decoder = new TextDecoder("utf-8", { fatal: true });
26
27 function decodeTrajectoryOwnership(blob: Uint8Array):
28 | {
29 readonly sessionId: string | undefined;
30 readonly workspaceUris: ReadonlyArray<string>;
31 }
32 | undefined {
33 try {
34 let sessionId: string | undefined;
35 const workspaceUris: Array<string> = [];
36 for (const [field, value] of protoFields(blob)) {
37 if (field === TRAJECTORY_SESSION_ID && sessionId === undefined) {
38 const decoded = utf8Decoder.decode(value).trim();
39 if (decoded.length > 0) sessionId = decoded;
40 } else if (field === TRAJECTORY_WORKSPACES) {
41 for (const [nestedField, nestedValue] of protoFields(value)) {
42 if (nestedField !== WORKSPACE_URI) continue;
43 const uri = utf8Decoder.decode(nestedValue).trim();
44 if (uri.length > 0) workspaceUris.push(uri);
45 }
46 } else if (field === TRAJECTORY_WORKSPACE_URIS) {
47 const uri = utf8Decoder.decode(value).trim();
48 if (uri.length > 0) workspaceUris.push(uri);
49 }
50 }
51 return { sessionId, workspaceUris };
52 } catch {
53 return undefined;
54 }
55 }
56
57 async function readDatabaseWorkspacePaths(
58 profileDirectory: string,
59 sessionId: string,
60 ): Promise<ReadonlyArray<string> | undefined> {
61 const profileRoot = await antigravityProfileRoot(profileDirectory);
62 if (profileRoot === undefined) return undefined;
63 const databasePath = (
64 await antigravityManagedPath(
65 profileRoot,
66 ["antigravity-acp", "conversations", `${sessionId}.db`],
67 "file",
68 )
69 )?.path;
70 if (databasePath === undefined) return undefined;
71
72 let database: NodeSqlite.DatabaseSync | undefined;
73 try {
74 database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
75 database.exec("PRAGMA busy_timeout = 100");
76 const rows = database
77 .prepare("SELECT data FROM trajectory_metadata_blob WHERE length(data) <= ? LIMIT 2")
78 .all(MAX_METADATA_BLOB_BYTES);
79 if (rows.length !== 1) return undefined;
80 const row = rows[0];
81 if (
82 row === null ||
83 typeof row !== "object" ||
84 !("data" in row) ||
85 !(row.data instanceof Uint8Array)
86 ) {
87 return undefined;
88 }
89 const metadata = decodeTrajectoryOwnership(row.data);
90 if (
91 metadata === undefined ||
92 metadata.workspaceUris.length === 0 ||
93 (metadata.sessionId !== undefined && metadata.sessionId !== sessionId)
94 ) {
95 return undefined;
96 }
97 return metadata.workspaceUris.map((uri) => NodeURL.fileURLToPath(uri));
98 } catch {
99 return undefined;
100 } finally {
101 database?.close();
102 }
103 }
104
105 // The runtime may store the resolved path (macOS `/var` -> `/private/var`) or another drive-letter case.
106 const pathKey = Effect.fnUntraced(function* (
107 fs: FileSystem.FileSystem,
108 path: Path.Path,
109 target: string,
110 ) {
111 const resolved = yield* fs
112 .realPath(target)
113 .pipe(Effect.orElseSucceed(() => path.resolve(target)));
114 return path.sep === "\\" ? resolved.toLowerCase() : resolved;
115 });
116
117 /** Call after the process closes. The unique temporary cwd proves which session we own. */
118 export const removeAntigravitySessionFiles = Effect.fn("removeAntigravitySessionFiles")(
119 function* (input: {
120 readonly profileDirectory: string;
121 readonly sessionId: string | undefined;
122 readonly cwd: string;
123 }) {
124 const { sessionId } = input;
125 if (sessionId === undefined || !isNativeSessionId(sessionId)) {
126 return;
127 }
128 const fs = yield* FileSystem.FileSystem;
129 const path = yield* Path.Path;
130 const acpDirectory = path.join(input.profileDirectory, "antigravity-acp");
131 const base = path.join(acpDirectory, "conversations", sessionId);
132
133 if (yield* fs.exists(`${base}.meta`)) {
134 const metadata = yield* fs
135 .readFileString(`${base}.meta`)
136 .pipe(Effect.flatMap(decodeSessionMetadata));
137 if (metadata.cwd !== input.cwd) {
138 return;
139 }
140 } else {
141 // Antigravity CLI 1.5+ writes no `.meta` sidecar; workspace URIs live in the session DB.
142 const workspacePaths = yield* Effect.promise(() =>
143 readDatabaseWorkspacePaths(input.profileDirectory, sessionId),
144 );
145 if (workspacePaths === undefined || workspacePaths.length === 0) {
146 return;
147 }
148 const cwdKey = yield* pathKey(fs, path, input.cwd);
149 for (const workspacePath of workspacePaths) {
150 if ((yield* pathKey(fs, path, workspacePath)) !== cwdKey) {
151 return;
152 }
153 }
154 }
155
156 for (const suffix of [".db", ".db-wal", ".db-shm", ".db-journal", ".meta"]) {
157 yield* fs.remove(`${base}${suffix}`, { force: true });
158 }
159 yield* fs.remove(path.join(acpDirectory, "brain", sessionId), {
160 recursive: true,
161 force: true,
162 });
163 yield* fs.remove(path.join(acpDirectory, "annotations", `${sessionId}.pbtxt`), {
164 force: true,
165 });
166 },
167 Effect.catch(() => Effect.logWarning("Could not remove temporary Antigravity session files.")),
168 );
169
170 const warnRuntimeTempLeftovers = Effect.logWarning(
171 "Could not remove leftover Antigravity runtime temp files.",
172 );
173
174 /**
175 * Sweep only private runtimes before launch; Windows does not protect live extracted data files from deletion.
176 * Moves leftovers aside and returns their slow deletion (seconds on Windows) to run off the startup path.
177 */
178 export const retireAntigravityRuntimeTempDirs = Effect.fn("retireAntigravityRuntimeTempDirs")(
179 function* (tempDirectory: string) {
180 const fs = yield* FileSystem.FileSystem;
181 const path = yield* Path.Path;
182 const parent = path.dirname(tempDirectory);
183 const prefix = `${path.basename(tempDirectory)}.old-`;
184 if (yield* fs.exists(tempDirectory)) {
185 yield* fs.makeTempDirectory({ directory: parent, prefix }).pipe(
186 Effect.flatMap((retired) => fs.rename(tempDirectory, path.join(retired, "runtime"))),
187 Effect.catch(() => fs.remove(tempDirectory, { recursive: true, force: true })),
188 );
189 }
190 const entries = yield* fs.readDirectory(parent).pipe(Effect.orElseSucceed(() => []));
191 return Effect.forEach(
192 entries.filter((entry) => entry.startsWith(prefix)),
193 (entry) =>
194 fs
195 .remove(path.join(parent, entry), { recursive: true, force: true })
196 .pipe(Effect.catch(() => warnRuntimeTempLeftovers)),
197 { discard: true },
198 );
199 },
200 Effect.catch(() => warnRuntimeTempLeftovers.pipe(Effect.as(Effect.void))),
201 );