@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,421 @@
|
|
|
1
|
+
// Bounded live metering state and its accumulation rules. See 9-6-SPEC-metering.md §11.
|
|
2
|
+
//
|
|
3
|
+
// The session keeps totals, the active baseline, and the last record — never an unbounded
|
|
4
|
+
// operation history. Consumers own durable accounting; the library hands them each
|
|
5
|
+
// immutable record plus the state to persist beside it.
|
|
6
|
+
//
|
|
7
|
+
// The counters exist so a partial total cannot look complete. "180k tokens" and "at least
|
|
8
|
+
// 180k tokens, with two operations we could not measure" are different claims, and per
|
|
9
|
+
// category they are different again: a harness may report input and output while never
|
|
10
|
+
// mentioning cache. Coverage distinguishes a category nobody could measure from one the
|
|
11
|
+
// model simply does not use.
|
|
12
|
+
|
|
13
|
+
import type { TokenUsage } from "../types.ts";
|
|
14
|
+
import {
|
|
15
|
+
CATEGORY_FIELD,
|
|
16
|
+
CATEGORY_TOTAL,
|
|
17
|
+
TOKEN_CATEGORY_KEYS,
|
|
18
|
+
USAGE_KEYS,
|
|
19
|
+
isTokenCount,
|
|
20
|
+
} from "./categories.ts";
|
|
21
|
+
import {
|
|
22
|
+
EMPTY_MONEY_TOTAL,
|
|
23
|
+
addMoney,
|
|
24
|
+
addToTotal,
|
|
25
|
+
canonicalizeMoney,
|
|
26
|
+
isValidMoney,
|
|
27
|
+
mergeTotals,
|
|
28
|
+
type Money,
|
|
29
|
+
type MoneyTotal,
|
|
30
|
+
} from "./money.ts";
|
|
31
|
+
import type { CategoryApplicability, TokenCategory } from "./pricing.ts";
|
|
32
|
+
import type { AttributableUsage } from "./rating.ts";
|
|
33
|
+
|
|
34
|
+
export type CategoryCoverage = "complete" | "partial" | "none" | "not_applicable";
|
|
35
|
+
|
|
36
|
+
export interface UsageCategoryTotal {
|
|
37
|
+
/** Sum of deltas that were actually attributable; always a lower bound. */
|
|
38
|
+
readonly knownTokens: number;
|
|
39
|
+
/** Applicable operations that supplied an attributable value, including explicit 0. */
|
|
40
|
+
readonly attributedOperationCount: number;
|
|
41
|
+
/** Operations explicitly known not to use this category. */
|
|
42
|
+
readonly notApplicableOperationCount: number;
|
|
43
|
+
/** Applicable/unknown operations for which this category could not be established. */
|
|
44
|
+
readonly unavailableOperationCount: number;
|
|
45
|
+
readonly coverage: CategoryCoverage;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface AggregateUsageTotal {
|
|
49
|
+
readonly knownTokens: number;
|
|
50
|
+
readonly attributedOperationCount: number;
|
|
51
|
+
readonly unavailableOperationCount: number;
|
|
52
|
+
/** Total usage is always applicable, so this never reads "not_applicable". */
|
|
53
|
+
readonly coverage: "complete" | "partial" | "none";
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface UsageTotals {
|
|
57
|
+
readonly total: AggregateUsageTotal;
|
|
58
|
+
readonly input: UsageCategoryTotal;
|
|
59
|
+
readonly output: UsageCategoryTotal;
|
|
60
|
+
readonly cachedRead: UsageCategoryTotal;
|
|
61
|
+
readonly cachedWrite: UsageCategoryTotal;
|
|
62
|
+
readonly thought: UsageCategoryTotal;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface UnallocatedUsageState {
|
|
66
|
+
/** Number of observed inference records not assigned to an operation. */
|
|
67
|
+
readonly recordCount: number;
|
|
68
|
+
/** Known unallocated tokens. Absent categories remain absent, never zero-filled. */
|
|
69
|
+
readonly knownTokens: Partial<TokenUsage>;
|
|
70
|
+
/**
|
|
71
|
+
* Rated unallocated amounts.
|
|
72
|
+
*
|
|
73
|
+
* MoneyTotal carries its own completeness, so the separate costed/uncosted counters this
|
|
74
|
+
* once needed are gone — an unaccounted cost is `ratedCosts.unaccounted`.
|
|
75
|
+
*/
|
|
76
|
+
readonly ratedCosts: MoneyTotal;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface MeteringBaseline {
|
|
80
|
+
readonly adapterId: string;
|
|
81
|
+
readonly internalSessionId: string;
|
|
82
|
+
readonly reportedUsage: TokenUsage;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface AgentSessionMeteringState {
|
|
86
|
+
readonly version: MeteringStateVersion;
|
|
87
|
+
readonly agentSessionId: string;
|
|
88
|
+
readonly operationCount: number;
|
|
89
|
+
readonly meteredOperationCount: number;
|
|
90
|
+
readonly unmeteredOperationCount: number;
|
|
91
|
+
readonly totals: UsageTotals;
|
|
92
|
+
/** Session cost across every operation. Multi-currency by design; see MoneyTotal. */
|
|
93
|
+
readonly ratedCosts: MoneyTotal;
|
|
94
|
+
readonly unallocatedUsage: UnallocatedUsageState;
|
|
95
|
+
readonly activeBaseline: MeteringBaseline | null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The persisted shape's version, declared ONCE.
|
|
100
|
+
*
|
|
101
|
+
* It previously appeared as a literal in four places, and the last bump missed one — the
|
|
102
|
+
* session snapshot reported restoring version 2 beside version-3 state. A number that has
|
|
103
|
+
* to be updated in several places is a number that will eventually disagree with itself.
|
|
104
|
+
*/
|
|
105
|
+
export type MeteringStateVersion = 3;
|
|
106
|
+
export const METERING_STATE_VERSION: MeteringStateVersion = 3;
|
|
107
|
+
|
|
108
|
+
/** Category → the TokenUsage field carrying it. */
|
|
109
|
+
function emptyCategoryTotal(): UsageCategoryTotal {
|
|
110
|
+
return Object.freeze({
|
|
111
|
+
knownTokens: 0,
|
|
112
|
+
attributedOperationCount: 0,
|
|
113
|
+
notApplicableOperationCount: 0,
|
|
114
|
+
unavailableOperationCount: 0,
|
|
115
|
+
coverage: "none" as const,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function deriveCoverage(total: Omit<UsageCategoryTotal, "coverage">): CategoryCoverage {
|
|
120
|
+
const { attributedOperationCount, notApplicableOperationCount, unavailableOperationCount } = total;
|
|
121
|
+
const seen = attributedOperationCount + notApplicableOperationCount + unavailableOperationCount;
|
|
122
|
+
if (seen === 0) return "none";
|
|
123
|
+
// Wholly inapplicable: a non-reasoning model never reports thought tokens, and that is
|
|
124
|
+
// not a metering gap.
|
|
125
|
+
if (notApplicableOperationCount === seen) return "not_applicable";
|
|
126
|
+
if (unavailableOperationCount === 0) return "complete";
|
|
127
|
+
if (attributedOperationCount === 0) return "none";
|
|
128
|
+
return "partial";
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function emptyMeteringState(agentSessionId: string): AgentSessionMeteringState {
|
|
132
|
+
return Object.freeze({
|
|
133
|
+
version: METERING_STATE_VERSION,
|
|
134
|
+
agentSessionId,
|
|
135
|
+
operationCount: 0,
|
|
136
|
+
meteredOperationCount: 0,
|
|
137
|
+
unmeteredOperationCount: 0,
|
|
138
|
+
totals: Object.freeze({
|
|
139
|
+
total: Object.freeze({
|
|
140
|
+
knownTokens: 0,
|
|
141
|
+
attributedOperationCount: 0,
|
|
142
|
+
unavailableOperationCount: 0,
|
|
143
|
+
coverage: "none" as const,
|
|
144
|
+
}),
|
|
145
|
+
input: emptyCategoryTotal(),
|
|
146
|
+
output: emptyCategoryTotal(),
|
|
147
|
+
cachedRead: emptyCategoryTotal(),
|
|
148
|
+
cachedWrite: emptyCategoryTotal(),
|
|
149
|
+
thought: emptyCategoryTotal(),
|
|
150
|
+
}),
|
|
151
|
+
ratedCosts: EMPTY_MONEY_TOTAL,
|
|
152
|
+
unallocatedUsage: Object.freeze({
|
|
153
|
+
recordCount: 0,
|
|
154
|
+
knownTokens: Object.freeze({}),
|
|
155
|
+
ratedCosts: EMPTY_MONEY_TOTAL,
|
|
156
|
+
}),
|
|
157
|
+
activeBaseline: null,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* One piece of observed work that no operation can claim.
|
|
163
|
+
*
|
|
164
|
+
* Carries its cost and the reason it went unattributed: a consumer reconciling against a
|
|
165
|
+
* provider invoice needs the amount, and anyone debugging a gap needs to know whether it
|
|
166
|
+
* was a replaced thread, background activity, or a lost report.
|
|
167
|
+
*/
|
|
168
|
+
export interface UnallocatedUsageAccrual {
|
|
169
|
+
readonly usage: TokenUsage;
|
|
170
|
+
readonly ratedCost: Money | null;
|
|
171
|
+
readonly reason: string;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export interface OperationAccrual {
|
|
175
|
+
/** Attributable usage, or null when the operation could not be measured. */
|
|
176
|
+
readonly attributable: AttributableUsage | null;
|
|
177
|
+
/** Applicability from the resolved policy; unknown when no policy was resolved. */
|
|
178
|
+
readonly applicability: Readonly<Record<TokenCategory, CategoryApplicability>> | null;
|
|
179
|
+
readonly baseline: MeteringBaseline | null;
|
|
180
|
+
/** Usage observed but belonging to no operation — never merged into totals. */
|
|
181
|
+
readonly unallocated?: readonly UnallocatedUsageAccrual[];
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Fold one completed operation into the running state.
|
|
186
|
+
*
|
|
187
|
+
* Returns a new frozen state; the previous one stays valid, because records already handed
|
|
188
|
+
* to a consumer embed it.
|
|
189
|
+
*/
|
|
190
|
+
export function accrueOperation(
|
|
191
|
+
previous: AgentSessionMeteringState,
|
|
192
|
+
accrual: OperationAccrual,
|
|
193
|
+
): AgentSessionMeteringState {
|
|
194
|
+
const { attributable, applicability } = accrual;
|
|
195
|
+
const measured = attributable !== null;
|
|
196
|
+
|
|
197
|
+
const aggregate = previous.totals.total;
|
|
198
|
+
const nextAggregate = {
|
|
199
|
+
knownTokens: aggregate.knownTokens + (attributable?.totalTokens ?? 0),
|
|
200
|
+
attributedOperationCount: aggregate.attributedOperationCount + (measured ? 1 : 0),
|
|
201
|
+
unavailableOperationCount: aggregate.unavailableOperationCount + (measured ? 0 : 1),
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const categoryTotals: Record<string, UsageCategoryTotal> = {};
|
|
205
|
+
for (const category of Object.keys(CATEGORY_FIELD) as TokenCategory[]) {
|
|
206
|
+
const key = CATEGORY_TOTAL[category];
|
|
207
|
+
const current = previous.totals[key];
|
|
208
|
+
const value = attributable?.reportedDelta[CATEGORY_FIELD[category]];
|
|
209
|
+
const notApplicable = applicability?.[category] === "not_applicable";
|
|
210
|
+
|
|
211
|
+
const next = {
|
|
212
|
+
knownTokens: current.knownTokens + (value ?? 0),
|
|
213
|
+
// An explicit reported zero counts as attributed: it is a measurement, unlike an
|
|
214
|
+
// absent counter.
|
|
215
|
+
attributedOperationCount: current.attributedOperationCount + (value !== undefined ? 1 : 0),
|
|
216
|
+
notApplicableOperationCount:
|
|
217
|
+
current.notApplicableOperationCount + (value === undefined && notApplicable ? 1 : 0),
|
|
218
|
+
unavailableOperationCount:
|
|
219
|
+
current.unavailableOperationCount + (value === undefined && !notApplicable ? 1 : 0),
|
|
220
|
+
};
|
|
221
|
+
categoryTotals[key] = Object.freeze({ ...next, coverage: deriveCoverage(next) });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Always accounted: a total that could not absorb an operation's cost records that,
|
|
225
|
+
// rather than leaving the session silently short.
|
|
226
|
+
const ratedCosts = attributable
|
|
227
|
+
? mergeTotals(previous.ratedCosts, attributable.ratedTotal)
|
|
228
|
+
: previous.ratedCosts;
|
|
229
|
+
|
|
230
|
+
return Object.freeze({
|
|
231
|
+
...previous,
|
|
232
|
+
operationCount: previous.operationCount + 1,
|
|
233
|
+
meteredOperationCount: previous.meteredOperationCount + (measured ? 1 : 0),
|
|
234
|
+
unmeteredOperationCount: previous.unmeteredOperationCount + (measured ? 0 : 1),
|
|
235
|
+
totals: Object.freeze({
|
|
236
|
+
total: Object.freeze({ ...nextAggregate, coverage: deriveAggregateCoverage(nextAggregate) }),
|
|
237
|
+
input: categoryTotals.input!,
|
|
238
|
+
output: categoryTotals.output!,
|
|
239
|
+
cachedRead: categoryTotals.cachedRead!,
|
|
240
|
+
cachedWrite: categoryTotals.cachedWrite!,
|
|
241
|
+
thought: categoryTotals.thought!,
|
|
242
|
+
}),
|
|
243
|
+
ratedCosts,
|
|
244
|
+
unallocatedUsage: accrueUnallocated(previous.unallocatedUsage, accrual.unallocated ?? []),
|
|
245
|
+
activeBaseline: accrual.baseline,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Fold observed-but-unattributed usage into its own bucket.
|
|
251
|
+
*
|
|
252
|
+
* Kept strictly apart from `totals`: §11 requires that late or background work is never
|
|
253
|
+
* charged to the next operation, and a consumer must be able to see that it happened.
|
|
254
|
+
* Absent categories stay absent rather than being zero-filled.
|
|
255
|
+
*/
|
|
256
|
+
function accrueUnallocated(
|
|
257
|
+
previous: UnallocatedUsageState,
|
|
258
|
+
additions: readonly UnallocatedUsageAccrual[],
|
|
259
|
+
): UnallocatedUsageState {
|
|
260
|
+
if (additions.length === 0) return previous;
|
|
261
|
+
const known: Partial<TokenUsage> = { ...previous.knownTokens };
|
|
262
|
+
let ratedCosts = previous.ratedCosts;
|
|
263
|
+
for (const { usage, ratedCost } of additions) {
|
|
264
|
+
// addToTotal counts what it cannot include, so a missing cost cannot vanish.
|
|
265
|
+
ratedCosts = addToTotal(ratedCosts, ratedCost);
|
|
266
|
+
for (const key of USAGE_KEYS) {
|
|
267
|
+
const value = usage[key];
|
|
268
|
+
if (value === undefined) continue;
|
|
269
|
+
known[key] = (known[key] ?? 0) + value;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return Object.freeze({
|
|
273
|
+
recordCount: previous.recordCount + additions.length,
|
|
274
|
+
knownTokens: Object.freeze(known),
|
|
275
|
+
ratedCosts,
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function deriveAggregateCoverage(
|
|
280
|
+
total: Omit<AggregateUsageTotal, "coverage">,
|
|
281
|
+
): AggregateUsageTotal["coverage"] {
|
|
282
|
+
if (total.attributedOperationCount === 0) return "none";
|
|
283
|
+
return total.unavailableOperationCount === 0 ? "complete" : "partial";
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Add one amount into a per-currency accumulation.
|
|
288
|
+
*
|
|
289
|
+
* Amounts are already-rounded operation totals, so the sum is exact and never re-rounded.
|
|
290
|
+
* Currencies are kept as separate facts rather than converted.
|
|
291
|
+
*/
|
|
292
|
+
export function accumulateByCurrency(
|
|
293
|
+
totals: readonly Money[],
|
|
294
|
+
addition: Money,
|
|
295
|
+
): { ok: true; value: readonly Money[] } | { ok: false; reason: string } {
|
|
296
|
+
const next: Money[] = [];
|
|
297
|
+
let merged = false;
|
|
298
|
+
for (const existing of totals) {
|
|
299
|
+
if (existing.currency !== addition.currency) {
|
|
300
|
+
next.push(existing);
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
const sum = addMoney(existing, addition);
|
|
304
|
+
if (!sum.ok) return { ok: false, reason: sum.reason };
|
|
305
|
+
next.push(sum.value);
|
|
306
|
+
merged = true;
|
|
307
|
+
}
|
|
308
|
+
if (!merged) {
|
|
309
|
+
const canonical = canonicalizeMoney(addition);
|
|
310
|
+
if (!canonical.ok) return { ok: false, reason: canonical.reason };
|
|
311
|
+
next.push(canonical.value);
|
|
312
|
+
}
|
|
313
|
+
return { ok: true, value: Object.freeze(next) };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export type StateRestoration =
|
|
317
|
+
| { readonly status: "not_provided" }
|
|
318
|
+
| {
|
|
319
|
+
readonly status: "restored";
|
|
320
|
+
readonly version: MeteringStateVersion;
|
|
321
|
+
readonly state: AgentSessionMeteringState;
|
|
322
|
+
}
|
|
323
|
+
| {
|
|
324
|
+
readonly status: "ignored";
|
|
325
|
+
readonly reason:
|
|
326
|
+
| "initial_state_version_unsupported"
|
|
327
|
+
| "initial_state_identity_mismatch"
|
|
328
|
+
| "initial_state_malformed";
|
|
329
|
+
readonly providedVersion?: number;
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Validate restored state before any version-specific field is read.
|
|
334
|
+
*
|
|
335
|
+
* A foreign version is refused wholesale rather than partially read: fields that happen to
|
|
336
|
+
* line up between versions are the most dangerous kind of near-match, because the result
|
|
337
|
+
* looks like a successful restore.
|
|
338
|
+
*/
|
|
339
|
+
function isMoneyTotal(value: unknown): boolean {
|
|
340
|
+
if (typeof value !== "object" || value === null) return false;
|
|
341
|
+
const total = value as Record<string, unknown>;
|
|
342
|
+
return (
|
|
343
|
+
Array.isArray(total.amounts) &&
|
|
344
|
+
total.amounts.every((amount) => isValidMoney(amount as Money)) &&
|
|
345
|
+
isTokenCount(total.unaccounted)
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function isCategoryTotal(value: unknown): boolean {
|
|
350
|
+
if (typeof value !== "object" || value === null) return false;
|
|
351
|
+
const total = value as Record<string, unknown>;
|
|
352
|
+
return (
|
|
353
|
+
isTokenCount(total.knownTokens) &&
|
|
354
|
+
isTokenCount(total.attributedOperationCount) &&
|
|
355
|
+
isTokenCount(total.unavailableOperationCount)
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Check the shape a restored state must have before any of it is trusted. */
|
|
360
|
+
function isStructurallyValid(state: AgentSessionMeteringState): boolean {
|
|
361
|
+
if (
|
|
362
|
+
!isTokenCount(state.operationCount) ||
|
|
363
|
+
!isTokenCount(state.meteredOperationCount) ||
|
|
364
|
+
!isTokenCount(state.unmeteredOperationCount)
|
|
365
|
+
) {
|
|
366
|
+
return false;
|
|
367
|
+
}
|
|
368
|
+
const totals = state.totals as unknown as Record<string, unknown> | undefined;
|
|
369
|
+
if (!totals) return false;
|
|
370
|
+
// `total` is an AggregateUsageTotal, but the three counters checked here are exactly the
|
|
371
|
+
// ones both shapes share, so one predicate covers it and the five categories alike.
|
|
372
|
+
if (!isCategoryTotal(totals.total)) return false;
|
|
373
|
+
for (const key of TOKEN_CATEGORY_KEYS) {
|
|
374
|
+
if (!isCategoryTotal(totals[key])) return false;
|
|
375
|
+
}
|
|
376
|
+
if (!isMoneyTotal(state.ratedCosts)) return false;
|
|
377
|
+
|
|
378
|
+
const unallocated = state.unallocatedUsage as unknown as Record<string, unknown> | undefined;
|
|
379
|
+
if (!unallocated || !isTokenCount(unallocated.recordCount) || !isMoneyTotal(unallocated.ratedCosts)) {
|
|
380
|
+
return false;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
const baseline = state.activeBaseline;
|
|
384
|
+
if (baseline !== null) {
|
|
385
|
+
if (typeof baseline !== "object") return false;
|
|
386
|
+
if (typeof baseline.adapterId !== "string" || typeof baseline.internalSessionId !== "string") {
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
const usage = baseline.reportedUsage as unknown as Record<string, unknown> | undefined;
|
|
390
|
+
if (!usage || !isTokenCount(usage.totalTokens) || !isTokenCount(usage.inputTokens) || !isTokenCount(usage.outputTokens)) {
|
|
391
|
+
return false;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return true;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export function restoreMeteringState(
|
|
398
|
+
provided: AgentSessionMeteringState | undefined,
|
|
399
|
+
agentSessionId: string,
|
|
400
|
+
): StateRestoration {
|
|
401
|
+
if (provided === undefined) return { status: "not_provided" };
|
|
402
|
+
|
|
403
|
+
const version = (provided as { version?: unknown }).version;
|
|
404
|
+
if (version !== METERING_STATE_VERSION) {
|
|
405
|
+
return {
|
|
406
|
+
status: "ignored",
|
|
407
|
+
reason: "initial_state_version_unsupported",
|
|
408
|
+
...(typeof version === "number" ? { providedVersion: version } : {}),
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
if (provided.agentSessionId !== agentSessionId) {
|
|
412
|
+
return { status: "ignored", reason: "initial_state_identity_mismatch" };
|
|
413
|
+
}
|
|
414
|
+
// A matching version and id is not proof the rest is intact. This state comes back from
|
|
415
|
+
// a consumer's database or a JSON file and feeds straight into totals a bill is drawn
|
|
416
|
+
// from, so a truncated write or a hand-edit must be refused rather than absorbed.
|
|
417
|
+
if (!isStructurallyValid(provided)) {
|
|
418
|
+
return { status: "ignored", reason: "initial_state_malformed" };
|
|
419
|
+
}
|
|
420
|
+
return { status: "restored", version: METERING_STATE_VERSION, state: provided };
|
|
421
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// ACP usage normalization. The ONLY place raw `PromptResponse.usage` is turned into the
|
|
2
|
+
// library's public TokenUsage shape. See 9-6-SPEC-metering.md §4.
|
|
3
|
+
//
|
|
4
|
+
// Two things this module deliberately does NOT do:
|
|
5
|
+
// 1. Coerce a missing or malformed counter to zero. Absence is not zero — a harness
|
|
6
|
+
// that omits cachedWriteTokens has told us nothing, not that it wrote no cache.
|
|
7
|
+
// 2. Decide whether the harness emits cumulative or per-turn counters. The installed
|
|
8
|
+
// ACP SDK contradicts itself (PromptResponse.usage says "for this turn", the Usage
|
|
9
|
+
// fields say "across all turns"/"across session") and exposes no discriminator, so
|
|
10
|
+
// the interpretation is adapter evidence recorded in provenance, never a heuristic
|
|
11
|
+
// applied here.
|
|
12
|
+
|
|
13
|
+
import type { TokenUsage } from "../types.ts";
|
|
14
|
+
import { OPTIONAL_USAGE_KEYS, REQUIRED_USAGE_KEYS, isTokenCount } from "./categories.ts";
|
|
15
|
+
|
|
16
|
+
export type UsageNormalization =
|
|
17
|
+
| { readonly ok: true; readonly usage: TokenUsage }
|
|
18
|
+
/** `reason` is a stable, safe-to-log string; it becomes MeteringUsageResult.reason. */
|
|
19
|
+
| { readonly ok: false; readonly reason: string };
|
|
20
|
+
|
|
21
|
+
function describe(value: unknown): string {
|
|
22
|
+
if (typeof value === "number") return Number.isFinite(value) ? String(value) : String(value);
|
|
23
|
+
if (value === null) return "null";
|
|
24
|
+
return typeof value;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Normalize a raw ACP usage object.
|
|
29
|
+
*
|
|
30
|
+
* Absent/null report → unavailable (the harness reported nothing).
|
|
31
|
+
* Malformed REQUIRED counter → unavailable, never zero-filled.
|
|
32
|
+
* Malformed PRESENT optional counter → unavailable. A present-but-corrupt value is not
|
|
33
|
+
* the same as absence: silently dropping it would assert the harness never reported
|
|
34
|
+
* the category, which is exactly the fabrication §4 forbids.
|
|
35
|
+
* Absent/null optional counter → omitted from the result, so absence stays absence.
|
|
36
|
+
*/
|
|
37
|
+
export function normalizeTokenUsage(raw: unknown): UsageNormalization {
|
|
38
|
+
if (raw === null || raw === undefined) {
|
|
39
|
+
return { ok: false, reason: "harness reported no usage" };
|
|
40
|
+
}
|
|
41
|
+
if (typeof raw !== "object") {
|
|
42
|
+
return { ok: false, reason: `usage is ${typeof raw}, not an object` };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const source = raw as Record<string, unknown>;
|
|
46
|
+
const required: Record<string, number> = {};
|
|
47
|
+
for (const key of REQUIRED_USAGE_KEYS) {
|
|
48
|
+
const value = source[key];
|
|
49
|
+
if (!isTokenCount(value)) {
|
|
50
|
+
return { ok: false, reason: `usage.${key} is ${describe(value)}, not a token count` };
|
|
51
|
+
}
|
|
52
|
+
required[key] = value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const usage: TokenUsage = {
|
|
56
|
+
totalTokens: required.totalTokens!,
|
|
57
|
+
inputTokens: required.inputTokens!,
|
|
58
|
+
outputTokens: required.outputTokens!,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
for (const key of OPTIONAL_USAGE_KEYS) {
|
|
62
|
+
const value = source[key];
|
|
63
|
+
// ACP types these as `number | null | undefined`; both nullish forms mean "not reported".
|
|
64
|
+
if (value === null || value === undefined) continue;
|
|
65
|
+
if (!isTokenCount(value)) {
|
|
66
|
+
return { ok: false, reason: `usage.${key} is ${describe(value)}, not a token count` };
|
|
67
|
+
}
|
|
68
|
+
usage[key] = value;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return { ok: true, usage: Object.freeze(usage) };
|
|
72
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { AggregatedRecord } from "../activity.ts";
|
|
2
|
+
import type { ActivityEvent, ToolActivity } from "../types.ts";
|
|
3
|
+
import type { JsonObject, JsonValue } from "./checkpoint.ts";
|
|
4
|
+
import type { NormalizedPersistenceEvent } from "./projection.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Classify an already-folded live activity record into persistence security buckets.
|
|
8
|
+
* This function deliberately does not serialize or hash values: capture projection gets
|
|
9
|
+
* to discard a bucket before the writer ever examines its potentially sensitive content.
|
|
10
|
+
*/
|
|
11
|
+
export function persistenceEventFromActivity(
|
|
12
|
+
record: AggregatedRecord,
|
|
13
|
+
operationId: string,
|
|
14
|
+
): NormalizedPersistenceEvent {
|
|
15
|
+
if (record.event.kind === "thinking") {
|
|
16
|
+
return {
|
|
17
|
+
kind: "reasoning",
|
|
18
|
+
reasoningId: record.recordId,
|
|
19
|
+
reasoningRevision: record.seq,
|
|
20
|
+
operationId,
|
|
21
|
+
text: record.event.text,
|
|
22
|
+
status: record.reason === "settled" || record.reason === "flushed" ? "completed" : "in_progress",
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (record.event.kind === "tool") {
|
|
27
|
+
return {
|
|
28
|
+
kind: "activity",
|
|
29
|
+
activity: toolProjection(record, record.event, operationId),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
kind: "activity",
|
|
35
|
+
activity: {
|
|
36
|
+
activityId: record.recordId,
|
|
37
|
+
activityRevision: record.seq,
|
|
38
|
+
operationId,
|
|
39
|
+
reason: record.reason,
|
|
40
|
+
kind: record.event.kind,
|
|
41
|
+
content: { event: record.event as unknown as JsonValue },
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function toolProjection(
|
|
47
|
+
record: AggregatedRecord,
|
|
48
|
+
event: ToolActivity,
|
|
49
|
+
operationId: string,
|
|
50
|
+
) {
|
|
51
|
+
const content: Record<string, JsonValue> = {
|
|
52
|
+
toolKind: event.toolKind,
|
|
53
|
+
...(event.title === undefined ? {} : { title: event.title }),
|
|
54
|
+
...(event.rawOutput === undefined ? {} : { rawOutput: event.rawOutput as JsonValue }),
|
|
55
|
+
...(event.content === undefined ? {} : { content: event.content as unknown as JsonValue }),
|
|
56
|
+
...(event.locations === undefined ? {} : { locations: event.locations as unknown as JsonValue }),
|
|
57
|
+
};
|
|
58
|
+
return {
|
|
59
|
+
activityId: record.recordId,
|
|
60
|
+
activityRevision: record.seq,
|
|
61
|
+
operationId,
|
|
62
|
+
reason: record.reason,
|
|
63
|
+
kind: "tool",
|
|
64
|
+
status: event.status,
|
|
65
|
+
metadata: { providerActivityId: event.toolCallId },
|
|
66
|
+
...(event.rawInput === undefined
|
|
67
|
+
? {}
|
|
68
|
+
: { input: { value: event.rawInput as JsonValue } as JsonObject }),
|
|
69
|
+
content: content as JsonObject,
|
|
70
|
+
};
|
|
71
|
+
}
|