@qlairoslabs/acp-client 0.5.0 → 0.7.0
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-metering.md +288 -0
- package/CONSUMER_GUIDE.md +579 -292
- package/README.md +25 -0
- package/package.json +6 -3
- package/src/agent-session.ts +2589 -96
- package/src/cli/index.ts +33 -5
- package/src/cli/managed.ts +220 -0
- package/src/client.ts +57 -1
- package/src/controller.ts +43 -0
- package/src/index.ts +379 -3
- package/src/metering/catalog/build.ts +285 -0
- package/src/metering/catalog/index.ts +243 -0
- package/src/metering/catalog/live.ts +171 -0
- package/src/metering/catalog/models-dev.catalog.json +8797 -0
- package/src/metering/catalog/models-dev.meta.json +6 -0
- package/src/metering/categories.ts +129 -0
- package/src/metering/certification.ts +86 -0
- package/src/metering/context.ts +134 -0
- package/src/metering/delta.ts +108 -0
- package/src/metering/engine.ts +999 -0
- package/src/metering/money.ts +356 -0
- package/src/metering/opencode/channel.ts +389 -0
- package/src/metering/opencode/index.ts +159 -0
- package/src/metering/opencode/plugin.js +90 -0
- package/src/metering/opencode/profile.ts +159 -0
- package/src/metering/pricing.ts +285 -0
- package/src/metering/provider.ts +121 -0
- package/src/metering/rating.ts +349 -0
- package/src/metering/record.ts +275 -0
- package/src/metering/state.ts +421 -0
- package/src/metering/usage.ts +72 -0
- package/src/persistence/activity-projection.ts +71 -0
- package/src/persistence/audit-log-reader.ts +506 -0
- package/src/persistence/audit-runtime.ts +162 -0
- package/src/persistence/checkpoint.ts +304 -0
- package/src/persistence/config.ts +538 -0
- package/src/persistence/configuration-state.ts +191 -0
- package/src/persistence/deletion.ts +227 -0
- package/src/persistence/file-registry-store.ts +740 -0
- package/src/persistence/integrity.ts +147 -0
- package/src/persistence/legacy-registry-import.ts +240 -0
- package/src/persistence/managed-checkpoint.ts +81 -0
- package/src/persistence/managed-creation.ts +456 -0
- package/src/persistence/managed-load.ts +172 -0
- package/src/persistence/managed-registry.ts +57 -0
- package/src/persistence/migration.ts +298 -0
- package/src/persistence/paths.ts +172 -0
- package/src/persistence/projection.ts +373 -0
- package/src/persistence/reconfiguration.ts +453 -0
- package/src/persistence/records.ts +873 -0
- package/src/persistence/reducer.ts +498 -0
- package/src/persistence/registry.ts +446 -0
- package/src/persistence/restoration.ts +689 -0
- package/src/persistence/session-log-writer.ts +480 -0
- package/src/persistence/state-runtime.ts +176 -0
- package/src/persistence/transcript-reader.ts +980 -0
- package/src/persistence/transcript-runtime.ts +667 -0
- package/src/persistence/transcript-scanner.ts +385 -0
- package/src/persistence/truncation.ts +276 -0
- package/src/session-manager.ts +257 -7
- package/src/transcript.ts +3 -3
- package/src/types.ts +28 -5
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
# Metering — breaking changes and migration
|
|
2
|
+
|
|
3
|
+
Pre-1.0 changes introduced by the `AgentSession` metering feature
|
|
4
|
+
(`.res/somelogs.md/9-5+/9-6-SPEC-metering.md` §21). Fold this into the release notes.
|
|
5
|
+
|
|
6
|
+
## 1. `Usage` → `TokenUsage`, with corrected field names
|
|
7
|
+
|
|
8
|
+
The old type was wrong in three ways: it used non-ACP field names, omitted the required
|
|
9
|
+
`totalTokens`, and documented itself as per-turn.
|
|
10
|
+
|
|
11
|
+
```diff
|
|
12
|
+
-export interface Usage {
|
|
13
|
+
+export interface TokenUsage {
|
|
14
|
+
+ totalTokens: number;
|
|
15
|
+
inputTokens: number;
|
|
16
|
+
outputTokens: number;
|
|
17
|
+
- cacheReadTokens?: number;
|
|
18
|
+
- cacheWriteTokens?: number;
|
|
19
|
+
+ cachedReadTokens?: number;
|
|
20
|
+
+ cachedWriteTokens?: number;
|
|
21
|
+
thoughtTokens?: number;
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`Usage` remains exported as a deprecated alias, so type-only consumers keep compiling.
|
|
26
|
+
Anything reading `usage.cacheReadTokens` gets `undefined` and must be renamed.
|
|
27
|
+
|
|
28
|
+
## 2. `PromptResult.usage` is a cumulative observation, not a per-turn amount
|
|
29
|
+
|
|
30
|
+
**This is the change most likely to produce silently wrong numbers.** The counters are
|
|
31
|
+
read as cumulative across the provider session, so summing successive reports
|
|
32
|
+
multiplies usage rather than accumulating it.
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
// WRONG — was already wrong, now demonstrably so.
|
|
36
|
+
let total = 0;
|
|
37
|
+
for (const result of results) total += result.usage?.inputTokens ?? 0;
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
// RIGHT — the library computes the per-operation delta for you.
|
|
42
|
+
const result = await session.prompt(text);
|
|
43
|
+
if (result.metering?.usage.status === "metered") {
|
|
44
|
+
const used = result.metering.usage.attributable; // this operation only
|
|
45
|
+
const cost = used.ratedTotal; // engraved at the price in force
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
ACP does not actually guarantee cumulative: the SDK documents `PromptResponse.usage` as
|
|
50
|
+
usage "for this turn" while documenting the individual `Usage` fields as totals across
|
|
51
|
+
the session, and offers no discriminator. The library states the interpretation it
|
|
52
|
+
applied in `record.provenance.counterInterpretation` rather than pretending the protocol
|
|
53
|
+
settled it.
|
|
54
|
+
|
|
55
|
+
**Which reading applies is per-harness evidence, not a guess.** OpenCode was measured
|
|
56
|
+
reporting PER-TURN counters, so it is registered as such and its delta is the report
|
|
57
|
+
itself. Everything else defaults to cumulative until measured.
|
|
58
|
+
`MeteringConfig.counterInterpretation` overrides it for a harness version you know
|
|
59
|
+
differs.
|
|
60
|
+
|
|
61
|
+
`usage` is also `null` — never zero-filled — when a harness reports nothing or reports
|
|
62
|
+
something malformed. Null means unknown, not free.
|
|
63
|
+
|
|
64
|
+
## 3. `prompt()` and `executeInternalSessionCommand()` return `AgentSessionPromptResult`
|
|
65
|
+
|
|
66
|
+
A superset of `PromptResult`, so existing field access is unaffected. It adds
|
|
67
|
+
`operationId` and `metering`.
|
|
68
|
+
|
|
69
|
+
`metering` is `null` only for a prompt cancelled before it was dispatched — that
|
|
70
|
+
operation never reached the provider and consumed nothing, so no record is minted for it.
|
|
71
|
+
|
|
72
|
+
`AcpClient.prompt()` still returns the plain `PromptResult`.
|
|
73
|
+
|
|
74
|
+
## 4. Failed operations reject with typed errors carrying their records
|
|
75
|
+
|
|
76
|
+
```diff
|
|
77
|
+
try {
|
|
78
|
+
await session.prompt(text);
|
|
79
|
+
} catch (err) {
|
|
80
|
+
- console.error(err.message);
|
|
81
|
+
+ if (err instanceof AgentSessionOperationError) {
|
|
82
|
+
+ await usageRepository.commit(err.metering, err.metering.nextState);
|
|
83
|
+
+ }
|
|
84
|
+
+ console.error(err.message); // preserved; original error is `err.cause`
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
A failed operation can still have consumed tokens. `AgentSession.prompt()` rejects with
|
|
89
|
+
`AgentSessionOperationError` and `handoff()` with `AgentSessionHandoffError` (carrying
|
|
90
|
+
`meteringRecords`). Consumers matching on exact error identity must inspect `cause`.
|
|
91
|
+
|
|
92
|
+
## 5. New events on `AgentSessionEvent`
|
|
93
|
+
|
|
94
|
+
Exhaustive `switch` statements over the event union need new cases:
|
|
95
|
+
`context_window_changed`, `provider_cost_changed`, `metering_recorded`,
|
|
96
|
+
`metering_blocked`, `metering_unblocked`, `metering_reconciled`.
|
|
97
|
+
|
|
98
|
+
`handoff_failed` gains `meteringRecords`, and `HandoffResult` gains `meteringRecords`.
|
|
99
|
+
|
|
100
|
+
## 6. Pricing is on by default; opting out is explicit
|
|
101
|
+
|
|
102
|
+
Omitting `metering` selects best-effort enforcement with the pinned models.dev catalog.
|
|
103
|
+
It adds no durable storage and no transcript writes. A consumer that deliberately wants
|
|
104
|
+
no local rating sets `pricing: false` — which is distinct from rating that *failed*
|
|
105
|
+
(`pricingStatus: "pricing_unavailable"`).
|
|
106
|
+
|
|
107
|
+
Refresh the pinned catalog at release time with `bun run generate:pricing`.
|
|
108
|
+
|
|
109
|
+
## 7. Pricing sources carry two different dates
|
|
110
|
+
|
|
111
|
+
A record can now answer both "when did we capture these prices" and "how old is the price
|
|
112
|
+
itself" — different questions that a single timestamp conflates.
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
pricingCapturedAt(record.usage.attributable.pricingSource)
|
|
116
|
+
// pinned → generatedAt live → fetchedAt consumer override → null
|
|
117
|
+
|
|
118
|
+
record.usage.attributable.pricingKey.modelLastUpdated
|
|
119
|
+
// "2026-04-21" — when that model's entry last changed upstream
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
A catalog fetched a second ago can still carry a year-old rate, which is why the upstream
|
|
123
|
+
entry date is engraved beside the lookup key rather than inferred from the source.
|
|
124
|
+
|
|
125
|
+
`PricingSource` gains a third variant, `models.dev_live`, carrying `artifactSha256` and
|
|
126
|
+
`fetchedAt`. Exhaustive switches over the union need a new case. Live prices deliberately
|
|
127
|
+
do NOT use `kind: "models.dev"`: that shape promises an immutable upstream commit, and a
|
|
128
|
+
runtime fetch has verified none.
|
|
129
|
+
|
|
130
|
+
## 8. Records carry a provider-cost reconciliation
|
|
131
|
+
|
|
132
|
+
Every record gains `costReconciliation`, comparing the rated total against the rise in the
|
|
133
|
+
harness's own cumulative cost across that operation.
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
const check = record.costReconciliation;
|
|
137
|
+
if (check.status === "checked" && !check.matches) {
|
|
138
|
+
// check.ratio === "2.032221" means the provider charged 2x what we accounted for
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
This exists because **ACP-derived metering undercounts any tool-using turn**. ACP reports
|
|
143
|
+
one model inference per prompt; a turn with N tool calls bills roughly N+1. Measured on
|
|
144
|
+
OpenCode: 1 tool call → 2.03x, 3 tool calls → 3.43x, 0 tool calls → 1.00x.
|
|
145
|
+
|
|
146
|
+
Do not bill from `attributable.ratedTotal` on the ACP backend. Bill from
|
|
147
|
+
`costReconciliation.providerDelta` where the harness reports cost, and treat the rated
|
|
148
|
+
total as the cross-check.
|
|
149
|
+
|
|
150
|
+
Agreement is judged on the ratio rounding to `1`, not on string equality: provider cost
|
|
151
|
+
arrives as a JSON float, so cumulative subtraction yields artifacts like
|
|
152
|
+
`0.002577469999999998` against an exact `0.00257747`.
|
|
153
|
+
|
|
154
|
+
## 9. `billing_required` needs a certified integration
|
|
155
|
+
|
|
156
|
+
The mode is refused unless the library has a certification registered for the adapter AND
|
|
157
|
+
a live `InferenceSource` presenting the matching `certificationId`. Neither a registry
|
|
158
|
+
entry alone nor a consumer-supplied flag opens it — certification describes evidence, not
|
|
159
|
+
configuration.
|
|
160
|
+
|
|
161
|
+
Only OpenCode qualifies today. For it:
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
const metering = await createOpencodeMetering();
|
|
165
|
+
const session = await AgentSession.create({
|
|
166
|
+
adapter: ADAPTERS.opencode,
|
|
167
|
+
adapterId: "opencode",
|
|
168
|
+
env: metering.env, // loads the plugin
|
|
169
|
+
metering: {
|
|
170
|
+
enforcement: "billing_required",
|
|
171
|
+
inferenceSource: metering.inferenceSource,
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
if (!(await metering.waitForPlugin())) throw new Error("metering plugin did not load");
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
The integration installs a plugin that observes one assistant message per model inference,
|
|
178
|
+
recovering the calls ACP hides. Verified against OpenCode's own database export: 9
|
|
179
|
+
inferences across 5 operations, cost and tokens matching exactly.
|
|
180
|
+
|
|
181
|
+
An unhealthy channel or zero observed inferences reports `usage_unavailable` and blocks in
|
|
182
|
+
`billing_required`, rather than falling back to a backend known to undercount.
|
|
183
|
+
|
|
184
|
+
**What blocks, and what only marks a record partial.** `billing_required` blocks on
|
|
185
|
+
PERMANENT loss — a report the channel refused for capacity, whose usage is accounted
|
|
186
|
+
nowhere. It does NOT block on an outstanding sequence gap: those usually resolve moments
|
|
187
|
+
later, and the late report then lands in `unallocatedUsage`, visible and costed. The
|
|
188
|
+
promise is "never silently under-account", not "every operation is perfectly attributed",
|
|
189
|
+
and halting a production session on a loopback reorder costs more than it prevents. Such
|
|
190
|
+
an operation still reports `attribution: "partial"`, and
|
|
191
|
+
`meteringSnapshot.outstandingReports` exposes the count so a consumer can alert on one
|
|
192
|
+
that stops falling.
|
|
193
|
+
|
|
194
|
+
A report arriving after its operation closed is routed to `unallocatedUsage` rather than
|
|
195
|
+
charged to whichever operation drains next — which is what makes not blocking defensible.
|
|
196
|
+
|
|
197
|
+
`routing` remains `"observed"` even here: the plugin reports what the harness ran, but a
|
|
198
|
+
library cannot prove no model call bypassed it.
|
|
199
|
+
|
|
200
|
+
## 10. Money totals carry their own completeness
|
|
201
|
+
|
|
202
|
+
`ratedTotal` and `ratedCosts` are no longer `Money | null` / `Money[]`. They are a
|
|
203
|
+
`MoneyTotal`:
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
interface MoneyTotal {
|
|
207
|
+
readonly amounts: readonly Money[]; // one per currency
|
|
208
|
+
readonly unaccounted: number; // contributions that could not be included
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
```diff
|
|
213
|
+
-const cost = record.usage.attributable.ratedTotal?.amount;
|
|
214
|
+
+const cost = soleAmount(record.usage.attributable.ratedTotal)?.amount;
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
`soleAmount()` returns a figure only when exactly one currency is involved and nothing was
|
|
218
|
+
unaccounted; otherwise null, so the ambiguous case has to be handled rather than read as
|
|
219
|
+
`amounts[0]`.
|
|
220
|
+
|
|
221
|
+
Why this exists: `Money[]` had nowhere to record a contribution it failed to include, so
|
|
222
|
+
every accumulation site wrote `if (sum.ok) total = sum.value` and a failure silently became
|
|
223
|
+
a no-op. That single missing concept produced six separate under-reporting bugs — the worst
|
|
224
|
+
of which dropped an entire currency from an operation while reporting it fully priced.
|
|
225
|
+
Tokens never had the problem, because `UsageCategoryTotal` forces a coverage answer;
|
|
226
|
+
`addToTotal` now forces the same answer for money by returning a total rather than a
|
|
227
|
+
Result, so there is no `.ok` to forget.
|
|
228
|
+
|
|
229
|
+
`pricingStatus: "priced"` is now derived from the total being complete rather than from a
|
|
230
|
+
separate flag travelling beside it.
|
|
231
|
+
|
|
232
|
+
`unaccounted` counts contributions that were **attempted and failed**. Setting
|
|
233
|
+
`pricing: false` is a choice, not a failure, so a deliberately unrated session reports
|
|
234
|
+
`{ amounts: [], unaccounted: 0 }` — the same distinction `not_applicable` versus
|
|
235
|
+
`unavailable` draws for token categories. `pricingStatus` still separates the two
|
|
236
|
+
(`not_configured` versus `pricing_unavailable`).
|
|
237
|
+
|
|
238
|
+
`UnallocatedUsageState` loses its `costedRecordCount`/`uncostedRecordCount` counters —
|
|
239
|
+
`ratedCosts.unaccounted` says the same thing.
|
|
240
|
+
|
|
241
|
+
## 11. How an unrepresentable cost is reported
|
|
242
|
+
|
|
243
|
+
Nothing in the metering path turns an unknown cost into zero. Each place says so
|
|
244
|
+
differently, and the difference matters when reconciling against an invoice:
|
|
245
|
+
|
|
246
|
+
| where | what a consumer sees |
|
|
247
|
+
|---|---|
|
|
248
|
+
| a category could not be rated | `pricingStatus: "pricing_unavailable"` plus `pricingFailureReason` naming the category |
|
|
249
|
+
| one category of a priced operation | `PricedTokenAmount.pricing: null` with `reportedTokens` still present |
|
|
250
|
+
| a multi-model operation | top-level `pricing: null`; each rate lives in its own `lineItems` entry |
|
|
251
|
+
| the harness reported a malformed cost | the inference record is rejected outright; nothing partial is stored |
|
|
252
|
+
| the harness reported no cost | `ProviderInference.cost: null` — tokens are still recorded |
|
|
253
|
+
| any money total | `unaccounted` > 0 marks `amounts` as a **lower bound** |
|
|
254
|
+
| a total spanning currencies | `amounts` has several entries; `soleAmount()` returns null |
|
|
255
|
+
| provider cost vs our rating | `costReconciliation.status: "unavailable"` with a reason |
|
|
256
|
+
|
|
257
|
+
Nothing turns an unknown cost into zero, and no total can be read as complete without
|
|
258
|
+
saying so — `unaccounted` is on the total itself, so a lower bound cannot be mistaken for
|
|
259
|
+
a final figure.
|
|
260
|
+
|
|
261
|
+
## 12. Metering state starts at version 3
|
|
262
|
+
|
|
263
|
+
There is no version 1 or 2 on disk — nothing shipped before the MoneyTotal change, so
|
|
264
|
+
there is no migration to write. Restoration validates `version` before reading any
|
|
265
|
+
version-specific field; an unknown version is a preflight error in a strict mode and is
|
|
266
|
+
ignored wholesale in best-effort, surfaced through `session.meteringSnapshot.restoration`.
|
|
267
|
+
|
|
268
|
+
## Persisting and restoring
|
|
269
|
+
|
|
270
|
+
```ts
|
|
271
|
+
const initialState = await usageRepository.loadState(agentSessionId);
|
|
272
|
+
const session = await AgentSession.create({
|
|
273
|
+
adapter,
|
|
274
|
+
adapterId: "codex",
|
|
275
|
+
agentSessionId,
|
|
276
|
+
metering: { initialState },
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
const result = await session.prompt(text);
|
|
280
|
+
if (result.metering) {
|
|
281
|
+
// Commit both together: a record stored without its state leaves the next session
|
|
282
|
+
// with a stale baseline, which is how correct code still double-counts.
|
|
283
|
+
await usageRepository.commit(result.metering, result.metering.nextState);
|
|
284
|
+
}
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
Enforce a unique constraint on `operationId` to make delivery idempotent. See
|
|
288
|
+
`smoke-tests/test6-metering/` for a runnable version of this contract.
|