pi-agy-acp 0.2.4 → 0.2.6
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 +14 -0
- package/README.md +1 -1
- package/docs/architecture.md +29 -14
- package/docs/development.md +1 -1
- package/docs/reference.md +21 -15
- package/package.json +1 -1
- package/src/acp-process.ts +1 -0
- package/src/config.ts +1 -1
- package/src/conversation.ts +115 -57
- package/src/format.ts +3 -3
- package/src/preflight.ts +2 -2
- package/src/quota.ts +8 -8
- package/src/runtime.ts +14 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.2.6](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.5...v0.2.6) (2026-12-03)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* **agy:** adapt to agy 1.5.23 usage subcommand, retry notices, and -32002 errors ([#62](https://github.com/fdkevin0/pi-agy-acp/issues/62)) ([5f9c705](https://github.com/fdkevin0/pi-agy-acp/commit/5f9c705e83ecc4798cb6d7b705dddd33464f1b2e))
|
|
9
|
+
|
|
10
|
+
## [0.2.5](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.4...v0.2.5) (2026-11-28)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
### Bug Fixes
|
|
14
|
+
|
|
15
|
+
* **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)
|
|
16
|
+
|
|
3
17
|
## [0.2.4](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.3...v0.2.4) (2026-11-26)
|
|
4
18
|
|
|
5
19
|
|
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ 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.
|
|
15
|
+
- The official `agy` CLI >= 1.5.23, signed in with your Google account.
|
|
16
16
|
Run `agy` (or `agy acp --login` in headless/SSH terminals) to complete sign-in
|
|
17
17
|
before using the extension.
|
|
18
18
|
|
package/docs/architecture.md
CHANGED
|
@@ -93,8 +93,9 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
|
|
|
93
93
|
`tier`, `contextWindows`, and the subprocess-free binary fingerprint
|
|
94
94
|
(`${realpath}:${dev}:${ino}:${size}:${mtimeNs}`).
|
|
95
95
|
- Both `agy --version` (30 s timeout) and ACP `initialize` (`agentInfo.version`)
|
|
96
|
-
enforce `MIN_AGY_VERSION` (`1.5.
|
|
97
|
-
|
|
96
|
+
enforce `MIN_AGY_VERSION` (`1.5.23`, which adds `agy usage`, standardizes
|
|
97
|
+
`-32002` unknown-session errors across ACP methods, and updates combined
|
|
98
|
+
reasoning+output retry guidance).
|
|
98
99
|
- Non-forced refreshes reuse `catalog.json` without spawning `agy` whenever
|
|
99
100
|
cached models match the current binary fingerprint. Loading a cache with a
|
|
100
101
|
mismatched fingerprint drops cached `contextWindows` while keeping models
|
|
@@ -133,7 +134,9 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
|
|
|
133
134
|
tenant, re-applies model/effort via `select()`, and sends only the delta
|
|
134
135
|
input. Any `JsonRpcRemoteError` from `session/resume` (including `-32603` and
|
|
135
136
|
`-32002`) or history divergence cleans the dormant DB and falls back to
|
|
136
|
-
`session/new` + `replayPrompt()`.
|
|
137
|
+
`session/new` + `replayPrompt()`. Unknown-session `-32002` errors from
|
|
138
|
+
`session/set_config_option` or `session/prompt` mark the conversation dirty
|
|
139
|
+
so the next turn rebuilds cleanly. Explicit teardown (`resetConversations()`,
|
|
137
140
|
`dispose()`, binary upgrade, LRU eviction) deletes dormant DBs immediately.
|
|
138
141
|
- **Pi lifecycle resets:** Compaction, tree navigation, and `session_start`
|
|
139
142
|
(`new`, `resume`, `fork`) perform a light reset (closing conversation sessions
|
|
@@ -220,14 +223,14 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
|
|
|
220
223
|
- Gates streaming reads with cached context window / positive `usage_update`
|
|
221
224
|
checks and `(mtimeNs, size)` stamps across `.db`, `.db-wal`, and
|
|
222
225
|
`.db-journal`. `gen_metadata.data` remains the authoritative per-model
|
|
223
|
-
`max_context_tokens` source in `agy` 1.5.
|
|
226
|
+
`max_context_tokens` source in `agy` 1.5.23 because `usage_update.size` still
|
|
224
227
|
reports a fixed `1048576` rather than per-model limits. `gen_metadata` scans
|
|
225
228
|
are bounded (`LIMIT 64`) and advance `metaFloorIdx` on mid-session model
|
|
226
229
|
switches so prior context windows cannot bleed across models.
|
|
227
230
|
- On `end_turn` and `refusal`, inspects the newest terminal `steps` row
|
|
228
231
|
(`step_type = 17`, cross-checked against `step_type = 15` model reachability)
|
|
229
232
|
to surface hidden API errors while preserving pure safety refusals. This
|
|
230
|
-
remains necessary in `agy` 1.5.
|
|
233
|
+
remains necessary in `agy` 1.5.23 because certain API errors (such as
|
|
231
234
|
`INVALID_ARGUMENT (code 400)` on malformed images) still complete
|
|
232
235
|
`session/prompt` with `stopReason: "end_turn"`:
|
|
233
236
|
- `QUOTA_EXHAUSTED` → `QUOTA` (extracts reset timestamp/delay)
|
|
@@ -245,18 +248,30 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
|
|
|
245
248
|
### Usage and `totalTokens` priority
|
|
246
249
|
|
|
247
250
|
`toTokenUsage()` emits usage only when `session/prompt` includes a `usage`
|
|
248
|
-
object.
|
|
249
|
-
`
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
251
|
+
object. Raw cumulative multi-call ACP usage is retained on
|
|
252
|
+
`RuntimeStatus.lastTurn.usage`, while the `AssistantMessage.usage` sent to Pi
|
|
253
|
+
normalizes prompt buckets to single-call occupancy so Pi's `isContextOverflow()`
|
|
254
|
+
(`input + cacheRead > contextWindow` on `stop` turns) does not false-positive on
|
|
255
|
+
tool-heavy or continued turns:
|
|
256
|
+
|
|
257
|
+
1. `totalTokens` resolves final-call context occupancy in priority order:
|
|
258
|
+
1. Positive `usage_update.used` from the current continuation segment.
|
|
259
|
+
2. Positive `estimated_tokens_used` from `gen_metadata` in the current segment.
|
|
260
|
+
3. Final-segment average fallback:
|
|
261
|
+
`round((input + cacheRead + cacheWrite) / max(1, segmentCalls)) + round(output)`.
|
|
262
|
+
2. Prompt buckets (`inputTokens`, `cacheReadTokens`, `cacheWriteTokens`) are
|
|
263
|
+
taken from the final segment (falling back to accumulated usage when the
|
|
264
|
+
final segment reports zero prompt tokens) and capped proportionally with
|
|
265
|
+
largest-remainder allocation so their sum never exceeds the resolved
|
|
266
|
+
single-call prompt budget (`totalTokens` for live/metadata occupancy, or the
|
|
267
|
+
averaged `segPrompt` fallback). Single-call turns that already fit remain
|
|
268
|
+
unscaled, and cache-hit ratios are preserved.
|
|
269
|
+
3. `outputTokens` and `reasoningTokens` remain cumulative across `max_tokens`
|
|
270
|
+
continuations.
|
|
256
271
|
|
|
257
272
|
## Quota reader and Pi stream contracts
|
|
258
273
|
|
|
259
|
-
- **Quota reader (`src/quota.ts`):** Runs `agy
|
|
274
|
+
- **Quota reader (`src/quota.ts`):** Runs `agy usage --output-format json`
|
|
260
275
|
with closed `stdin`, a 1 MiB `stdout` cap, a 45 s timeout, and early abort if
|
|
261
276
|
`stderr` matches `Authentication required`. Uses a monotonic clock
|
|
262
277
|
(`performance.now()`) for its 2-minute TTL, filters `disabled === true`
|
package/docs/development.md
CHANGED
|
@@ -47,7 +47,7 @@ SQLite telemetry, and transport boundary invariants.
|
|
|
47
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. |
|
|
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,
|
|
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. |
|
|
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/docs/reference.md
CHANGED
|
@@ -21,7 +21,7 @@ In interactive TUI mode, `/agy-acp quota` (`Fetching Antigravity quota...`) and
|
|
|
21
21
|
`/agy-acp refresh` (`Refreshing Antigravity models...`) display a cancellable
|
|
22
22
|
loader. Pressing Escape returns to the editor: `/agy-acp refresh` cancels the
|
|
23
23
|
caller's wait, while `/agy-acp quota` hides the pending panel even if the
|
|
24
|
-
underlying
|
|
24
|
+
underlying `agy usage` query finishes updating the cache. Non-TUI modes run
|
|
25
25
|
directly without a loader.
|
|
26
26
|
|
|
27
27
|
### Status panel
|
|
@@ -41,7 +41,7 @@ healthy runtime uses a warning.
|
|
|
41
41
|
|
|
42
42
|
### Quota panel
|
|
43
43
|
|
|
44
|
-
Quota is read through `agy
|
|
44
|
+
Quota is read through `agy usage --output-format json`. Disabled quota
|
|
45
45
|
buckets are excluded. Each model group renders one row per usable quota window
|
|
46
46
|
with a 12-cell bar, a rounded percentage, and a relative reset countdown:
|
|
47
47
|
|
|
@@ -95,7 +95,7 @@ unavailable fields:
|
|
|
95
95
|
|
|
96
96
|
### Quota status and warnings
|
|
97
97
|
|
|
98
|
-
After an `antigravity-acp` run settles, the extension refreshes
|
|
98
|
+
After an `antigravity-acp` run settles, the extension refreshes `agy usage` in the
|
|
99
99
|
background (sharing any in-flight request and respecting the 2-minute TTL) and
|
|
100
100
|
displays a compact status bar indicator such as `AGY 20%` (or `AGY 80%` in
|
|
101
101
|
`remaining` mode):
|
|
@@ -164,7 +164,7 @@ session databases).
|
|
|
164
164
|
refusing symlinked paths. Sync failures warn rather than aborting startup. A
|
|
165
165
|
custom `PI_AGY_HOME` stays isolated and never copies tokens from default `agy`
|
|
166
166
|
directories.
|
|
167
|
-
- **Global quota scope:** `agy
|
|
167
|
+
- **Global quota scope:** `agy usage` does not accept `--gemini-dir`, so
|
|
168
168
|
quota queries always reflect the global `agy` CLI account. Do not commit or
|
|
169
169
|
share `PI_AGY_HOME`.
|
|
170
170
|
|
|
@@ -195,22 +195,27 @@ Usage comes from the ACP session rather than per-step HTTP headers. Parked
|
|
|
195
195
|
ACP turn completes (accumulated across any automatic `max_tokens` continuations)
|
|
196
196
|
whenever `session/prompt` reports usage.
|
|
197
197
|
|
|
198
|
-
The extension
|
|
199
|
-
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`:
|
|
200
201
|
|
|
201
|
-
- `input`, `output`, `cacheRead`, `cacheWrite`, and `reasoning` preserve
|
|
202
|
-
unscaled cumulative turn totals, so Pi session totals and flat pricing
|
|
203
|
-
overrides reflect full multi-step consumption.
|
|
204
202
|
- `totalTokens` (feeding Pi's context meter and auto-compaction threshold) uses
|
|
205
203
|
the final call's live token occupancy when reported by `agy`, falling back to
|
|
206
204
|
the same turn's session metadata estimate and then a final-segment average
|
|
207
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.
|
|
208
213
|
|
|
209
214
|
Default model prices are zero because upstream pricing is unavailable. With Pi
|
|
210
|
-
pricing overrides,
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
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.
|
|
214
219
|
|
|
215
220
|
Read-only SQLite inspection is restricted strictly to session-scoped databases
|
|
216
221
|
inside `PI_AGY_HOME` (for context windows, occupancy estimates, and hidden
|
|
@@ -220,8 +225,9 @@ or invokes/distributes binary patches.
|
|
|
220
225
|
## Compatibility limits
|
|
221
226
|
|
|
222
227
|
- Requires Node.js >= 22.19.0, Pi (`@earendil-works/*`) 1.5.x, and `agy` >=
|
|
223
|
-
1.5.
|
|
224
|
-
|
|
228
|
+
1.5.23 (which adds the standalone `agy usage` subcommand, standardizes
|
|
229
|
+
`-32002` unknown-session ACP errors, and updates combined reasoning+output
|
|
230
|
+
retry handling). Older `@mariozechner/*` Pi interfaces are not supported.
|
|
225
231
|
- Sampling parameters, output limits, forced `toolChoice`, and provider-scoped
|
|
226
232
|
environment overrides are not mapped to ACP.
|
|
227
233
|
|
package/package.json
CHANGED
package/src/acp-process.ts
CHANGED
package/src/config.ts
CHANGED
|
@@ -38,7 +38,7 @@ export interface Config {
|
|
|
38
38
|
relayAfterMs: number
|
|
39
39
|
/** Automatic continuations after an output-length stop (long decode). */
|
|
40
40
|
longDecodeContinuations: number
|
|
41
|
-
/** Minimum interval between quota refreshes through `agy
|
|
41
|
+
/** Minimum interval between quota refreshes through `agy usage`. */
|
|
42
42
|
quotaTtlMs: number
|
|
43
43
|
}
|
|
44
44
|
|
package/src/conversation.ts
CHANGED
|
@@ -33,12 +33,11 @@ import { AsyncQueue, deferred, type Deferred } from './util.ts'
|
|
|
33
33
|
|
|
34
34
|
/** Agent-side transport retry notice streamed as message text, e.g. `⚠ API error (attempt 1): …`. */
|
|
35
35
|
const AGENT_RETRY_NOTICE = /^\s*⚠\s*API error \(attempt \d+\)/
|
|
36
|
-
/**
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
'please continue from where you left off, keeping your response shorter'
|
|
36
|
+
/** Discarded-attempt prefix agy 1.5.23+ emits on retryable generation failures (`%s\n%s\nRetries remaining: %d`). */
|
|
37
|
+
const DISCARDED_ATTEMPT_PREFIX = 'a response attempt was discarded'
|
|
38
|
+
/** Standalone retry guidance agy 1.5.23+ pairs with combined reasoning+output limit discards. */
|
|
39
|
+
const REASONING_OUTPUT_LIMIT_TAIL =
|
|
40
|
+
'please keep your reasoning and response shorter'
|
|
42
41
|
/** Internal retry notice agy emits when an upstream stream is interrupted mid-turn. */
|
|
43
42
|
const STREAM_INTERRUPTED =
|
|
44
43
|
'the stream was interrupted. please continue the task you were working on.'
|
|
@@ -49,7 +48,7 @@ const EMPTY_MODEL_OUTPUT_BODY =
|
|
|
49
48
|
'model output must contain either output text or tool calls, these cannot both be empty, please try again'
|
|
50
49
|
/** Generic retry notice prefix paired with a trailing `Retries remaining: <N>`. */
|
|
51
50
|
const PROBLEM_RETRY_PREFIX = 'there was a problem'
|
|
52
|
-
/** Cap on held characters while waiting for `Retries remaining: <N>` after
|
|
51
|
+
/** Cap on held characters while waiting for `Retries remaining: <N>` after a generic retry prefix. */
|
|
53
52
|
const MAX_PROBLEM_NOTICE_CHARS = 512
|
|
54
53
|
|
|
55
54
|
/** Collapse agy's warning mark, line-leading `Error:`, and line breaks so notices match across chunks. */
|
|
@@ -87,11 +86,9 @@ export function classifyOutputLimitNotice(
|
|
|
87
86
|
if (/^retries remaining:\s*[1-9]\d*$/i.test(text)) return 'drop'
|
|
88
87
|
return /^retries remaining:\s*$/i.test(text) ? 'hold' : 'emit'
|
|
89
88
|
}
|
|
90
|
-
const
|
|
89
|
+
const normalized = stripped.replace(/\./g, '').replace(/\s+/g, ' ').trim()
|
|
91
90
|
if (
|
|
92
|
-
|
|
93
|
-
stripped === OUTPUT_LIMIT_HEAD ||
|
|
94
|
-
stripped === OUTPUT_LIMIT_TAIL ||
|
|
91
|
+
normalized === REASONING_OUTPUT_LIMIT_TAIL ||
|
|
95
92
|
stripped === STREAM_INTERRUPTED ||
|
|
96
93
|
stripped === EMPTY_MODEL_OUTPUT ||
|
|
97
94
|
stripped === EMPTY_MODEL_OUTPUT_BODY
|
|
@@ -100,11 +97,18 @@ export function classifyOutputLimitNotice(
|
|
|
100
97
|
return 'drop'
|
|
101
98
|
return /^retries remaining:\s*$/i.test(retry) ? 'hold' : 'emit'
|
|
102
99
|
}
|
|
103
|
-
if (
|
|
100
|
+
if (/^a response attempt was discarded\b/.test(text)) {
|
|
101
|
+
if (/\bretries remaining:\s*[1-9]\d*$/.test(text)) return 'drop'
|
|
102
|
+
return text.length <= MAX_PROBLEM_NOTICE_CHARS ? 'hold' : 'emit'
|
|
103
|
+
}
|
|
104
|
+
if (
|
|
105
|
+
DISCARDED_ATTEMPT_PREFIX.startsWith(text) &&
|
|
106
|
+
text.startsWith('a response attempt')
|
|
107
|
+
)
|
|
104
108
|
return 'hold'
|
|
105
109
|
if (
|
|
106
|
-
|
|
107
|
-
|
|
110
|
+
REASONING_OUTPUT_LIMIT_TAIL.startsWith(normalized) &&
|
|
111
|
+
normalized.startsWith('please keep your reasoning')
|
|
108
112
|
)
|
|
109
113
|
return 'hold'
|
|
110
114
|
if (
|
|
@@ -730,25 +734,87 @@ function accumulateRawUsage(
|
|
|
730
734
|
}
|
|
731
735
|
}
|
|
732
736
|
|
|
737
|
+
function nonNegativeInt(value: number | undefined): number {
|
|
738
|
+
return value !== undefined && Number.isFinite(value)
|
|
739
|
+
? Math.max(0, Math.round(value))
|
|
740
|
+
: 0
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
function positiveInt(value: number | undefined): number | undefined {
|
|
744
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
|
745
|
+
? Math.round(value)
|
|
746
|
+
: undefined
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
function promptBuckets(
|
|
750
|
+
usage: NonNullable<AcpPromptResult['usage']>,
|
|
751
|
+
): [number, number, number] {
|
|
752
|
+
return [
|
|
753
|
+
nonNegativeInt(usage.inputTokens),
|
|
754
|
+
nonNegativeInt(usage.cachedReadTokens),
|
|
755
|
+
nonNegativeInt(usage.cachedWriteTokens),
|
|
756
|
+
]
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* Proportionally cap prompt buckets (`input`, `cacheRead`, `cacheWrite`) to
|
|
761
|
+
* `cap` using largest-remainder allocation so their sum never exceeds `cap`,
|
|
762
|
+
* cache-hit ratios stay accurate, and zero buckets stay zero.
|
|
763
|
+
*/
|
|
764
|
+
function capPromptBuckets(
|
|
765
|
+
buckets: readonly [number, number, number],
|
|
766
|
+
cap: number,
|
|
767
|
+
): [number, number, number] {
|
|
768
|
+
const [input, cacheRead, cacheWrite] = buckets
|
|
769
|
+
const sum = input + cacheRead + cacheWrite
|
|
770
|
+
if (sum <= cap || sum === 0) return [input, cacheRead, cacheWrite]
|
|
771
|
+
if (cap <= 0) return [0, 0, 0]
|
|
772
|
+
const exact: [number, number, number] = [
|
|
773
|
+
(input / sum) * cap,
|
|
774
|
+
(cacheRead / sum) * cap,
|
|
775
|
+
(cacheWrite / sum) * cap,
|
|
776
|
+
]
|
|
777
|
+
const floors: [number, number, number] = [
|
|
778
|
+
Math.min(input, Math.floor(exact[0])),
|
|
779
|
+
Math.min(cacheRead, Math.floor(exact[1])),
|
|
780
|
+
Math.min(cacheWrite, Math.floor(exact[2])),
|
|
781
|
+
]
|
|
782
|
+
let remaining = cap - (floors[0] + floors[1] + floors[2])
|
|
783
|
+
const order = ([0, 1, 2] as const)
|
|
784
|
+
.slice()
|
|
785
|
+
.sort((a, b) => exact[b] - floors[b] - (exact[a] - floors[a]))
|
|
786
|
+
for (const idx of order) {
|
|
787
|
+
if (remaining <= 0) break
|
|
788
|
+
if (floors[idx] >= buckets[idx]) continue
|
|
789
|
+
floors[idx] += 1
|
|
790
|
+
remaining -= 1
|
|
791
|
+
}
|
|
792
|
+
return floors
|
|
793
|
+
}
|
|
794
|
+
|
|
733
795
|
/**
|
|
734
|
-
* Map accumulated ACP turn usage into Pi token usage.
|
|
796
|
+
* Map accumulated ACP turn usage into Pi single-call token usage.
|
|
735
797
|
*
|
|
736
|
-
*
|
|
737
|
-
* `
|
|
738
|
-
*
|
|
739
|
-
*
|
|
798
|
+
* Pi's `AssistantMessage.usage` represents one model call: `isContextOverflow()`
|
|
799
|
+
* checks `input + cacheRead` against `contextWindow` even on successful `stop`
|
|
800
|
+
* turns, while `calculateContextTokens()` reads `totalTokens`. Raw cumulative
|
|
801
|
+
* multi-call ACP usage therefore stays on `turn.usage` (`RuntimeStatus.lastTurn`),
|
|
802
|
+
* while prompt buckets (`inputTokens`, `cacheReadTokens`, `cacheWriteTokens`)
|
|
803
|
+
* emitted to Pi are normalized to the final call's prompt occupancy (preserving
|
|
804
|
+
* cache-hit ratios and leaving single-call turns untouched). `outputTokens` and
|
|
805
|
+
* `reasoningTokens` remain cumulative turn totals.
|
|
740
806
|
*
|
|
741
|
-
* `totalTokens`
|
|
742
|
-
*
|
|
743
|
-
*
|
|
744
|
-
*
|
|
745
|
-
*
|
|
807
|
+
* `totalTokens` resolves final-call context occupancy in priority order:
|
|
808
|
+
* 1. Positive live `options.contextTokens` (`usage_update.used`).
|
|
809
|
+
* 2. Positive `options.estimatedContextTokens` (same-turn `gen_metadata`).
|
|
810
|
+
* 3. Final-segment average prompt tokens divided by `calls`, plus final-segment
|
|
811
|
+
* output tokens.
|
|
746
812
|
*
|
|
747
813
|
* `agy acp` reports `inputTokens` as uncached input only, disjoint from
|
|
748
814
|
* `cachedReadTokens` and `cachedWriteTokens`.
|
|
749
815
|
* @param usage - accumulated turn usage.
|
|
750
816
|
* @param calls - model calls inside the final `session/prompt` segment (>= 1).
|
|
751
|
-
* @param options - optional live `usage_update` count and final segment usage.
|
|
817
|
+
* @param options - optional live `usage_update` count, metadata estimate, and final segment usage.
|
|
752
818
|
* @returns Pi usage.
|
|
753
819
|
*/
|
|
754
820
|
export function toTokenUsage(
|
|
@@ -757,48 +823,40 @@ export function toTokenUsage(
|
|
|
757
823
|
options?: TokenUsageOptions,
|
|
758
824
|
): TokenUsage | undefined {
|
|
759
825
|
if (usage === undefined) return undefined
|
|
760
|
-
const
|
|
761
|
-
const cacheRead = Math.max(0, Math.round(usage.cachedReadTokens ?? 0))
|
|
762
|
-
const cacheWrite = Math.max(0, Math.round(usage.cachedWriteTokens ?? 0))
|
|
763
|
-
const output = Math.max(0, Math.round(usage.outputTokens ?? 0))
|
|
826
|
+
const output = nonNegativeInt(usage.outputTokens)
|
|
764
827
|
const reasoning =
|
|
765
|
-
usage.thoughtTokens !== undefined &&
|
|
828
|
+
usage.thoughtTokens !== undefined &&
|
|
829
|
+
Number.isFinite(usage.thoughtTokens) &&
|
|
830
|
+
usage.thoughtTokens > 0
|
|
766
831
|
? Math.min(output, Math.round(usage.thoughtTokens))
|
|
767
832
|
: undefined
|
|
768
|
-
const
|
|
769
|
-
const
|
|
833
|
+
const seg = options?.lastSegmentUsage ?? usage
|
|
834
|
+
const segBuckets = promptBuckets(seg)
|
|
835
|
+
const segPromptSum = segBuckets[0] + segBuckets[1] + segBuckets[2]
|
|
836
|
+
const promptSource = segPromptSum > 0 ? seg : usage
|
|
837
|
+
const rawPrompt = segPromptSum > 0 ? segBuckets : promptBuckets(usage)
|
|
838
|
+
|
|
839
|
+
const liveContext =
|
|
840
|
+
positiveInt(options?.contextTokens) ??
|
|
841
|
+
positiveInt(options?.estimatedContextTokens)
|
|
842
|
+
let promptCap: number
|
|
770
843
|
let totalTokens: number
|
|
771
|
-
if (
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
liveContext > 0
|
|
775
|
-
) {
|
|
776
|
-
totalTokens = Math.round(liveContext)
|
|
777
|
-
} else if (
|
|
778
|
-
typeof estimatedContext === 'number' &&
|
|
779
|
-
Number.isFinite(estimatedContext) &&
|
|
780
|
-
estimatedContext > 0
|
|
781
|
-
) {
|
|
782
|
-
totalTokens = Math.round(estimatedContext)
|
|
844
|
+
if (liveContext !== undefined) {
|
|
845
|
+
promptCap = liveContext
|
|
846
|
+
totalTokens = liveContext
|
|
783
847
|
} else {
|
|
784
|
-
const seg = options?.lastSegmentUsage ?? usage
|
|
785
848
|
const scale = Math.max(1, calls)
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
Math.round(
|
|
789
|
-
((seg.inputTokens ?? 0) +
|
|
790
|
-
(seg.cachedReadTokens ?? 0) +
|
|
791
|
-
(seg.cachedWriteTokens ?? 0)) /
|
|
792
|
-
scale,
|
|
793
|
-
),
|
|
794
|
-
)
|
|
795
|
-
const segOutput = Math.max(0, Math.round(seg.outputTokens ?? 0))
|
|
796
|
-
totalTokens = segPrompt + segOutput
|
|
849
|
+
promptCap = Math.max(0, Math.round(segPromptSum / scale))
|
|
850
|
+
totalTokens = promptCap + nonNegativeInt(seg.outputTokens)
|
|
797
851
|
}
|
|
852
|
+
|
|
853
|
+
const [input, cacheRead, cacheWrite] = capPromptBuckets(rawPrompt, promptCap)
|
|
798
854
|
return {
|
|
799
855
|
inputTokens: input,
|
|
800
856
|
outputTokens: output,
|
|
801
|
-
...(
|
|
857
|
+
...(promptSource.cachedReadTokens !== undefined ||
|
|
858
|
+
usage.cachedReadTokens !== undefined ||
|
|
859
|
+
cacheRead > 0
|
|
802
860
|
? { cacheReadTokens: cacheRead }
|
|
803
861
|
: {}),
|
|
804
862
|
...(cacheWrite > 0 ? { cacheWriteTokens: cacheWrite } : {}),
|
package/src/format.ts
CHANGED
|
@@ -22,13 +22,13 @@ function formatAccount(account?: AccountInfo): string {
|
|
|
22
22
|
return [account?.email, account?.plan].filter(Boolean).join(' · ')
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
/** Active model identity from Pi (`id` plus optional display `name` for
|
|
25
|
+
/** Active model identity from Pi (`id` plus optional display `name` for `agy usage` labels such as `Orchestrator (Carbon)`). */
|
|
26
26
|
export interface QuotaModelRef {
|
|
27
27
|
readonly id: string
|
|
28
28
|
readonly name?: string
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
// `agy
|
|
31
|
+
// `agy usage` prefixes closed, exhaustive member lists with "Models within this group:";
|
|
32
32
|
// unprefixed descriptions are free-form prose notes.
|
|
33
33
|
const EXPLICIT_MEMBERS_PREFIX = /^\s*models within this group:\s*/i
|
|
34
34
|
const CLAUSE_SPLIT = /[,;\n/|&+]+|\b(?:and|or)\b/i
|
|
@@ -40,7 +40,7 @@ const EFFORT_QUALIFIER_PATTERN = [
|
|
|
40
40
|
'extra[-_]low',
|
|
41
41
|
...[...EFFORTS].sort((a, b) => b.length - a.length),
|
|
42
42
|
].join('|')
|
|
43
|
-
// Effort or thinking-mode suffixes in model IDs (`-thinking`) and
|
|
43
|
+
// Effort or thinking-mode suffixes in model IDs (`-thinking`) and `agy usage` labels (`(Thinking)`).
|
|
44
44
|
const ID_QUALIFIER_SUFFIX = new RegExp(
|
|
45
45
|
`[-_](?:(${EFFORT_QUALIFIER_PATTERN})(?:[-_]effort)?|(thinking))$`,
|
|
46
46
|
'i',
|
package/src/preflight.ts
CHANGED
|
@@ -33,8 +33,8 @@ export { atomicWriteFile }
|
|
|
33
33
|
|
|
34
34
|
/** Agent id installed in the isolated home. */
|
|
35
35
|
export const BRIDGE_AGENT = 'pi-bridge'
|
|
36
|
-
/** Minimum official CLI version supported (`agy 1.5.
|
|
37
|
-
export const MIN_AGY_VERSION: readonly [number, number, number] = [1, 5,
|
|
36
|
+
/** Minimum official CLI version supported (`agy 1.5.23+`). */
|
|
37
|
+
export const MIN_AGY_VERSION: readonly [number, number, number] = [1, 5, 23]
|
|
38
38
|
|
|
39
39
|
/** Output of one finished helper command. */
|
|
40
40
|
export interface CommandOutput {
|
package/src/quota.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Plan quota read through the official CLI's local
|
|
3
|
-
* reports each model group's weekly and five-hour windows without
|
|
4
|
-
* model request.
|
|
2
|
+
* Plan quota read through the official CLI's local `agy usage` command, which
|
|
3
|
+
* reports each model group's weekly and five-hour windows without starting a
|
|
4
|
+
* conversation or sending a model request.
|
|
5
5
|
* @module pi-agy-acp/quota
|
|
6
6
|
*/
|
|
7
7
|
|
|
@@ -216,7 +216,7 @@ function parseBucket(raw: unknown): QuotaBucket | undefined {
|
|
|
216
216
|
}
|
|
217
217
|
|
|
218
218
|
/**
|
|
219
|
-
* Parse `agy
|
|
219
|
+
* Parse `agy usage --output-format json` output.
|
|
220
220
|
* @param stdout - command stdout.
|
|
221
221
|
* @returns the quota groups.
|
|
222
222
|
*/
|
|
@@ -235,7 +235,7 @@ export function parseUsage(stdout: string): QuotaGroup[] {
|
|
|
235
235
|
? (data as { groups?: unknown }).groups
|
|
236
236
|
: undefined
|
|
237
237
|
if (!Array.isArray(groups))
|
|
238
|
-
throw new Error('agy
|
|
238
|
+
throw new Error('agy usage returned no quota groups')
|
|
239
239
|
return groups
|
|
240
240
|
.filter(
|
|
241
241
|
(raw): raw is Record<string, unknown> =>
|
|
@@ -309,7 +309,7 @@ export class QuotaReader {
|
|
|
309
309
|
try {
|
|
310
310
|
const binary = this.binary()
|
|
311
311
|
const result = await this.run(
|
|
312
|
-
[binary, '
|
|
312
|
+
[binary, 'usage', '--output-format', 'json'],
|
|
313
313
|
45_000,
|
|
314
314
|
{
|
|
315
315
|
maxStdoutBytes: USAGE_MAX_STDOUT_BYTES,
|
|
@@ -326,12 +326,12 @@ export class QuotaReader {
|
|
|
326
326
|
}
|
|
327
327
|
if (result.abortedBy === 'maxStdout') {
|
|
328
328
|
throw new Error(
|
|
329
|
-
`agy
|
|
329
|
+
`agy usage stdout exceeded ${USAGE_MAX_STDOUT_BYTES} bytes`,
|
|
330
330
|
)
|
|
331
331
|
}
|
|
332
332
|
if (result.code !== 0)
|
|
333
333
|
throw new Error(
|
|
334
|
-
`agy
|
|
334
|
+
`agy usage failed (exit ${result.code}): ${result.stderr.trim() || result.stdout.trim()}`,
|
|
335
335
|
)
|
|
336
336
|
const snapshot: QuotaSnapshot = {
|
|
337
337
|
status: 'ok',
|
package/src/runtime.ts
CHANGED
|
@@ -399,6 +399,13 @@ export class AntigravityRuntime {
|
|
|
399
399
|
}
|
|
400
400
|
return result
|
|
401
401
|
} catch (error) {
|
|
402
|
+
if (
|
|
403
|
+
error instanceof JsonRpcRemoteError &&
|
|
404
|
+
error.rpc.code === -32002 &&
|
|
405
|
+
this.owns(proc, conv, sessionId)
|
|
406
|
+
) {
|
|
407
|
+
conv.dirty = true
|
|
408
|
+
}
|
|
402
409
|
if (!harvested) {
|
|
403
410
|
this.harvestSessionTurnData(conv, sessionId, model, modelFloor, {
|
|
404
411
|
turn,
|
|
@@ -1443,6 +1450,13 @@ export class AntigravityRuntime {
|
|
|
1443
1450
|
const configOptions = await proc
|
|
1444
1451
|
.setConfigOption(sessionId, optionId, value)
|
|
1445
1452
|
.catch((error: unknown) => {
|
|
1453
|
+
if (
|
|
1454
|
+
error instanceof JsonRpcRemoteError &&
|
|
1455
|
+
error.rpc.code === -32002 &&
|
|
1456
|
+
this.owns(proc, conv, sessionId)
|
|
1457
|
+
) {
|
|
1458
|
+
conv.dirty = true
|
|
1459
|
+
}
|
|
1446
1460
|
throw mapError(error)
|
|
1447
1461
|
})
|
|
1448
1462
|
this.assertOwner(proc, conv, sessionId)
|