pi-agy-acp 0.2.0 → 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
@@ -23,26 +23,39 @@ import {
23
23
  type Stats,
24
24
  } from 'node:fs'
25
25
  import { homedir } from 'node:os'
26
- import { delimiter, isAbsolute, join, relative } from 'node:path'
26
+ import { delimiter, isAbsolute, join, relative, resolve } from 'node:path'
27
27
  import { DatabaseSync } from 'node:sqlite'
28
28
  import { readJson } from './config.ts'
29
29
 
30
30
  /** Agent id installed in the isolated home. */
31
31
  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]
32
+ /** Minimum official CLI version supported (`agy 1.5.10+`). */
33
+ export const MIN_AGY_VERSION: readonly [number, number, number] = [1, 5, 10]
34
34
 
35
35
  /** Output of one finished helper command. */
36
36
  export interface CommandOutput {
37
37
  code: number | null
38
38
  stdout: string
39
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
40
52
  }
41
53
 
42
54
  /** Runs one helper command to completion. */
43
55
  export type CommandRunner = (
44
56
  argv: readonly string[],
45
57
  timeoutMs: number,
58
+ options?: CommandOptions,
46
59
  ) => Promise<CommandOutput>
47
60
 
48
61
  /** Prepared launch facts. */
@@ -152,6 +165,48 @@ export function assertSupportedAgyVersion(
152
165
  }
153
166
  }
154
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
+
155
210
  /**
156
211
  * Default isolated home.
157
212
  * @returns `~/.pi/agent/cache/antigravity-acp`.
@@ -165,45 +220,42 @@ export function defaultHome(): string {
165
220
 
166
221
  /**
167
222
  * 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.
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.
171
226
  * @param home - isolated `--gemini-dir` root.
172
227
  * @param userHome - optional user home override for testing.
228
+ * @param env - optional environment override for testing.
173
229
  */
174
230
  export function syncOAuthToken(
175
231
  home: string,
176
232
  userHome: string = homedir(),
233
+ env: NodeJS.ProcessEnv = process.env,
177
234
  ): void {
178
235
  const appData = join(home, 'agy')
179
236
  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) {
237
+ let chosen: { path: string; mtimeMs: number } | undefined
238
+ for (const dir of defaultAgyHomes(userHome, env)) {
239
+ const candidate = join(dir, 'antigravity-oauth-token')
186
240
  try {
187
241
  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 }
242
+ if (st.isFile() && st.size > 0) {
243
+ chosen = { path: candidate, mtimeMs: st.mtimeMs }
244
+ break
193
245
  }
194
246
  } catch {
195
- // Source token file does not exist.
247
+ // Directory has no token file; fall through to the next candidate.
196
248
  }
197
249
  }
198
- if (newestSrc === undefined) return
250
+ if (chosen === undefined) return
199
251
  try {
200
252
  const dstStat = statSync(dst)
201
- if (dstStat.size > 0 && dstStat.mtimeMs >= newestSrc.mtimeMs) return
253
+ if (dstStat.size > 0 && dstStat.mtimeMs >= chosen.mtimeMs) return
202
254
  } catch {
203
255
  // Destination token file does not exist yet.
204
256
  }
205
257
  mkdirSync(appData, { recursive: true })
206
- copyFileSync(newestSrc.path, dst)
258
+ copyFileSync(chosen.path, dst)
207
259
  try {
208
260
  chmodSync(dst, 0o600)
209
261
  } catch {
@@ -301,22 +353,61 @@ function scanMessage<T>(
301
353
  return result
302
354
  }
303
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
+
304
398
  /**
305
- * Decode `max_context_tokens` from `gen_metadata.data` along protobuf wire path
306
- * `1 (bytes) -> 9 (bytes) -> 10 (bytes) -> 4 (varint)`.
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}`.
307
401
  * @param blob - raw protobuf bytes from `gen_metadata.data`.
308
- * @returns positive token count, or `undefined` when absent or malformed.
402
+ * @returns positive token counts, or `undefined` when absent or malformed.
309
403
  */
310
- export function extractMaxContextTokens(blob: Uint8Array): number | undefined {
404
+ export function extractContextWindowMetadata(
405
+ blob: Uint8Array,
406
+ ): ContextWindowMetadata | undefined {
311
407
  if (!(blob instanceof Uint8Array) || blob.length === 0) return undefined
312
408
  return scanMessage(blob, 1, 2, (chatModel) =>
313
409
  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
- ),
410
+ scanMessage(chatStart, 10, 2, (ctxWindow) => decodeCtxWindow(ctxWindow)),
320
411
  ),
321
412
  )
322
413
  }
@@ -373,21 +464,35 @@ function resolveSessionDbPath(
373
464
  if (dbStat === 'invalid' || dbStat.isSymbolicLink() || !dbStat.isFile())
374
465
  return { kind: 'invalid' }
375
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
+
376
480
  return { kind: 'ok', dbPath }
377
481
  }
378
482
 
379
483
  /**
380
- * Read server-issued `max_context_tokens` from one ACP session's SQLite database.
484
+ * Read context window telemetry (`max_context_tokens` and `estimated_tokens_used`)
485
+ * from one ACP session's SQLite database.
381
486
  * @param home - isolated `--gemini-dir` root.
382
487
  * @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.
488
+ * @param minIdx - lowest `gen_metadata.idx` owned by the current scope.
489
+ * @returns decoded positive counts, or `undefined` when unavailable.
385
490
  */
386
- export function readSessionMaxContextTokens(
491
+ export function readSessionContextMetadata(
387
492
  home: string,
388
493
  sessionId: string,
389
494
  minIdx = 0,
390
- ): number | undefined {
495
+ ): ContextWindowMetadata | undefined {
391
496
  if (typeof minIdx !== 'number' || !Number.isSafeInteger(minIdx) || minIdx < 0)
392
497
  return undefined
393
498
  const resolved = resolveSessionDbPath(home, sessionId)
@@ -398,12 +503,28 @@ export function readSessionMaxContextTokens(
398
503
  const stmt = db.prepare(
399
504
  'SELECT data FROM gen_metadata WHERE idx >= ? ORDER BY idx DESC',
400
505
  )
506
+ let maxContextTokens: number | undefined
507
+ let estimatedTokensUsed: number | undefined
401
508
  for (const row of stmt.iterate(minIdx) as Iterable<{ data?: unknown }>) {
402
509
  if (!(row.data instanceof Uint8Array)) continue
403
- const tokens = extractMaxContextTokens(row.data)
404
- if (tokens !== undefined) return tokens
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 } : {}),
405
527
  }
406
- return undefined
407
528
  } catch {
408
529
  return undefined
409
530
  } finally {
@@ -490,6 +611,7 @@ function removeArtifacts(directory: string, names: readonly string[]): void {
490
611
  export function prepareHome(
491
612
  home: string,
492
613
  userHome: string = homedir(),
614
+ env: NodeJS.ProcessEnv = process.env,
493
615
  ): string {
494
616
  const agentDir = join(home, 'config', 'plugins', BRIDGE_AGENT, 'agents')
495
617
  mkdirSync(agentDir, { recursive: true })
@@ -531,7 +653,7 @@ export function prepareHome(
531
653
  } catch {
532
654
  // Log cleanup is best-effort when the home cannot be listed.
533
655
  }
534
- syncOAuthToken(home, userHome)
656
+ syncOAuthToken(home, userHome, env)
535
657
  const settingsPath = join(appData, 'settings.json')
536
658
  const settings = readJson(settingsPath)
537
659
  writeIfChanged(
package/src/quota.ts CHANGED
@@ -5,7 +5,16 @@
5
5
  * @module pi-agy-acp/quota
6
6
  */
7
7
 
8
- import { openSync, fstatSync, readSync, closeSync } from 'node:fs'
8
+ import {
9
+ closeSync,
10
+ fstatSync,
11
+ openSync,
12
+ readdirSync,
13
+ readSync,
14
+ realpathSync,
15
+ statSync,
16
+ } from 'node:fs'
17
+ import { isAbsolute, join, relative } from 'node:path'
9
18
  import type { CommandRunner } from './preflight.ts'
10
19
 
11
20
  /** Best-effort identity from local logs and ACP subscription metadata. */
@@ -15,26 +24,147 @@ export interface AccountInfo {
15
24
  tierId?: string
16
25
  }
17
26
 
18
- /** Read the latest login in the first matching log, bounded to its last 64 KiB. */
27
+ const LOG_SCAN_WINDOW = 64 * 1024
28
+ const MAX_ROTATED_LOGS = 10
29
+ const ROTATED_LOG_FILE = /^(?:cli|acp-server)-.+\.log$/
30
+ const AUTH_EMAIL_PATTERN =
31
+ /(?:applyAuthResult:\s*email=|OAuth:\s*authenticated successfully as\s+)([^\s,]+)/g
32
+ const AUTH_REQUIRED_STDERR = /Authentication required\b/i
33
+ const USAGE_MAX_STDOUT_BYTES = 1024 * 1024
34
+
35
+ function isContainedIn(root: string, target: string): boolean {
36
+ const rel = relative(root, target)
37
+ return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel)
38
+ }
39
+
40
+ function lastEmailInText(text: string): string | undefined {
41
+ let email: string | undefined
42
+ for (const match of text.matchAll(AUTH_EMAIL_PATTERN)) email = match[1]
43
+ return email
44
+ }
45
+
46
+ function readLoggedEmailFromFile(path: string): string | undefined {
47
+ let fd: number | undefined
48
+ try {
49
+ fd = openSync(path, 'r')
50
+ const st = fstatSync(fd)
51
+ if (!st.isFile() || st.size <= 0) return undefined
52
+ const tailSize = Math.min(st.size, LOG_SCAN_WINDOW)
53
+ const buf = Buffer.alloc(tailSize)
54
+ const tailLength = readSync(fd, buf, 0, tailSize, st.size - tailSize)
55
+ const fromTail = lastEmailInText(buf.toString('utf8', 0, tailLength))
56
+ if (fromTail) return fromTail
57
+ if (st.size > LOG_SCAN_WINDOW) {
58
+ const headLength = readSync(fd, buf, 0, LOG_SCAN_WINDOW, 0)
59
+ return lastEmailInText(buf.toString('utf8', 0, headLength))
60
+ }
61
+ } catch {
62
+ // Missing or unreadable logs do not prevent quota checks.
63
+ } finally {
64
+ if (fd !== undefined) closeSync(fd)
65
+ }
66
+ return undefined
67
+ }
68
+
69
+ interface LogCandidate {
70
+ realPath: string
71
+ mtimeMs: number
72
+ name: string
73
+ }
74
+
75
+ function resolveContainedLog(
76
+ realRoot: string,
77
+ candidatePath: string,
78
+ name: string,
79
+ ): LogCandidate | undefined {
80
+ try {
81
+ const realPath = realpathSync(candidatePath)
82
+ if (!isContainedIn(realRoot, realPath)) return undefined
83
+ const st = statSync(realPath)
84
+ if (!st.isFile()) return undefined
85
+ return { realPath, mtimeMs: st.mtimeMs, name }
86
+ } catch {
87
+ return undefined
88
+ }
89
+ }
90
+
91
+ function compareLogCandidates(a: LogCandidate, b: LogCandidate): number {
92
+ if (b.mtimeMs !== a.mtimeMs) return b.mtimeMs - a.mtimeMs
93
+ return a.name < b.name ? 1 : a.name > b.name ? -1 : 0
94
+ }
95
+
96
+ function collectDirectoryLogs(dir: string): string[] {
97
+ let realRoot: string
98
+ try {
99
+ realRoot = realpathSync(dir)
100
+ } catch {
101
+ return []
102
+ }
103
+ const rotated: LogCandidate[] = []
104
+ const logDir = join(realRoot, 'log')
105
+ try {
106
+ const realLogDir = realpathSync(logDir)
107
+ if (isContainedIn(realRoot, realLogDir) && statSync(realLogDir).isDirectory()) {
108
+ for (const name of readdirSync(realLogDir)) {
109
+ if (!ROTATED_LOG_FILE.test(name)) continue
110
+ const entry = resolveContainedLog(realRoot, join(realLogDir, name), name)
111
+ if (entry !== undefined) rotated.push(entry)
112
+ }
113
+ }
114
+ } catch {
115
+ // Missing or unreadable rotated log directory.
116
+ }
117
+ rotated.sort(compareLogCandidates)
118
+ const candidates: LogCandidate[] = rotated.slice(0, MAX_ROTATED_LOGS)
119
+ const direct = resolveContainedLog(realRoot, join(realRoot, 'cli.log'), 'cli.log')
120
+ if (direct !== undefined) candidates.push(direct)
121
+ candidates.sort(compareLogCandidates)
122
+ const seen = new Set<string>()
123
+ const unique: string[] = []
124
+ for (const item of candidates) {
125
+ if (seen.has(item.realPath)) continue
126
+ seen.add(item.realPath)
127
+ unique.push(item.realPath)
128
+ }
129
+ return unique
130
+ }
131
+
132
+ /**
133
+ * Read the latest login email across candidate log files and directories.
134
+ * Directory entries scan `cli.log` plus the newest 10 `log/cli-*.log` and
135
+ * `log/acp-server-*.log` files contained within that directory (sorted newest
136
+ * first and deduplicated). Each file scans its tail 64 KiB first, falling back
137
+ * to its head 64 KiB when larger than 64 KiB.
138
+ */
19
139
  export function readLoggedEmail(paths: readonly string[]): string | undefined {
140
+ const seen = new Set<string>()
20
141
  for (const path of paths) {
21
- let fd: number | undefined
142
+ let st
22
143
  try {
23
- fd = openSync(path, 'r')
24
- const size = fstatSync(fd).size
25
- const tail = Buffer.alloc(Math.min(size, 64 * 1024))
26
- const length = readSync(fd, tail, 0, tail.length, size - tail.length)
27
- const pattern =
28
- /(?:applyAuthResult:\s*email=|OAuth:\s*authenticated successfully as\s+)([^\s,]+)/g
29
- let email: string | undefined
30
- for (const match of tail.toString('utf8', 0, length).matchAll(pattern))
31
- email = match[1]
32
- if (email) return email
144
+ st = statSync(path)
33
145
  } catch {
34
- // Missing or unreadable logs do not prevent quota checks.
35
- } finally {
36
- if (fd !== undefined) closeSync(fd)
146
+ continue
147
+ }
148
+ if (st.isDirectory()) {
149
+ for (const filePath of collectDirectoryLogs(path)) {
150
+ if (seen.has(filePath)) continue
151
+ seen.add(filePath)
152
+ const email = readLoggedEmailFromFile(filePath)
153
+ if (email) return email
154
+ }
155
+ continue
37
156
  }
157
+ if (!st.isFile()) continue
158
+ let realPath: string
159
+ try {
160
+ realPath = realpathSync(path)
161
+ } catch {
162
+ continue
163
+ }
164
+ if (seen.has(realPath)) continue
165
+ seen.add(realPath)
166
+ const email = readLoggedEmailFromFile(realPath)
167
+ if (email) return email
38
168
  }
39
169
  return undefined
40
170
  }
@@ -159,7 +289,24 @@ export class QuotaReader {
159
289
  const result = await this.run(
160
290
  [binary, '-p', '/usage', '--output-format', 'json'],
161
291
  45_000,
292
+ {
293
+ maxStdoutBytes: USAGE_MAX_STDOUT_BYTES,
294
+ abortOnStderr: AUTH_REQUIRED_STDERR,
295
+ },
162
296
  )
297
+ if (
298
+ result.abortedBy === 'stderr' ||
299
+ AUTH_REQUIRED_STDERR.test(result.stderr)
300
+ ) {
301
+ throw new Error(
302
+ 'Antigravity requires sign-in: run `agy` once in a terminal (Authentication required)',
303
+ )
304
+ }
305
+ if (result.abortedBy === 'maxStdout') {
306
+ throw new Error(
307
+ `agy /usage stdout exceeded ${USAGE_MAX_STDOUT_BYTES} bytes`,
308
+ )
309
+ }
163
310
  if (result.code !== 0)
164
311
  throw new Error(
165
312
  `agy /usage failed (exit ${result.code}): ${result.stderr.trim() || result.stdout.trim()}`,