pi-agy-acp 0.2.0 → 0.2.2

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/src/preflight.ts CHANGED
@@ -8,41 +8,67 @@
8
8
  * @module pi-agy-acp/preflight
9
9
  */
10
10
 
11
+ import { randomBytes } from 'node:crypto'
11
12
  import {
13
+ accessSync,
12
14
  chmodSync,
13
- copyFileSync,
14
- existsSync,
15
+ closeSync,
16
+ constants as fsConstants,
17
+ fstatSync,
15
18
  mkdirSync,
19
+ openSync,
16
20
  writeFileSync,
17
21
  readFileSync,
18
22
  realpathSync,
23
+ renameSync,
19
24
  statSync,
20
25
  lstatSync,
21
26
  readdirSync,
22
- rmSync,
27
+ unlinkSync,
28
+ type BigIntStats,
23
29
  type Stats,
24
30
  } from 'node:fs'
25
31
  import { homedir } from 'node:os'
26
- import { delimiter, isAbsolute, join, relative } from 'node:path'
27
- import { DatabaseSync } from 'node:sqlite'
32
+ import {
33
+ basename,
34
+ delimiter,
35
+ dirname,
36
+ isAbsolute,
37
+ join,
38
+ resolve,
39
+ } from 'node:path'
28
40
  import { readJson } from './config.ts'
41
+ import { removeArtifacts } from './session-db.ts'
29
42
 
30
43
  /** Agent id installed in the isolated home. */
31
44
  export const BRIDGE_AGENT = 'pi-bridge'
32
- /** Minimum official CLI version supporting `agy acp --process-per-session`. */
33
- export const MIN_AGY_VERSION: readonly [number, number, number] = [1, 4, 12]
45
+ /** Minimum official CLI version supported (`agy 1.5.10+`). */
46
+ export const MIN_AGY_VERSION: readonly [number, number, number] = [1, 5, 10]
34
47
 
35
48
  /** Output of one finished helper command. */
36
49
  export interface CommandOutput {
37
50
  code: number | null
38
51
  stdout: string
39
52
  stderr: string
53
+ /** Set when aborted early by stderr match, stdout cap, timeout, or signal. */
54
+ abortedBy?: 'stderr' | 'maxStdout' | 'timeout' | 'signal'
55
+ }
56
+
57
+ /** Optional execution controls for one helper command. */
58
+ export interface CommandOptions {
59
+ /** Maximum stdout bytes buffered before aborting the command. */
60
+ maxStdoutBytes?: number
61
+ /** Abort the command early when buffered stderr matches this pattern. */
62
+ abortOnStderr?: RegExp
63
+ /** Cancel the command externally. */
64
+ signal?: AbortSignal
40
65
  }
41
66
 
42
67
  /** Runs one helper command to completion. */
43
68
  export type CommandRunner = (
44
69
  argv: readonly string[],
45
70
  timeoutMs: number,
71
+ options?: CommandOptions,
46
72
  ) => Promise<CommandOutput>
47
73
 
48
74
  /** Prepared launch facts. */
@@ -61,11 +87,24 @@ export interface ResolveBinaryOptions {
61
87
  home?: string
62
88
  }
63
89
 
90
+ function getEnvCaseInsensitive(
91
+ env: NodeJS.ProcessEnv,
92
+ key: string,
93
+ ): string | undefined {
94
+ const direct = env[key]
95
+ if (direct !== undefined) return direct
96
+ const lower = key.toLowerCase()
97
+ for (const [entryKey, value] of Object.entries(env)) {
98
+ if (entryKey.toLowerCase() === lower && value !== undefined) return value
99
+ }
100
+ return undefined
101
+ }
102
+
64
103
  function splitPathDirs(
65
104
  env: NodeJS.ProcessEnv,
66
105
  platform: NodeJS.Platform,
67
106
  ): string[] {
68
- const raw = env.PATH ?? env.Path ?? ''
107
+ const raw = getEnvCaseInsensitive(env, 'PATH') ?? ''
69
108
  const sep = platform === 'win32' ? ';' : delimiter
70
109
  const dirs: string[] = []
71
110
  for (const part of raw.split(sep)) {
@@ -75,6 +114,22 @@ function splitPathDirs(
75
114
  return dirs
76
115
  }
77
116
 
117
+ function winPathExtensions(env: NodeJS.ProcessEnv): string[] {
118
+ const raw = getEnvCaseInsensitive(env, 'PATHEXT') ?? '.COM;.EXE;.BAT;.CMD'
119
+ const seen = new Set<string>()
120
+ const exts: string[] = []
121
+ for (const part of raw.split(';')) {
122
+ const trimmed = part.trim().toLowerCase()
123
+ if (trimmed.length === 0) continue
124
+ const ext = trimmed.startsWith('.') ? trimmed : `.${trimmed}`
125
+ if (seen.has(ext)) continue
126
+ seen.add(ext)
127
+ exts.push(ext)
128
+ }
129
+ if (!seen.has('.exe')) exts.unshift('.exe')
130
+ return exts
131
+ }
132
+
78
133
  /**
79
134
  * Locate the `agy` executable.
80
135
  * @param configured - configured absolute path, or empty.
@@ -85,36 +140,47 @@ export function resolveAgyBinary(
85
140
  configured: string,
86
141
  options: ResolveBinaryOptions = {},
87
142
  ): string {
143
+ const platform = options.platform ?? process.platform
88
144
  if (configured.length > 0) {
89
145
  if (!isAbsolute(configured))
90
146
  throw new Error(
91
147
  `antigravity-acp: command must be an absolute path, got ${configured}`,
92
148
  )
93
- if (!isFile(configured))
149
+ if (!isExecutableFile(configured, platform))
94
150
  throw new Error(
95
151
  `antigravity-acp: configured agy binary not found at ${configured}`,
96
152
  )
97
153
  return configured
98
154
  }
99
- const platform = options.platform ?? process.platform
100
155
  const env = options.env ?? process.env
101
156
  const home = options.home ?? homedir()
102
- const exeName = platform === 'win32' ? 'agy.exe' : 'agy'
103
157
  const candidates: string[] = []
104
158
  if (platform === 'win32') {
105
159
  const localAppData =
106
- env.LOCALAPPDATA && env.LOCALAPPDATA.length > 0
107
- ? env.LOCALAPPDATA
108
- : join(home, 'AppData', 'Local')
160
+ getEnvCaseInsensitive(env, 'LOCALAPPDATA') ||
161
+ join(home, 'AppData', 'Local')
109
162
  candidates.push(join(localAppData, 'agy', 'bin', 'agy.exe'))
110
163
  candidates.push(join(home, '.local', 'bin', 'agy.exe'))
164
+ const pathDirs = splitPathDirs(env, platform)
165
+ const exts = winPathExtensions(env)
166
+ // Prefer native agy.exe across PATH before PATHEXT wrapper shims (such as IDE agy.cmd).
167
+ for (const dir of pathDirs) {
168
+ candidates.push(join(dir, 'agy.exe'))
169
+ }
170
+ for (const dir of pathDirs) {
171
+ for (const ext of exts) {
172
+ if (ext !== '.exe') candidates.push(join(dir, `agy${ext}`))
173
+ }
174
+ }
111
175
  } else {
112
176
  candidates.push(join(home, '.local', 'bin', 'agy'))
177
+ for (const dir of splitPathDirs(env, platform)) {
178
+ candidates.push(join(dir, 'agy'))
179
+ }
113
180
  }
114
- for (const dir of splitPathDirs(env, platform)) {
115
- candidates.push(join(dir, exeName))
116
- }
117
- const found = candidates.find((candidate) => isFile(candidate))
181
+ const found = candidates.find((candidate) =>
182
+ isExecutableFile(candidate, platform),
183
+ )
118
184
  if (found === undefined) {
119
185
  throw new Error(
120
186
  'antigravity-acp: the Antigravity CLI (agy) was not found; install it from https://antigravity.google/docs/install?tab=cli and sign in once with `agy`',
@@ -152,6 +218,48 @@ export function assertSupportedAgyVersion(
152
218
  }
153
219
  }
154
220
 
221
+ /**
222
+ * Compute a subprocess-free identity fingerprint for a resolved `agy` binary.
223
+ * @param binary - path to the executable.
224
+ * @returns `${real}:${dev}:${ino}:${size}:${mtimeNs}`, or `undefined` when unavailable.
225
+ */
226
+ export function binaryFingerprint(binary: string): string | undefined {
227
+ if (!binary) return undefined
228
+ try {
229
+ const real = realpathSync(binary)
230
+ const st = statSync(real, { bigint: true })
231
+ if (!st.isFile()) return undefined
232
+ return `${real}:${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}`
233
+ } catch {
234
+ return undefined
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Default Antigravity CLI directories in priority order:
240
+ * `ANTIGRAVITY_CLI_HOME`, then `AGY_HOME`, then `~/.gemini/antigravity-cli`.
241
+ */
242
+ export function defaultAgyHomes(
243
+ userHome: string = homedir(),
244
+ env: NodeJS.ProcessEnv = process.env,
245
+ ): string[] {
246
+ const candidates = [
247
+ env.ANTIGRAVITY_CLI_HOME?.trim(),
248
+ env.AGY_HOME?.trim(),
249
+ join(userHome, '.gemini', 'antigravity-cli'),
250
+ ]
251
+ const seen = new Set<string>()
252
+ const dirs: string[] = []
253
+ for (const dir of candidates) {
254
+ if (!dir) continue
255
+ const normalized = resolve(dir)
256
+ if (seen.has(normalized)) continue
257
+ seen.add(normalized)
258
+ dirs.push(normalized)
259
+ }
260
+ return dirs
261
+ }
262
+
155
263
  /**
156
264
  * Default isolated home.
157
265
  * @returns `~/.pi/agent/cache/antigravity-acp`.
@@ -164,319 +272,229 @@ export function defaultHome(): string {
164
272
  }
165
273
 
166
274
  /**
167
- * Seed or refresh the isolated `antigravity-oauth-token` file from the user's
168
- * default CLI home (`~/.gemini/antigravity-cli` or `~/.gemini/antigravity`)
169
- * whenever the host uses file-backed token storage (Windows / headless Linux)
170
- * or the user signed in again from a terminal.
171
- * @param home - isolated `--gemini-dir` root.
172
- * @param userHome - optional user home override for testing.
275
+ * Whether `home` points to the default isolated Pi Antigravity home
276
+ * (`~/.pi/agent/cache/antigravity-acp`) rather than a custom `PI_AGY_HOME`.
173
277
  */
174
- export function syncOAuthToken(
278
+ export function isDefaultPiAgyHome(
175
279
  home: string,
176
280
  userHome: string = homedir(),
177
- ): void {
178
- const appData = join(home, 'agy')
179
- const dst = join(appData, 'antigravity-oauth-token')
180
- const sources = [
181
- join(userHome, '.gemini', 'antigravity-cli', 'antigravity-oauth-token'),
182
- join(userHome, '.gemini', 'antigravity', 'antigravity-oauth-token'),
183
- ]
184
- let newestSrc: { path: string; mtimeMs: number } | undefined
185
- for (const candidate of sources) {
186
- try {
187
- const st = statSync(candidate)
188
- if (
189
- st.size > 0 &&
190
- (newestSrc === undefined || st.mtimeMs > newestSrc.mtimeMs)
191
- ) {
192
- newestSrc = { path: candidate, mtimeMs: st.mtimeMs }
193
- }
194
- } catch {
195
- // Source token file does not exist.
196
- }
197
- }
198
- if (newestSrc === undefined) return
199
- try {
200
- const dstStat = statSync(dst)
201
- if (dstStat.size > 0 && dstStat.mtimeMs >= newestSrc.mtimeMs) return
202
- } catch {
203
- // Destination token file does not exist yet.
204
- }
205
- mkdirSync(appData, { recursive: true })
206
- copyFileSync(newestSrc.path, dst)
207
- try {
208
- chmodSync(dst, 0o600)
209
- } catch {
210
- // Mode bits are advisory on Windows.
211
- }
212
- }
213
-
214
- const EMPTY_BYTES = new Uint8Array(0)
215
- const MAX_VARINT_SHIFT = 63n
216
-
217
- function isValidSessionId(sessionId: string): boolean {
218
- return (
219
- typeof sessionId === 'string' &&
220
- sessionId.length > 0 &&
221
- !/[^A-Za-z0-9._-]/.test(sessionId) &&
222
- sessionId !== '.' &&
223
- !sessionId.includes('..')
281
+ platform: NodeJS.Platform = process.platform,
282
+ ): boolean {
283
+ const actual = resolve(home)
284
+ const expected = resolve(
285
+ join(userHome, '.pi', 'agent', 'cache', 'antigravity-acp'),
224
286
  )
287
+ return platform === 'win32'
288
+ ? actual.toLowerCase() === expected.toLowerCase()
289
+ : actual === expected
225
290
  }
226
291
 
227
- function readVarint(
228
- buf: Uint8Array,
229
- start: number,
230
- ): { value: bigint; next: number } | undefined {
231
- let value = 0n
232
- let shift = 0n
233
- let pos = start
234
- while (pos < buf.length && shift <= MAX_VARINT_SHIFT) {
235
- const byte = buf[pos++] as number
236
- value |= BigInt(byte & 0x7f) << shift
237
- if ((byte & 0x80) === 0) return { value, next: pos }
238
- shift += 7n
292
+ function ensureRealDirectory(
293
+ root: string,
294
+ segments: readonly string[],
295
+ ): string {
296
+ let rootStat: Stats | undefined
297
+ try {
298
+ rootStat = lstatSync(root)
299
+ } catch (error) {
300
+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error
239
301
  }
240
- return undefined
241
- }
242
-
243
- function skipField(
244
- buf: Uint8Array,
245
- pos: number,
246
- wireType: number,
247
- ): number | undefined {
248
- if (wireType === 0) return readVarint(buf, pos)?.next
249
- if (wireType === 1) return pos + 8 <= buf.length ? pos + 8 : undefined
250
- if (wireType === 2) {
251
- const len = readVarint(buf, pos)
252
- if (len === undefined) return undefined
253
- const byteLen = Number(len.value)
254
- if (!Number.isSafeInteger(byteLen) || byteLen < 0) return undefined
255
- const end = len.next + byteLen
256
- return end <= buf.length ? end : undefined
302
+ if (rootStat === undefined) {
303
+ mkdirSync(root, { recursive: true })
304
+ } else if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
305
+ throw new Error(`Refusing to use symlink or non-directory path: ${root}`)
257
306
  }
258
- if (wireType === 5) return pos + 4 <= buf.length ? pos + 4 : undefined
259
- return undefined
260
- }
261
-
262
- function scanMessage<T>(
263
- buf: Uint8Array,
264
- targetField: number,
265
- expectedWireType: 0 | 2,
266
- onMatch: (payload: Uint8Array, varint: bigint) => T | undefined,
267
- ): T | undefined {
268
- let pos = 0
269
- let result: T | undefined
270
- while (pos < buf.length) {
271
- const tag = readVarint(buf, pos)
272
- if (tag === undefined) break
273
- pos = tag.next
274
- const fieldNumber = Number(tag.value >> 3n)
275
- const wireType = Number(tag.value & 7n)
276
- if (fieldNumber <= 0) break
277
- if (fieldNumber === targetField && wireType === expectedWireType) {
278
- if (wireType === 0) {
279
- const val = readVarint(buf, pos)
280
- if (val === undefined) break
281
- pos = val.next
282
- const matched = onMatch(EMPTY_BYTES, val.value)
283
- if (matched !== undefined) result = matched
284
- continue
285
- }
286
- const len = readVarint(buf, pos)
287
- if (len === undefined) break
288
- const byteLen = Number(len.value)
289
- if (!Number.isSafeInteger(byteLen) || byteLen < 0) break
290
- const end = len.next + byteLen
291
- if (end > buf.length) break
292
- const matched = onMatch(buf.subarray(len.next, end), 0n)
293
- if (matched !== undefined) result = matched
294
- pos = end
295
- continue
307
+ let current = root
308
+ for (const segment of segments) {
309
+ current = join(current, segment)
310
+ let st: Stats | undefined
311
+ try {
312
+ st = lstatSync(current)
313
+ } catch (error) {
314
+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error
315
+ }
316
+ if (st === undefined) {
317
+ mkdirSync(current)
318
+ } else if (st.isSymbolicLink() || !st.isDirectory()) {
319
+ throw new Error(
320
+ `Refusing to use symlink or non-directory path: ${current}`,
321
+ )
296
322
  }
297
- const next = skipField(buf, pos, wireType)
298
- if (next === undefined) break
299
- pos = next
300
323
  }
301
- return result
324
+ return current
302
325
  }
303
326
 
304
327
  /**
305
- * Decode `max_context_tokens` from `gen_metadata.data` along protobuf wire path
306
- * `1 (bytes) -> 9 (bytes) -> 10 (bytes) -> 4 (varint)`.
307
- * @param blob - raw protobuf bytes from `gen_metadata.data`.
308
- * @returns positive token count, or `undefined` when absent or malformed.
328
+ * Atomically write a regular file in the target directory while rejecting
329
+ * symlinked or non-regular destination paths.
309
330
  */
310
- export function extractMaxContextTokens(blob: Uint8Array): number | undefined {
311
- if (!(blob instanceof Uint8Array) || blob.length === 0) return undefined
312
- return scanMessage(blob, 1, 2, (chatModel) =>
313
- scanMessage(chatModel, 9, 2, (chatStart) =>
314
- scanMessage(chatStart, 10, 2, (ctxWindow) =>
315
- scanMessage(ctxWindow, 4, 0, (_empty, value) => {
316
- const num = Number(value)
317
- return value > 0n && Number.isSafeInteger(num) ? num : undefined
318
- }),
319
- ),
320
- ),
321
- )
322
- }
323
-
324
- function lstatOrMissing(path: string): Stats | 'missing' | 'invalid' {
331
+ export function atomicWriteFile(
332
+ path: string,
333
+ content: string | Uint8Array,
334
+ options?: { mode?: number },
335
+ ): void {
336
+ let existing: Stats | undefined
325
337
  try {
326
- return lstatSync(path)
338
+ existing = lstatSync(path)
327
339
  } catch (error) {
328
- return (error as NodeJS.ErrnoException)?.code === 'ENOENT'
329
- ? 'missing'
330
- : 'invalid'
340
+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error
331
341
  }
332
- }
333
-
334
- function resolveSessionDbPath(
335
- home: string,
336
- sessionId: string,
337
- ): { kind: 'ok'; dbPath: string } | { kind: 'missing' } | { kind: 'invalid' } {
338
- if (!isValidSessionId(sessionId)) return { kind: 'invalid' }
339
- const appData = join(home, 'agy')
340
- const appStat = lstatOrMissing(appData)
341
- if (appStat === 'missing') return { kind: 'missing' }
342
342
  if (
343
- appStat === 'invalid' ||
344
- appStat.isSymbolicLink() ||
345
- !appStat.isDirectory()
346
- )
347
- return { kind: 'invalid' }
348
-
349
- const convDir = join(appData, 'conversations')
350
- const convStat = lstatOrMissing(convDir)
351
- if (convStat === 'missing') return { kind: 'missing' }
352
- if (
353
- convStat === 'invalid' ||
354
- convStat.isSymbolicLink() ||
355
- !convStat.isDirectory()
343
+ existing !== undefined &&
344
+ (existing.isSymbolicLink() || !existing.isFile())
345
+ ) {
346
+ throw new Error(
347
+ `Refusing to write to symlink or non-regular file: ${path}`,
348
+ )
349
+ }
350
+ const tmpPath = join(
351
+ dirname(path),
352
+ `.${basename(path)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`,
356
353
  )
357
- return { kind: 'invalid' }
358
-
359
- let realHome: string
360
- let realConvDir: string
354
+ const mode = options?.mode
355
+ let fd: number | undefined
356
+ let created = false
361
357
  try {
362
- realHome = realpathSync(home)
363
- realConvDir = realpathSync(convDir)
364
- } catch {
365
- return { kind: 'invalid' }
358
+ fd = openSync(
359
+ tmpPath,
360
+ fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL,
361
+ mode ?? 0o666,
362
+ )
363
+ created = true
364
+ writeFileSync(fd, content)
365
+ closeSync(fd)
366
+ fd = undefined
367
+ if (mode !== undefined) {
368
+ try {
369
+ chmodSync(tmpPath, mode)
370
+ } catch {
371
+ // Mode bits are advisory on Windows.
372
+ }
373
+ }
374
+ renameSync(tmpPath, path)
375
+ } catch (error) {
376
+ if (fd !== undefined) {
377
+ try {
378
+ closeSync(fd)
379
+ } catch {
380
+ // Ignore close errors during cleanup.
381
+ }
382
+ }
383
+ if (created) {
384
+ try {
385
+ unlinkSync(tmpPath)
386
+ } catch {
387
+ // Best-effort temp file cleanup.
388
+ }
389
+ }
390
+ throw error
366
391
  }
367
- const rel = relative(realHome, realConvDir)
368
- if (rel.startsWith('..') || isAbsolute(rel)) return { kind: 'invalid' }
369
-
370
- const dbPath = join(convDir, `${sessionId}.db`)
371
- const dbStat = lstatOrMissing(dbPath)
372
- if (dbStat === 'missing') return { kind: 'missing' }
373
- if (dbStat === 'invalid' || dbStat.isSymbolicLink() || !dbStat.isFile())
374
- return { kind: 'invalid' }
375
-
376
- return { kind: 'ok', dbPath }
377
392
  }
378
393
 
379
394
  /**
380
- * Read server-issued `max_context_tokens` from one ACP session's SQLite database.
395
+ * Seed or refresh the isolated `antigravity-oauth-token` file from the user's
396
+ * Antigravity CLI home (`ANTIGRAVITY_CLI_HOME`, `AGY_HOME`, or
397
+ * `~/.gemini/antigravity-cli`) whenever the default `PI_AGY_HOME` is in use
398
+ * and the host uses file-backed token storage. Custom `PI_AGY_HOME` roots stay
399
+ * strictly isolated.
381
400
  * @param home - isolated `--gemini-dir` root.
382
- * @param sessionId - ACP session id.
383
- * @param minIdx - lowest `gen_metadata.idx` owned by the current model.
384
- * @returns positive `max_context_tokens`, or `undefined` when unavailable.
401
+ * @param userHome - optional user home override for testing.
402
+ * @param env - optional environment override for testing.
385
403
  */
386
- export function readSessionMaxContextTokens(
404
+ export function syncOAuthToken(
387
405
  home: string,
388
- sessionId: string,
389
- minIdx = 0,
390
- ): number | undefined {
391
- if (typeof minIdx !== 'number' || !Number.isSafeInteger(minIdx) || minIdx < 0)
392
- return undefined
393
- const resolved = resolveSessionDbPath(home, sessionId)
394
- if (resolved.kind !== 'ok') return undefined
395
- let db: DatabaseSync | undefined
406
+ userHome: string = homedir(),
407
+ env: NodeJS.ProcessEnv = process.env,
408
+ ): void {
409
+ if (!isDefaultPiAgyHome(home, userHome)) return
410
+ const appData = join(home, 'agy')
411
+ const dst = join(appData, 'antigravity-oauth-token')
412
+ let appStat: Stats | undefined
396
413
  try {
397
- db = new DatabaseSync(resolved.dbPath, { readOnly: true, timeout: 50 })
398
- const stmt = db.prepare(
399
- 'SELECT data FROM gen_metadata WHERE idx >= ? ORDER BY idx DESC',
414
+ appStat = lstatSync(appData)
415
+ } catch (error) {
416
+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error
417
+ }
418
+ if (
419
+ appStat !== undefined &&
420
+ (appStat.isSymbolicLink() || !appStat.isDirectory())
421
+ ) {
422
+ throw new Error(
423
+ `Refusing to sync OAuth token into symlink or non-directory path: ${appData}`,
400
424
  )
401
- for (const row of stmt.iterate(minIdx) as Iterable<{ data?: unknown }>) {
402
- if (!(row.data instanceof Uint8Array)) continue
403
- const tokens = extractMaxContextTokens(row.data)
404
- if (tokens !== undefined) return tokens
405
- }
406
- return undefined
407
- } catch {
408
- return undefined
409
- } finally {
410
- db?.close()
411
425
  }
412
- }
413
-
414
- /**
415
- * Compute the next `gen_metadata.idx` floor (`MAX(idx) + 1`, or `0` when no rows exist)
416
- * before switching models inside a reused ACP session. Returns `null` when the
417
- * session database path is invalid, symlinked, corrupt, or unreadable (fail-closed).
418
- */
419
- export function readSessionNextMetadataIndex(
420
- home: string,
421
- sessionId: string,
422
- ): number | null {
423
- const resolved = resolveSessionDbPath(home, sessionId)
424
- if (resolved.kind === 'missing') return 0
425
- if (resolved.kind === 'invalid') return null
426
- let db: DatabaseSync | undefined
426
+ let dstStat: BigIntStats | undefined
427
427
  try {
428
- db = new DatabaseSync(resolved.dbPath, { readOnly: true, timeout: 50 })
429
- const hasTable = db
430
- .prepare(
431
- "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'gen_metadata'",
428
+ dstStat = lstatSync(dst, { bigint: true })
429
+ } catch (error) {
430
+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error
431
+ }
432
+ if (
433
+ dstStat !== undefined &&
434
+ (dstStat.isSymbolicLink() || !dstStat.isFile())
435
+ ) {
436
+ throw new Error(
437
+ `Refusing to overwrite symlink or non-regular OAuth token: ${dst}`,
438
+ )
439
+ }
440
+ let chosenFd: number | undefined
441
+ let chosenPath: string | undefined
442
+ let chosenStat: BigIntStats | undefined
443
+ const openFlags = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0)
444
+ try {
445
+ for (const dir of defaultAgyHomes(userHome, env)) {
446
+ const candidate = join(dir, 'antigravity-oauth-token')
447
+ let fd: number | undefined
448
+ try {
449
+ // Pre-check symlink for platforms where O_NOFOLLOW is unavailable (Windows).
450
+ if (lstatSync(candidate).isSymbolicLink()) continue
451
+ fd = openSync(candidate, openFlags)
452
+ const st = fstatSync(fd, { bigint: true })
453
+ if (st.isFile() && st.size > 0n) {
454
+ chosenFd = fd
455
+ chosenPath = candidate
456
+ chosenStat = st
457
+ fd = undefined
458
+ break
459
+ }
460
+ } catch {
461
+ // Directory has no usable token file; fall through to the next candidate.
462
+ } finally {
463
+ if (fd !== undefined) {
464
+ try {
465
+ closeSync(fd)
466
+ } catch {
467
+ // Ignore close errors while probing candidates.
468
+ }
469
+ }
470
+ }
471
+ }
472
+ if (
473
+ chosenFd === undefined ||
474
+ chosenPath === undefined ||
475
+ chosenStat === undefined
476
+ )
477
+ return
478
+ if (resolve(chosenPath) === resolve(dst)) return
479
+ if (dstStat !== undefined) {
480
+ if (
481
+ dstStat.ino !== 0n &&
482
+ dstStat.dev === chosenStat.dev &&
483
+ dstStat.ino === chosenStat.ino
432
484
  )
433
- .get()
434
- if (hasTable === undefined) return 0
435
- const row = db
436
- .prepare('SELECT MAX(idx) AS maxIdx FROM gen_metadata')
437
- .get() as { maxIdx?: unknown } | undefined
438
- if (row?.maxIdx === null || row?.maxIdx === undefined) return 0
439
- if (typeof row.maxIdx === 'number' && Number.isSafeInteger(row.maxIdx)) {
440
- const next = row.maxIdx + 1
441
- return Number.isSafeInteger(next) ? Math.max(0, next) : null
485
+ return
486
+ if (dstStat.size > 0n && dstStat.mtimeNs >= chosenStat.mtimeNs) return
442
487
  }
443
- return null
444
- } catch {
445
- return null
488
+ const content = readFileSync(chosenFd)
489
+ ensureRealDirectory(home, ['agy'])
490
+ atomicWriteFile(dst, content, { mode: 0o600 })
446
491
  } finally {
447
- db?.close()
448
- }
449
- }
450
-
451
- /** Remove only one closed ACP session's files; session ids come from the agent. */
452
- export function removeSessionArtifacts(home: string, sessionId: string): void {
453
- if (!isValidSessionId(sessionId)) return
454
- const appData = join(home, 'agy')
455
- if (!isRealDirectory(appData)) return
456
- removeArtifacts(join(appData, 'conversations'), [
457
- `${sessionId}.db`,
458
- `${sessionId}.db-wal`,
459
- `${sessionId}.db-shm`,
460
- ])
461
- removeArtifacts(join(appData, 'brain'), [sessionId])
462
- }
463
-
464
- function isRealDirectory(path: string): boolean {
465
- try {
466
- return lstatSync(path).isDirectory()
467
- } catch {
468
- return false
469
- }
470
- }
471
-
472
- function removeArtifacts(directory: string, names: readonly string[]): void {
473
- // Never follow a replaced parent directory into data outside the isolated home.
474
- if (!isRealDirectory(directory)) return
475
- for (const name of names) {
476
- try {
477
- rmSync(join(directory, name), { recursive: true, force: true })
478
- } catch {
479
- // Locked or unreadable leftovers can be retried on the next startup.
492
+ if (chosenFd !== undefined) {
493
+ try {
494
+ closeSync(chosenFd)
495
+ } catch {
496
+ // Ignore close errors after reading.
497
+ }
480
498
  }
481
499
  }
482
500
  }
@@ -490,11 +508,17 @@ function removeArtifacts(directory: string, names: readonly string[]): void {
490
508
  export function prepareHome(
491
509
  home: string,
492
510
  userHome: string = homedir(),
511
+ env: NodeJS.ProcessEnv = process.env,
512
+ onWarn?: (message: string) => void,
493
513
  ): string {
494
- const agentDir = join(home, 'config', 'plugins', BRIDGE_AGENT, 'agents')
495
- mkdirSync(agentDir, { recursive: true })
514
+ const pluginDir = ensureRealDirectory(home, [
515
+ 'config',
516
+ 'plugins',
517
+ BRIDGE_AGENT,
518
+ ])
519
+ const agentDir = ensureRealDirectory(pluginDir, ['agents'])
496
520
  writeIfChanged(
497
- join(home, 'config', 'plugins', BRIDGE_AGENT, 'plugin.json'),
521
+ join(pluginDir, 'plugin.json'),
498
522
  `${JSON.stringify({ name: BRIDGE_AGENT }, null, 2)}\n`,
499
523
  )
500
524
  writeIfChanged(
@@ -511,16 +535,17 @@ export function prepareHome(
511
535
  '',
512
536
  ].join('\n'),
513
537
  )
514
- const appData = join(home, 'agy')
515
- mkdirSync(appData, { recursive: true })
538
+ const appData = ensureRealDirectory(home, ['agy'])
516
539
  // Pi owns conversation history; no ACP session is restored across processes.
517
540
  // shortcut: cleanup requires an exclusive home; add locking before supporting shared homes.
518
541
  removeArtifacts(appData, [
519
542
  'conversations',
520
543
  'brain',
544
+ 'annotations',
521
545
  'conversation_summaries.db',
522
546
  'conversation_summaries.db-wal',
523
547
  'conversation_summaries.db-shm',
548
+ 'conversation_summaries.db-journal',
524
549
  'jetbox_summaries_proto.pb',
525
550
  ])
526
551
  try {
@@ -531,15 +556,20 @@ export function prepareHome(
531
556
  } catch {
532
557
  // Log cleanup is best-effort when the home cannot be listed.
533
558
  }
534
- syncOAuthToken(home, userHome)
559
+ try {
560
+ syncOAuthToken(home, userHome, env)
561
+ } catch (error) {
562
+ onWarn?.(
563
+ `antigravity-acp: OAuth token sync skipped: ${error instanceof Error ? error.message : String(error)}`,
564
+ )
565
+ }
535
566
  const settingsPath = join(appData, 'settings.json')
536
567
  const settings = readJson(settingsPath)
537
568
  writeIfChanged(
538
569
  settingsPath,
539
570
  `${JSON.stringify({ ...settings, toolPermission: 'request-review', agentMode: '' }, null, 2)}\n`,
540
571
  )
541
- const workspace = join(home, 'workspace')
542
- mkdirSync(workspace, { recursive: true })
572
+ const workspace = ensureRealDirectory(home, ['workspace'])
543
573
  return workspace
544
574
  }
545
575
 
@@ -565,13 +595,30 @@ export async function readVersion(
565
595
  }
566
596
 
567
597
  function writeIfChanged(path: string, content: string): void {
568
- if (existsSync(path) && readFileSync(path, 'utf8') === content) return
569
- writeFileSync(path, content)
598
+ let existing: Stats | undefined
599
+ try {
600
+ existing = lstatSync(path)
601
+ } catch (error) {
602
+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error
603
+ }
604
+ if (existing !== undefined) {
605
+ if (existing.isSymbolicLink() || !existing.isFile()) {
606
+ throw new Error(
607
+ `Refusing to write to symlink or non-regular file: ${path}`,
608
+ )
609
+ }
610
+ if (readFileSync(path, 'utf8') === content) return
611
+ }
612
+ atomicWriteFile(path, content)
570
613
  }
571
614
 
572
- function isFile(path: string): boolean {
615
+ function isExecutableFile(path: string, platform: NodeJS.Platform): boolean {
573
616
  try {
574
- return statSync(path).isFile()
617
+ if (!statSync(path).isFile()) return false
618
+ if (platform !== 'win32' && process.platform !== 'win32') {
619
+ accessSync(path, fsConstants.X_OK)
620
+ }
621
+ return true
575
622
  } catch {
576
623
  return false
577
624
  }