pi-agy-acp 0.2.4 → 0.2.5

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.5](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.4...v0.2.5) (2026-11-28)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **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)
9
+
3
10
  ## [0.2.4](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.3...v0.2.4) (2026-11-26)
4
11
 
5
12
 
@@ -245,14 +245,26 @@ Working directory is `<PI_AGY_HOME>/workspace`. ACP JSON-RPC timeouts:
245
245
  ### Usage and `totalTokens` priority
246
246
 
247
247
  `toTokenUsage()` emits usage only when `session/prompt` includes a `usage`
248
- object. Cumulative buckets (`inputTokens`, `outputTokens`, `cacheReadTokens`,
249
- `cacheWriteTokens`, `reasoningTokens`) sum across `max_tokens` continuations;
250
- `totalTokens` resolves in priority order:
251
-
252
- 1. Positive `usage_update.used` from the current continuation segment.
253
- 2. Positive `estimated_tokens_used` from `gen_metadata` in the current segment.
254
- 3. Final-segment average fallback:
255
- `round((input + cacheRead + cacheWrite) / max(1, segmentCalls)) + round(output)`.
248
+ object. Raw cumulative multi-call ACP usage is retained on
249
+ `RuntimeStatus.lastTurn.usage`, while the `AssistantMessage.usage` sent to Pi
250
+ normalizes prompt buckets to single-call occupancy so Pi's `isContextOverflow()`
251
+ (`input + cacheRead > contextWindow` on `stop` turns) does not false-positive on
252
+ tool-heavy or continued turns:
253
+
254
+ 1. `totalTokens` resolves final-call context occupancy in priority order:
255
+ 1. Positive `usage_update.used` from the current continuation segment.
256
+ 2. Positive `estimated_tokens_used` from `gen_metadata` in the current segment.
257
+ 3. Final-segment average fallback:
258
+ `round((input + cacheRead + cacheWrite) / max(1, segmentCalls)) + round(output)`.
259
+ 2. Prompt buckets (`inputTokens`, `cacheReadTokens`, `cacheWriteTokens`) are
260
+ taken from the final segment (falling back to accumulated usage when the
261
+ final segment reports zero prompt tokens) and capped proportionally with
262
+ largest-remainder allocation so their sum never exceeds the resolved
263
+ single-call prompt budget (`totalTokens` for live/metadata occupancy, or the
264
+ averaged `segPrompt` fallback). Single-call turns that already fit remain
265
+ unscaled, and cache-hit ratios are preserved.
266
+ 3. `outputTokens` and `reasoningTokens` remain cumulative across `max_tokens`
267
+ continuations.
256
268
 
257
269
  ## Quota reader and Pi stream contracts
258
270
 
package/docs/reference.md CHANGED
@@ -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 separates cumulative turn consumption from final-call context
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, flat per-million rates price cumulative turn buckets
211
- accurately; tiered `inputTokensAbove` rules evaluate against cumulative turn
212
- prompt tokens rather than per-call prompt sizes. These numbers are estimates,
213
- not an invoice or a promise of free access.
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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-agy-acp",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Google Antigravity ACP provider extension for Pi Coding Agent",
@@ -730,25 +730,87 @@ function accumulateRawUsage(
730
730
  }
731
731
  }
732
732
 
733
+ function nonNegativeInt(value: number | undefined): number {
734
+ return value !== undefined && Number.isFinite(value)
735
+ ? Math.max(0, Math.round(value))
736
+ : 0
737
+ }
738
+
739
+ function positiveInt(value: number | undefined): number | undefined {
740
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
741
+ ? Math.round(value)
742
+ : undefined
743
+ }
744
+
745
+ function promptBuckets(
746
+ usage: NonNullable<AcpPromptResult['usage']>,
747
+ ): [number, number, number] {
748
+ return [
749
+ nonNegativeInt(usage.inputTokens),
750
+ nonNegativeInt(usage.cachedReadTokens),
751
+ nonNegativeInt(usage.cachedWriteTokens),
752
+ ]
753
+ }
754
+
733
755
  /**
734
- * Map accumulated ACP turn usage into Pi token usage.
756
+ * Proportionally cap prompt buckets (`input`, `cacheRead`, `cacheWrite`) to
757
+ * `cap` using largest-remainder allocation so their sum never exceeds `cap`,
758
+ * cache-hit ratios stay accurate, and zero buckets stay zero.
759
+ */
760
+ function capPromptBuckets(
761
+ buckets: readonly [number, number, number],
762
+ cap: number,
763
+ ): [number, number, number] {
764
+ const [input, cacheRead, cacheWrite] = buckets
765
+ const sum = input + cacheRead + cacheWrite
766
+ if (sum <= cap || sum === 0) return [input, cacheRead, cacheWrite]
767
+ if (cap <= 0) return [0, 0, 0]
768
+ const exact: [number, number, number] = [
769
+ (input / sum) * cap,
770
+ (cacheRead / sum) * cap,
771
+ (cacheWrite / sum) * cap,
772
+ ]
773
+ const floors: [number, number, number] = [
774
+ Math.min(input, Math.floor(exact[0])),
775
+ Math.min(cacheRead, Math.floor(exact[1])),
776
+ Math.min(cacheWrite, Math.floor(exact[2])),
777
+ ]
778
+ let remaining = cap - (floors[0] + floors[1] + floors[2])
779
+ const order = ([0, 1, 2] as const)
780
+ .slice()
781
+ .sort((a, b) => exact[b] - floors[b] - (exact[a] - floors[a]))
782
+ for (const idx of order) {
783
+ if (remaining <= 0) break
784
+ if (floors[idx] >= buckets[idx]) continue
785
+ floors[idx] += 1
786
+ remaining -= 1
787
+ }
788
+ return floors
789
+ }
790
+
791
+ /**
792
+ * Map accumulated ACP turn usage into Pi single-call token usage.
735
793
  *
736
- * Consumption buckets (`inputTokens`, `outputTokens`, `cacheReadTokens`,
737
- * `cacheWriteTokens`, `reasoningTokens`) stay unscaled cumulative turn totals
738
- * because intermediate `toolUse` steps emit zero usage and Pi sums those
739
- * buckets across steps for session accounting and flat pricing overrides.
794
+ * Pi's `AssistantMessage.usage` represents one model call: `isContextOverflow()`
795
+ * checks `input + cacheRead` against `contextWindow` even on successful `stop`
796
+ * turns, while `calculateContextTokens()` reads `totalTokens`. Raw cumulative
797
+ * multi-call ACP usage therefore stays on `turn.usage` (`RuntimeStatus.lastTurn`),
798
+ * while prompt buckets (`inputTokens`, `cacheReadTokens`, `cacheWriteTokens`)
799
+ * emitted to Pi are normalized to the final call's prompt occupancy (preserving
800
+ * cache-hit ratios and leaving single-call turns untouched). `outputTokens` and
801
+ * `reasoningTokens` remain cumulative turn totals.
740
802
  *
741
- * `totalTokens` feeds Pi's `calculateContextTokens` / ContextMeter / compaction
742
- * threshold as final-call context occupancy: when `options.contextTokens`
743
- * (from live `usage_update.used`) is positive, it is used directly; otherwise
744
- * final-segment prompt buckets are normalized by `calls` and added to final-
745
- * segment output tokens.
803
+ * `totalTokens` resolves final-call context occupancy in priority order:
804
+ * 1. Positive live `options.contextTokens` (`usage_update.used`).
805
+ * 2. Positive `options.estimatedContextTokens` (same-turn `gen_metadata`).
806
+ * 3. Final-segment average prompt tokens divided by `calls`, plus final-segment
807
+ * output tokens.
746
808
  *
747
809
  * `agy acp` reports `inputTokens` as uncached input only, disjoint from
748
810
  * `cachedReadTokens` and `cachedWriteTokens`.
749
811
  * @param usage - accumulated turn usage.
750
812
  * @param calls - model calls inside the final `session/prompt` segment (>= 1).
751
- * @param options - optional live `usage_update` count and final segment usage.
813
+ * @param options - optional live `usage_update` count, metadata estimate, and final segment usage.
752
814
  * @returns Pi usage.
753
815
  */
754
816
  export function toTokenUsage(
@@ -757,48 +819,40 @@ export function toTokenUsage(
757
819
  options?: TokenUsageOptions,
758
820
  ): TokenUsage | undefined {
759
821
  if (usage === undefined) return undefined
760
- const input = Math.max(0, Math.round(usage.inputTokens ?? 0))
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))
822
+ const output = nonNegativeInt(usage.outputTokens)
764
823
  const reasoning =
765
- usage.thoughtTokens !== undefined && usage.thoughtTokens > 0
824
+ usage.thoughtTokens !== undefined &&
825
+ Number.isFinite(usage.thoughtTokens) &&
826
+ usage.thoughtTokens > 0
766
827
  ? Math.min(output, Math.round(usage.thoughtTokens))
767
828
  : undefined
768
- const liveContext = options?.contextTokens
769
- const estimatedContext = options?.estimatedContextTokens
829
+ const seg = options?.lastSegmentUsage ?? usage
830
+ const segBuckets = promptBuckets(seg)
831
+ const segPromptSum = segBuckets[0] + segBuckets[1] + segBuckets[2]
832
+ const promptSource = segPromptSum > 0 ? seg : usage
833
+ const rawPrompt = segPromptSum > 0 ? segBuckets : promptBuckets(usage)
834
+
835
+ const liveContext =
836
+ positiveInt(options?.contextTokens) ??
837
+ positiveInt(options?.estimatedContextTokens)
838
+ let promptCap: number
770
839
  let totalTokens: number
771
- if (
772
- typeof liveContext === 'number' &&
773
- Number.isFinite(liveContext) &&
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)
840
+ if (liveContext !== undefined) {
841
+ promptCap = liveContext
842
+ totalTokens = liveContext
783
843
  } else {
784
- const seg = options?.lastSegmentUsage ?? usage
785
844
  const scale = Math.max(1, calls)
786
- const segPrompt = Math.max(
787
- 0,
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
845
+ promptCap = Math.max(0, Math.round(segPromptSum / scale))
846
+ totalTokens = promptCap + nonNegativeInt(seg.outputTokens)
797
847
  }
848
+
849
+ const [input, cacheRead, cacheWrite] = capPromptBuckets(rawPrompt, promptCap)
798
850
  return {
799
851
  inputTokens: input,
800
852
  outputTokens: output,
801
- ...(usage.cachedReadTokens !== undefined || cacheRead > 0
853
+ ...(promptSource.cachedReadTokens !== undefined ||
854
+ usage.cachedReadTokens !== undefined ||
855
+ cacheRead > 0
802
856
  ? { cacheReadTokens: cacheRead }
803
857
  : {}),
804
858
  ...(cacheWrite > 0 ? { cacheWriteTokens: cacheWrite } : {}),