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/catalog.ts CHANGED
@@ -7,8 +7,20 @@
7
7
  * @module pi-agy-acp/catalog
8
8
  */
9
9
 
10
- import { existsSync, readFileSync, writeFileSync } from 'node:fs'
11
- import type { AcpConfigOption, AcpTierInfo } from './acp-process.ts'
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'
19
+ import type {
20
+ AcpConfigOption,
21
+ AcpConfigOptionValue,
22
+ AcpTierInfo,
23
+ } from './acp-process.ts'
12
24
  import { EFFORTS, type Effort } from './config.ts'
13
25
 
14
26
  /** One advertised model family. */
@@ -23,17 +35,38 @@ export interface AvailableModel {
23
35
  name?: string
24
36
  }
25
37
 
26
- /** Families shown before the first ACP session reports the account's catalog. */
27
- export const FALLBACK_MODELS: readonly CatalogModel[] = [
28
- { id: 'gemini-4-argon', name: 'Gemini 4 Argon' },
29
- { id: 'gemini-3.8-flash', name: 'Gemini 3.8 Flash' },
30
- { id: 'claude-opus-5-5', name: 'Claude Opus 5.5' },
31
- { id: 'claude-sonnet-5-5', name: 'Claude Sonnet 5.5' },
32
- { id: 'gpt-oss-120b-medium', name: 'GPT-OSS 120B' },
33
- ]
38
+ /** Flatten flat or grouped ACP select option entries. */
39
+ export function flattenConfigOptions(
40
+ options: AcpConfigOption['options'],
41
+ ): AcpConfigOptionValue[] {
42
+ if (!Array.isArray(options)) return []
43
+ return options.flatMap((entry) => {
44
+ if (entry === null || typeof entry !== 'object') return []
45
+ return 'group' in entry
46
+ ? Array.isArray(entry.options)
47
+ ? entry.options
48
+ : []
49
+ : [entry]
50
+ })
51
+ }
52
+
53
+ /** Effort suffixes ordered longest-first so `-<effort>-effort` beats `-<effort>`. */
54
+ const EFFORT_SUFFIXES: readonly { suffix: string; effort: Effort }[] =
55
+ EFFORTS.flatMap((effort) => [
56
+ { suffix: `-${effort}-effort`, effort },
57
+ { suffix: `-${effort}`, effort },
58
+ ]).sort((a, b) => b.suffix.length - a.suffix.length)
34
59
 
35
- /** An id that already names one fixed effort instead of a selectable family. */
36
- const FIXED_EFFORT = /-(low|medium|high)$/
60
+ function splitEffortSuffix(
61
+ id: string,
62
+ ): { base: string; effort: Effort } | undefined {
63
+ for (const { suffix, effort } of EFFORT_SUFFIXES) {
64
+ if (id.length > suffix.length && id.endsWith(suffix)) {
65
+ return { base: id.slice(0, -suffix.length), effort }
66
+ }
67
+ }
68
+ return undefined
69
+ }
37
70
 
38
71
  function normalizeTier(
39
72
  tier: AcpTierInfo | undefined,
@@ -68,25 +101,79 @@ function isValidContextWindow(value: unknown): value is number {
68
101
  return typeof value === 'number' && Number.isInteger(value) && value > 0
69
102
  }
70
103
 
71
- /** Observed catalog with a disk cache. */
104
+ /** Observed catalog with a disk cache. Starts empty until loaded or observed from ACP. */
72
105
  export class ModelCatalog {
73
106
  private models: CatalogModel[]
74
107
  private tierInfo: { id?: string; name: string } | undefined
75
- private efforts: Effort[] = [...EFFORTS]
76
- /** Efforts per model family; an empty array marks a fixed-effort model. */
108
+ private efforts: Effort[] = []
109
+ /** Efforts per model family; an empty array marks a fixed-effort or non-selectable model. */
77
110
  private byModel = new Map<string, Effort[]>()
78
111
  /** Server-reported `max_context_tokens` keyed by model id. */
79
112
  private readonly contextWindows = new Map<string, number>()
113
+ /** Server-reported `agentCapabilities.promptCapabilities.image` from `initialize`. */
114
+ private supportsImageInput: boolean | undefined
80
115
  /** Latest `availableModels` snapshot, kept for later option updates. */
81
116
  private available: readonly AvailableModel[] | undefined
117
+ /** Subprocess-free fingerprint of the `agy` binary that produced the cached catalog. */
118
+ private binaryFingerprint: string | undefined
119
+ /** Set when `binaryFingerprint` differs from the value last persisted on disk. */
120
+ private fingerprintDirty = false
82
121
  /** Whether a live ACP session has reported the catalog. */
83
122
  observed = false
84
123
  private readonly cachePath: string
85
124
 
86
- /** @param cachePath - JSON cache file. */
87
- constructor(cachePath: string) {
125
+ /**
126
+ * @param cachePath - JSON cache file.
127
+ * @param binaryFingerprint - current `agy` binary fingerprint, if resolved.
128
+ */
129
+ constructor(cachePath: string, binaryFingerprint?: string) {
88
130
  this.cachePath = cachePath
89
- this.models = this.load() ?? [...FALLBACK_MODELS]
131
+ this.models = this.load(binaryFingerprint) ?? []
132
+ if (binaryFingerprint && this.binaryFingerprint === undefined) {
133
+ this.binaryFingerprint = binaryFingerprint
134
+ }
135
+ }
136
+
137
+ /** Input modalities advertised to Pi, derived from `initialize` `promptCapabilities.image`. */
138
+ inputModalities(): ('text' | 'image')[] {
139
+ return this.supportsImageInput === false ? ['text'] : ['text', 'image']
140
+ }
141
+
142
+ /**
143
+ * Record `agentCapabilities.promptCapabilities.image` from ACP `initialize`.
144
+ * @returns whether the advertised input modalities changed.
145
+ */
146
+ observeImageSupport(supported: boolean | undefined): boolean {
147
+ if (typeof supported !== 'boolean') return false
148
+ const before = this.supportsImageInput !== false
149
+ const changed = this.supportsImageInput !== supported
150
+ if (!changed) return false
151
+ this.supportsImageInput = supported
152
+ this.save()
153
+ return before !== supported
154
+ }
155
+
156
+ /**
157
+ * Reconcile cached state against the current `agy` binary fingerprint.
158
+ * Invalidates cached `contextWindows` and `observed` when the binary changed
159
+ * so the next warmup or session re-probes fresh models and context limits.
160
+ * @returns whether cached context windows were invalidated.
161
+ */
162
+ syncBinaryFingerprint(fingerprint: string | undefined): boolean {
163
+ if (!fingerprint) return false
164
+ if (this.binaryFingerprint === fingerprint) return false
165
+ const hadContextWindows = this.contextWindows.size > 0
166
+ const hadState =
167
+ this.binaryFingerprint !== undefined || hadContextWindows || this.observed
168
+ this.binaryFingerprint = fingerprint
169
+ if (hadState) {
170
+ this.contextWindows.clear()
171
+ this.observed = false
172
+ this.fingerprintDirty = true
173
+ this.save()
174
+ return hadContextWindows
175
+ }
176
+ return false
90
177
  }
91
178
 
92
179
  /**
@@ -138,7 +225,7 @@ export class ModelCatalog {
138
225
 
139
226
  /**
140
227
  * Efforts one family actually offers. Empty means the family is a single
141
- * fixed variant (for example `gpt-oss-120b-medium`).
228
+ * fixed variant (for example `gpt-oss-120b-medium`) or offers no selector.
142
229
  * @param id - family id.
143
230
  * @returns offered efforts.
144
231
  */
@@ -148,14 +235,23 @@ export class ModelCatalog {
148
235
  return this.fixedEffort(id) === undefined ? this.efforts : []
149
236
  }
150
237
 
238
+ /**
239
+ * Whether a model accepts `thought_level` writes on a live ACP session.
240
+ * Fixed-effort models and models observed with zero effort variants return false.
241
+ */
242
+ supportsEffortSelection(id: string): boolean {
243
+ const observed = this.byModel.get(id)
244
+ if (observed !== undefined) return observed.length > 0
245
+ return this.fixedEffort(id) === undefined
246
+ }
247
+
151
248
  /**
152
249
  * Effort baked into a fixed-variant id.
153
250
  * @param id - family id.
154
251
  * @returns the effort, or undefined for a selectable family.
155
252
  */
156
253
  fixedEffort(id: string): Effort | undefined {
157
- const match = FIXED_EFFORT.exec(id)
158
- return match === null ? undefined : (match[1] as Effort)
254
+ return splitEffortSuffix(id)?.effort
159
255
  }
160
256
 
161
257
  /**
@@ -189,38 +285,76 @@ export class ModelCatalog {
189
285
  (o) => o.id === 'thought_level' || o.category === 'thought_level',
190
286
  )
191
287
  const beforeEfforts = JSON.stringify(this.efforts)
192
- if (levelOption?.options !== undefined) {
193
- const offered = levelOption.options
194
- .map((o) => o.value)
195
- .filter((v): v is Effort => (EFFORTS as readonly string[]).includes(v))
196
- if (offered.length > 0)
197
- this.efforts = EFFORTS.filter((e) => offered.includes(e))
198
- }
199
- const next = modelOption?.options?.length
200
- ? modelOption.options.map((o) => ({
201
- id: o.value,
202
- name: o.name ?? o.value,
203
- }))
204
- : this.models
288
+ const levelEfforts =
289
+ levelOption?.options !== undefined
290
+ ? flattenConfigOptions(levelOption.options)
291
+ .map((o) => o.value)
292
+ .filter((v): v is Effort =>
293
+ (EFFORTS as readonly string[]).includes(v),
294
+ )
295
+ : []
296
+ const modelEntries = flattenConfigOptions(modelOption?.options)
297
+ const next =
298
+ modelEntries.length > 0
299
+ ? modelEntries.map((o) => ({
300
+ id: o.value,
301
+ name: o.name ?? o.value,
302
+ }))
303
+ : this.models
205
304
  this.observed = true
206
305
  const changed = JSON.stringify(next) !== JSON.stringify(this.models)
207
306
  if (changed) this.models = next
307
+ let prunedChanged = false
308
+ if (modelEntries.length > 0) {
309
+ const activeIds = new Set(this.models.map((m) => m.id))
310
+ for (const id of [...this.byModel.keys()]) {
311
+ if (!activeIds.has(id)) {
312
+ this.byModel.delete(id)
313
+ prunedChanged = true
314
+ }
315
+ }
316
+ }
317
+ const derivedChanged = this.deriveEfforts()
318
+ const union = new Set<Effort>(levelEfforts)
319
+ for (const model of this.models) {
320
+ const values = this.byModel.get(model.id)
321
+ if (values !== undefined) {
322
+ for (const effort of values) union.add(effort)
323
+ }
324
+ }
325
+ if (union.size > 0) {
326
+ this.efforts = EFFORTS.filter((e) => union.has(e))
327
+ }
208
328
  const effortsChanged =
209
- this.deriveEfforts() || beforeEfforts !== JSON.stringify(this.efforts)
210
- if (changed || effortsChanged || tierChanged) this.save()
329
+ prunedChanged ||
330
+ derivedChanged ||
331
+ beforeEfforts !== JSON.stringify(this.efforts)
332
+ if (changed || effortsChanged || tierChanged || this.fingerprintDirty)
333
+ this.save()
211
334
  return changed || effortsChanged
212
335
  }
213
336
 
214
337
  /** Recompute per-family efforts from the latest inventory. */
215
338
  private deriveEfforts(): boolean {
216
339
  if (this.available === undefined) return false
340
+ const byBase = new Map<string, Set<Effort>>()
341
+ for (const entry of this.available) {
342
+ const split = splitEffortSuffix(entry.modelId)
343
+ if (split === undefined) continue
344
+ let set = byBase.get(split.base)
345
+ if (set === undefined) {
346
+ set = new Set<Effort>()
347
+ byBase.set(split.base, set)
348
+ }
349
+ set.add(split.effort)
350
+ }
217
351
  let changed = false
218
352
  for (const model of this.models) {
219
- const offered = EFFORTS.filter((effort) =>
220
- this.available!.some(
221
- (entry) => entry.modelId === `${model.id}-${effort}`,
222
- ),
223
- )
353
+ const matched = byBase.get(model.id)
354
+ const offered =
355
+ matched !== undefined
356
+ ? EFFORTS.filter((effort) => matched.has(effort))
357
+ : []
224
358
  if (offered.length > 0) {
225
359
  if (
226
360
  JSON.stringify(this.byModel.get(model.id)) !== JSON.stringify(offered)
@@ -230,24 +364,27 @@ export class ModelCatalog {
230
364
  }
231
365
  continue
232
366
  }
233
- const present = this.available.some(
234
- (entry) =>
235
- entry.modelId === model.id ||
236
- entry.modelId.startsWith(`${model.id}-`),
237
- )
367
+ const present = this.available.some((entry) => entry.modelId === model.id)
238
368
  if (!present) continue
239
- if ((this.byModel.get(model.id) ?? []).length !== 0) {
369
+ const prevEfforts = this.effortsFor(model.id)
370
+ if (this.byModel.get(model.id)?.length !== 0) {
240
371
  this.byModel.set(model.id, [])
241
- changed = true
372
+ if (prevEfforts.length !== 0) changed = true
242
373
  }
243
374
  }
244
375
  return changed
245
376
  }
246
377
 
247
378
  private save(): void {
379
+ const dir = dirname(this.cachePath)
380
+ const tempPath = join(
381
+ dir,
382
+ `.${basename(this.cachePath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2, 8)}.tmp`,
383
+ )
248
384
  try {
385
+ mkdirSync(dir, { recursive: true })
249
386
  writeFileSync(
250
- this.cachePath,
387
+ tempPath,
251
388
  `${JSON.stringify(
252
389
  {
253
390
  models: this.models,
@@ -255,17 +392,30 @@ export class ModelCatalog {
255
392
  byModel: Object.fromEntries(this.byModel),
256
393
  contextWindows: Object.fromEntries(this.contextWindows),
257
394
  tier: this.tierInfo,
395
+ ...(this.supportsImageInput !== undefined
396
+ ? { supportsImage: this.supportsImageInput }
397
+ : {}),
398
+ ...(this.binaryFingerprint !== undefined
399
+ ? { binaryFingerprint: this.binaryFingerprint }
400
+ : {}),
258
401
  },
259
402
  null,
260
403
  2,
261
404
  )}\n`,
262
405
  )
406
+ renameSync(tempPath, this.cachePath)
407
+ this.fingerprintDirty = false
263
408
  } catch (_cacheWrite) {
409
+ try {
410
+ unlinkSync(tempPath)
411
+ } catch {
412
+ // Best-effort cleanup.
413
+ }
264
414
  // The cache only speeds up the next cold start.
265
415
  }
266
416
  }
267
417
 
268
- private load(): CatalogModel[] | undefined {
418
+ private load(expectedFingerprint?: string): CatalogModel[] | undefined {
269
419
  if (!existsSync(this.cachePath)) return undefined
270
420
  try {
271
421
  const parsed = JSON.parse(readFileSync(this.cachePath, 'utf8')) as {
@@ -274,9 +424,26 @@ export class ModelCatalog {
274
424
  byModel?: Record<string, string[]>
275
425
  contextWindows?: Record<string, unknown>
276
426
  tier?: AcpTierInfo
427
+ supportsImage?: unknown
428
+ binaryFingerprint?: unknown
277
429
  } | null
278
430
  if (parsed === null || typeof parsed !== 'object') return undefined
431
+ const storedFingerprint =
432
+ typeof parsed.binaryFingerprint === 'string' &&
433
+ parsed.binaryFingerprint.length > 0
434
+ ? parsed.binaryFingerprint
435
+ : undefined
436
+ const fingerprintMatches =
437
+ expectedFingerprint === undefined ||
438
+ storedFingerprint === expectedFingerprint
439
+ this.binaryFingerprint = fingerprintMatches
440
+ ? (storedFingerprint ?? expectedFingerprint)
441
+ : expectedFingerprint
442
+ this.fingerprintDirty = !fingerprintMatches
279
443
  this.tierInfo = normalizeTier(parsed.tier)
444
+ if (typeof parsed.supportsImage === 'boolean') {
445
+ this.supportsImageInput = parsed.supportsImage
446
+ }
280
447
  if (Array.isArray(parsed.efforts)) {
281
448
  const efforts = parsed.efforts.filter((v): v is Effort =>
282
449
  (EFFORTS as readonly string[]).includes(v),
@@ -293,6 +460,7 @@ export class ModelCatalog {
293
460
  }
294
461
  }
295
462
  if (
463
+ fingerprintMatches &&
296
464
  parsed.contextWindows !== null &&
297
465
  typeof parsed.contextWindows === 'object'
298
466
  ) {
@@ -308,7 +476,7 @@ export class ModelCatalog {
308
476
  : []
309
477
  return models.length > 0 ? models : undefined
310
478
  } catch (_cacheRead) {
311
- // A corrupt cache falls back to the built-in families.
479
+ // A corrupt cache starts empty until live ACP discovery populates it.
312
480
  return undefined
313
481
  }
314
482
  }
package/src/config.ts CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  import { join } from 'node:path'
9
9
 
10
10
  /** Reasoning effort ids accepted by the Antigravity ACP `thought_level` option. */
11
- export const EFFORTS = ['low', 'medium', 'high'] as const
11
+ export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const
12
12
  /** One Antigravity reasoning effort. */
13
13
  export type Effort = (typeof EFFORTS)[number]
14
14