pi-agy-acp 0.2.7 → 0.2.8

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,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.8](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.7...v0.2.8) (2026-12-06)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **runtime:** unify error classification, session/turn state, and module naming ([#67](https://github.com/fdkevin0/pi-agy-acp/issues/67)) ([bc52ba9](https://github.com/fdkevin0/pi-agy-acp/commit/bc52ba9eabf08c3321d8cf9d5a642008c2e34070))
9
+
3
10
  ## [0.2.7](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.6...v0.2.7) (2026-12-03)
4
11
 
5
12
 
@@ -79,12 +79,13 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
79
79
  - Completing (`end_turn`/`max_tokens`) while `waiting` fails with
80
80
  `PROVIDER_ERROR`; completing with only `unawaited`/`notified` entries appends
81
81
  an unretrieved-result note and finishes normally.
82
- - `callDelivery` (`waiting` | `delivered`) guards against concurrent or
83
- duplicate `pi_await_result` calls.
82
+ - `ToolCallEntry.delivery` (`idle` | `waiting` | `delivered`) inside
83
+ `AcpTurn.calls` guards against concurrent or duplicate `pi_await_result`
84
+ calls.
84
85
  - The MCP bridge passes a synchronous `commit(finalize)` callback into
85
- `handleCall` so `deliverCallResult()` mutates `callDelivery`, relay state,
86
- and deferred suffixes only while the SSE stream is still writable and
87
- unaborted.
86
+ `handleCall` so `deliverCallResult()` mutates `ToolCallEntry.delivery`,
87
+ relay state, and deferred suffixes only while the SSE stream is still
88
+ writable and unaborted.
88
89
  - `max_tokens` auto-continues up to `longDecodeContinuations` (3) when not
89
90
  relaying, resetting per-segment usage counters. Transient `agy` retry and
90
91
  output-limit notices are suppressed and counted in `retryNotices`, while
@@ -120,10 +121,13 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
120
121
 
121
122
  ## Session and process lifecycle
122
123
 
123
- - **Capacity and ephemeral sessions:** `capacityMutex` enforces
124
- `maxLiveSessions` (16), evicting the oldest idle non-opening conversation
125
- first and failing fast with `CAPACITY_EXCEEDED` (`RATE_LIMIT`) to avoid
126
- parent/subagent deadlocks. Requests without a `sessionId` use ephemeral
124
+ - **Capacity, atomic `LiveSession` state, and ephemeral sessions:** Each
125
+ conversation stores its live binding in an atomic `LiveSession` object
126
+ (`sessionId`, `tenantKey`, `tenantSecret`, `process`) so a conversation is
127
+ either bound to one complete session or cleanly unbound. `capacityMutex`
128
+ enforces `maxLiveSessions` (16), evicting the oldest idle non-opening
129
+ conversation first and failing fast with `CAPACITY_EXCEEDED` (`RATE_LIMIT`) to
130
+ avoid parent/subagent deadlocks. Requests without a `sessionId` use ephemeral
127
131
  `anon-*` keys torn down immediately after each idle step.
128
132
  - **Idle sweeper and `session/resume`:** Runs every 60 s (`.unref()`) with a
129
133
  monotonic delta capped at 120 s per tick for sleep resilience. Idle
@@ -176,6 +180,8 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
176
180
 
177
181
  ### MCP HTTP/SSE bridge (`src/mcp-bridge.ts`)
178
182
 
183
+ - Owns the centralized MCP bridge constants (`MCP_SERVER_NAME`,
184
+ `AGENT_TOOL_PREFIX`, `CALL_TOOL_NAME`, `AWAIT_TOOL_NAME`).
179
185
  - Binds `127.0.0.1` on an ephemeral port with per-session bearer credentials
180
186
  checked in constant time (`timingSafeEqual`).
181
187
  - Enforces Node HTTP parser deadlines of 10 s for headers and 30 s for
@@ -239,11 +245,13 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
239
245
  remains necessary in `agy` 1.5.23 because certain API errors (such as
240
246
  `INVALID_ARGUMENT (code 400)` on malformed images) still complete
241
247
  `session/prompt` with `stopReason: "end_turn"`:
242
- - `QUOTA_EXHAUSTED` → `QUOTA` (extracts reset timestamp/delay)
248
+ - `QUOTA_EXHAUSTED` / explicit quota exhaustion → `QUOTA` (extracts reset
249
+ timestamp/delay)
243
250
  - Thinking signature validation errors (`thinking.signature: Field required`
244
251
  or `Invalid \`signature\` in \`thinking\` block`) → `PROVIDER_ERROR` and
245
252
  marks the session dirty for rebuild
246
- - `429` / `RESOURCE_EXHAUSTED` → `RATE_LIMIT`
253
+ - `429` / `RESOURCE_EXHAUSTED` (without explicit quota exhaustion) →
254
+ `RATE_LIMIT` (unified across both RPC `mapError()` and SQLite hidden errors)
247
255
  - `400` / `INVALID_ARGUMENT` (including malformed-image rejections) →
248
256
  `INVALID_REQUEST`
249
257
  - `404` / `NOT_FOUND` → `SERVER` if the model was reached, else
@@ -277,20 +285,25 @@ tool-heavy or continued turns:
277
285
 
278
286
  ## Quota reader and Pi stream contracts
279
287
 
280
- - **Quota reader (`src/quota.ts`):** Runs `agy usage --output-format json`
281
- with closed `stdin`, a 1 MiB `stdout` cap, a 45 s timeout, and early abort if
282
- `stderr` matches `Authentication required`. Uses a monotonic clock
283
- (`performance.now()`) for its 2-minute TTL, filters `disabled === true`
284
- buckets, and shares concurrent in-flight queries.
288
+ - **Quota reader and model matching (`src/quota.ts`):** Runs
289
+ `agy usage --output-format json` with closed `stdin`, a 1 MiB `stdout` cap, a
290
+ 45 s timeout, and early abort if `stderr` matches `Authentication required`.
291
+ Uses a monotonic clock (`performance.now()`) for its 2-minute TTL, filters
292
+ `disabled === true` buckets, shares concurrent in-flight queries, and owns
293
+ model-to-group quota matching (`quotaForModel`), leaving `src/format.ts`
294
+ focused on TUI notice formatting.
285
295
  - **Account email scan (`src/quota.ts`):** Checks `cli.log` plus the newest 10
286
296
  contained `log/cli-*.log` and `log/acp-server-*.log` files (newest-first,
287
297
  realpath-deduplicated), reading the tail 64 KiB first and falling back to the
288
298
  head 64 KiB when larger, cached for 10 s by path stat signatures.
289
- - **Warning keys and UI freshness (`index.ts`):** UI generation checks discard
290
- stale background results; `model_select` retargets an in-flight settled check
291
- when switching between `antigravity-acp` models. Low-quota warning keys
292
- include group, bucket ID, window label, reset time, and threshold (`20` or
293
- `5`).
299
+ - **Warning keys, UI freshness, and reset coordination (`index.ts`):** Visual
300
+ status clearing (`clearStatusDisplay`) is decoupled from invalidating pending
301
+ async UI work (`invalidatePendingUi`), so intra-provider `model_select`
302
+ retargets an in-flight settled check while discarding stale `session_start`
303
+ or command updates. Low-quota warning keys include group, bucket ID, window
304
+ label, reset time, and threshold (`20` or `5`). `streamSimple` and network
305
+ `refreshModels` wait on an in-flight `/agy-acp reset` (abortable via
306
+ `signal`) before using the replacement active runtime.
294
307
  - **Pi stream hooks (`src/pi-stream.ts`):**
295
308
  - `onPayload` can replace the request (strictly validated; invalid shapes
296
309
  throw `INVALID_PAYLOAD`; `sessionId` and `signal` are always preserved;
@@ -43,11 +43,11 @@ SQLite telemetry, and transport boundary invariants.
43
43
  | --- | --- |
44
44
  | `index.ts` | Provider registration, `/agy-acp` commands, TUI loaders/warnings, and Pi lifecycle hooks. |
45
45
  | `src/pi-stream.ts`, `src/protocol.ts` | Pi message/stream conversion, hook contracts, and internal bridge event types. |
46
- | `src/runtime.ts`, `src/conversation.ts`, `src/history.ts` | Session orchestration, capacity/sweeper lifecycle, pending/relayed tool calls, usage accounting, and history replay. |
47
- | `src/acp-process.ts`, `src/jsonrpc.ts`, `src/mcp-bridge.ts` | ACP stdio transport, NDJSON JSON-RPC peer, loopback MCP HTTP/SSE bridge, schema compression, and tool deltas. |
46
+ | `src/runtime.ts`, `src/conversation.ts`, `src/history.ts` | Session orchestration, capacity/sweeper lifecycle, turn/retry/usage and pending/relayed tool-call logic, and history replay. |
47
+ | `src/acp-process.ts`, `src/jsonrpc.ts`, `src/mcp-bridge.ts` | ACP stdio transport, NDJSON JSON-RPC peer, loopback MCP HTTP/SSE bridge, MCP bridge constants, schema compression, and tool deltas. |
48
48
  | `src/config.ts` | Default runtime thresholds, effort/display types, and atomic `settings.json` persistence. |
49
49
  | `src/host.ts`, `src/preflight.ts`, `src/session-db.ts` | Subprocess management and env/stderr hardening, binary discovery/fingerprinting/OAuth sync, and read-only session SQLite telemetry/error inspection and artifact cleanup. |
50
- | `src/catalog.ts`, `src/quota.ts`, `src/format.ts`, `src/util.ts` | Model catalog persistence, `agy usage` quota reader and login-log email lookup, TUI notice formatting and model-to-group matching, and shared utilities. |
50
+ | `src/catalog.ts`, `src/quota.ts`, `src/format.ts`, `src/util.ts` | Model catalog persistence, `agy usage` quota reader, login-log email lookup, and model-to-group matching, TUI notice formatting, and shared utilities. |
51
51
  | `src/version.ts` | Package version read from `package.json` for ACP/MCP handshakes. |
52
52
  | `tests/` | Scripted local `agy` fixture (`fake-agy.mjs`), unit tests, and Pi integration tests. |
53
53
 
package/index.ts CHANGED
@@ -7,22 +7,22 @@ import {
7
7
  import { AntigravityRuntime, type RuntimeHost } from './src/runtime.ts'
8
8
  import {
9
9
  asQuotaDisplay,
10
+ DEFAULT_CONFIG,
10
11
  DEFAULT_QUOTA_DISPLAY,
11
- defaults,
12
12
  readQuotaDisplayPreference,
13
13
  writeQuotaDisplayPreference,
14
14
  type QuotaDisplay,
15
15
  } from './src/config.ts'
16
16
  import { spawnAcp, runCommand } from './src/host.ts'
17
- import { streamPi } from './src/pi-stream.ts'
17
+ import { streamPi, type StreamRuntime } from './src/pi-stream.ts'
18
18
  import {
19
19
  displayFraction,
20
20
  formatQuota,
21
21
  formatStatus,
22
22
  formatQuotaStatus,
23
- quotaForModel,
24
23
  } from './src/format.ts'
25
- import type { QuotaSnapshot } from './src/quota.ts'
24
+ import { quotaForModel, type QuotaSnapshot } from './src/quota.ts'
25
+ import { abortable } from './src/util.ts'
26
26
 
27
27
  export default function (
28
28
  pi: ExtensionAPI,
@@ -31,13 +31,18 @@ export default function (
31
31
  const envQuotaDisplay = asQuotaDisplay(process.env.PI_AGY_QUOTA_DISPLAY)
32
32
  const debug = process.env.PI_AGY_DEBUG === '1'
33
33
  const config = {
34
- ...defaults,
34
+ ...DEFAULT_CONFIG,
35
35
  command: process.env.PI_AGY_COMMAND || '',
36
36
  home: process.env.PI_AGY_HOME || '',
37
37
  }
38
38
  let refreshDepth = 0
39
- const createRuntime = () =>
40
- new AntigravityRuntime({
39
+ let uiEpoch = 0
40
+ let shutDown = false
41
+ let runtime!: AntigravityRuntime
42
+ let activeRuntime: AntigravityRuntime | undefined
43
+ let resetting: Promise<void> | undefined
44
+ const createRuntime = () => {
45
+ const instance: AntigravityRuntime = new AntigravityRuntime({
41
46
  config,
42
47
  spawnAcp: host.spawnAcp ?? spawnAcp,
43
48
  runCommand: host.runCommand ?? runCommand,
@@ -51,19 +56,38 @@ export default function (
51
56
  : () => {},
52
57
  },
53
58
  onModelsChanged: () => {
54
- if (refreshDepth === 0) register()
59
+ if (refreshDepth === 0 && !shutDown && activeRuntime === instance)
60
+ register()
55
61
  },
56
62
  })
57
- let runtime = createRuntime()
63
+ return instance
64
+ }
65
+ runtime = activeRuntime = createRuntime()
58
66
  const home = runtime.status().home
59
67
  let quotaDisplay: QuotaDisplay =
60
68
  envQuotaDisplay ??
61
69
  readQuotaDisplayPreference(home) ??
62
70
  DEFAULT_QUOTA_DISPLAY
63
- const models = (): ProviderModelConfig[] => {
64
- const input = runtime.catalog.inputModalities()
65
- return runtime.catalog.list().map((m) => {
66
- const efforts = runtime.catalog.effortsFor(m.id)
71
+ const waitForActiveRuntime = async (
72
+ signal?: AbortSignal,
73
+ ): Promise<AntigravityRuntime> => {
74
+ while (resetting) await abortable(resetting, signal)
75
+ if (shutDown || !activeRuntime)
76
+ throw new Error('Antigravity ACP runtime is disposed.')
77
+ return activeRuntime
78
+ }
79
+ const streamRuntime: StreamRuntime = {
80
+ async *stream(request) {
81
+ const current = await waitForActiveRuntime(request.signal)
82
+ yield* current.stream(request)
83
+ },
84
+ }
85
+ const models = (
86
+ target: AntigravityRuntime = activeRuntime ?? runtime,
87
+ ): ProviderModelConfig[] => {
88
+ const input = target.catalog.inputModalities()
89
+ return target.catalog.list().map((m) => {
90
+ const efforts = target.catalog.effortsFor(m.id)
67
91
  return {
68
92
  id: m.id,
69
93
  name: m.name,
@@ -82,7 +106,7 @@ export default function (
82
106
  }
83
107
  : undefined,
84
108
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
85
- contextWindow: runtime.contextWindowFor(m.id),
109
+ contextWindow: target.contextWindowFor(m.id),
86
110
  maxTokens: 65536,
87
111
  }
88
112
  })
@@ -95,39 +119,38 @@ export default function (
95
119
  apiKey: 'local-agy',
96
120
  models: models(),
97
121
  streamSimple: (model, context, options) =>
98
- streamPi(runtime, model, context, options),
122
+ streamPi(streamRuntime, model, context, options),
99
123
  refreshModels: async (context) => {
100
124
  refreshDepth++
101
125
  try {
126
+ let current = activeRuntime
102
127
  if (context?.allowNetwork !== false && !context?.signal?.aborted) {
103
- await runtime.warmup({
128
+ current = await waitForActiveRuntime(context?.signal)
129
+ await current.warmup({
104
130
  force: context?.force,
105
131
  signal: context?.signal,
106
132
  })
107
133
  }
108
- return models()
134
+ return models(current ?? activeRuntime ?? runtime)
109
135
  } finally {
110
136
  refreshDepth--
111
137
  }
112
138
  },
113
139
  })
114
140
  register()
115
- let uiEpoch = 0
116
- let shutDown = false
117
- let activeRuntime: AntigravityRuntime | undefined = runtime
118
- let resetting: Promise<void> | undefined
119
141
  interface PendingSettle {
120
142
  runtime: AntigravityRuntime
121
- epoch: number
122
143
  ctx: ExtensionContext
123
144
  model: ExtensionContext['model']
124
145
  }
125
146
  let pendingSettle: PendingSettle | undefined
126
147
  const warned = new Set<string>()
127
- const clearStatus = (ctx?: ExtensionContext) => {
148
+ const clearStatusDisplay = (ctx?: ExtensionContext) => {
149
+ if (!shutDown && ctx?.hasUI) ctx.ui.setStatus(config.provider, undefined)
150
+ }
151
+ const invalidatePendingUi = () => {
128
152
  uiEpoch++
129
153
  pendingSettle = undefined
130
- if (!shutDown && ctx?.hasUI) ctx.ui.setStatus(config.provider, undefined)
131
154
  }
132
155
  const updateStatus = (
133
156
  ctx: ExtensionContext,
@@ -143,9 +166,8 @@ export default function (
143
166
  )
144
167
  }
145
168
  const reset = () => {
146
- uiEpoch++
169
+ invalidatePendingUi()
147
170
  warned.clear()
148
- pendingSettle = undefined
149
171
  activeRuntime = undefined
150
172
  if (resetting) return resetting
151
173
  const previous = runtime
@@ -163,7 +185,8 @@ export default function (
163
185
  pi.on('session_tree', () => activeRuntime?.resetConversations())
164
186
  pi.on('session_compact', () => activeRuntime?.resetConversations())
165
187
  pi.on('session_start', async (event, ctx) => {
166
- clearStatus(ctx)
188
+ invalidatePendingUi()
189
+ clearStatusDisplay(ctx)
167
190
  const epoch = uiEpoch
168
191
  if (resetting) await resetting.catch(() => {})
169
192
  if (shutDown) return
@@ -173,10 +196,10 @@ export default function (
173
196
  updateStatus(ctx, activeRuntime?.quota.peek())
174
197
  })
175
198
  pi.on('session_shutdown', async (_event, ctx) => {
176
- clearStatus(ctx)
199
+ invalidatePendingUi()
200
+ clearStatusDisplay(ctx)
177
201
  shutDown = true
178
202
  activeRuntime = undefined
179
- pendingSettle = undefined
180
203
  if (resetting) await resetting.catch(() => {})
181
204
  await runtime.dispose()
182
205
  })
@@ -191,19 +214,19 @@ export default function (
191
214
  : undefined,
192
215
  )
193
216
  pi.on('model_select', (event, ctx) => {
194
- const retarget =
217
+ clearStatusDisplay(ctx)
218
+ if (
219
+ event.model?.provider === config.provider &&
195
220
  pendingSettle &&
196
- pendingSettle.runtime === activeRuntime &&
197
- pendingSettle.epoch === uiEpoch &&
198
- event.model?.provider === config.provider
199
- ? pendingSettle
200
- : undefined
201
- clearStatus(ctx)
202
- if (retarget) {
203
- retarget.epoch = uiEpoch
204
- retarget.ctx = ctx
205
- retarget.model = event.model
206
- pendingSettle = retarget
221
+ pendingSettle.runtime === activeRuntime
222
+ ) {
223
+ // Advance uiEpoch so in-flight session_start or command updates cannot
224
+ // overwrite the new model, while retargeting the active settled check.
225
+ uiEpoch++
226
+ pendingSettle.ctx = ctx
227
+ pendingSettle.model = event.model
228
+ } else {
229
+ invalidatePendingUi()
207
230
  }
208
231
  updateStatus(ctx, activeRuntime?.quota.peek(), event.model)
209
232
  })
@@ -213,14 +236,12 @@ export default function (
213
236
  const current = activeRuntime
214
237
  if (!current || !ctx.hasUI || ctx.model?.provider !== config.provider) return
215
238
  if (pendingSettle?.runtime === current) {
216
- pendingSettle.epoch = uiEpoch
217
239
  pendingSettle.ctx = ctx
218
240
  pendingSettle.model = ctx.model
219
241
  return
220
242
  }
221
243
  const state: PendingSettle = {
222
244
  runtime: current,
223
- epoch: uiEpoch,
224
245
  ctx,
225
246
  model: ctx.model,
226
247
  }
@@ -232,7 +253,6 @@ export default function (
232
253
  shutDown ||
233
254
  pendingSettle !== state ||
234
255
  state.runtime !== activeRuntime ||
235
- state.epoch !== uiEpoch ||
236
256
  snapshot.status !== 'ok'
237
257
  )
238
258
  return
@@ -376,7 +396,7 @@ export default function (
376
396
  return
377
397
  }
378
398
  if (command === 'reset' && tokens.length === 1) {
379
- clearStatus(ctx)
399
+ clearStatusDisplay(ctx)
380
400
  await reset()
381
401
  if (!shutDown) ctx.ui.notify('Antigravity ACP sessions reset', 'info')
382
402
  return
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-agy-acp",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Google Antigravity ACP provider extension for Pi Coding Agent",
@@ -9,6 +9,7 @@
9
9
 
10
10
  import type { Readable, Writable } from 'node:stream'
11
11
  import { JsonRpcPeer, JsonRpcRemoteError } from './jsonrpc.ts'
12
+ import { isRecord } from './util.ts'
12
13
 
13
14
  /** Minimal handle of a spawned ACP process. */
14
15
  export interface AcpChild {
@@ -131,8 +132,8 @@ export interface AcpTierInfo {
131
132
  upgradeUri?: string
132
133
  }
133
134
 
134
- /** `session/new` result. */
135
- export interface AcpNewSessionResult {
135
+ /** `session/new` and `session/resume` result. */
136
+ export interface AcpSessionResult {
136
137
  sessionId: string
137
138
  configOptions?: AcpConfigOption[]
138
139
  /** Full model inventory, including one entry per effort variant. */
@@ -269,8 +270,8 @@ export class AcpProcess {
269
270
  params: Record<string, unknown>,
270
271
  listener: AcpSessionListener,
271
272
  timeoutMs: number,
272
- ): Promise<AcpNewSessionResult> {
273
- const result = await this.link().request<AcpNewSessionResult>(
273
+ ): Promise<AcpSessionResult> {
274
+ const result = await this.link().request<AcpSessionResult>(
274
275
  'session/new',
275
276
  params,
276
277
  { timeoutMs },
@@ -291,8 +292,8 @@ export class AcpProcess {
291
292
  params: Record<string, unknown>,
292
293
  listener: AcpSessionListener,
293
294
  timeoutMs: number,
294
- ): Promise<AcpNewSessionResult> {
295
- const result = await this.link().request<AcpNewSessionResult>(
295
+ ): Promise<AcpSessionResult> {
296
+ const result = await this.link().request<AcpSessionResult>(
296
297
  'session/resume',
297
298
  params,
298
299
  { timeoutMs },
@@ -388,33 +389,18 @@ export class AcpProcess {
388
389
 
389
390
  private onNotification(method: string, params: unknown): void {
390
391
  if (method !== 'session/update') return
391
- if (params === null || typeof params !== 'object' || Array.isArray(params))
392
- return
393
- const record = params as { sessionId?: unknown; update?: unknown }
394
- if (
395
- typeof record.sessionId !== 'string' ||
396
- record.update === null ||
397
- typeof record.update !== 'object' ||
398
- Array.isArray(record.update)
399
- )
400
- return
392
+ if (!isRecord(params)) return
393
+ if (typeof params.sessionId !== 'string' || !isRecord(params.update)) return
401
394
  this.listeners
402
- .get(record.sessionId)
403
- ?.onUpdate(record.update as AcpSessionUpdate)
395
+ .get(params.sessionId)
396
+ ?.onUpdate(params.update as AcpSessionUpdate)
404
397
  }
405
398
 
406
399
  private onRequest(method: string, params: unknown): unknown {
407
400
  if (method === 'session/request_permission') {
408
- if (
409
- params === null ||
410
- typeof params !== 'object' ||
411
- Array.isArray(params)
412
- )
413
- return { outcome: { outcome: 'cancelled' } }
414
- const record = params as { sessionId?: unknown }
415
- if (typeof record.sessionId !== 'string')
401
+ if (!isRecord(params) || typeof params.sessionId !== 'string')
416
402
  return { outcome: { outcome: 'cancelled' } }
417
- const request = params as AcpPermissionRequest
403
+ const request = params as unknown as AcpPermissionRequest
418
404
  const outcome = this.listeners
419
405
  .get(request.sessionId)
420
406
  ?.onPermission?.(request)
package/src/catalog.ts CHANGED
@@ -15,7 +15,7 @@ import type {
15
15
  AcpTierInfo,
16
16
  } from './acp-process.ts'
17
17
  import { asEffort, EFFORTS, type Effort } from './config.ts'
18
- import { atomicWriteFile } from './util.ts'
18
+ import { atomicWriteFile, isRecord } from './util.ts'
19
19
 
20
20
  /** One advertised model family. */
21
21
  export interface CatalogModel {
@@ -35,7 +35,7 @@ export function flattenConfigOptions(
35
35
  ): AcpConfigOptionValue[] {
36
36
  if (!Array.isArray(options)) return []
37
37
  return options.flatMap((entry) => {
38
- if (entry === null || typeof entry !== 'object') return []
38
+ if (!isRecord(entry)) return []
39
39
  return 'group' in entry
40
40
  ? Array.isArray(entry.options)
41
41
  ? entry.options
@@ -113,6 +113,34 @@ function isValidContextWindow(value: unknown): value is number {
113
113
  return typeof value === 'number' && Number.isInteger(value) && value > 0
114
114
  }
115
115
 
116
+ function equalTier(
117
+ a: { id?: string; name: string } | undefined,
118
+ b: { id?: string; name: string } | undefined,
119
+ ): boolean {
120
+ return a?.id === b?.id && a?.name === b?.name
121
+ }
122
+
123
+ function equalEfforts(
124
+ a: readonly Effort[] | undefined,
125
+ b: readonly Effort[] | undefined,
126
+ ): boolean {
127
+ if (a === b) return true
128
+ if (a === undefined || b === undefined || a.length !== b.length) return false
129
+ return a.every((value, index) => value === b[index])
130
+ }
131
+
132
+ function equalModels(
133
+ a: readonly CatalogModel[],
134
+ b: readonly CatalogModel[],
135
+ ): boolean {
136
+ if (a === b) return true
137
+ if (a.length !== b.length) return false
138
+ return a.every(
139
+ (model, index) =>
140
+ model.id === b[index]?.id && model.name === b[index]?.name,
141
+ )
142
+ }
143
+
116
144
  /** Observed catalog with a disk cache. Starts empty until loaded or observed from ACP. */
117
145
  export class ModelCatalog {
118
146
  private models: CatalogModel[]
@@ -131,7 +159,7 @@ export class ModelCatalog {
131
159
  /** Fingerprint of the `agy` binary that produced the cached catalog. */
132
160
  private observedFingerprint: string | undefined
133
161
  /** Whether a live ACP session has reported the catalog in this process. */
134
- observed = false
162
+ private observed = false
135
163
  private readonly cachePath: string
136
164
 
137
165
  /**
@@ -144,6 +172,11 @@ export class ModelCatalog {
144
172
  this.models = this.load(binaryFingerprint) ?? []
145
173
  }
146
174
 
175
+ /** Whether a live ACP session has reported the catalog in this process. */
176
+ isObserved(): boolean {
177
+ return this.observed
178
+ }
179
+
147
180
  /** Whether disk-cached models match the current `agy` binary fingerprint. */
148
181
  hasFreshCache(): boolean {
149
182
  return (
@@ -288,8 +321,7 @@ export class ModelCatalog {
288
321
  ): boolean {
289
322
  const nextTier = normalizeTier(tier)
290
323
  const tierChanged =
291
- nextTier !== undefined &&
292
- JSON.stringify(nextTier) !== JSON.stringify(this.tierInfo)
324
+ nextTier !== undefined && !equalTier(nextTier, this.tierInfo)
293
325
  if (tierChanged) this.tierInfo = nextTier
294
326
  if (available !== undefined && available.length > 0)
295
327
  this.available = available
@@ -299,7 +331,7 @@ export class ModelCatalog {
299
331
  }
300
332
  const modelOption = findConfigOption(options, 'model')
301
333
  const levelOption = findConfigOption(options, 'thought_level')
302
- const beforeEfforts = JSON.stringify(this.efforts)
334
+ const beforeEfforts = this.efforts
303
335
  const levelEfforts = offeredEffortsFrom(levelOption) ?? []
304
336
  const modelEntries = flattenConfigOptions(modelOption?.options)
305
337
  const next =
@@ -310,7 +342,7 @@ export class ModelCatalog {
310
342
  }))
311
343
  : this.models
312
344
  this.observed = true
313
- const changed = JSON.stringify(next) !== JSON.stringify(this.models)
345
+ const changed = !equalModels(next, this.models)
314
346
  if (changed) this.models = next
315
347
  const fingerprintChanged =
316
348
  modelEntries.length > 0 &&
@@ -341,7 +373,7 @@ export class ModelCatalog {
341
373
  const effortsChanged =
342
374
  prunedChanged ||
343
375
  derivedChanged ||
344
- beforeEfforts !== JSON.stringify(this.efforts)
376
+ !equalEfforts(beforeEfforts, this.efforts)
345
377
  if (changed || effortsChanged || tierChanged || fingerprintChanged)
346
378
  this.save()
347
379
  return changed || effortsChanged
@@ -369,9 +401,7 @@ export class ModelCatalog {
369
401
  ? EFFORTS.filter((effort) => matched.has(effort))
370
402
  : []
371
403
  if (offered.length > 0) {
372
- if (
373
- JSON.stringify(this.byModel.get(model.id)) !== JSON.stringify(offered)
374
- ) {
404
+ if (!equalEfforts(this.byModel.get(model.id), offered)) {
375
405
  this.byModel.set(model.id, offered)
376
406
  changed = true
377
407
  }
@@ -419,16 +449,8 @@ export class ModelCatalog {
419
449
  private load(expectedFingerprint?: string): CatalogModel[] | undefined {
420
450
  if (!existsSync(this.cachePath)) return undefined
421
451
  try {
422
- const parsed = JSON.parse(readFileSync(this.cachePath, 'utf8')) as {
423
- models?: CatalogModel[]
424
- efforts?: string[]
425
- byModel?: Record<string, string[]>
426
- contextWindows?: Record<string, unknown>
427
- tier?: AcpTierInfo
428
- supportsImage?: unknown
429
- binaryFingerprint?: unknown
430
- } | null
431
- if (parsed === null || typeof parsed !== 'object') return undefined
452
+ const parsed: unknown = JSON.parse(readFileSync(this.cachePath, 'utf8'))
453
+ if (!isRecord(parsed)) return undefined
432
454
  const storedFingerprint =
433
455
  typeof parsed.binaryFingerprint === 'string' &&
434
456
  parsed.binaryFingerprint.length > 0
@@ -438,30 +460,31 @@ export class ModelCatalog {
438
460
  expectedFingerprint === undefined ||
439
461
  storedFingerprint === expectedFingerprint
440
462
  this.observedFingerprint = storedFingerprint
441
- this.tierInfo = normalizeTier(parsed.tier)
463
+ this.tierInfo = normalizeTier(
464
+ isRecord(parsed.tier) ? (parsed.tier as AcpTierInfo) : undefined,
465
+ )
442
466
  if (typeof parsed.supportsImage === 'boolean') {
443
467
  this.supportsImageInput = parsed.supportsImage
444
468
  }
445
469
  if (Array.isArray(parsed.efforts)) {
446
- const efforts = parsed.efforts.filter((v): v is Effort =>
447
- (EFFORTS as readonly string[]).includes(v),
470
+ const efforts = parsed.efforts.filter(
471
+ (v): v is Effort =>
472
+ typeof v === 'string' && (EFFORTS as readonly string[]).includes(v),
448
473
  )
449
474
  if (efforts.length > 0) this.efforts = efforts
450
475
  }
451
- if (parsed.byModel !== null && typeof parsed.byModel === 'object') {
476
+ if (isRecord(parsed.byModel)) {
452
477
  for (const [id, values] of Object.entries(parsed.byModel)) {
453
478
  if (!Array.isArray(values)) continue
454
- const efforts = values.filter((v): v is Effort =>
455
- (EFFORTS as readonly string[]).includes(v),
479
+ const efforts = values.filter(
480
+ (v): v is Effort =>
481
+ typeof v === 'string' &&
482
+ (EFFORTS as readonly string[]).includes(v),
456
483
  )
457
484
  this.byModel.set(id, efforts)
458
485
  }
459
486
  }
460
- if (
461
- fingerprintMatches &&
462
- parsed.contextWindows !== null &&
463
- typeof parsed.contextWindows === 'object'
464
- ) {
487
+ if (fingerprintMatches && isRecord(parsed.contextWindows)) {
465
488
  for (const [id, value] of Object.entries(parsed.contextWindows)) {
466
489
  if (id.length > 0 && isValidContextWindow(value))
467
490
  this.contextWindows.set(id, value)
@@ -469,7 +492,10 @@ export class ModelCatalog {
469
492
  }
470
493
  const models = Array.isArray(parsed.models)
471
494
  ? parsed.models.filter(
472
- (m) => typeof m?.id === 'string' && typeof m?.name === 'string',
495
+ (m): m is CatalogModel =>
496
+ isRecord(m) &&
497
+ typeof m.id === 'string' &&
498
+ typeof m.name === 'string',
473
499
  )
474
500
  : []
475
501
  return models.length > 0 ? models : undefined