pi-agy-acp 0.2.3 → 0.2.5

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.
@@ -730,25 +730,87 @@ function accumulateRawUsage(
730
730
  }
731
731
  }
732
732
 
733
+ function nonNegativeInt(value: number | undefined): number {
734
+ return value !== undefined && Number.isFinite(value)
735
+ ? Math.max(0, Math.round(value))
736
+ : 0
737
+ }
738
+
739
+ function positiveInt(value: number | undefined): number | undefined {
740
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
741
+ ? Math.round(value)
742
+ : undefined
743
+ }
744
+
745
+ function promptBuckets(
746
+ usage: NonNullable<AcpPromptResult['usage']>,
747
+ ): [number, number, number] {
748
+ return [
749
+ nonNegativeInt(usage.inputTokens),
750
+ nonNegativeInt(usage.cachedReadTokens),
751
+ nonNegativeInt(usage.cachedWriteTokens),
752
+ ]
753
+ }
754
+
733
755
  /**
734
- * Map accumulated ACP turn usage into Pi token usage.
756
+ * Proportionally cap prompt buckets (`input`, `cacheRead`, `cacheWrite`) to
757
+ * `cap` using largest-remainder allocation so their sum never exceeds `cap`,
758
+ * cache-hit ratios stay accurate, and zero buckets stay zero.
759
+ */
760
+ function capPromptBuckets(
761
+ buckets: readonly [number, number, number],
762
+ cap: number,
763
+ ): [number, number, number] {
764
+ const [input, cacheRead, cacheWrite] = buckets
765
+ const sum = input + cacheRead + cacheWrite
766
+ if (sum <= cap || sum === 0) return [input, cacheRead, cacheWrite]
767
+ if (cap <= 0) return [0, 0, 0]
768
+ const exact: [number, number, number] = [
769
+ (input / sum) * cap,
770
+ (cacheRead / sum) * cap,
771
+ (cacheWrite / sum) * cap,
772
+ ]
773
+ const floors: [number, number, number] = [
774
+ Math.min(input, Math.floor(exact[0])),
775
+ Math.min(cacheRead, Math.floor(exact[1])),
776
+ Math.min(cacheWrite, Math.floor(exact[2])),
777
+ ]
778
+ let remaining = cap - (floors[0] + floors[1] + floors[2])
779
+ const order = ([0, 1, 2] as const)
780
+ .slice()
781
+ .sort((a, b) => exact[b] - floors[b] - (exact[a] - floors[a]))
782
+ for (const idx of order) {
783
+ if (remaining <= 0) break
784
+ if (floors[idx] >= buckets[idx]) continue
785
+ floors[idx] += 1
786
+ remaining -= 1
787
+ }
788
+ return floors
789
+ }
790
+
791
+ /**
792
+ * Map accumulated ACP turn usage into Pi single-call token usage.
735
793
  *
736
- * Consumption buckets (`inputTokens`, `outputTokens`, `cacheReadTokens`,
737
- * `cacheWriteTokens`, `reasoningTokens`) stay unscaled cumulative turn totals
738
- * because intermediate `toolUse` steps emit zero usage and Pi sums those
739
- * buckets across steps for session accounting and flat pricing overrides.
794
+ * Pi's `AssistantMessage.usage` represents one model call: `isContextOverflow()`
795
+ * checks `input + cacheRead` against `contextWindow` even on successful `stop`
796
+ * turns, while `calculateContextTokens()` reads `totalTokens`. Raw cumulative
797
+ * multi-call ACP usage therefore stays on `turn.usage` (`RuntimeStatus.lastTurn`),
798
+ * while prompt buckets (`inputTokens`, `cacheReadTokens`, `cacheWriteTokens`)
799
+ * emitted to Pi are normalized to the final call's prompt occupancy (preserving
800
+ * cache-hit ratios and leaving single-call turns untouched). `outputTokens` and
801
+ * `reasoningTokens` remain cumulative turn totals.
740
802
  *
741
- * `totalTokens` feeds Pi's `calculateContextTokens` / ContextMeter / compaction
742
- * threshold as final-call context occupancy: when `options.contextTokens`
743
- * (from live `usage_update.used`) is positive, it is used directly; otherwise
744
- * final-segment prompt buckets are normalized by `calls` and added to final-
745
- * segment output tokens.
803
+ * `totalTokens` resolves final-call context occupancy in priority order:
804
+ * 1. Positive live `options.contextTokens` (`usage_update.used`).
805
+ * 2. Positive `options.estimatedContextTokens` (same-turn `gen_metadata`).
806
+ * 3. Final-segment average prompt tokens divided by `calls`, plus final-segment
807
+ * output tokens.
746
808
  *
747
809
  * `agy acp` reports `inputTokens` as uncached input only, disjoint from
748
810
  * `cachedReadTokens` and `cachedWriteTokens`.
749
811
  * @param usage - accumulated turn usage.
750
812
  * @param calls - model calls inside the final `session/prompt` segment (>= 1).
751
- * @param options - optional live `usage_update` count and final segment usage.
813
+ * @param options - optional live `usage_update` count, metadata estimate, and final segment usage.
752
814
  * @returns Pi usage.
753
815
  */
754
816
  export function toTokenUsage(
@@ -757,48 +819,40 @@ export function toTokenUsage(
757
819
  options?: TokenUsageOptions,
758
820
  ): TokenUsage | undefined {
759
821
  if (usage === undefined) return undefined
760
- const input = Math.max(0, Math.round(usage.inputTokens ?? 0))
761
- const cacheRead = Math.max(0, Math.round(usage.cachedReadTokens ?? 0))
762
- const cacheWrite = Math.max(0, Math.round(usage.cachedWriteTokens ?? 0))
763
- const output = Math.max(0, Math.round(usage.outputTokens ?? 0))
822
+ const output = nonNegativeInt(usage.outputTokens)
764
823
  const reasoning =
765
- usage.thoughtTokens !== undefined && usage.thoughtTokens > 0
824
+ usage.thoughtTokens !== undefined &&
825
+ Number.isFinite(usage.thoughtTokens) &&
826
+ usage.thoughtTokens > 0
766
827
  ? Math.min(output, Math.round(usage.thoughtTokens))
767
828
  : undefined
768
- const liveContext = options?.contextTokens
769
- const estimatedContext = options?.estimatedContextTokens
829
+ const seg = options?.lastSegmentUsage ?? usage
830
+ const segBuckets = promptBuckets(seg)
831
+ const segPromptSum = segBuckets[0] + segBuckets[1] + segBuckets[2]
832
+ const promptSource = segPromptSum > 0 ? seg : usage
833
+ const rawPrompt = segPromptSum > 0 ? segBuckets : promptBuckets(usage)
834
+
835
+ const liveContext =
836
+ positiveInt(options?.contextTokens) ??
837
+ positiveInt(options?.estimatedContextTokens)
838
+ let promptCap: number
770
839
  let totalTokens: number
771
- if (
772
- typeof liveContext === 'number' &&
773
- Number.isFinite(liveContext) &&
774
- liveContext > 0
775
- ) {
776
- totalTokens = Math.round(liveContext)
777
- } else if (
778
- typeof estimatedContext === 'number' &&
779
- Number.isFinite(estimatedContext) &&
780
- estimatedContext > 0
781
- ) {
782
- totalTokens = Math.round(estimatedContext)
840
+ if (liveContext !== undefined) {
841
+ promptCap = liveContext
842
+ totalTokens = liveContext
783
843
  } else {
784
- const seg = options?.lastSegmentUsage ?? usage
785
844
  const scale = Math.max(1, calls)
786
- const segPrompt = Math.max(
787
- 0,
788
- Math.round(
789
- ((seg.inputTokens ?? 0) +
790
- (seg.cachedReadTokens ?? 0) +
791
- (seg.cachedWriteTokens ?? 0)) /
792
- scale,
793
- ),
794
- )
795
- const segOutput = Math.max(0, Math.round(seg.outputTokens ?? 0))
796
- totalTokens = segPrompt + segOutput
845
+ promptCap = Math.max(0, Math.round(segPromptSum / scale))
846
+ totalTokens = promptCap + nonNegativeInt(seg.outputTokens)
797
847
  }
848
+
849
+ const [input, cacheRead, cacheWrite] = capPromptBuckets(rawPrompt, promptCap)
798
850
  return {
799
851
  inputTokens: input,
800
852
  outputTokens: output,
801
- ...(usage.cachedReadTokens !== undefined || cacheRead > 0
853
+ ...(promptSource.cachedReadTokens !== undefined ||
854
+ usage.cachedReadTokens !== undefined ||
855
+ cacheRead > 0
802
856
  ? { cacheReadTokens: cacheRead }
803
857
  : {}),
804
858
  ...(cacheWrite > 0 ? { cacheWriteTokens: cacheWrite } : {}),
@@ -1057,7 +1111,7 @@ async function* stepChunks(
1057
1111
  * @param call - the still-running call.
1058
1112
  * @returns MCP result instructing the agent to keep waiting.
1059
1113
  */
1060
- export function relayNotice(call: ParkedCall): BridgeToolResult {
1114
+ function relayNotice(call: ParkedCall): BridgeToolResult {
1061
1115
  return {
1062
1116
  content: [
1063
1117
  {
package/src/history.ts CHANGED
@@ -212,7 +212,7 @@ function renderBlocks(content: readonly ContentBlock[]): string {
212
212
  * @param content - user content blocks.
213
213
  * @returns prompt blocks in content order.
214
214
  */
215
- export function promptBlocks(
215
+ function promptBlocks(
216
216
  content: readonly ContentBlock[],
217
217
  ): AcpPromptBlock[] {
218
218
  const blocks: AcpPromptBlock[] = []
@@ -221,9 +221,6 @@ export function promptBlocks(
221
221
  if (block.text.length > 0) blocks.push({ type: 'text', text: block.text })
222
222
  } else if (block.type === 'image') {
223
223
  blocks.push({ type: 'image', data: block.data, mimeType: block.mimeType })
224
- } else {
225
- const text = renderBlocks([block])
226
- if (text.length > 0) blocks.push({ type: 'text', text })
227
224
  }
228
225
  }
229
226
  return blocks
package/src/host.ts CHANGED
@@ -21,6 +21,8 @@ const FORCED_AGY_ENV_KEYS_LOWER = new Set([
21
21
  'agy_cli_disable_auto_update',
22
22
  'pythonunbuffered',
23
23
  ])
24
+ const AUTO_COMPACT_OVERRIDE_KEY = 'AGY_CLI_AUTO_COMPACT_OVERRIDE'
25
+ const AUTO_COMPACT_OVERRIDE_KEY_LOWER = AUTO_COMPACT_OVERRIDE_KEY.toLowerCase()
24
26
 
25
27
  /** Build a sanitized environment for spawning `agy` subprocesses. */
26
28
  export function buildAgyEnv(
@@ -29,6 +31,7 @@ export function buildAgyEnv(
29
31
  ): NodeJS.ProcessEnv {
30
32
  const env: NodeJS.ProcessEnv = {}
31
33
  const caseInsensitive = platform === 'win32'
34
+ let hasAutoCompactOverride = false
32
35
  for (const [key, value] of Object.entries(baseEnv)) {
33
36
  if (value === undefined) continue
34
37
  if (caseInsensitive) {
@@ -38,13 +41,24 @@ export function buildAgyEnv(
38
41
  FORCED_AGY_ENV_KEYS_LOWER.has(lower)
39
42
  )
40
43
  continue
41
- } else if (STRIPPED_AGY_ENV_KEYS.has(key)) {
42
- continue
44
+ if (lower === AUTO_COMPACT_OVERRIDE_KEY_LOWER) {
45
+ hasAutoCompactOverride = true
46
+ }
47
+ } else {
48
+ if (STRIPPED_AGY_ENV_KEYS.has(key)) continue
49
+ if (key === AUTO_COMPACT_OVERRIDE_KEY) {
50
+ hasAutoCompactOverride = true
51
+ }
43
52
  }
44
53
  env[key] = value
45
54
  }
46
55
  env.AGY_CLI_DISABLE_AUTO_UPDATE = '1'
47
56
  env.PYTHONUNBUFFERED = '1'
57
+ // Keep agy's internal auto-compaction at the highest valid threshold so Pi
58
+ // owns compaction unless the user explicitly sets AGY_CLI_AUTO_COMPACT_OVERRIDE.
59
+ if (!hasAutoCompactOverride) {
60
+ env[AUTO_COMPACT_OVERRIDE_KEY] = '100%'
61
+ }
48
62
  return env
49
63
  }
50
64
 
package/src/jsonrpc.ts CHANGED
@@ -188,6 +188,7 @@ export class JsonRpcPeer {
188
188
  }
189
189
 
190
190
  private write(message: unknown): void {
191
+ if (this.closed !== undefined) return
191
192
  try {
192
193
  this.output.write(`${JSON.stringify(message)}\n`)
193
194
  } catch (error) {
package/src/mcp-bridge.ts CHANGED
@@ -104,6 +104,7 @@ export class McpBridge {
104
104
  private server: Server | undefined
105
105
  private port = 0
106
106
  private readonly openResponses = new Set<ServerResponse>()
107
+ private readonly pendingCloses = new Set<Promise<void>>()
107
108
  /** Tenant keys whose agent completed the MCP `initialize` handshake. */
108
109
  private readonly handshakes = new Set<string>()
109
110
  private readonly router: BridgeRouter
@@ -178,12 +179,19 @@ export class McpBridge {
178
179
  for (const res of this.openResponses) res.destroy()
179
180
  this.openResponses.clear()
180
181
  this.handshakes.clear()
181
- if (server !== undefined)
182
- await new Promise<void>((resolve) => {
182
+ if (server !== undefined) {
183
+ const closing = new Promise<void>((resolve) => {
183
184
  server.close(() => resolve())
184
185
  // Node's closeAllConnections includes parsers with incomplete headers/bodies.
185
186
  server.closeAllConnections()
187
+ }).finally(() => {
188
+ this.pendingCloses.delete(closing)
186
189
  })
190
+ this.pendingCloses.add(closing)
191
+ }
192
+ if (this.pendingCloses.size > 0) {
193
+ await Promise.all([...this.pendingCloses])
194
+ }
187
195
  }
188
196
 
189
197
  /**
@@ -415,36 +423,39 @@ export class McpBridge {
415
423
  return finalResult
416
424
  }
417
425
 
418
- let result: BridgeToolResult
419
426
  try {
420
- result = await this.router.callTool({
421
- tenantKey,
422
- conversationId,
423
- name,
424
- arguments: args,
425
- signal: controller.signal,
426
- commit,
427
- })
428
- } catch (error) {
429
- result = {
430
- content: [
431
- {
432
- type: 'text',
433
- text: error instanceof Error ? error.message : String(error),
434
- },
435
- ],
436
- isError: true,
427
+ let result: BridgeToolResult
428
+ try {
429
+ result = await this.router.callTool({
430
+ tenantKey,
431
+ conversationId,
432
+ name,
433
+ arguments: args,
434
+ signal: controller.signal,
435
+ commit,
436
+ })
437
+ } catch (error) {
438
+ result = {
439
+ content: [
440
+ {
441
+ type: 'text',
442
+ text: error instanceof Error ? error.message : String(error),
443
+ },
444
+ ],
445
+ isError: true,
446
+ }
447
+ } finally {
448
+ settled = true
449
+ clearInterval(keepAlive)
450
+ }
451
+ if (!wroteResponse && !res.writableEnded && !res.destroyed) {
452
+ writeEvent(res, { jsonrpc: '2.0', id: request.id, result })
453
+ res.end()
437
454
  }
438
455
  } finally {
439
- settled = true
440
- clearInterval(keepAlive)
441
- }
442
- if (!wroteResponse && !res.writableEnded && !res.destroyed) {
443
- writeEvent(res, { jsonrpc: '2.0', id: request.id, result })
444
- res.end()
456
+ this.openResponses.delete(res)
457
+ res.off('close', onClose)
445
458
  }
446
- this.openResponses.delete(res)
447
- res.off('close', onClose)
448
459
  if (controller.signal.aborted)
449
460
  this.log(
450
461
  `mcp: call ${name} finished after the agent disconnected`,
package/src/pi-stream.ts CHANGED
@@ -183,12 +183,33 @@ export function streamPi(
183
183
  'INVALID_PAYLOAD',
184
184
  )
185
185
  }
186
+ if (
187
+ candidate.system !== undefined &&
188
+ typeof candidate.system !== 'string'
189
+ ) {
190
+ throw new LlmError(
191
+ 'onPayload replacement system must be a string when provided',
192
+ 'INVALID_PAYLOAD',
193
+ )
194
+ }
195
+ if (
196
+ candidate.reasoningEffort !== undefined &&
197
+ typeof candidate.reasoningEffort !== 'string'
198
+ ) {
199
+ throw new LlmError(
200
+ 'onPayload replacement reasoningEffort must be a string when provided',
201
+ 'INVALID_PAYLOAD',
202
+ )
203
+ }
186
204
  request = {
187
- ...(candidate as unknown as GenerateOptions),
205
+ model: candidate.model,
206
+ messages: candidate.messages as GenerateOptions['messages'],
207
+ system: candidate.system,
188
208
  tools:
189
209
  candidate.tools === undefined
190
210
  ? request.tools
191
211
  : (candidate.tools as GenerateOptions['tools']),
212
+ reasoningEffort: candidate.reasoningEffort,
192
213
  sessionId: options.sessionId,
193
214
  signal: options.signal,
194
215
  }
package/src/preflight.ts CHANGED
@@ -8,42 +8,33 @@
8
8
  * @module pi-agy-acp/preflight
9
9
  */
10
10
 
11
- import { randomBytes } from 'node:crypto'
12
11
  import {
13
12
  accessSync,
14
- chmodSync,
15
13
  closeSync,
16
14
  constants as fsConstants,
17
15
  fstatSync,
18
16
  mkdirSync,
19
17
  openSync,
20
- writeFileSync,
21
18
  readFileSync,
22
19
  realpathSync,
23
- renameSync,
24
20
  statSync,
25
21
  lstatSync,
26
22
  readdirSync,
27
- unlinkSync,
28
23
  type BigIntStats,
29
24
  type Stats,
30
25
  } from 'node:fs'
31
26
  import { homedir } from 'node:os'
32
- import {
33
- basename,
34
- delimiter,
35
- dirname,
36
- isAbsolute,
37
- join,
38
- resolve,
39
- } from 'node:path'
27
+ import { delimiter, isAbsolute, join, resolve } from 'node:path'
40
28
  import { readJson } from './config.ts'
41
29
  import { removeArtifacts } from './session-db.ts'
30
+ import { atomicWriteFile } from './util.ts'
31
+
32
+ export { atomicWriteFile }
42
33
 
43
34
  /** Agent id installed in the isolated home. */
44
35
  export const BRIDGE_AGENT = 'pi-bridge'
45
- /** Minimum official CLI version supported (`agy 1.5.10+`). */
46
- export const MIN_AGY_VERSION: readonly [number, number, number] = [1, 5, 10]
36
+ /** Minimum official CLI version supported (`agy 1.5.18+`). */
37
+ export const MIN_AGY_VERSION: readonly [number, number, number] = [1, 5, 18]
47
38
 
48
39
  /** Output of one finished helper command. */
49
40
  export interface CommandOutput {
@@ -183,7 +174,7 @@ export function resolveAgyBinary(
183
174
  )
184
175
  if (found === undefined) {
185
176
  throw new Error(
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`',
177
+ '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` (or `agy acp --login` for headless/SSH setups)',
187
178
  )
188
179
  }
189
180
  return found
@@ -324,73 +315,6 @@ function ensureRealDirectory(
324
315
  return current
325
316
  }
326
317
 
327
- /**
328
- * Atomically write a regular file in the target directory while rejecting
329
- * symlinked or non-regular destination paths.
330
- */
331
- export function atomicWriteFile(
332
- path: string,
333
- content: string | Uint8Array,
334
- options?: { mode?: number },
335
- ): void {
336
- let existing: Stats | undefined
337
- try {
338
- existing = lstatSync(path)
339
- } catch (error) {
340
- if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error
341
- }
342
- if (
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`,
353
- )
354
- const mode = options?.mode
355
- let fd: number | undefined
356
- let created = false
357
- try {
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
- }
389
- }
390
- throw error
391
- }
392
- }
393
-
394
318
  /**
395
319
  * Seed or refresh the isolated `antigravity-oauth-token` file from the user's
396
320
  * Antigravity CLI home (`ANTIGRAVITY_CLI_HOME`, `AGY_HOME`, or
@@ -499,10 +423,19 @@ export function syncOAuthToken(
499
423
  }
500
424
  }
501
425
 
426
+ /** Optional controls for isolated home preparation. */
427
+ export interface PrepareHomeOptions {
428
+ /** Remove stale ACP conversation/brain/annotation artifacts and rotated logs. Defaults to `true`. */
429
+ cleanArtifacts?: boolean
430
+ }
431
+
502
432
  /**
503
433
  * Write the isolated Antigravity home: bridge agent and ACP settings.
504
434
  * @param home - absolute home directory used as `--gemini-dir`.
505
435
  * @param userHome - optional user home override for testing.
436
+ * @param env - optional environment override for testing.
437
+ * @param onWarn - optional warning callback for non-fatal OAuth sync issues.
438
+ * @param options - optional preparation controls.
506
439
  * @returns the empty workspace directory used as every session's cwd.
507
440
  */
508
441
  export function prepareHome(
@@ -510,6 +443,7 @@ export function prepareHome(
510
443
  userHome: string = homedir(),
511
444
  env: NodeJS.ProcessEnv = process.env,
512
445
  onWarn?: (message: string) => void,
446
+ options: PrepareHomeOptions = {},
513
447
  ): string {
514
448
  const pluginDir = ensureRealDirectory(home, [
515
449
  'config',
@@ -536,25 +470,27 @@ export function prepareHome(
536
470
  ].join('\n'),
537
471
  )
538
472
  const appData = ensureRealDirectory(home, ['agy'])
539
- // Pi owns conversation history; no ACP session is restored across processes.
540
- // shortcut: cleanup requires an exclusive home; add locking before supporting shared homes.
541
- removeArtifacts(appData, [
542
- 'conversations',
543
- 'brain',
544
- 'annotations',
545
- 'conversation_summaries.db',
546
- 'conversation_summaries.db-wal',
547
- 'conversation_summaries.db-shm',
548
- 'conversation_summaries.db-journal',
549
- 'jetbox_summaries_proto.pb',
550
- ])
551
- try {
552
- removeArtifacts(
553
- home,
554
- readdirSync(home).filter((name) => /^acp\.log\.\d+$/.test(name)),
555
- )
556
- } catch {
557
- // Log cleanup is best-effort when the home cannot be listed.
473
+ if (options.cleanArtifacts !== false) {
474
+ // Pi owns conversation history; cold startup cleans stale ACP artifacts from prior processes.
475
+ // shortcut: cleanup requires an exclusive home; add locking before supporting shared homes.
476
+ removeArtifacts(appData, [
477
+ 'conversations',
478
+ 'brain',
479
+ 'annotations',
480
+ 'conversation_summaries.db',
481
+ 'conversation_summaries.db-wal',
482
+ 'conversation_summaries.db-shm',
483
+ 'conversation_summaries.db-journal',
484
+ 'jetbox_summaries_proto.pb',
485
+ ])
486
+ try {
487
+ removeArtifacts(
488
+ home,
489
+ readdirSync(home).filter((name) => /^acp\.log\.\d+$/.test(name)),
490
+ )
491
+ } catch {
492
+ // Log cleanup is best-effort when the home cannot be listed.
493
+ }
558
494
  }
559
495
  try {
560
496
  syncOAuthToken(home, userHome, env)
package/src/quota.ts CHANGED
@@ -221,26 +221,33 @@ function parseBucket(raw: unknown): QuotaBucket | undefined {
221
221
  * @returns the quota groups.
222
222
  */
223
223
  export function parseUsage(stdout: string): QuotaGroup[] {
224
- const parsed = JSON.parse(stdout) as {
225
- command?: { data?: { groups?: unknown[] } }
226
- }
227
- const groups = parsed.command?.data?.groups
224
+ const parsed: unknown = JSON.parse(stdout)
225
+ const command =
226
+ parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
227
+ ? (parsed as { command?: unknown }).command
228
+ : undefined
229
+ const data =
230
+ command !== null && typeof command === 'object' && !Array.isArray(command)
231
+ ? (command as { data?: unknown }).data
232
+ : undefined
233
+ const groups =
234
+ data !== null && typeof data === 'object' && !Array.isArray(data)
235
+ ? (data as { groups?: unknown }).groups
236
+ : undefined
228
237
  if (!Array.isArray(groups))
229
238
  throw new Error('agy /usage returned no quota groups')
230
- return groups.map((raw) => {
231
- const group = raw as {
232
- name?: string
233
- description?: string
234
- buckets?: unknown[]
235
- }
236
- return {
239
+ return groups
240
+ .filter(
241
+ (raw): raw is Record<string, unknown> =>
242
+ raw !== null && typeof raw === 'object' && !Array.isArray(raw),
243
+ )
244
+ .map((group) => ({
237
245
  name: String(group.name ?? ''),
238
246
  description: String(group.description ?? ''),
239
247
  buckets: (Array.isArray(group.buckets) ? group.buckets : [])
240
248
  .map(parseBucket)
241
249
  .filter((bucket): bucket is QuotaBucket => bucket !== undefined),
242
- }
243
- })
250
+ }))
244
251
  }
245
252
 
246
253
  /** Cached quota reader with request coalescing. */
@@ -280,10 +287,6 @@ export class QuotaReader {
280
287
  : undefined
281
288
  }
282
289
 
283
- get pending(): boolean {
284
- return this.inflight !== undefined
285
- }
286
-
287
290
  /**
288
291
  * Read the quota snapshot.
289
292
  * @param force - bypass the cache.
@@ -318,7 +321,7 @@ export class QuotaReader {
318
321
  AUTH_REQUIRED_STDERR.test(result.stderr)
319
322
  ) {
320
323
  throw new Error(
321
- 'Antigravity requires sign-in: run `agy` once in a terminal (Authentication required)',
324
+ 'Antigravity requires sign-in: run `agy` once in a terminal or `agy acp --login` for headless/SSH setups (Authentication required)',
322
325
  )
323
326
  }
324
327
  if (result.abortedBy === 'maxStdout') {