pi-agy-acp 0.1.4 → 0.2.1

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/host.ts CHANGED
@@ -1,15 +1,35 @@
1
- import { spawn, execFile } from 'node:child_process'
1
+ import { spawn, type ChildProcess } from 'node:child_process'
2
2
  import type { AcpSpawner } from './acp-process.ts'
3
- import type { CommandRunner } from './preflight.ts'
3
+ import type { CommandOptions, CommandOutput, CommandRunner } from './preflight.ts'
4
+
5
+ const DEFAULT_MAX_STDOUT_BYTES = 8 * 1024 * 1024
6
+ const MAX_STDERR_TAIL_CHARS = 65_536
7
+
8
+ function signalChild(child: ChildProcess, signal: NodeJS.Signals): void {
9
+ if (process.platform !== 'win32' && child.pid !== undefined) {
10
+ try {
11
+ process.kill(-child.pid, signal)
12
+ return
13
+ } catch {
14
+ // Fall back to signaling the direct child if process-group signaling fails.
15
+ }
16
+ }
17
+ try {
18
+ child.kill(signal)
19
+ } catch {
20
+ // Process already exited.
21
+ }
22
+ }
4
23
 
5
24
  export const spawnAcp: AcpSpawner = (argv, cwd) => {
6
25
  const child = spawn(argv[0]!, argv.slice(1), {
7
26
  cwd,
8
27
  stdio: ['pipe', 'pipe', 'pipe'],
28
+ detached: process.platform !== 'win32',
9
29
  })
10
30
  let stderr = ''
11
31
  child.stderr.on('data', (chunk) => {
12
- stderr = (stderr + chunk).slice(-65536)
32
+ stderr = (stderr + chunk).slice(-MAX_STDERR_TAIL_CHARS)
13
33
  })
14
34
  const exited = new Promise<{ code: number | null; signal: string | null }>(
15
35
  (resolve) => {
@@ -26,28 +46,110 @@ export const spawnAcp: AcpSpawner = (argv, cwd) => {
26
46
  exited,
27
47
  stderrTail: () => stderr,
28
48
  terminate: () => {
29
- child.kill('SIGTERM')
49
+ signalChild(child, 'SIGTERM')
30
50
  const timer = setTimeout(() => {
31
51
  if (child.exitCode === null && child.signalCode === null)
32
- child.kill('SIGKILL')
52
+ signalChild(child, 'SIGKILL')
33
53
  }, 5000)
34
54
  timer.unref()
35
55
  void exited.then(() => clearTimeout(timer))
36
56
  },
37
57
  }
38
58
  }
39
- export const runCommand: CommandRunner = (argv, timeout) =>
59
+
60
+ export const runCommand: CommandRunner = (
61
+ argv: readonly string[],
62
+ timeout: number,
63
+ options?: CommandOptions,
64
+ ): Promise<CommandOutput> =>
40
65
  new Promise((resolve) => {
41
- execFile(
42
- argv[0]!,
43
- argv.slice(1),
44
- { timeout, maxBuffer: 8 * 1024 * 1024 },
45
- (error, stdout, stderr) => {
46
- resolve({
47
- code: error ? (typeof error.code === 'number' ? error.code : -1) : 0,
48
- stdout,
49
- stderr: stderr || error?.message || '',
50
- })
51
- },
52
- )
66
+ if (options?.signal?.aborted) {
67
+ resolve({
68
+ code: -1,
69
+ stdout: '',
70
+ stderr: 'command aborted',
71
+ abortedBy: 'signal',
72
+ })
73
+ return
74
+ }
75
+ const maxStdoutBytes = options?.maxStdoutBytes ?? DEFAULT_MAX_STDOUT_BYTES
76
+ const child = spawn(argv[0]!, argv.slice(1), {
77
+ stdio: ['ignore', 'pipe', 'pipe'],
78
+ detached: process.platform !== 'win32',
79
+ })
80
+ const stdoutChunks: Buffer[] = []
81
+ let stdoutBytes = 0
82
+ let stderr = ''
83
+ let settled = false
84
+ let abortedBy: CommandOutput['abortedBy']
85
+ let killTimer: ReturnType<typeof setTimeout> | undefined
86
+
87
+ const finish = (code: number | null, errorMessage?: string): void => {
88
+ if (settled) return
89
+ settled = true
90
+ clearTimeout(timeoutTimer)
91
+ if (killTimer !== undefined) clearTimeout(killTimer)
92
+ options?.signal?.removeEventListener('abort', onSignalAbort)
93
+ const stdout = Buffer.concat(stdoutChunks).toString('utf8')
94
+ let finalStderr = stderr || errorMessage || ''
95
+ if (abortedBy === 'timeout' && finalStderr.trim().length === 0) {
96
+ finalStderr = 'command timed out'
97
+ } else if (abortedBy === 'maxStdout' && finalStderr.trim().length === 0) {
98
+ finalStderr = `stdout exceeded ${maxStdoutBytes} bytes`
99
+ } else if (abortedBy === 'signal' && finalStderr.trim().length === 0) {
100
+ finalStderr = 'command aborted'
101
+ }
102
+ resolve({
103
+ code:
104
+ abortedBy !== undefined
105
+ ? code !== null && code !== 0
106
+ ? code
107
+ : -1
108
+ : (code ?? -1),
109
+ stdout,
110
+ stderr: finalStderr,
111
+ ...(abortedBy !== undefined ? { abortedBy } : {}),
112
+ })
113
+ }
114
+
115
+ const abort = (reason: NonNullable<CommandOutput['abortedBy']>): void => {
116
+ if (settled || abortedBy !== undefined) return
117
+ abortedBy = reason
118
+ signalChild(child, 'SIGTERM')
119
+ killTimer = setTimeout(() => {
120
+ if (!settled) signalChild(child, 'SIGKILL')
121
+ }, 1000)
122
+ killTimer.unref()
123
+ }
124
+
125
+ const onSignalAbort = (): void => abort('signal')
126
+ options?.signal?.addEventListener('abort', onSignalAbort, { once: true })
127
+
128
+ const timeoutTimer = setTimeout(() => abort('timeout'), timeout)
129
+ timeoutTimer.unref()
130
+
131
+ child.stdout.on('data', (chunk: Buffer) => {
132
+ if (abortedBy !== undefined) return
133
+ stdoutBytes += chunk.length
134
+ if (stdoutBytes > maxStdoutBytes) {
135
+ abort('maxStdout')
136
+ return
137
+ }
138
+ stdoutChunks.push(chunk)
139
+ })
140
+
141
+ child.stderr.on('data', (chunk: Buffer) => {
142
+ stderr = (stderr + chunk.toString('utf8')).slice(-MAX_STDERR_TAIL_CHARS)
143
+ if (abortedBy === undefined && options?.abortOnStderr?.test(stderr)) {
144
+ abort('stderr')
145
+ }
146
+ })
147
+
148
+ child.once('error', (error) => {
149
+ finish(-1, error.message)
150
+ })
151
+
152
+ child.once('close', (code) => {
153
+ finish(code)
154
+ })
53
155
  })
package/src/pi-stream.ts CHANGED
@@ -142,8 +142,8 @@ export function streamPi(
142
142
  low: 'low',
143
143
  medium: 'medium',
144
144
  high: 'high',
145
- xhigh: 'high',
146
- max: 'high',
145
+ xhigh: 'xhigh',
146
+ max: 'max',
147
147
  }[options.reasoning ?? 'off'],
148
148
  }
149
149
  // onPayload may replace request content, but harness-owned routing/cancellation
package/src/preflight.ts CHANGED
@@ -15,35 +15,47 @@ import {
15
15
  mkdirSync,
16
16
  writeFileSync,
17
17
  readFileSync,
18
+ realpathSync,
18
19
  statSync,
19
20
  lstatSync,
20
21
  readdirSync,
21
22
  rmSync,
23
+ type Stats,
22
24
  } from 'node:fs'
23
25
  import { homedir } from 'node:os'
24
- import { delimiter, isAbsolute, join } from 'node:path'
26
+ import { delimiter, isAbsolute, join, relative, resolve } from 'node:path'
27
+ import { DatabaseSync } from 'node:sqlite'
25
28
  import { readJson } from './config.ts'
26
29
 
27
30
  /** Agent id installed in the isolated home. */
28
31
  export const BRIDGE_AGENT = 'pi-bridge'
29
- /** Minimum official CLI version supporting `agy acp --process-per-session`. */
30
- export const MIN_AGY_VERSION: readonly [number, number, number] = [1, 4, 12]
31
- /** Default context window for the official CLI. */
32
- export const DEFAULT_CONTEXT_WINDOW = 256_000
33
- /** GPT-OSS 120B has its own 128K-class window. */
34
- export const GPT_OSS_CONTEXT_WINDOW = 131_072
32
+ /** Minimum official CLI version supported (`agy 1.5.10+`). */
33
+ export const MIN_AGY_VERSION: readonly [number, number, number] = [1, 5, 10]
35
34
 
36
35
  /** Output of one finished helper command. */
37
36
  export interface CommandOutput {
38
37
  code: number | null
39
38
  stdout: string
40
39
  stderr: string
40
+ /** Set when aborted early by stderr match, stdout cap, timeout, or signal. */
41
+ abortedBy?: 'stderr' | 'maxStdout' | 'timeout' | 'signal'
42
+ }
43
+
44
+ /** Optional execution controls for one helper command. */
45
+ export interface CommandOptions {
46
+ /** Maximum stdout bytes buffered before aborting the command. */
47
+ maxStdoutBytes?: number
48
+ /** Abort the command early when buffered stderr matches this pattern. */
49
+ abortOnStderr?: RegExp
50
+ /** Cancel the command externally. */
51
+ signal?: AbortSignal
41
52
  }
42
53
 
43
54
  /** Runs one helper command to completion. */
44
55
  export type CommandRunner = (
45
56
  argv: readonly string[],
46
57
  timeoutMs: number,
58
+ options?: CommandOptions,
47
59
  ) => Promise<CommandOutput>
48
60
 
49
61
  /** Prepared launch facts. */
@@ -153,6 +165,48 @@ export function assertSupportedAgyVersion(
153
165
  }
154
166
  }
155
167
 
168
+ /**
169
+ * Compute a subprocess-free identity fingerprint for a resolved `agy` binary.
170
+ * @param binary - path to the executable.
171
+ * @returns `${real}:${dev}:${ino}:${size}:${mtimeNs}`, or `undefined` when unavailable.
172
+ */
173
+ export function binaryFingerprint(binary: string): string | undefined {
174
+ if (!binary) return undefined
175
+ try {
176
+ const real = realpathSync(binary)
177
+ const st = statSync(real, { bigint: true })
178
+ if (!st.isFile()) return undefined
179
+ return `${real}:${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}`
180
+ } catch {
181
+ return undefined
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Default Antigravity CLI directories in priority order:
187
+ * `ANTIGRAVITY_CLI_HOME`, then `AGY_HOME`, then `~/.gemini/antigravity-cli`.
188
+ */
189
+ export function defaultAgyHomes(
190
+ userHome: string = homedir(),
191
+ env: NodeJS.ProcessEnv = process.env,
192
+ ): string[] {
193
+ const candidates = [
194
+ env.ANTIGRAVITY_CLI_HOME?.trim(),
195
+ env.AGY_HOME?.trim(),
196
+ join(userHome, '.gemini', 'antigravity-cli'),
197
+ ]
198
+ const seen = new Set<string>()
199
+ const dirs: string[] = []
200
+ for (const dir of candidates) {
201
+ if (!dir) continue
202
+ const normalized = resolve(dir)
203
+ if (seen.has(normalized)) continue
204
+ seen.add(normalized)
205
+ dirs.push(normalized)
206
+ }
207
+ return dirs
208
+ }
209
+
156
210
  /**
157
211
  * Default isolated home.
158
212
  * @returns `~/.pi/agent/cache/antigravity-acp`.
@@ -166,45 +220,42 @@ export function defaultHome(): string {
166
220
 
167
221
  /**
168
222
  * Seed or refresh the isolated `antigravity-oauth-token` file from the user's
169
- * default CLI home (`~/.gemini/antigravity-cli` or `~/.gemini/antigravity`)
170
- * whenever the host uses file-backed token storage (Windows / headless Linux)
171
- * or the user signed in again from a terminal.
223
+ * Antigravity CLI home (`ANTIGRAVITY_CLI_HOME`, `AGY_HOME`, or
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.
172
226
  * @param home - isolated `--gemini-dir` root.
173
227
  * @param userHome - optional user home override for testing.
228
+ * @param env - optional environment override for testing.
174
229
  */
175
230
  export function syncOAuthToken(
176
231
  home: string,
177
232
  userHome: string = homedir(),
233
+ env: NodeJS.ProcessEnv = process.env,
178
234
  ): void {
179
235
  const appData = join(home, 'agy')
180
236
  const dst = join(appData, 'antigravity-oauth-token')
181
- const sources = [
182
- join(userHome, '.gemini', 'antigravity-cli', 'antigravity-oauth-token'),
183
- join(userHome, '.gemini', 'antigravity', 'antigravity-oauth-token'),
184
- ]
185
- let newestSrc: { path: string; mtimeMs: number } | undefined
186
- for (const candidate of sources) {
237
+ let chosen: { path: string; mtimeMs: number } | undefined
238
+ for (const dir of defaultAgyHomes(userHome, env)) {
239
+ const candidate = join(dir, 'antigravity-oauth-token')
187
240
  try {
188
241
  const st = statSync(candidate)
189
- if (
190
- st.size > 0 &&
191
- (newestSrc === undefined || st.mtimeMs > newestSrc.mtimeMs)
192
- ) {
193
- newestSrc = { path: candidate, mtimeMs: st.mtimeMs }
242
+ if (st.isFile() && st.size > 0) {
243
+ chosen = { path: candidate, mtimeMs: st.mtimeMs }
244
+ break
194
245
  }
195
246
  } catch {
196
- // Source token file does not exist.
247
+ // Directory has no token file; fall through to the next candidate.
197
248
  }
198
249
  }
199
- if (newestSrc === undefined) return
250
+ if (chosen === undefined) return
200
251
  try {
201
252
  const dstStat = statSync(dst)
202
- if (dstStat.size > 0 && dstStat.mtimeMs >= newestSrc.mtimeMs) return
253
+ if (dstStat.size > 0 && dstStat.mtimeMs >= chosen.mtimeMs) return
203
254
  } catch {
204
255
  // Destination token file does not exist yet.
205
256
  }
206
257
  mkdirSync(appData, { recursive: true })
207
- copyFileSync(newestSrc.path, dst)
258
+ copyFileSync(chosen.path, dst)
208
259
  try {
209
260
  chmodSync(dst, 0o600)
210
261
  } catch {
@@ -212,16 +263,315 @@ export function syncOAuthToken(
212
263
  }
213
264
  }
214
265
 
215
- /** Remove only one closed ACP session's files; session ids come from the agent. */
216
- export function removeSessionArtifacts(home: string, sessionId: string): void {
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('..')
276
+ )
277
+ }
278
+
279
+ function readVarint(
280
+ buf: Uint8Array,
281
+ start: number,
282
+ ): { value: bigint; next: number } | undefined {
283
+ let value = 0n
284
+ let shift = 0n
285
+ let pos = start
286
+ while (pos < buf.length && shift <= MAX_VARINT_SHIFT) {
287
+ const byte = buf[pos++] as number
288
+ value |= BigInt(byte & 0x7f) << shift
289
+ if ((byte & 0x80) === 0) return { value, next: pos }
290
+ shift += 7n
291
+ }
292
+ return undefined
293
+ }
294
+
295
+ function skipField(
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
309
+ }
310
+ if (wireType === 5) return pos + 4 <= buf.length ? pos + 4 : undefined
311
+ return undefined
312
+ }
313
+
314
+ function scanMessage<T>(
315
+ buf: Uint8Array,
316
+ targetField: number,
317
+ expectedWireType: 0 | 2,
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
348
+ }
349
+ const next = skipField(buf, pos, wireType)
350
+ if (next === undefined) break
351
+ pos = next
352
+ }
353
+ return result
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
385
+ }
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
+ }
396
+ }
397
+
398
+ /**
399
+ * Decode context window telemetry from `gen_metadata.data` along protobuf wire path
400
+ * `1 (chatModel) -> 9 (chatStart) -> 10 (ctxWindow) -> {1: estimated_tokens_used, 4: max_context_tokens}`.
401
+ * @param blob - raw protobuf bytes from `gen_metadata.data`.
402
+ * @returns positive token counts, or `undefined` when absent or malformed.
403
+ */
404
+ export function extractContextWindowMetadata(
405
+ blob: Uint8Array,
406
+ ): ContextWindowMetadata | undefined {
407
+ if (!(blob instanceof Uint8Array) || blob.length === 0) return undefined
408
+ return scanMessage(blob, 1, 2, (chatModel) =>
409
+ scanMessage(chatModel, 9, 2, (chatStart) =>
410
+ scanMessage(chatStart, 10, 2, (ctxWindow) => decodeCtxWindow(ctxWindow)),
411
+ ),
412
+ )
413
+ }
414
+
415
+ function lstatOrMissing(path: string): Stats | 'missing' | 'invalid' {
416
+ try {
417
+ return lstatSync(path)
418
+ } catch (error) {
419
+ return (error as NodeJS.ErrnoException)?.code === 'ENOENT'
420
+ ? 'missing'
421
+ : 'invalid'
422
+ }
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
+ if (
434
+ appStat === 'invalid' ||
435
+ appStat.isSymbolicLink() ||
436
+ !appStat.isDirectory()
437
+ )
438
+ return { kind: 'invalid' }
439
+
440
+ const convDir = join(appData, 'conversations')
441
+ const convStat = lstatOrMissing(convDir)
442
+ if (convStat === 'missing') return { kind: 'missing' }
217
443
  if (
218
- typeof sessionId !== 'string' ||
219
- sessionId.length === 0 ||
220
- /[^A-Za-z0-9._-]/.test(sessionId) ||
221
- sessionId === '.' ||
222
- sessionId.includes('..')
444
+ convStat === 'invalid' ||
445
+ convStat.isSymbolicLink() ||
446
+ !convStat.isDirectory()
223
447
  )
224
- return
448
+ return { kind: 'invalid' }
449
+
450
+ let realHome: string
451
+ let realConvDir: string
452
+ try {
453
+ realHome = realpathSync(home)
454
+ realConvDir = realpathSync(convDir)
455
+ } catch {
456
+ return { kind: 'invalid' }
457
+ }
458
+ const rel = relative(realHome, realConvDir)
459
+ if (rel.startsWith('..') || isAbsolute(rel)) return { kind: 'invalid' }
460
+
461
+ const dbPath = join(convDir, `${sessionId}.db`)
462
+ const dbStat = lstatOrMissing(dbPath)
463
+ if (dbStat === 'missing') return { kind: 'missing' }
464
+ if (dbStat === 'invalid' || dbStat.isSymbolicLink() || !dbStat.isFile())
465
+ return { kind: 'invalid' }
466
+
467
+ // Reject symlinked or non-regular SQLite WAL/SHM sidecar files before opening.
468
+ for (const suffix of ['-wal', '-shm']) {
469
+ const sidecarStat = lstatOrMissing(`${dbPath}${suffix}`)
470
+ if (sidecarStat === 'missing') continue
471
+ if (
472
+ sidecarStat === 'invalid' ||
473
+ sidecarStat.isSymbolicLink() ||
474
+ !sidecarStat.isFile()
475
+ ) {
476
+ return { kind: 'invalid' }
477
+ }
478
+ }
479
+
480
+ return { kind: 'ok', dbPath }
481
+ }
482
+
483
+ /**
484
+ * Read context window telemetry (`max_context_tokens` and `estimated_tokens_used`)
485
+ * from one ACP session's SQLite database.
486
+ * @param home - isolated `--gemini-dir` root.
487
+ * @param sessionId - ACP session id.
488
+ * @param minIdx - lowest `gen_metadata.idx` owned by the current scope.
489
+ * @returns decoded positive counts, or `undefined` when unavailable.
490
+ */
491
+ export function readSessionContextMetadata(
492
+ home: string,
493
+ sessionId: string,
494
+ minIdx = 0,
495
+ ): ContextWindowMetadata | undefined {
496
+ if (typeof minIdx !== 'number' || !Number.isSafeInteger(minIdx) || minIdx < 0)
497
+ return undefined
498
+ const resolved = resolveSessionDbPath(home, sessionId)
499
+ if (resolved.kind !== 'ok') return undefined
500
+ let db: DatabaseSync | undefined
501
+ try {
502
+ db = new DatabaseSync(resolved.dbPath, { readOnly: true, timeout: 50 })
503
+ const stmt = db.prepare(
504
+ 'SELECT data FROM gen_metadata WHERE idx >= ? ORDER BY idx DESC',
505
+ )
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
+ }
533
+ }
534
+
535
+ /**
536
+ * Compute the next `gen_metadata.idx` floor (`MAX(idx) + 1`, or `0` when no rows exist)
537
+ * before switching models inside a reused ACP session. Returns `null` when the
538
+ * session database path is invalid, symlinked, corrupt, or unreadable (fail-closed).
539
+ */
540
+ export function readSessionNextMetadataIndex(
541
+ home: string,
542
+ sessionId: string,
543
+ ): number | null {
544
+ const resolved = resolveSessionDbPath(home, sessionId)
545
+ if (resolved.kind === 'missing') return 0
546
+ if (resolved.kind === 'invalid') return null
547
+ let db: DatabaseSync | undefined
548
+ try {
549
+ db = new DatabaseSync(resolved.dbPath, { readOnly: true, timeout: 50 })
550
+ const hasTable = db
551
+ .prepare(
552
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'gen_metadata'",
553
+ )
554
+ .get()
555
+ if (hasTable === undefined) return 0
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
563
+ }
564
+ return null
565
+ } catch {
566
+ return null
567
+ } finally {
568
+ db?.close()
569
+ }
570
+ }
571
+
572
+ /** Remove only one closed ACP session's files; session ids come from the agent. */
573
+ export function removeSessionArtifacts(home: string, sessionId: string): void {
574
+ if (!isValidSessionId(sessionId)) return
225
575
  const appData = join(home, 'agy')
226
576
  if (!isRealDirectory(appData)) return
227
577
  removeArtifacts(join(appData, 'conversations'), [
@@ -261,6 +611,7 @@ function removeArtifacts(directory: string, names: readonly string[]): void {
261
611
  export function prepareHome(
262
612
  home: string,
263
613
  userHome: string = homedir(),
614
+ env: NodeJS.ProcessEnv = process.env,
264
615
  ): string {
265
616
  const agentDir = join(home, 'config', 'plugins', BRIDGE_AGENT, 'agents')
266
617
  mkdirSync(agentDir, { recursive: true })
@@ -302,7 +653,7 @@ export function prepareHome(
302
653
  } catch {
303
654
  // Log cleanup is best-effort when the home cannot be listed.
304
655
  }
305
- syncOAuthToken(home, userHome)
656
+ syncOAuthToken(home, userHome, env)
306
657
  const settingsPath = join(appData, 'settings.json')
307
658
  const settings = readJson(settingsPath)
308
659
  writeIfChanged(