pi-agy-acp 0.1.1 → 0.1.3

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/index.ts CHANGED
@@ -2,29 +2,51 @@ import {
2
2
  BorderedLoader,
3
3
  type ExtensionAPI,
4
4
  type ProviderModelConfig,
5
+ type ExtensionContext,
5
6
  } from '@earendil-works/pi-coding-agent'
6
7
  import { AntigravityRuntime } from './src/runtime.ts'
7
- import { defaults } from './src/config.ts'
8
+ import {
9
+ asQuotaDisplay,
10
+ DEFAULT_QUOTA_DISPLAY,
11
+ defaults,
12
+ readQuotaDisplayPreference,
13
+ writeQuotaDisplayPreference,
14
+ type QuotaDisplay,
15
+ } from './src/config.ts'
8
16
  import { spawnAcp, runCommand } from './src/host.ts'
9
17
  import { streamPi } from './src/pi-stream.ts'
10
- import { formatQuota, formatStatus } from './src/format.ts'
18
+ import {
19
+ displayFraction,
20
+ formatQuota,
21
+ formatStatus,
22
+ formatQuotaStatus,
23
+ quotaForModel,
24
+ } from './src/format.ts'
11
25
  import type { QuotaSnapshot } from './src/quota.ts'
12
26
 
13
27
  export default function (pi: ExtensionAPI) {
28
+ const envQuotaDisplay = asQuotaDisplay(process.env.PI_AGY_QUOTA_DISPLAY)
14
29
  const config = {
15
30
  ...defaults,
16
31
  command: process.env.PI_AGY_COMMAND || '',
17
32
  home: process.env.PI_AGY_HOME || '',
18
33
  }
34
+ let refreshDepth = 0
19
35
  const createRuntime = () =>
20
36
  new AntigravityRuntime({
21
37
  config,
22
38
  spawnAcp,
23
39
  runCommand,
24
- log: { info: () => {}, warn: (message) => console.error(message) },
25
- onModelsChanged: () => register(),
40
+ log: { info: () => {}, warn: () => {} },
41
+ onModelsChanged: () => {
42
+ if (refreshDepth === 0) register()
43
+ },
26
44
  })
27
45
  let runtime = createRuntime()
46
+ let quotaDisplay: QuotaDisplay =
47
+ envQuotaDisplay ??
48
+ readQuotaDisplayPreference(runtime.status().home) ??
49
+ DEFAULT_QUOTA_DISPLAY
28
50
  const models = (): ProviderModelConfig[] =>
29
51
  runtime.catalog.list().map((m) => {
30
52
  const efforts = runtime.catalog.effortsFor(m.id)
@@ -60,42 +82,154 @@ export default function (pi: ExtensionAPI) {
60
82
  streamSimple: (model, context, options) =>
61
83
  streamPi(runtime, model, context, options),
62
84
  refreshModels: async (context) => {
63
- if (context?.allowNetwork !== false && !context?.signal?.aborted) {
64
- await runtime.warmup()
85
+ refreshDepth++
86
+ try {
87
+ if (context?.allowNetwork !== false && !context?.signal?.aborted) {
88
+ await runtime.warmup({
89
+ force: context?.force,
90
+ signal: context?.signal,
91
+ })
92
+ }
93
+ return models()
94
+ } finally {
95
+ refreshDepth--
65
96
  }
66
- return models()
67
97
  },
68
98
  })
69
99
  register()
100
+ let uiEpoch = 0
101
+ let checkingQuota = false
102
+ const warned = new Set<string>()
103
+ const clearStatus = (ctx?: ExtensionContext) => {
104
+ uiEpoch++
105
+ if (ctx?.hasUI) ctx.ui.setStatus(config.provider, undefined)
106
+ }
107
+ const updateStatus = (
108
+ ctx: ExtensionContext,
109
+ snapshot?: QuotaSnapshot,
110
+ explicit = false,
111
+ model = ctx.model,
112
+ ) => {
113
+ if (ctx.hasUI && (explicit || model?.provider === config.provider))
114
+ ctx.ui.setStatus(
115
+ config.provider,
116
+ snapshot
117
+ ? formatQuotaStatus(snapshot, model?.id, quotaDisplay)
118
+ : undefined,
119
+ )
120
+ }
70
121
  const reset = async () => {
122
+ uiEpoch++
123
+ warned.clear()
71
124
  await runtime.dispose()
72
125
  runtime = createRuntime()
73
126
  }
74
- pi.on('session_tree', reset)
75
- pi.on('session_compact', reset)
76
- pi.on('session_shutdown', async () => {
127
+ pi.on('session_tree', () => runtime.resetConversations())
128
+ pi.on('session_compact', () => runtime.resetConversations())
129
+ pi.on('session_start', async (event, ctx) => {
130
+ clearStatus(ctx)
131
+ if (['new', 'resume', 'fork'].includes(event.reason))
132
+ await runtime.resetConversations()
133
+ updateStatus(ctx, runtime.quota.peek())
134
+ })
135
+ pi.on('session_shutdown', async (_event, ctx) => {
136
+ clearStatus(ctx)
77
137
  await runtime.dispose()
78
138
  })
139
+ pi.on('cache_warming_decision', () => ({ action: 'stop' }))
140
+ pi.on('model_select', (event, ctx) => {
141
+ clearStatus(ctx)
142
+ updateStatus(ctx, runtime.quota.peek(), false, event.model)
143
+ })
144
+ pi.on('agent_settled', (_event, ctx) => {
145
+ // Pi 1.5.2 AgentSession._emitAgentSettled runs after tools and the run finish.
146
+ runtime.settleSession(ctx.sessionManager.getSessionId())
147
+ if (
148
+ ctx.model?.provider !== config.provider ||
149
+ checkingQuota ||
150
+ runtime.quota.pending
151
+ )
152
+ return
153
+ const current = runtime
154
+ const epoch = uiEpoch
155
+ checkingQuota = true
156
+ void current.quota
157
+ .read(false)
158
+ .then((snapshot) => {
159
+ if (
160
+ current !== runtime ||
161
+ epoch !== uiEpoch ||
162
+ snapshot.status !== 'ok'
163
+ )
164
+ return
165
+ updateStatus(ctx, snapshot)
166
+ if (!ctx.hasUI || ctx.model?.provider !== config.provider) return
167
+ const quota = quotaForModel(snapshot, ctx.model.id)
168
+ if (!quota || quota.fraction > 0.2) return
169
+ const threshold = quota.fraction <= 0.05 ? 5 : 20
170
+ const key = `${quota.group.name}:${quota.bucket.id}:${quota.bucket.window}:${quota.bucket.resetTime || 'none'}:${threshold}`
171
+ if (warned.has(key)) return
172
+ warned.add(key)
173
+ const percent = Math.round(
174
+ displayFraction(quota.fraction, quotaDisplay) * 100,
175
+ )
176
+ const metric = `${percent}% ${quotaDisplay}`
177
+ ctx.ui.notify(
178
+ `Antigravity quota low: ${metric} (${quota.group.name}, ${quota.bucket.window}).`,
179
+ 'warning',
180
+ )
181
+ })
182
+ .catch(() => {})
183
+ .finally(() => {
184
+ checkingQuota = false
185
+ })
186
+ })
79
187
  pi.registerCommand('agy-acp', {
80
188
  description: 'Antigravity ACP status, quota, or reset',
81
189
  getArgumentCompletions: (prefix) => {
82
- const items = ['status', 'quota', 'reset']
83
- .filter((command) => command.startsWith(prefix.trim()))
190
+ const normalized = prefix.trimStart()
191
+ const items = [
192
+ 'status',
193
+ 'quota',
194
+ 'quota used',
195
+ 'quota remaining',
196
+ 'reset',
197
+ ]
198
+ .filter((command) => command.startsWith(normalized))
84
199
  .map((value) => ({ value, label: value }))
85
200
  return items.length > 0 ? items : null
86
201
  },
87
202
  handler: async (args, ctx) => {
88
- const command = args.trim()
89
- if (command === 'reset') {
203
+ const tokens = args.trim().split(/\s+/).filter(Boolean)
204
+ const command = tokens[0] ?? ''
205
+ const requestedDisplay =
206
+ command === 'quota' && tokens.length === 2
207
+ ? asQuotaDisplay(tokens[1])
208
+ : undefined
209
+ if (command === 'reset' && tokens.length === 1) {
210
+ clearStatus(ctx)
90
211
  await reset()
91
212
  ctx.ui.notify('Antigravity ACP sessions reset', 'info')
92
213
  return
93
214
  }
94
- if (command !== '' && command !== 'status' && command !== 'quota') {
95
- ctx.ui.notify('Usage: /agy-acp [status|quota|reset]', 'warning')
215
+ const isStatus =
216
+ (command === '' || command === 'status') && tokens.length <= 1
217
+ const isQuota =
218
+ command === 'quota' &&
219
+ (tokens.length === 1 || requestedDisplay !== undefined)
220
+ if (!isStatus && !isQuota) {
221
+ ctx.ui.notify(
222
+ 'Usage: /agy-acp [status|quota [used|remaining]|reset]',
223
+ 'warning',
224
+ )
96
225
  return
97
226
  }
227
+ if (requestedDisplay !== undefined) {
228
+ quotaDisplay = requestedDisplay
229
+ writeQuotaDisplayPreference(runtime.status().home, quotaDisplay)
230
+ }
98
231
  let snapshot: QuotaSnapshot | null = null
232
+ const epoch = uiEpoch
99
233
  if (command === 'quota') {
100
234
  snapshot =
101
235
  ctx.mode === 'tui' && typeof ctx.ui.custom === 'function'
@@ -116,13 +250,17 @@ export default function (pi: ExtensionAPI) {
116
250
  )
117
251
  : await runtime.readQuota(true)
118
252
  if (snapshot === null) {
253
+ if (epoch === uiEpoch)
254
+ updateStatus(ctx, runtime.quota.peek(), true)
119
255
  ctx.ui.notify('Quota check cancelled', 'info')
120
256
  return
121
257
  }
122
258
  }
123
259
  const notice = snapshot
124
- ? formatQuota(snapshot)
260
+ ? formatQuota(snapshot, undefined, quotaDisplay)
125
261
  : formatStatus(runtime.status())
262
+ if (epoch === uiEpoch)
263
+ updateStatus(ctx, snapshot ?? runtime.quota.peek(), true)
126
264
  ctx.ui.notify(notice.text, notice.level)
127
265
  },
128
266
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-agy-acp",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Google Antigravity ACP provider extension for Pi Coding Agent",
@@ -21,16 +21,18 @@
21
21
  "index.ts",
22
22
  "src",
23
23
  "README.md",
24
+ "CHANGELOG.md",
24
25
  "docs",
25
26
  "LICENSE",
26
27
  "NOTICE"
27
28
  ],
28
29
  "engines": {
29
- "node": ">=22.18.0"
30
+ "node": ">=22.19.0"
30
31
  },
31
32
  "peerDependencies": {
32
33
  "@earendil-works/pi-ai": "*",
33
- "@earendil-works/pi-coding-agent": "*"
34
+ "@earendil-works/pi-coding-agent": "*",
35
+ "@earendil-works/pi-tui": "*"
34
36
  },
35
37
  "scripts": {
36
38
  "test": "node --test tests/*.test.mjs",
@@ -38,7 +40,10 @@
38
40
  },
39
41
  "devDependencies": {
40
42
  "typescript": "^5.9.0",
41
- "@types/node": "^22.0.0"
43
+ "@types/node": "^22.0.0",
44
+ "@earendil-works/pi-ai": "~1.5.0",
45
+ "@earendil-works/pi-coding-agent": "~1.5.0",
46
+ "@earendil-works/pi-tui": "~1.5.0"
42
47
  },
43
48
  "keywords": [
44
49
  "pi-package",
@@ -136,8 +136,6 @@ export class AcpProcess {
136
136
  private child: AcpChild | undefined
137
137
  private peer: JsonRpcPeer | undefined
138
138
  private exitError: Error | undefined
139
- /** Agent `initialize` result. */
140
- initializeResult: Record<string, unknown> | undefined
141
139
  private readonly exitListeners = new Set<(error: Error) => void>()
142
140
  private readonly options: AcpProcessOptions
143
141
 
@@ -188,7 +186,7 @@ export class AcpProcess {
188
186
  peer.close(error)
189
187
  this.fail(error)
190
188
  })
191
- this.initializeResult = await peer.request<Record<string, unknown>>(
189
+ await peer.request(
192
190
  'initialize',
193
191
  {
194
192
  protocolVersion: 1,
@@ -204,7 +202,9 @@ export class AcpProcess {
204
202
 
205
203
  /** Terminate the process. */
206
204
  stop(): void {
207
- this.fail(new Error('ACP process stopped'))
205
+ const error = new Error('ACP process stopped')
206
+ this.fail(error)
207
+ this.peer?.close(error)
208
208
  this.child?.terminate()
209
209
  }
210
210
 
@@ -225,7 +225,8 @@ export class AcpProcess {
225
225
  params,
226
226
  { timeoutMs },
227
227
  )
228
- this.listeners.set(result.sessionId, listener)
228
+ // JsonRpcPeer can resolve a buffered reply before stop; leave its rollback to the owner.
229
+ if (this.alive) this.listeners.set(result.sessionId, listener)
229
230
  return result
230
231
  }
231
232
 
@@ -309,6 +310,7 @@ export class AcpProcess {
309
310
  private fail(error: Error): void {
310
311
  if (this.exitError !== undefined) return
311
312
  this.exitError = error
313
+ this.listeners.clear()
312
314
  for (const listener of this.exitListeners) listener(error)
313
315
  }
314
316
 
package/src/config.ts CHANGED
@@ -1,8 +1,24 @@
1
+ import {
2
+ mkdirSync,
3
+ readFileSync,
4
+ renameSync,
5
+ unlinkSync,
6
+ writeFileSync,
7
+ } from 'node:fs'
8
+ import { join } from 'node:path'
9
+
1
10
  /** Reasoning effort ids accepted by the Antigravity ACP `thought_level` option. */
2
11
  export const EFFORTS = ['low', 'medium', 'high'] as const
3
12
  /** One Antigravity reasoning effort. */
4
13
  export type Effort = (typeof EFFORTS)[number]
5
14
 
15
+ /** Supported quota percentage display conventions. */
16
+ export const QUOTA_DISPLAY_MODES = ['used', 'remaining'] as const
17
+ /** Quota percentage display convention (`used` counts up from 0%, `remaining` counts down from 100%). */
18
+ export type QuotaDisplay = (typeof QUOTA_DISPLAY_MODES)[number]
19
+ /** Default quota percentage display convention when no env var or saved preference is set. */
20
+ export const DEFAULT_QUOTA_DISPLAY: QuotaDisplay = 'used'
21
+
6
22
  /** Validated plugin configuration. */
7
23
  export interface Config {
8
24
  /** Provider route id shown in the model picker. */
@@ -45,6 +61,65 @@ export const defaults: Config = {
45
61
  longDecodeContinuations: 3,
46
62
  quotaTtlMs: 120000,
47
63
  }
64
+
48
65
  export function asEffort(value: string | undefined): Effort | undefined {
49
66
  return EFFORTS.includes(value as Effort) ? (value as Effort) : undefined
50
67
  }
68
+
69
+ export function asQuotaDisplay(
70
+ value: string | undefined,
71
+ ): QuotaDisplay | undefined {
72
+ const normalized = value?.trim().toLowerCase()
73
+ return QUOTA_DISPLAY_MODES.includes(normalized as QuotaDisplay)
74
+ ? (normalized as QuotaDisplay)
75
+ : undefined
76
+ }
77
+
78
+ const SETTINGS_FILE = 'settings.json'
79
+
80
+ /** Read a JSON file as a plain object, returning `{}` when missing or invalid. */
81
+ export function readJson(path: string): Record<string, unknown> {
82
+ try {
83
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))
84
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
85
+ ? (parsed as Record<string, unknown>)
86
+ : {}
87
+ } catch {
88
+ return {}
89
+ }
90
+ }
91
+
92
+ /** Read the last remembered quota display preference from `home/settings.json`. */
93
+ export function readQuotaDisplayPreference(
94
+ home: string,
95
+ ): QuotaDisplay | undefined {
96
+ const settings = readJson(join(home, SETTINGS_FILE))
97
+ return typeof settings.quotaDisplay === 'string'
98
+ ? asQuotaDisplay(settings.quotaDisplay)
99
+ : undefined
100
+ }
101
+
102
+ /** Persist the user's quota display preference in `home/settings.json`. */
103
+ export function writeQuotaDisplayPreference(
104
+ home: string,
105
+ quotaDisplay: QuotaDisplay,
106
+ ): void {
107
+ const path = join(home, SETTINGS_FILE)
108
+ const tempPath = join(
109
+ home,
110
+ `.${SETTINGS_FILE}.${process.pid}.${Date.now()}.tmp`,
111
+ )
112
+ try {
113
+ mkdirSync(home, { recursive: true })
114
+ const existing = readJson(path)
115
+ const content = `${JSON.stringify({ ...existing, quotaDisplay }, null, 2)}\n`
116
+ writeFileSync(tempPath, content)
117
+ renameSync(tempPath, path)
118
+ } catch {
119
+ try {
120
+ unlinkSync(tempPath)
121
+ } catch {
122
+ // Best-effort cleanup.
123
+ }
124
+ }
125
+ }