pi-agy-acp 0.2.2 → 0.2.4

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.
@@ -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) => [
@@ -114,11 +126,11 @@ export class ModelCatalog {
114
126
  private supportsImageInput: boolean | undefined
115
127
  /** Latest `availableModels` snapshot, kept for later option updates. */
116
128
  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
121
- /** Whether a live ACP session has reported the catalog. */
129
+ /** Current on-disk `agy` binary fingerprint, if resolved. */
130
+ private currentFingerprint: string | undefined
131
+ /** Fingerprint of the `agy` binary that produced the cached catalog. */
132
+ private observedFingerprint: string | undefined
133
+ /** Whether a live ACP session has reported the catalog in this process. */
122
134
  observed = false
123
135
  private readonly cachePath: string
124
136
 
@@ -128,10 +140,22 @@ export class ModelCatalog {
128
140
  */
129
141
  constructor(cachePath: string, binaryFingerprint?: string) {
130
142
  this.cachePath = cachePath
143
+ this.currentFingerprint = binaryFingerprint
131
144
  this.models = this.load(binaryFingerprint) ?? []
132
- if (binaryFingerprint && this.binaryFingerprint === undefined) {
133
- this.binaryFingerprint = binaryFingerprint
134
- }
145
+ }
146
+
147
+ /** Whether disk-cached models match the current `agy` binary fingerprint. */
148
+ hasFreshCache(): boolean {
149
+ return (
150
+ this.models.length > 0 &&
151
+ (this.currentFingerprint === undefined ||
152
+ this.observedFingerprint === this.currentFingerprint)
153
+ )
154
+ }
155
+
156
+ /** Whether the catalog is current without probing ACP. */
157
+ isCurrent(): boolean {
158
+ return this.observed || this.hasFreshCache()
135
159
  }
136
160
 
137
161
  /** Input modalities advertised to Pi, derived from `initialize` `promptCapabilities.image`. */
@@ -160,20 +184,15 @@ export class ModelCatalog {
160
184
  * @returns whether cached context windows were invalidated.
161
185
  */
162
186
  syncBinaryFingerprint(fingerprint: string | undefined): boolean {
163
- if (!fingerprint) return false
164
- if (this.binaryFingerprint === fingerprint) return false
187
+ if (!fingerprint || this.currentFingerprint === fingerprint) return false
188
+ this.currentFingerprint = fingerprint
189
+ if (this.observedFingerprint === fingerprint) return false
165
190
  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
191
+ this.contextWindows.clear()
192
+ this.observed = false
193
+ // Persist cleared contextWindows while keeping observedFingerprint intact until live ACP re-observes.
194
+ if (hadContextWindows) this.save()
195
+ return hadContextWindows
177
196
  }
178
197
 
179
198
  /**
@@ -278,21 +297,10 @@ export class ModelCatalog {
278
297
  if (tierChanged) this.save()
279
298
  return false
280
299
  }
281
- const modelOption = options.find(
282
- (o) => o.id === 'model' || o.category === 'model',
283
- )
284
- const levelOption = options.find(
285
- (o) => o.id === 'thought_level' || o.category === 'thought_level',
286
- )
300
+ const modelOption = findConfigOption(options, 'model')
301
+ const levelOption = findConfigOption(options, 'thought_level')
287
302
  const beforeEfforts = JSON.stringify(this.efforts)
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
- : []
303
+ const levelEfforts = offeredEffortsFrom(levelOption) ?? []
296
304
  const modelEntries = flattenConfigOptions(modelOption?.options)
297
305
  const next =
298
306
  modelEntries.length > 0
@@ -304,6 +312,11 @@ export class ModelCatalog {
304
312
  this.observed = true
305
313
  const changed = JSON.stringify(next) !== JSON.stringify(this.models)
306
314
  if (changed) this.models = next
315
+ const fingerprintChanged =
316
+ modelEntries.length > 0 &&
317
+ this.currentFingerprint !== undefined &&
318
+ this.observedFingerprint !== this.currentFingerprint
319
+ if (fingerprintChanged) this.observedFingerprint = this.currentFingerprint
307
320
  let prunedChanged = false
308
321
  if (modelEntries.length > 0) {
309
322
  const activeIds = new Set(this.models.map((m) => m.id))
@@ -329,7 +342,7 @@ export class ModelCatalog {
329
342
  prunedChanged ||
330
343
  derivedChanged ||
331
344
  beforeEfforts !== JSON.stringify(this.efforts)
332
- if (changed || effortsChanged || tierChanged || this.fingerprintDirty)
345
+ if (changed || effortsChanged || tierChanged || fingerprintChanged)
333
346
  this.save()
334
347
  return changed || effortsChanged
335
348
  }
@@ -376,15 +389,10 @@ export class ModelCatalog {
376
389
  }
377
390
 
378
391
  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
- )
384
392
  try {
385
- mkdirSync(dir, { recursive: true })
386
- writeFileSync(
387
- tempPath,
393
+ mkdirSync(dirname(this.cachePath), { recursive: true })
394
+ atomicWriteFile(
395
+ this.cachePath,
388
396
  `${JSON.stringify(
389
397
  {
390
398
  models: this.models,
@@ -395,22 +403,15 @@ export class ModelCatalog {
395
403
  ...(this.supportsImageInput !== undefined
396
404
  ? { supportsImage: this.supportsImageInput }
397
405
  : {}),
398
- ...(this.binaryFingerprint !== undefined
399
- ? { binaryFingerprint: this.binaryFingerprint }
406
+ ...(this.observedFingerprint !== undefined
407
+ ? { binaryFingerprint: this.observedFingerprint }
400
408
  : {}),
401
409
  },
402
410
  null,
403
411
  2,
404
412
  )}\n`,
405
413
  )
406
- renameSync(tempPath, this.cachePath)
407
- this.fingerprintDirty = false
408
414
  } catch (_cacheWrite) {
409
- try {
410
- unlinkSync(tempPath)
411
- } catch {
412
- // Best-effort cleanup.
413
- }
414
415
  // The cache only speeds up the next cold start.
415
416
  }
416
417
  }
@@ -436,10 +437,7 @@ export class ModelCatalog {
436
437
  const fingerprintMatches =
437
438
  expectedFingerprint === undefined ||
438
439
  storedFingerprint === expectedFingerprint
439
- this.binaryFingerprint = fingerprintMatches
440
- ? (storedFingerprint ?? expectedFingerprint)
441
- : expectedFingerprint
442
- this.fingerprintDirty = !fingerprintMatches
440
+ this.observedFingerprint = storedFingerprint
443
441
  this.tierInfo = normalizeTier(parsed.tier)
444
442
  if (typeof parsed.supportsImage === 'boolean') {
445
443
  this.supportsImageInput = parsed.supportsImage
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. */
@@ -33,7 +28,7 @@ export interface Config {
33
28
  defaultEffort: Effort
34
29
  /** Maximum concurrent ACP sessions kept alive across conversations, subagents, and auxiliary calls. */
35
30
  maxLiveSessions: number
36
- /** Idle time after which an inactive ACP session is closed. */
31
+ /** Idle time after which inactive ACP sessions and an otherwise idle ACP process are closed. */
37
32
  idleSessionTtlMs: number
38
33
  /** Window that groups parallel tool calls into one Pi step. */
39
34
  parkSettleMs: number
@@ -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
  }
@@ -1057,7 +1057,7 @@ async function* stepChunks(
1057
1057
  * @param call - the still-running call.
1058
1058
  * @returns MCP result instructing the agent to keep waiting.
1059
1059
  */
1060
- export function relayNotice(call: ParkedCall): BridgeToolResult {
1060
+ function relayNotice(call: ParkedCall): BridgeToolResult {
1061
1061
  return {
1062
1062
  content: [
1063
1063
  {
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
  }