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/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()}`,