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/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
143
+ try {
144
+ st = statSync(path)
145
+ } catch {
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
156
+ }
157
+ if (!st.isFile()) continue
158
+ let realPath: string
22
159
  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
160
+ realPath = realpathSync(path)
33
161
  } catch {
34
- // Missing or unreadable logs do not prevent quota checks.
35
- } finally {
36
- if (fd !== undefined) closeSync(fd)
162
+ continue
37
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
  }
@@ -64,6 +194,27 @@ export interface QuotaSnapshot {
64
194
  account?: AccountInfo
65
195
  }
66
196
 
197
+ function parseBucket(raw: unknown): QuotaBucket | undefined {
198
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
199
+ return undefined
200
+ const bucket = raw as Record<string, unknown>
201
+ if (bucket.disabled === true) return undefined
202
+ const id = String(bucket.id ?? '').trim()
203
+ const window = String(bucket.window ?? '').trim()
204
+ if (id.length === 0 || window.length === 0) return undefined
205
+ return {
206
+ id,
207
+ name: String(bucket.name ?? ''),
208
+ window,
209
+ remainingFraction:
210
+ typeof bucket.remaining_fraction === 'number' &&
211
+ Number.isFinite(bucket.remaining_fraction)
212
+ ? bucket.remaining_fraction
213
+ : undefined,
214
+ resetTime: String(bucket.reset_time ?? ''),
215
+ }
216
+ }
217
+
67
218
  /**
68
219
  * Parse `agy -p /usage --output-format json` output.
69
220
  * @param stdout - command stdout.
@@ -85,20 +236,9 @@ export function parseUsage(stdout: string): QuotaGroup[] {
85
236
  return {
86
237
  name: String(group.name ?? ''),
87
238
  description: String(group.description ?? ''),
88
- buckets: (Array.isArray(group.buckets) ? group.buckets : []).map((b) => {
89
- const bucket = b as Record<string, unknown>
90
- return {
91
- id: String(bucket.id ?? ''),
92
- name: String(bucket.name ?? ''),
93
- window: String(bucket.window ?? ''),
94
- remainingFraction:
95
- typeof bucket.remaining_fraction === 'number' &&
96
- Number.isFinite(bucket.remaining_fraction)
97
- ? bucket.remaining_fraction
98
- : undefined,
99
- resetTime: String(bucket.reset_time ?? ''),
100
- }
101
- }),
239
+ buckets: (Array.isArray(group.buckets) ? group.buckets : [])
240
+ .map(parseBucket)
241
+ .filter((bucket): bucket is QuotaBucket => bucket !== undefined),
102
242
  }
103
243
  })
104
244
  }
@@ -106,27 +246,36 @@ export function parseUsage(stdout: string): QuotaGroup[] {
106
246
  /** Cached quota reader with request coalescing. */
107
247
  export class QuotaReader {
108
248
  private cached: QuotaSnapshot | undefined
109
- private cachedAt = 0
249
+ // Monotonic `performance.now()` starts near 0, so `-Infinity` guarantees an empty cache is never fresh.
250
+ private cachedAt = -Infinity
110
251
  private inflight: Promise<QuotaSnapshot> | undefined
111
252
  private readonly binary: () => string
112
253
  private readonly run: CommandRunner
113
254
  private readonly ttlMs: number
255
+ private readonly now: () => number
114
256
 
115
257
  /**
116
258
  * @param binary - returns the agy executable.
117
259
  * @param run - helper command runner.
118
260
  * @param ttlMs - cache lifetime.
261
+ * @param now - monotonic clock in milliseconds.
119
262
  */
120
- constructor(binary: () => string, run: CommandRunner, ttlMs: number) {
263
+ constructor(
264
+ binary: () => string,
265
+ run: CommandRunner,
266
+ ttlMs: number,
267
+ now: () => number = () => performance.now(),
268
+ ) {
121
269
  this.binary = binary
122
270
  this.run = run
123
271
  this.ttlMs = ttlMs
272
+ this.now = now
124
273
  }
125
274
 
126
275
  /** Fresh successful data only; never starts a command. */
127
276
  peek(): QuotaSnapshot | undefined {
128
277
  return this.cached?.status === 'ok' &&
129
- Date.now() - this.cachedAt < this.ttlMs
278
+ this.now() - this.cachedAt < this.ttlMs
130
279
  ? this.cached
131
280
  : undefined
132
281
  }
@@ -144,7 +293,7 @@ export class QuotaReader {
144
293
  if (
145
294
  !force &&
146
295
  this.cached !== undefined &&
147
- Date.now() - this.cachedAt < this.ttlMs
296
+ this.now() - this.cachedAt < this.ttlMs
148
297
  )
149
298
  return this.cached
150
299
  this.inflight ??= this.fetch().finally(() => {
@@ -159,7 +308,24 @@ export class QuotaReader {
159
308
  const result = await this.run(
160
309
  [binary, '-p', '/usage', '--output-format', 'json'],
161
310
  45_000,
311
+ {
312
+ maxStdoutBytes: USAGE_MAX_STDOUT_BYTES,
313
+ abortOnStderr: AUTH_REQUIRED_STDERR,
314
+ },
162
315
  )
316
+ if (
317
+ result.abortedBy === 'stderr' ||
318
+ AUTH_REQUIRED_STDERR.test(result.stderr)
319
+ ) {
320
+ throw new Error(
321
+ 'Antigravity requires sign-in: run `agy` once in a terminal (Authentication required)',
322
+ )
323
+ }
324
+ if (result.abortedBy === 'maxStdout') {
325
+ throw new Error(
326
+ `agy /usage stdout exceeded ${USAGE_MAX_STDOUT_BYTES} bytes`,
327
+ )
328
+ }
163
329
  if (result.code !== 0)
164
330
  throw new Error(
165
331
  `agy /usage failed (exit ${result.code}): ${result.stderr.trim() || result.stdout.trim()}`,
@@ -170,7 +336,7 @@ export class QuotaReader {
170
336
  groups: parseUsage(result.stdout),
171
337
  }
172
338
  this.cached = snapshot
173
- this.cachedAt = Date.now()
339
+ this.cachedAt = this.now()
174
340
  return snapshot
175
341
  } catch (error) {
176
342
  const snapshot: QuotaSnapshot = {
@@ -181,7 +347,7 @@ export class QuotaReader {
181
347
  }
182
348
  // Apply the same TTL to failures so settled events cannot hammer an unavailable CLI.
183
349
  this.cached = snapshot
184
- this.cachedAt = Date.now()
350
+ this.cachedAt = this.now()
185
351
  return snapshot
186
352
  }
187
353
  }