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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.5](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.4...v0.2.5) (2026-11-28)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **usage:** cap Pi prompt usage buckets to single-call occupancy ([#57](https://github.com/fdkevin0/pi-agy-acp/issues/57)) ([74a3e2e](https://github.com/fdkevin0/pi-agy-acp/commit/74a3e2e6887f9ee6cbadb17339f5537b340dfe80)), closes [#47](https://github.com/fdkevin0/pi-agy-acp/issues/47)
9
+
10
+ ## [0.2.4](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.3...v0.2.4) (2026-11-26)
11
+
12
+
13
+ ### Features
14
+
15
+ * default AGY_CLI_AUTO_COMPACT_OVERRIDE=100% and idle session/resume ([#54](https://github.com/fdkevin0/pi-agy-acp/issues/54)) ([bf7c1f4](https://github.com/fdkevin0/pi-agy-acp/commit/bf7c1f45eb19d39b2a1c1fcf56fdbfa756187ab2))
16
+ * **preflight:** raise agy minimum to 1.5.18, add headless login hints, and sync 1.5.18 fixtures ([#48](https://github.com/fdkevin0/pi-agy-acp/issues/48)) ([fe3b58e](https://github.com/fdkevin0/pi-agy-acp/commit/fe3b58e2c7f1a3782ca6e4512e0560a72b6e11e4))
17
+
18
+
19
+ ### Bug Fixes
20
+
21
+ * **runtime:** classify hidden 400 INVALID_ARGUMENT and billing/prepaid quota errors ([#50](https://github.com/fdkevin0/pi-agy-acp/issues/50)) ([d0ddc3d](https://github.com/fdkevin0/pi-agy-acp/commit/d0ddc3d8d426049bd7e36f7d437d3cb33b1aa241))
22
+
3
23
  ## [0.2.3](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.2...v0.2.3) (2026-11-23)
4
24
 
5
25
 
package/README.md CHANGED
@@ -12,8 +12,9 @@ parallel tool calls.
12
12
 
13
13
  - Node.js >= 22.19.0.
14
14
  - Pi (`@earendil-works/pi-coding-agent`) 1.5.x.
15
- - The official `agy` CLI >= 1.5.10, signed in with your Google account.
16
- Run `agy` in your terminal to complete sign-in before using the extension.
15
+ - The official `agy` CLI >= 1.5.18, signed in with your Google account.
16
+ Run `agy` (or `agy acp --login` in headless/SSH terminals) to complete sign-in
17
+ before using the extension.
17
18
 
18
19
  ## Install
19
20
 
@@ -21,6 +21,7 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
21
21
  | --- | --- |
22
22
  | `initialize` | 120 s |
23
23
  | `session/new` | 120 s |
24
+ | `session/resume` | 120 s |
24
25
  | `session/set_config_option` | 60 s |
25
26
  | `session/close` | 15 s |
26
27
  | `session/prompt` | None (bounded by turn/abort lifecycle) |
@@ -92,7 +93,8 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
92
93
  `tier`, `contextWindows`, and the subprocess-free binary fingerprint
93
94
  (`${realpath}:${dev}:${ino}:${size}:${mtimeNs}`).
94
95
  - Both `agy --version` (30 s timeout) and ACP `initialize` (`agentInfo.version`)
95
- enforce `MIN_AGY_VERSION` (`1.5.10`).
96
+ enforce `MIN_AGY_VERSION` (`1.5.18`, which adds long-turn OAuth/503 recovery
97
+ and fixes Windows cross-drive plugin loading).
96
98
  - Non-forced refreshes reuse `catalog.json` without spawning `agy` whenever
97
99
  cached models match the current binary fingerprint. Loading a cache with a
98
100
  mismatched fingerprint drops cached `contextWindows` while keeping models
@@ -116,12 +118,23 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
116
118
  first and failing fast with `CAPACITY_EXCEEDED` (`RATE_LIMIT`) to avoid
117
119
  parent/subagent deadlocks. Requests without a `sessionId` use ephemeral
118
120
  `anon-*` keys torn down immediately after each idle step.
119
- - **Idle sweeper:** Runs every 60 s (`.unref()`) with a monotonic delta capped
120
- at 120 s per tick for sleep resilience. Idle conversations expire after
121
- `idleSessionTtlMs` (30 min); once no live sessions or in-flight streams remain
122
- and the front has been idle past `idleSessionTtlMs`, the sweeper stops the
123
- ACP process, MCP bridge, and itself (waiting for evicted sessions to close
124
- first).
121
+ - **Idle sweeper and `session/resume`:** Runs every 60 s (`.unref()`) with a
122
+ monotonic delta capped at 120 s per tick for sleep resilience. Idle
123
+ conversations expire after `idleSessionTtlMs` (30 min): clean, named
124
+ conversations close via `session/close` while retaining their SQLite DB in a
125
+ bounded `resumableSessions` map (`maxLiveSessions * 2`, LRU-evicted with
126
+ artifact cleanup), whereas dirty or ephemeral `anon-*` sessions delete their
127
+ artifacts immediately. Once no live sessions or in-flight streams remain and
128
+ the front has been idle past `idleSessionTtlMs`, the sweeper stops the ACP
129
+ process, MCP bridge, and itself (waiting for evicted sessions to close first).
130
+ On an idle front restart (`prepareHome(..., { cleanArtifacts: false })`),
131
+ retained DBs survive; when the next turn arrives with an intact system prompt
132
+ and history prefix, the runtime calls `session/resume` with a fresh MCP
133
+ tenant, re-applies model/effort via `select()`, and sends only the delta
134
+ input. Any `JsonRpcRemoteError` from `session/resume` (including `-32603` and
135
+ `-32002`) or history divergence cleans the dormant DB and falls back to
136
+ `session/new` + `replayPrompt()`. Explicit teardown (`resetConversations()`,
137
+ `dispose()`, binary upgrade, LRU eviction) deletes dormant DBs immediately.
125
138
  - **Pi lifecycle resets:** Compaction, tree navigation, and `session_start`
126
139
  (`new`, `resume`, `fork`) perform a light reset (closing conversation sessions
127
140
  and artifacts while keeping the ACP process, bridge, and caches).
@@ -140,8 +153,10 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
140
153
  trees via `taskkill /T /F /PID`. Helper commands wait up to 250 ms
141
154
  (`EXIT_DRAIN_MS`) after exit to avoid hangs from inherited stdio handles.
142
155
  - Subprocess environments strip `GEMINI_API_KEY`, `GOOGLE_API_KEY`,
143
- `GEMINI_HOME`, `ELECTRON_RUN_AS_NODE`, and `CHROME_CRASHPAD_PIPE_NAME`, and
144
- force `AGY_CLI_DISABLE_AUTO_UPDATE=1` and `PYTHONUNBUFFERED=1`.
156
+ `GEMINI_HOME`, `ELECTRON_RUN_AS_NODE`, and `CHROME_CRASHPAD_PIPE_NAME`,
157
+ force `AGY_CLI_DISABLE_AUTO_UPDATE=1` and `PYTHONUNBUFFERED=1`, and default
158
+ `AGY_CLI_AUTO_COMPACT_OVERRIDE=100%` when unset (case-insensitively on
159
+ Windows) so Pi owns compaction while preserving explicit user overrides.
145
160
  - Binary auto-discovery checks `~/.local/bin/agy` and `PATH` on Unix, and
146
161
  `%LOCALAPPDATA%\agy\bin\agy.exe`, `~/.local/bin/agy.exe`, then `PATH`
147
162
  (`.exe` prioritized ahead of `PATHEXT` wrappers) on Windows.
@@ -204,17 +219,24 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
204
219
  files across `.db`, `.db-wal`, `.db-shm`, and `.db-journal`.
205
220
  - Gates streaming reads with cached context window / positive `usage_update`
206
221
  checks and `(mtimeNs, size)` stamps across `.db`, `.db-wal`, and
207
- `.db-journal`. `gen_metadata` scans are bounded (`LIMIT 64`) and advance
208
- `metaFloorIdx` on mid-session model switches so prior context windows cannot
209
- bleed across models.
222
+ `.db-journal`. `gen_metadata.data` remains the authoritative per-model
223
+ `max_context_tokens` source in `agy` 1.5.18 because `usage_update.size` still
224
+ reports a fixed `1048576` rather than per-model limits. `gen_metadata` scans
225
+ are bounded (`LIMIT 64`) and advance `metaFloorIdx` on mid-session model
226
+ switches so prior context windows cannot bleed across models.
210
227
  - On `end_turn` and `refusal`, inspects the newest terminal `steps` row
211
228
  (`step_type = 17`, cross-checked against `step_type = 15` model reachability)
212
- to surface hidden API errors while preserving pure safety refusals:
229
+ to surface hidden API errors while preserving pure safety refusals. This
230
+ remains necessary in `agy` 1.5.18 because certain API errors (such as
231
+ `INVALID_ARGUMENT (code 400)` on malformed images) still complete
232
+ `session/prompt` with `stopReason: "end_turn"`:
213
233
  - `QUOTA_EXHAUSTED` → `QUOTA` (extracts reset timestamp/delay)
214
234
  - Thinking signature validation errors (`thinking.signature: Field required`
215
235
  or `Invalid \`signature\` in \`thinking\` block`) → `PROVIDER_ERROR` and
216
236
  marks the session dirty for rebuild
217
237
  - `429` / `RESOURCE_EXHAUSTED` → `RATE_LIMIT`
238
+ - `400` / `INVALID_ARGUMENT` (including malformed-image rejections) →
239
+ `INVALID_REQUEST`
218
240
  - `404` / `NOT_FOUND` → `SERVER` if the model was reached, else
219
241
  `UNKNOWN_MODEL`
220
242
  - Scoped artifact cleanup removes `conversations/<id>.db*`, `brain/<id>`, and
@@ -223,14 +245,26 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
223
245
  ### Usage and `totalTokens` priority
224
246
 
225
247
  `toTokenUsage()` emits usage only when `session/prompt` includes a `usage`
226
- object. Cumulative buckets (`inputTokens`, `outputTokens`, `cacheReadTokens`,
227
- `cacheWriteTokens`, `reasoningTokens`) sum across `max_tokens` continuations;
228
- `totalTokens` resolves in priority order:
229
-
230
- 1. Positive `usage_update.used` from the current continuation segment.
231
- 2. Positive `estimated_tokens_used` from `gen_metadata` in the current segment.
232
- 3. Final-segment average fallback:
233
- `round((input + cacheRead + cacheWrite) / max(1, segmentCalls)) + round(output)`.
248
+ object. Raw cumulative multi-call ACP usage is retained on
249
+ `RuntimeStatus.lastTurn.usage`, while the `AssistantMessage.usage` sent to Pi
250
+ normalizes prompt buckets to single-call occupancy so Pi's `isContextOverflow()`
251
+ (`input + cacheRead > contextWindow` on `stop` turns) does not false-positive on
252
+ tool-heavy or continued turns:
253
+
254
+ 1. `totalTokens` resolves final-call context occupancy in priority order:
255
+ 1. Positive `usage_update.used` from the current continuation segment.
256
+ 2. Positive `estimated_tokens_used` from `gen_metadata` in the current segment.
257
+ 3. Final-segment average fallback:
258
+ `round((input + cacheRead + cacheWrite) / max(1, segmentCalls)) + round(output)`.
259
+ 2. Prompt buckets (`inputTokens`, `cacheReadTokens`, `cacheWriteTokens`) are
260
+ taken from the final segment (falling back to accumulated usage when the
261
+ final segment reports zero prompt tokens) and capped proportionally with
262
+ largest-remainder allocation so their sum never exceeds the resolved
263
+ single-call prompt budget (`totalTokens` for live/metadata occupancy, or the
264
+ averaged `segPrompt` fallback). Single-call turns that already fit remain
265
+ unscaled, and cache-hit ratios are preserved.
266
+ 3. `outputTokens` and `reasoningTokens` remain cumulative across `max_tokens`
267
+ continuations.
234
268
 
235
269
  ## Quota reader and Pi stream contracts
236
270
 
@@ -62,10 +62,9 @@ npm test
62
62
  pi --no-extensions -e ./index.ts --list-models antigravity-acp
63
63
  ```
64
64
 
65
- Tests run directly with Node's native TypeScript support (`tsx` is not
66
- required) using a scripted local `agy` substitute so `npm test` runs offline
67
- without consuming account quota. Tests bind ephemeral loopback sockets on
68
- `127.0.0.1`.
65
+ Tests run directly with Node's native TypeScript support using a scripted local
66
+ `agy` substitute so `npm test` runs offline without consuming account quota.
67
+ Tests bind ephemeral loopback sockets on `127.0.0.1`.
69
68
 
70
69
  Automated tests cover ACP transport and sessions, JSON-RPC framing, MCP bridge
71
70
  boundaries and permissions, model/account discovery, session SQLite inspection,
package/docs/reference.md CHANGED
@@ -133,6 +133,7 @@ Set environment variables before starting Pi:
133
133
  | `PI_AGY_HOME` | Dedicated directory for this extension's state. | `~/.pi/agent/cache/antigravity-acp` |
134
134
  | `PI_AGY_QUOTA_DISPLAY` | Startup quota display mode (`used` or `remaining`), overriding `settings.json` for startup. Invalid values are ignored; `/agy-acp quota <mode>` overrides it for the active session. | `settings.json`, then `used` |
135
135
  | `PI_AGY_DEBUG` | Set to `1` to print runtime warnings on `stderr` (silent by default to protect the TUI). | Unset (silent) |
136
+ | `AGY_CLI_AUTO_COMPACT_OVERRIDE` | Forwarded to `agy` to control its internal auto-compaction threshold (e.g. `80%`, or `0` to revert to `agy`'s server default). | `100%` (when unset) |
136
137
 
137
138
  ```sh
138
139
  PI_AGY_COMMAND=/absolute/path/to/agy pi -e ./index.ts
@@ -145,11 +146,17 @@ plugins. It stores the extension's `catalog.json`, `settings.json` (quota
145
146
  display preference), ACP logs, and `agy/` (isolated `agy` state, settings, and
146
147
  session databases).
147
148
 
148
- - **Cleanup:** Temporary session artifacts and old logs are removed
149
- automatically (best-effort if locked). Current logs, `catalog.json`,
150
- `settings.json`, and authentication files are retained; sessions rebuild from
151
- Pi's history. Use a separate `PI_AGY_HOME` for each concurrently running Pi
152
- instance because startup cleanup assumes exclusive directory ownership.
149
+ - **Cleanup:** Temporary session artifacts and old logs are removed on cold
150
+ startup and explicit resets (best-effort if locked). Clean idle-expired
151
+ sessions retain their database across idle front restarts so the next turn can
152
+ resume via `session/resume` without history replay, falling back automatically
153
+ to a fresh session rebuild if resume fails or history diverged. Current logs,
154
+ `catalog.json`, `settings.json`, and authentication files are retained. Use a
155
+ separate `PI_AGY_HOME` for each concurrently running Pi instance because
156
+ startup cleanup assumes exclusive directory ownership.
157
+ - **Sign-in:** Sign in with `agy` before starting Pi, or run `agy acp --login`
158
+ in headless, SSH, or terminal-only environments. Authentication and token
159
+ refresh remain `agy`'s responsibility.
153
160
  - **OAuth sync:** With the default `PI_AGY_HOME` and file-backed auth, the
154
161
  extension atomically syncs `antigravity-oauth-token` from your normal `agy`
155
162
  directory (`ANTIGRAVITY_CLI_HOME`, `AGY_HOME`, or `~/.gemini/antigravity-cli`)
@@ -159,8 +166,7 @@ session databases).
159
166
  directories.
160
167
  - **Global quota scope:** `agy -p /usage` does not accept `--gemini-dir`, so
161
168
  quota queries always reflect the global `agy` CLI account. Do not commit or
162
- share `PI_AGY_HOME`; authentication and token refresh remain `agy`'s
163
- responsibility.
169
+ share `PI_AGY_HOME`.
164
170
 
165
171
  ## Models and context
166
172
 
@@ -189,22 +195,27 @@ Usage comes from the ACP session rather than per-step HTTP headers. Parked
189
195
  ACP turn completes (accumulated across any automatic `max_tokens` continuations)
190
196
  whenever `session/prompt` reports usage.
191
197
 
192
- The extension separates cumulative turn consumption from final-call context
193
- occupancy:
198
+ The extension aligns Pi's per-message prompt usage with single-call context
199
+ occupancy while retaining raw cumulative ACP turn totals on
200
+ `RuntimeStatus.lastTurn.usage`:
194
201
 
195
- - `input`, `output`, `cacheRead`, `cacheWrite`, and `reasoning` preserve
196
- unscaled cumulative turn totals, so Pi session totals and flat pricing
197
- overrides reflect full multi-step consumption.
198
202
  - `totalTokens` (feeding Pi's context meter and auto-compaction threshold) uses
199
203
  the final call's live token occupancy when reported by `agy`, falling back to
200
204
  the same turn's session metadata estimate and then a final-segment average
201
205
  estimate.
206
+ - `input`, `cacheRead`, and `cacheWrite` are proportionally capped to that
207
+ single-call prompt occupancy (preserving cache-hit ratios and leaving
208
+ single-call turns unchanged), preventing Pi's silent-overflow check
209
+ (`input + cacheRead > contextWindow`) from falsely triggering auto-compaction
210
+ after tool-heavy turns while preserving genuine overflow detection.
211
+ - `output` and `reasoning` preserve cumulative turn totals across any automatic
212
+ `max_tokens` continuations.
202
213
 
203
214
  Default model prices are zero because upstream pricing is unavailable. With Pi
204
- pricing overrides, flat per-million rates price cumulative turn buckets
205
- accurately; tiered `inputTokensAbove` rules evaluate against cumulative turn
206
- prompt tokens rather than per-call prompt sizes. These numbers are estimates,
207
- not an invoice or a promise of free access.
215
+ pricing overrides, per-turn prompt costs reflect the normalized single-call
216
+ prompt buckets on multi-step turns rather than the sum across every internal
217
+ tool call; these numbers are estimates, not an invoice or a promise of free
218
+ access.
208
219
 
209
220
  Read-only SQLite inspection is restricted strictly to session-scoped databases
210
221
  inside `PI_AGY_HOME` (for context windows, occupancy estimates, and hidden
@@ -214,7 +225,8 @@ or invokes/distributes binary patches.
214
225
  ## Compatibility limits
215
226
 
216
227
  - Requires Node.js >= 22.19.0, Pi (`@earendil-works/*`) 1.5.x, and `agy` >=
217
- 1.5.10. Older `@mariozechner/*` Pi interfaces are not supported.
228
+ 1.5.18 (which adds long-turn OAuth/503 recovery and fixes Windows cross-drive
229
+ plugin loading). Older `@mariozechner/*` Pi interfaces are not supported.
218
230
  - Sampling parameters, output limits, forced `toolChoice`, and provider-scoped
219
231
  environment overrides are not mapped to ACP.
220
232
 
package/index.ts CHANGED
@@ -209,7 +209,7 @@ export default function (
209
209
  })
210
210
  pi.on('agent_settled', (_event, ctx) => {
211
211
  // Pi 1.5.2 AgentSession._emitAgentSettled runs after tools and the run finish.
212
- runtime.settleSession(ctx.sessionManager.getSessionId())
212
+ activeRuntime?.settleSession(ctx.sessionManager.getSessionId())
213
213
  const current = activeRuntime
214
214
  if (!current || !ctx.hasUI || ctx.model?.provider !== config.provider) return
215
215
  if (pendingSettle?.runtime === current) {
@@ -414,15 +414,21 @@ export default function (
414
414
  return
415
415
  }
416
416
  }
417
- const notice = snapshot
418
- ? formatQuota(snapshot, undefined, quotaDisplay)
419
- : formatStatus(
420
- runtime.status(
421
- ctx.model?.provider === config.provider
422
- ? ctx.model.id
423
- : undefined,
424
- ),
425
- )
417
+ let notice: { text: string; level: 'info' | 'warning' | 'error' }
418
+ if (snapshot) {
419
+ notice = formatQuota(snapshot, undefined, quotaDisplay)
420
+ } else {
421
+ const current = activeRuntime
422
+ if (!current) {
423
+ ctx.ui.notify('Antigravity ACP runtime is disposed.', 'error')
424
+ return
425
+ }
426
+ notice = formatStatus(
427
+ current.status(
428
+ ctx.model?.provider === config.provider ? ctx.model.id : undefined,
429
+ ),
430
+ )
431
+ }
426
432
  if (epoch === uiEpoch)
427
433
  updateStatus(ctx, snapshot ?? activeRuntime?.quota.peek())
428
434
  ctx.ui.notify(notice.text, notice.level)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-agy-acp",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Google Antigravity ACP provider extension for Pi Coding Agent",
@@ -31,8 +31,7 @@
31
31
  },
32
32
  "peerDependencies": {
33
33
  "@earendil-works/pi-ai": "*",
34
- "@earendil-works/pi-coding-agent": "*",
35
- "@earendil-works/pi-tui": "*"
34
+ "@earendil-works/pi-coding-agent": "*"
36
35
  },
37
36
  "scripts": {
38
37
  "test": "node --test tests/*.test.mjs",
@@ -42,8 +41,7 @@
42
41
  "typescript": "7.0.2",
43
42
  "@types/node": "22.20.5",
44
43
  "@earendil-works/pi-ai": "1.5.2",
45
- "@earendil-works/pi-coding-agent": "1.5.2",
46
- "@earendil-works/pi-tui": "1.5.2"
44
+ "@earendil-works/pi-coding-agent": "1.5.2"
47
45
  },
48
46
  "keywords": [
49
47
  "pi-package",
@@ -97,6 +97,9 @@ export interface AcpInitializeResult {
97
97
  audio?: boolean
98
98
  embeddedContext?: boolean
99
99
  }
100
+ sessionCapabilities?: {
101
+ resume?: Record<string, unknown>
102
+ }
100
103
  }
101
104
  }
102
105
 
@@ -276,6 +279,28 @@ export class AcpProcess {
276
279
  return result
277
280
  }
278
281
 
282
+ /**
283
+ * Resume one persisted ACP session.
284
+ * @param params - `session/resume` parameters.
285
+ * @param listener - observer bound to the resumed session id.
286
+ * @param timeoutMs - setup deadline.
287
+ * @returns the session result.
288
+ */
289
+ async resumeSession(
290
+ params: Record<string, unknown>,
291
+ listener: AcpSessionListener,
292
+ timeoutMs: number,
293
+ ): Promise<AcpNewSessionResult> {
294
+ const result = await this.link().request<AcpNewSessionResult>(
295
+ 'session/resume',
296
+ params,
297
+ { timeoutMs },
298
+ )
299
+ // JsonRpcPeer can resolve a buffered reply before stop; leave its rollback to the owner.
300
+ if (this.alive) this.listeners.set(result.sessionId, listener)
301
+ return result
302
+ }
303
+
279
304
  /**
280
305
  * Select one configuration option value.
281
306
  * @param sessionId - ACP session.
@@ -362,13 +387,32 @@ export class AcpProcess {
362
387
 
363
388
  private onNotification(method: string, params: unknown): void {
364
389
  if (method !== 'session/update') return
365
- const record = params as { sessionId?: string; update?: AcpSessionUpdate }
366
- if (record.sessionId === undefined || record.update === undefined) return
367
- this.listeners.get(record.sessionId)?.onUpdate(record.update)
390
+ if (params === null || typeof params !== 'object' || Array.isArray(params))
391
+ return
392
+ const record = params as { sessionId?: unknown; update?: unknown }
393
+ if (
394
+ typeof record.sessionId !== 'string' ||
395
+ record.update === null ||
396
+ typeof record.update !== 'object' ||
397
+ Array.isArray(record.update)
398
+ )
399
+ return
400
+ this.listeners
401
+ .get(record.sessionId)
402
+ ?.onUpdate(record.update as AcpSessionUpdate)
368
403
  }
369
404
 
370
405
  private onRequest(method: string, params: unknown): unknown {
371
406
  if (method === 'session/request_permission') {
407
+ if (
408
+ params === null ||
409
+ typeof params !== 'object' ||
410
+ Array.isArray(params)
411
+ )
412
+ return { outcome: { outcome: 'cancelled' } }
413
+ const record = params as { sessionId?: unknown }
414
+ if (typeof record.sessionId !== 'string')
415
+ return { outcome: { outcome: 'cancelled' } }
372
416
  const request = params as AcpPermissionRequest
373
417
  const outcome = this.listeners
374
418
  .get(request.sessionId)
package/src/catalog.ts CHANGED
@@ -7,21 +7,15 @@
7
7
  * @module pi-agy-acp/catalog
8
8
  */
9
9
 
10
- import {
11
- existsSync,
12
- mkdirSync,
13
- readFileSync,
14
- renameSync,
15
- unlinkSync,
16
- writeFileSync,
17
- } from 'node:fs'
18
- import { basename, dirname, join } from 'node:path'
10
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
11
+ import { dirname } from 'node:path'
19
12
  import type {
20
13
  AcpConfigOption,
21
14
  AcpConfigOptionValue,
22
15
  AcpTierInfo,
23
16
  } from './acp-process.ts'
24
- import { EFFORTS, type Effort } from './config.ts'
17
+ import { asEffort, EFFORTS, type Effort } from './config.ts'
18
+ import { atomicWriteFile } from './util.ts'
25
19
 
26
20
  /** One advertised model family. */
27
21
  export interface CatalogModel {
@@ -50,6 +44,24 @@ export function flattenConfigOptions(
50
44
  })
51
45
  }
52
46
 
47
+ /** Find an ACP config option by id or category. */
48
+ export function findConfigOption(
49
+ options: readonly AcpConfigOption[] | undefined,
50
+ id: string,
51
+ ): AcpConfigOption | undefined {
52
+ return options?.find((o) => o.id === id || o.category === id)
53
+ }
54
+
55
+ /** Extract valid `Effort` values from a `thought_level` config option. */
56
+ export function offeredEffortsFrom(
57
+ option: AcpConfigOption | undefined,
58
+ ): Effort[] | undefined {
59
+ if (option?.options === undefined) return undefined
60
+ return flattenConfigOptions(option.options)
61
+ .map((o) => asEffort(o.value))
62
+ .filter((v): v is Effort => v !== undefined)
63
+ }
64
+
53
65
  /** Effort suffixes ordered longest-first so `-<effort>-effort` beats `-<effort>`. */
54
66
  const EFFORT_SUFFIXES: readonly { suffix: string; effort: Effort }[] =
55
67
  EFFORTS.flatMap((effort) => [
@@ -285,21 +297,10 @@ export class ModelCatalog {
285
297
  if (tierChanged) this.save()
286
298
  return false
287
299
  }
288
- const modelOption = options.find(
289
- (o) => o.id === 'model' || o.category === 'model',
290
- )
291
- const levelOption = options.find(
292
- (o) => o.id === 'thought_level' || o.category === 'thought_level',
293
- )
300
+ const modelOption = findConfigOption(options, 'model')
301
+ const levelOption = findConfigOption(options, 'thought_level')
294
302
  const beforeEfforts = JSON.stringify(this.efforts)
295
- const levelEfforts =
296
- levelOption?.options !== undefined
297
- ? flattenConfigOptions(levelOption.options)
298
- .map((o) => o.value)
299
- .filter((v): v is Effort =>
300
- (EFFORTS as readonly string[]).includes(v),
301
- )
302
- : []
303
+ const levelEfforts = offeredEffortsFrom(levelOption) ?? []
303
304
  const modelEntries = flattenConfigOptions(modelOption?.options)
304
305
  const next =
305
306
  modelEntries.length > 0
@@ -388,15 +389,10 @@ export class ModelCatalog {
388
389
  }
389
390
 
390
391
  private save(): void {
391
- const dir = dirname(this.cachePath)
392
- const tempPath = join(
393
- dir,
394
- `.${basename(this.cachePath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2, 8)}.tmp`,
395
- )
396
392
  try {
397
- mkdirSync(dir, { recursive: true })
398
- writeFileSync(
399
- tempPath,
393
+ mkdirSync(dirname(this.cachePath), { recursive: true })
394
+ atomicWriteFile(
395
+ this.cachePath,
400
396
  `${JSON.stringify(
401
397
  {
402
398
  models: this.models,
@@ -415,13 +411,7 @@ export class ModelCatalog {
415
411
  2,
416
412
  )}\n`,
417
413
  )
418
- renameSync(tempPath, this.cachePath)
419
414
  } catch (_cacheWrite) {
420
- try {
421
- unlinkSync(tempPath)
422
- } catch {
423
- // Best-effort cleanup.
424
- }
425
415
  // The cache only speeds up the next cold start.
426
416
  }
427
417
  }
package/src/config.ts CHANGED
@@ -1,11 +1,6 @@
1
- import {
2
- mkdirSync,
3
- readFileSync,
4
- renameSync,
5
- unlinkSync,
6
- writeFileSync,
7
- } from 'node:fs'
1
+ import { mkdirSync, readFileSync } from 'node:fs'
8
2
  import { join } from 'node:path'
3
+ import { atomicWriteFile } from './util.ts'
9
4
 
10
5
  /** Reasoning effort ids accepted by the Antigravity ACP `thought_level` option. */
11
6
  export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const
@@ -13,7 +8,7 @@ export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const
13
8
  export type Effort = (typeof EFFORTS)[number]
14
9
 
15
10
  /** Supported quota percentage display conventions. */
16
- export const QUOTA_DISPLAY_MODES = ['used', 'remaining'] as const
11
+ const QUOTA_DISPLAY_MODES = ['used', 'remaining'] as const
17
12
  /** Quota percentage display convention (`used` counts up from 0%, `remaining` counts down from 100%). */
18
13
  export type QuotaDisplay = (typeof QUOTA_DISPLAY_MODES)[number]
19
14
  /** Default quota percentage display convention when no env var or saved preference is set. */
@@ -105,21 +100,12 @@ export function writeQuotaDisplayPreference(
105
100
  quotaDisplay: QuotaDisplay,
106
101
  ): void {
107
102
  const path = join(home, SETTINGS_FILE)
108
- const tempPath = join(
109
- home,
110
- `.${SETTINGS_FILE}.${process.pid}.${Date.now()}.tmp`,
111
- )
112
103
  try {
113
104
  mkdirSync(home, { recursive: true })
114
105
  const existing = readJson(path)
115
106
  const content = `${JSON.stringify({ ...existing, quotaDisplay }, null, 2)}\n`
116
- writeFileSync(tempPath, content)
117
- renameSync(tempPath, path)
107
+ atomicWriteFile(path, content)
118
108
  } catch {
119
- try {
120
- unlinkSync(tempPath)
121
- } catch {
122
- // Best-effort cleanup.
123
- }
109
+ // Best-effort preference persistence.
124
110
  }
125
111
  }