pi-agy-acp 0.2.1 → 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/CHANGELOG.md +9 -0
- package/docs/development.md +15 -6
- package/docs/reference.md +15 -8
- package/index.ts +11 -2
- package/package.json +1 -1
- package/src/acp-process.ts +15 -1
- package/src/catalog.ts +29 -19
- package/src/conversation.ts +66 -16
- package/src/format.ts +68 -23
- package/src/host.ts +148 -13
- package/src/jsonrpc.ts +38 -4
- package/src/mcp-bridge.ts +26 -2
- package/src/preflight.ts +296 -371
- package/src/quota.ts +39 -20
- package/src/runtime.ts +305 -104
- package/src/session-db.ts +670 -0
package/src/preflight.ts
CHANGED
|
@@ -8,24 +8,37 @@
|
|
|
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
|
-
|
|
14
|
-
|
|
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
|
-
|
|
27
|
+
unlinkSync,
|
|
28
|
+
type BigIntStats,
|
|
23
29
|
type Stats,
|
|
24
30
|
} from 'node:fs'
|
|
25
31
|
import { homedir } from 'node:os'
|
|
26
|
-
import {
|
|
27
|
-
|
|
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'
|
|
@@ -74,11 +87,24 @@ export interface ResolveBinaryOptions {
|
|
|
74
87
|
home?: string
|
|
75
88
|
}
|
|
76
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
|
+
|
|
77
103
|
function splitPathDirs(
|
|
78
104
|
env: NodeJS.ProcessEnv,
|
|
79
105
|
platform: NodeJS.Platform,
|
|
80
106
|
): string[] {
|
|
81
|
-
const raw = env
|
|
107
|
+
const raw = getEnvCaseInsensitive(env, 'PATH') ?? ''
|
|
82
108
|
const sep = platform === 'win32' ? ';' : delimiter
|
|
83
109
|
const dirs: string[] = []
|
|
84
110
|
for (const part of raw.split(sep)) {
|
|
@@ -88,6 +114,22 @@ function splitPathDirs(
|
|
|
88
114
|
return dirs
|
|
89
115
|
}
|
|
90
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
|
+
|
|
91
133
|
/**
|
|
92
134
|
* Locate the `agy` executable.
|
|
93
135
|
* @param configured - configured absolute path, or empty.
|
|
@@ -98,36 +140,47 @@ export function resolveAgyBinary(
|
|
|
98
140
|
configured: string,
|
|
99
141
|
options: ResolveBinaryOptions = {},
|
|
100
142
|
): string {
|
|
143
|
+
const platform = options.platform ?? process.platform
|
|
101
144
|
if (configured.length > 0) {
|
|
102
145
|
if (!isAbsolute(configured))
|
|
103
146
|
throw new Error(
|
|
104
147
|
`antigravity-acp: command must be an absolute path, got ${configured}`,
|
|
105
148
|
)
|
|
106
|
-
if (!
|
|
149
|
+
if (!isExecutableFile(configured, platform))
|
|
107
150
|
throw new Error(
|
|
108
151
|
`antigravity-acp: configured agy binary not found at ${configured}`,
|
|
109
152
|
)
|
|
110
153
|
return configured
|
|
111
154
|
}
|
|
112
|
-
const platform = options.platform ?? process.platform
|
|
113
155
|
const env = options.env ?? process.env
|
|
114
156
|
const home = options.home ?? homedir()
|
|
115
|
-
const exeName = platform === 'win32' ? 'agy.exe' : 'agy'
|
|
116
157
|
const candidates: string[] = []
|
|
117
158
|
if (platform === 'win32') {
|
|
118
159
|
const localAppData =
|
|
119
|
-
env
|
|
120
|
-
|
|
121
|
-
: join(home, 'AppData', 'Local')
|
|
160
|
+
getEnvCaseInsensitive(env, 'LOCALAPPDATA') ||
|
|
161
|
+
join(home, 'AppData', 'Local')
|
|
122
162
|
candidates.push(join(localAppData, 'agy', 'bin', 'agy.exe'))
|
|
123
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
|
+
}
|
|
124
175
|
} else {
|
|
125
176
|
candidates.push(join(home, '.local', 'bin', 'agy'))
|
|
177
|
+
for (const dir of splitPathDirs(env, platform)) {
|
|
178
|
+
candidates.push(join(dir, 'agy'))
|
|
179
|
+
}
|
|
126
180
|
}
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
const found = candidates.find((candidate) => isFile(candidate))
|
|
181
|
+
const found = candidates.find((candidate) =>
|
|
182
|
+
isExecutableFile(candidate, platform),
|
|
183
|
+
)
|
|
131
184
|
if (found === undefined) {
|
|
132
185
|
throw new Error(
|
|
133
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`',
|
|
@@ -219,385 +272,229 @@ export function defaultHome(): string {
|
|
|
219
272
|
}
|
|
220
273
|
|
|
221
274
|
/**
|
|
222
|
-
*
|
|
223
|
-
*
|
|
224
|
-
* `~/.gemini/antigravity-cli`) whenever the host uses file-backed token storage
|
|
225
|
-
* (Windows / headless Linux) or the user signed in again from a terminal.
|
|
226
|
-
* @param home - isolated `--gemini-dir` root.
|
|
227
|
-
* @param userHome - optional user home override for testing.
|
|
228
|
-
* @param env - optional environment 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`.
|
|
229
277
|
*/
|
|
230
|
-
export function
|
|
278
|
+
export function isDefaultPiAgyHome(
|
|
231
279
|
home: string,
|
|
232
280
|
userHome: string = homedir(),
|
|
233
|
-
|
|
234
|
-
):
|
|
235
|
-
const
|
|
236
|
-
const
|
|
237
|
-
|
|
238
|
-
for (const dir of defaultAgyHomes(userHome, env)) {
|
|
239
|
-
const candidate = join(dir, 'antigravity-oauth-token')
|
|
240
|
-
try {
|
|
241
|
-
const st = statSync(candidate)
|
|
242
|
-
if (st.isFile() && st.size > 0) {
|
|
243
|
-
chosen = { path: candidate, mtimeMs: st.mtimeMs }
|
|
244
|
-
break
|
|
245
|
-
}
|
|
246
|
-
} catch {
|
|
247
|
-
// Directory has no token file; fall through to the next candidate.
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
if (chosen === undefined) return
|
|
251
|
-
try {
|
|
252
|
-
const dstStat = statSync(dst)
|
|
253
|
-
if (dstStat.size > 0 && dstStat.mtimeMs >= chosen.mtimeMs) return
|
|
254
|
-
} catch {
|
|
255
|
-
// Destination token file does not exist yet.
|
|
256
|
-
}
|
|
257
|
-
mkdirSync(appData, { recursive: true })
|
|
258
|
-
copyFileSync(chosen.path, dst)
|
|
259
|
-
try {
|
|
260
|
-
chmodSync(dst, 0o600)
|
|
261
|
-
} catch {
|
|
262
|
-
// Mode bits are advisory on Windows.
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
const EMPTY_BYTES = new Uint8Array(0)
|
|
267
|
-
const MAX_VARINT_SHIFT = 63n
|
|
268
|
-
|
|
269
|
-
function isValidSessionId(sessionId: string): boolean {
|
|
270
|
-
return (
|
|
271
|
-
typeof sessionId === 'string' &&
|
|
272
|
-
sessionId.length > 0 &&
|
|
273
|
-
!/[^A-Za-z0-9._-]/.test(sessionId) &&
|
|
274
|
-
sessionId !== '.' &&
|
|
275
|
-
!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'),
|
|
276
286
|
)
|
|
287
|
+
return platform === 'win32'
|
|
288
|
+
? actual.toLowerCase() === expected.toLowerCase()
|
|
289
|
+
: actual === expected
|
|
277
290
|
}
|
|
278
291
|
|
|
279
|
-
function
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
):
|
|
283
|
-
let
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
value |= BigInt(byte & 0x7f) << shift
|
|
289
|
-
if ((byte & 0x80) === 0) return { value, next: pos }
|
|
290
|
-
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
|
|
291
301
|
}
|
|
292
|
-
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
buf: Uint8Array,
|
|
297
|
-
pos: number,
|
|
298
|
-
wireType: number,
|
|
299
|
-
): number | undefined {
|
|
300
|
-
if (wireType === 0) return readVarint(buf, pos)?.next
|
|
301
|
-
if (wireType === 1) return pos + 8 <= buf.length ? pos + 8 : undefined
|
|
302
|
-
if (wireType === 2) {
|
|
303
|
-
const len = readVarint(buf, pos)
|
|
304
|
-
if (len === undefined) return undefined
|
|
305
|
-
const byteLen = Number(len.value)
|
|
306
|
-
if (!Number.isSafeInteger(byteLen) || byteLen < 0) return undefined
|
|
307
|
-
const end = len.next + byteLen
|
|
308
|
-
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}`)
|
|
309
306
|
}
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
onMatch: (payload: Uint8Array, varint: bigint) => T | undefined,
|
|
319
|
-
): T | undefined {
|
|
320
|
-
let pos = 0
|
|
321
|
-
let result: T | undefined
|
|
322
|
-
while (pos < buf.length) {
|
|
323
|
-
const tag = readVarint(buf, pos)
|
|
324
|
-
if (tag === undefined) break
|
|
325
|
-
pos = tag.next
|
|
326
|
-
const fieldNumber = Number(tag.value >> 3n)
|
|
327
|
-
const wireType = Number(tag.value & 7n)
|
|
328
|
-
if (fieldNumber <= 0) break
|
|
329
|
-
if (fieldNumber === targetField && wireType === expectedWireType) {
|
|
330
|
-
if (wireType === 0) {
|
|
331
|
-
const val = readVarint(buf, pos)
|
|
332
|
-
if (val === undefined) break
|
|
333
|
-
pos = val.next
|
|
334
|
-
const matched = onMatch(EMPTY_BYTES, val.value)
|
|
335
|
-
if (matched !== undefined) result = matched
|
|
336
|
-
continue
|
|
337
|
-
}
|
|
338
|
-
const len = readVarint(buf, pos)
|
|
339
|
-
if (len === undefined) break
|
|
340
|
-
const byteLen = Number(len.value)
|
|
341
|
-
if (!Number.isSafeInteger(byteLen) || byteLen < 0) break
|
|
342
|
-
const end = len.next + byteLen
|
|
343
|
-
if (end > buf.length) break
|
|
344
|
-
const matched = onMatch(buf.subarray(len.next, end), 0n)
|
|
345
|
-
if (matched !== undefined) result = matched
|
|
346
|
-
pos = end
|
|
347
|
-
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
|
|
348
315
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
/** Context window telemetry decoded from `gen_metadata.data`. */
|
|
357
|
-
export interface ContextWindowMetadata {
|
|
358
|
-
maxContextTokens?: number
|
|
359
|
-
estimatedTokensUsed?: number
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
function decodeCtxWindow(
|
|
363
|
-
ctxWindow: Uint8Array,
|
|
364
|
-
): ContextWindowMetadata | undefined {
|
|
365
|
-
let maxContextTokens: number | undefined
|
|
366
|
-
let estimatedTokensUsed: number | undefined
|
|
367
|
-
let pos = 0
|
|
368
|
-
while (pos < ctxWindow.length) {
|
|
369
|
-
const tag = readVarint(ctxWindow, pos)
|
|
370
|
-
if (tag === undefined) break
|
|
371
|
-
pos = tag.next
|
|
372
|
-
const fieldNumber = Number(tag.value >> 3n)
|
|
373
|
-
const wireType = Number(tag.value & 7n)
|
|
374
|
-
if (fieldNumber <= 0) break
|
|
375
|
-
if (wireType === 0 && (fieldNumber === 1 || fieldNumber === 4)) {
|
|
376
|
-
const val = readVarint(ctxWindow, pos)
|
|
377
|
-
if (val === undefined) break
|
|
378
|
-
pos = val.next
|
|
379
|
-
const num = Number(val.value)
|
|
380
|
-
if (val.value > 0n && Number.isSafeInteger(num)) {
|
|
381
|
-
if (fieldNumber === 1) estimatedTokensUsed = num
|
|
382
|
-
else maxContextTokens = num
|
|
383
|
-
}
|
|
384
|
-
continue
|
|
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
|
+
)
|
|
385
322
|
}
|
|
386
|
-
const next = skipField(ctxWindow, pos, wireType)
|
|
387
|
-
if (next === undefined) break
|
|
388
|
-
pos = next
|
|
389
|
-
}
|
|
390
|
-
if (maxContextTokens === undefined && estimatedTokensUsed === undefined)
|
|
391
|
-
return undefined
|
|
392
|
-
return {
|
|
393
|
-
...(maxContextTokens !== undefined ? { maxContextTokens } : {}),
|
|
394
|
-
...(estimatedTokensUsed !== undefined ? { estimatedTokensUsed } : {}),
|
|
395
323
|
}
|
|
324
|
+
return current
|
|
396
325
|
}
|
|
397
326
|
|
|
398
327
|
/**
|
|
399
|
-
*
|
|
400
|
-
*
|
|
401
|
-
* @param blob - raw protobuf bytes from `gen_metadata.data`.
|
|
402
|
-
* @returns positive token counts, 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.
|
|
403
330
|
*/
|
|
404
|
-
export function
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
scanMessage(chatStart, 10, 2, (ctxWindow) => decodeCtxWindow(ctxWindow)),
|
|
411
|
-
),
|
|
412
|
-
)
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
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
|
|
416
337
|
try {
|
|
417
|
-
|
|
338
|
+
existing = lstatSync(path)
|
|
418
339
|
} catch (error) {
|
|
419
|
-
|
|
420
|
-
? 'missing'
|
|
421
|
-
: 'invalid'
|
|
340
|
+
if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error
|
|
422
341
|
}
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
function resolveSessionDbPath(
|
|
426
|
-
home: string,
|
|
427
|
-
sessionId: string,
|
|
428
|
-
): { kind: 'ok'; dbPath: string } | { kind: 'missing' } | { kind: 'invalid' } {
|
|
429
|
-
if (!isValidSessionId(sessionId)) return { kind: 'invalid' }
|
|
430
|
-
const appData = join(home, 'agy')
|
|
431
|
-
const appStat = lstatOrMissing(appData)
|
|
432
|
-
if (appStat === 'missing') return { kind: 'missing' }
|
|
433
342
|
if (
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
const
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
convStat === 'invalid' ||
|
|
445
|
-
convStat.isSymbolicLink() ||
|
|
446
|
-
!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`,
|
|
447
353
|
)
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
let
|
|
451
|
-
let realConvDir: string
|
|
354
|
+
const mode = options?.mode
|
|
355
|
+
let fd: number | undefined
|
|
356
|
+
let created = false
|
|
452
357
|
try {
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
if (
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
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
|
+
}
|
|
477
389
|
}
|
|
390
|
+
throw error
|
|
478
391
|
}
|
|
479
|
-
|
|
480
|
-
return { kind: 'ok', dbPath }
|
|
481
392
|
}
|
|
482
393
|
|
|
483
394
|
/**
|
|
484
|
-
*
|
|
485
|
-
*
|
|
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.
|
|
486
400
|
* @param home - isolated `--gemini-dir` root.
|
|
487
|
-
* @param
|
|
488
|
-
* @param
|
|
489
|
-
* @returns decoded positive counts, or `undefined` when unavailable.
|
|
401
|
+
* @param userHome - optional user home override for testing.
|
|
402
|
+
* @param env - optional environment override for testing.
|
|
490
403
|
*/
|
|
491
|
-
export function
|
|
404
|
+
export function syncOAuthToken(
|
|
492
405
|
home: string,
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
):
|
|
496
|
-
if (
|
|
497
|
-
|
|
498
|
-
const
|
|
499
|
-
|
|
500
|
-
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
|
|
501
413
|
try {
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
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}`,
|
|
505
424
|
)
|
|
506
|
-
let maxContextTokens: number | undefined
|
|
507
|
-
let estimatedTokensUsed: number | undefined
|
|
508
|
-
for (const row of stmt.iterate(minIdx) as Iterable<{ data?: unknown }>) {
|
|
509
|
-
if (!(row.data instanceof Uint8Array)) continue
|
|
510
|
-
const meta = extractContextWindowMetadata(row.data)
|
|
511
|
-
if (meta === undefined) continue
|
|
512
|
-
if (maxContextTokens === undefined && meta.maxContextTokens !== undefined)
|
|
513
|
-
maxContextTokens = meta.maxContextTokens
|
|
514
|
-
if (
|
|
515
|
-
estimatedTokensUsed === undefined &&
|
|
516
|
-
meta.estimatedTokensUsed !== undefined
|
|
517
|
-
)
|
|
518
|
-
estimatedTokensUsed = meta.estimatedTokensUsed
|
|
519
|
-
if (maxContextTokens !== undefined && estimatedTokensUsed !== undefined)
|
|
520
|
-
break
|
|
521
|
-
}
|
|
522
|
-
if (maxContextTokens === undefined && estimatedTokensUsed === undefined)
|
|
523
|
-
return undefined
|
|
524
|
-
return {
|
|
525
|
-
...(maxContextTokens !== undefined ? { maxContextTokens } : {}),
|
|
526
|
-
...(estimatedTokensUsed !== undefined ? { estimatedTokensUsed } : {}),
|
|
527
|
-
}
|
|
528
|
-
} catch {
|
|
529
|
-
return undefined
|
|
530
|
-
} finally {
|
|
531
|
-
db?.close()
|
|
532
425
|
}
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
let
|
|
426
|
+
let dstStat: BigIntStats | undefined
|
|
427
|
+
try {
|
|
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)
|
|
548
444
|
try {
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
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
|
|
553
484
|
)
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
const row = db
|
|
557
|
-
.prepare('SELECT MAX(idx) AS maxIdx FROM gen_metadata')
|
|
558
|
-
.get() as { maxIdx?: unknown } | undefined
|
|
559
|
-
if (row?.maxIdx === null || row?.maxIdx === undefined) return 0
|
|
560
|
-
if (typeof row.maxIdx === 'number' && Number.isSafeInteger(row.maxIdx)) {
|
|
561
|
-
const next = row.maxIdx + 1
|
|
562
|
-
return Number.isSafeInteger(next) ? Math.max(0, next) : null
|
|
485
|
+
return
|
|
486
|
+
if (dstStat.size > 0n && dstStat.mtimeNs >= chosenStat.mtimeNs) return
|
|
563
487
|
}
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
488
|
+
const content = readFileSync(chosenFd)
|
|
489
|
+
ensureRealDirectory(home, ['agy'])
|
|
490
|
+
atomicWriteFile(dst, content, { mode: 0o600 })
|
|
567
491
|
} finally {
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
if (!isValidSessionId(sessionId)) return
|
|
575
|
-
const appData = join(home, 'agy')
|
|
576
|
-
if (!isRealDirectory(appData)) return
|
|
577
|
-
removeArtifacts(join(appData, 'conversations'), [
|
|
578
|
-
`${sessionId}.db`,
|
|
579
|
-
`${sessionId}.db-wal`,
|
|
580
|
-
`${sessionId}.db-shm`,
|
|
581
|
-
])
|
|
582
|
-
removeArtifacts(join(appData, 'brain'), [sessionId])
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
function isRealDirectory(path: string): boolean {
|
|
586
|
-
try {
|
|
587
|
-
return lstatSync(path).isDirectory()
|
|
588
|
-
} catch {
|
|
589
|
-
return false
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
function removeArtifacts(directory: string, names: readonly string[]): void {
|
|
594
|
-
// Never follow a replaced parent directory into data outside the isolated home.
|
|
595
|
-
if (!isRealDirectory(directory)) return
|
|
596
|
-
for (const name of names) {
|
|
597
|
-
try {
|
|
598
|
-
rmSync(join(directory, name), { recursive: true, force: true })
|
|
599
|
-
} catch {
|
|
600
|
-
// 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
|
+
}
|
|
601
498
|
}
|
|
602
499
|
}
|
|
603
500
|
}
|
|
@@ -612,11 +509,16 @@ export function prepareHome(
|
|
|
612
509
|
home: string,
|
|
613
510
|
userHome: string = homedir(),
|
|
614
511
|
env: NodeJS.ProcessEnv = process.env,
|
|
512
|
+
onWarn?: (message: string) => void,
|
|
615
513
|
): string {
|
|
616
|
-
const
|
|
617
|
-
|
|
514
|
+
const pluginDir = ensureRealDirectory(home, [
|
|
515
|
+
'config',
|
|
516
|
+
'plugins',
|
|
517
|
+
BRIDGE_AGENT,
|
|
518
|
+
])
|
|
519
|
+
const agentDir = ensureRealDirectory(pluginDir, ['agents'])
|
|
618
520
|
writeIfChanged(
|
|
619
|
-
join(
|
|
521
|
+
join(pluginDir, 'plugin.json'),
|
|
620
522
|
`${JSON.stringify({ name: BRIDGE_AGENT }, null, 2)}\n`,
|
|
621
523
|
)
|
|
622
524
|
writeIfChanged(
|
|
@@ -633,16 +535,17 @@ export function prepareHome(
|
|
|
633
535
|
'',
|
|
634
536
|
].join('\n'),
|
|
635
537
|
)
|
|
636
|
-
const appData =
|
|
637
|
-
mkdirSync(appData, { recursive: true })
|
|
538
|
+
const appData = ensureRealDirectory(home, ['agy'])
|
|
638
539
|
// Pi owns conversation history; no ACP session is restored across processes.
|
|
639
540
|
// shortcut: cleanup requires an exclusive home; add locking before supporting shared homes.
|
|
640
541
|
removeArtifacts(appData, [
|
|
641
542
|
'conversations',
|
|
642
543
|
'brain',
|
|
544
|
+
'annotations',
|
|
643
545
|
'conversation_summaries.db',
|
|
644
546
|
'conversation_summaries.db-wal',
|
|
645
547
|
'conversation_summaries.db-shm',
|
|
548
|
+
'conversation_summaries.db-journal',
|
|
646
549
|
'jetbox_summaries_proto.pb',
|
|
647
550
|
])
|
|
648
551
|
try {
|
|
@@ -653,15 +556,20 @@ export function prepareHome(
|
|
|
653
556
|
} catch {
|
|
654
557
|
// Log cleanup is best-effort when the home cannot be listed.
|
|
655
558
|
}
|
|
656
|
-
|
|
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
|
+
}
|
|
657
566
|
const settingsPath = join(appData, 'settings.json')
|
|
658
567
|
const settings = readJson(settingsPath)
|
|
659
568
|
writeIfChanged(
|
|
660
569
|
settingsPath,
|
|
661
570
|
`${JSON.stringify({ ...settings, toolPermission: 'request-review', agentMode: '' }, null, 2)}\n`,
|
|
662
571
|
)
|
|
663
|
-
const workspace =
|
|
664
|
-
mkdirSync(workspace, { recursive: true })
|
|
572
|
+
const workspace = ensureRealDirectory(home, ['workspace'])
|
|
665
573
|
return workspace
|
|
666
574
|
}
|
|
667
575
|
|
|
@@ -687,13 +595,30 @@ export async function readVersion(
|
|
|
687
595
|
}
|
|
688
596
|
|
|
689
597
|
function writeIfChanged(path: string, content: string): void {
|
|
690
|
-
|
|
691
|
-
|
|
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)
|
|
692
613
|
}
|
|
693
614
|
|
|
694
|
-
function
|
|
615
|
+
function isExecutableFile(path: string, platform: NodeJS.Platform): boolean {
|
|
695
616
|
try {
|
|
696
|
-
|
|
617
|
+
if (!statSync(path).isFile()) return false
|
|
618
|
+
if (platform !== 'win32' && process.platform !== 'win32') {
|
|
619
|
+
accessSync(path, fsConstants.X_OK)
|
|
620
|
+
}
|
|
621
|
+
return true
|
|
697
622
|
} catch {
|
|
698
623
|
return false
|
|
699
624
|
}
|