@trazum/core 1.65.0 → 1.67.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.
Files changed (50) hide show
  1. package/dist/config-schema.d.ts +32 -1
  2. package/dist/config-schema.d.ts.map +1 -1
  3. package/dist/config-schema.js +55 -3
  4. package/dist/config-schema.js.map +1 -1
  5. package/dist/conform.d.ts +1 -1
  6. package/dist/conform.d.ts.map +1 -1
  7. package/dist/conform.js +13 -0
  8. package/dist/conform.js.map +1 -1
  9. package/dist/gateway.d.ts +32 -1
  10. package/dist/gateway.d.ts.map +1 -1
  11. package/dist/gateway.js +64 -3
  12. package/dist/gateway.js.map +1 -1
  13. package/dist/guard.d.ts +20 -0
  14. package/dist/guard.d.ts.map +1 -1
  15. package/dist/guard.js +41 -3
  16. package/dist/guard.js.map +1 -1
  17. package/dist/index.d.ts +8 -2
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +4 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/judgement.d.ts +159 -0
  22. package/dist/judgement.d.ts.map +1 -0
  23. package/dist/judgement.js +188 -0
  24. package/dist/judgement.js.map +1 -0
  25. package/dist/position-report.d.ts +107 -0
  26. package/dist/position-report.d.ts.map +1 -0
  27. package/dist/position-report.js +180 -0
  28. package/dist/position-report.js.map +1 -0
  29. package/dist/position.d.ts +74 -0
  30. package/dist/position.d.ts.map +1 -0
  31. package/dist/position.js +93 -0
  32. package/dist/position.js.map +1 -0
  33. package/dist/schemas.d.ts.map +1 -1
  34. package/dist/schemas.js +9 -0
  35. package/dist/schemas.js.map +1 -1
  36. package/dist/session-cost.d.ts +2 -0
  37. package/dist/session-cost.d.ts.map +1 -1
  38. package/dist/session-cost.js +1 -1
  39. package/dist/session-cost.js.map +1 -1
  40. package/package.json +1 -1
  41. package/src/config-schema.ts +89 -3
  42. package/src/conform.ts +12 -0
  43. package/src/gateway.ts +108 -4
  44. package/src/guard.ts +73 -3
  45. package/src/index.ts +24 -1
  46. package/src/judgement.ts +346 -0
  47. package/src/position-report.ts +275 -0
  48. package/src/position.ts +126 -0
  49. package/src/schemas.ts +9 -0
  50. package/src/session-cost.ts +1 -1
@@ -0,0 +1,275 @@
1
+ /**
2
+ * The month, ended on a measured position — the 1.67 arc's one answer.
3
+ *
4
+ * The product refuses to forecast, and that refusal stays. But "refuses to
5
+ * forecast" and "cannot say where the month stands" are different sentences:
6
+ * the measured burn, the days measured, and the arithmetic distance to each
7
+ * configured ceiling are all measurements — and before this module they were
8
+ * scattered across `profile`, `budgetPositions` and `watch` rather than
9
+ * answerable as one question.
10
+ *
11
+ * **One source, named.** Everything here is measured from a usage log — the
12
+ * record of what was called, priced record by record. The store's monthly
13
+ * standing (provider-billed buckets, the number `serve` and `store` report)
14
+ * is a different measurement of a different thing, and folding the two into
15
+ * one figure would be the two-doors defect with extra steps. The document
16
+ * says `source: "usage-log"` so no reader has to guess which this is.
17
+ *
18
+ * **The distance is division, labelled as division.** "At this measured
19
+ * rate, the limit is N days away" is `remaining ÷ (measured ÷ days
20
+ * measured)` — arithmetic on the past, stated with its own denominators. It
21
+ * is absent, not zeroed, when the rate stands on fewer measured days than
22
+ * `MIN_SCALE_DAYS`, the same floor every scaled figure in this product
23
+ * respects; absent when nothing was measured; and absent on an `over`,
24
+ * because the distance to a place you have already passed is not a number
25
+ * this tool prints. There is no field naming a date, here or anywhere.
26
+ */
27
+
28
+ import { monthOf } from './budget.js';
29
+ import type { BudgetPeriod } from './budget.js';
30
+ import { MIN_SCALE_DAYS } from './measured-profile.js';
31
+ import { costOf } from './session-cost.js';
32
+ import type { UsageRecord } from './usage.js';
33
+ import type { PricingCatalogue } from './pricing.js';
34
+ import type { LimitsConfig, SpendConfig } from './config-schema.js';
35
+
36
+ const DAY_MS = 24 * 60 * 60 * 1000;
37
+
38
+ /** What a position is measured against, and over which window. */
39
+ export type PositionScope = 'month' | 'day' | 'label';
40
+
41
+ export interface PositionDistance {
42
+ /** `remainingUsd ÷ usdPerDay`. Division on the past, not a prediction. */
43
+ daysAway: number;
44
+ /** The measured rate: month-to-date spend over the days that measured it. */
45
+ usdPerDay: number;
46
+ /** The denominator of the rate — how many measured days stand behind it. */
47
+ overDays: number;
48
+ /** Always `division`: what this number is, stated in the number. */
49
+ arithmetic: 'division';
50
+ }
51
+
52
+ export interface PositionStanding {
53
+ scope: PositionScope;
54
+ /** Which label, when the scope is `label`. Null otherwise. */
55
+ label: string | null;
56
+ limitUsd: number;
57
+ /** Priced from the log's own records. Never an estimate. */
58
+ measuredUsd: number;
59
+ remainingUsd: number;
60
+ /** The window the measured figure covers. */
61
+ window: { fromMs: number; toMs: number };
62
+ /** Distinct UTC days inside the window carrying any measurement. */
63
+ daysMeasured: number;
64
+ /** Days of the window already elapsed when this was computed. */
65
+ daysElapsed: number;
66
+ verdict: 'within' | 'over' | 'cannot-tell';
67
+ /**
68
+ * Present only when it means something: a `within` verdict standing on at
69
+ * least `MIN_SCALE_DAYS` measured days and a non-zero rate. Null is "this
70
+ * arithmetic would mislead", never "we forgot".
71
+ */
72
+ distance: PositionDistance | null;
73
+ }
74
+
75
+ /** A configured ceiling this log cannot measure, with the reason stated. */
76
+ export interface UnmeasuredPosition {
77
+ scope: PositionScope;
78
+ label: string | null;
79
+ limitUsd: number;
80
+ why: 'no-clock' | 'no-labels' | 'nothing-recorded' | 'label-unseen';
81
+ }
82
+
83
+ export interface PositionDocument {
84
+ schemaVersion: 1;
85
+ /** Where every figure below was measured from. */
86
+ source: 'usage-log';
87
+ month: BudgetPeriod;
88
+ positions: PositionStanding[];
89
+ /** Configured ceilings the log cannot answer for, each with the reason. */
90
+ unmeasured: UnmeasuredPosition[];
91
+ /**
92
+ * What this document deliberately does not answer, stated rather than
93
+ * implied. The per-session ceiling is judged per call at the doors — a
94
+ * session is not a calendar scope, and a "session position for the month"
95
+ * would be an average wearing a limit's name.
96
+ */
97
+ cannotSay: string[];
98
+ /** Records whose model the catalogue cannot price — money nobody can see. */
99
+ unpricedRecords: number;
100
+ }
101
+
102
+ const daysIn = (stamps: Iterable<number>): number => {
103
+ const days = new Set<string>();
104
+ for (const ms of stamps) days.add(new Date(ms).toISOString().slice(0, 10));
105
+ return days.size;
106
+ };
107
+
108
+ /**
109
+ * The position, measured from one parsed usage log.
110
+ *
111
+ * Pure over its inputs, like `judgeLimits` and for the same reason: the
112
+ * same function answers at the CLI, in the HTML door and over MCP, so the
113
+ * surfaces cannot disagree about where the month stands.
114
+ */
115
+ export function positionReport(
116
+ records: readonly UsageRecord[],
117
+ config: { spend?: SpendConfig; limits?: LimitsConfig },
118
+ options: { catalogue: PricingCatalogue; on?: Date },
119
+ ): PositionDocument {
120
+ const { catalogue, on = new Date() } = options;
121
+ const month = monthOf(on);
122
+ const dayFromMs = Math.floor(on.getTime() / DAY_MS) * DAY_MS;
123
+ const dayWindow = { fromMs: dayFromMs, toMs: dayFromMs + DAY_MS };
124
+ const monthWindow = { fromMs: month.fromMs, toMs: month.toMs };
125
+ const elapsedDays = Math.max(
126
+ 1,
127
+ Math.min(month.days, Math.ceil((on.getTime() - month.fromMs) / DAY_MS)),
128
+ );
129
+
130
+ let unpricedRecords = 0;
131
+ let clocksSeen = false;
132
+ let labelsSeen = false;
133
+ let monthUsd = 0;
134
+ let dayUsd = 0;
135
+ const monthDays = new Set<number>();
136
+ const labelUsd = new Map<string, number>();
137
+ const labelDays = new Map<string, Set<number>>();
138
+
139
+ for (const record of records) {
140
+ if (record.ts !== null) clocksSeen = true;
141
+ if (record.label !== null) labelsSeen = true;
142
+ const usd = costOf(record, catalogue, on);
143
+ if (usd === null) {
144
+ unpricedRecords += 1;
145
+ continue;
146
+ }
147
+ if (record.ts === null) continue; // a clockless record belongs to no window
148
+ const day = Math.floor(record.ts / DAY_MS) * DAY_MS;
149
+ if (record.ts >= month.fromMs && record.ts < month.toMs) {
150
+ monthUsd += usd;
151
+ monthDays.add(day);
152
+ if (record.label !== null) {
153
+ labelUsd.set(record.label, (labelUsd.get(record.label) ?? 0) + usd);
154
+ if (!labelDays.has(record.label)) labelDays.set(record.label, new Set());
155
+ labelDays.get(record.label)!.add(day);
156
+ }
157
+ }
158
+ if (record.ts >= dayWindow.fromMs && record.ts < dayWindow.toMs) dayUsd += usd;
159
+ }
160
+
161
+ const positions: PositionStanding[] = [];
162
+ const unmeasured: UnmeasuredPosition[] = [];
163
+
164
+ const standing = (
165
+ scope: PositionScope,
166
+ label: string | null,
167
+ limitUsd: number,
168
+ measuredUsd: number,
169
+ window: { fromMs: number; toMs: number },
170
+ daysMeasured: number,
171
+ daysElapsed: number,
172
+ measured: boolean,
173
+ ): PositionStanding => {
174
+ const verdict = !measured ? 'cannot-tell' : measuredUsd > limitUsd ? 'over' : 'within';
175
+ const usdPerDay = daysMeasured > 0 ? measuredUsd / daysMeasured : 0;
176
+ const distance: PositionDistance | null =
177
+ verdict === 'within' && daysMeasured >= MIN_SCALE_DAYS && usdPerDay > 0
178
+ ? {
179
+ daysAway: (limitUsd - measuredUsd) / usdPerDay,
180
+ usdPerDay,
181
+ overDays: daysMeasured,
182
+ arithmetic: 'division',
183
+ }
184
+ : null;
185
+ return {
186
+ scope,
187
+ label,
188
+ limitUsd,
189
+ measuredUsd,
190
+ remainingUsd: limitUsd - measuredUsd,
191
+ window,
192
+ daysMeasured,
193
+ daysElapsed,
194
+ verdict,
195
+ distance,
196
+ };
197
+ };
198
+
199
+ const monthly = config.spend?.monthlyUsd;
200
+ if (monthly !== undefined) {
201
+ if (!clocksSeen) {
202
+ unmeasured.push({ scope: 'month', label: null, limitUsd: monthly, why: records.length === 0 ? 'nothing-recorded' : 'no-clock' });
203
+ } else {
204
+ /**
205
+ * A month with zero measured days is a stale log, not a quiet month:
206
+ * `budgetPositions` has held that line since 1.49 ("coverage none is
207
+ * cannot-tell"), and this module agreeing with it is the point of the
208
+ * arc. Contrast the day scope below, deliberately.
209
+ */
210
+ positions.push(
211
+ standing('month', null, monthly, monthUsd, monthWindow, monthDays.size, elapsedDays, monthDays.size > 0),
212
+ );
213
+ }
214
+ }
215
+
216
+ const day = config.limits?.dayUsd;
217
+ if (day !== undefined) {
218
+ if (!clocksSeen) {
219
+ unmeasured.push({ scope: 'day', label: null, limitUsd: day, why: records.length === 0 ? 'nothing-recorded' : 'no-clock' });
220
+ } else {
221
+ /**
222
+ * A day with no records inside a log that records clocks is a quiet
223
+ * day, measured at $0 — the same reading `positionAt` gives the doors,
224
+ * because a position page and an enforcement door disagreeing about
225
+ * today's spend is the exact defect the 1.66 arc closed. And one day
226
+ * is one day: the distance arithmetic needs a multi-day rate, so a
227
+ * day position never carries a `distance` — always under the floor.
228
+ */
229
+ positions.push(standing('day', null, day, dayUsd, dayWindow, monthDays.has(dayFromMs) ? 1 : 0, 1, true));
230
+ }
231
+ }
232
+
233
+ for (const [label, limitUsd] of Object.entries(config.limits?.byLabel ?? {})) {
234
+ if (!clocksSeen || !labelsSeen) {
235
+ unmeasured.push({
236
+ scope: 'label',
237
+ label,
238
+ limitUsd,
239
+ why: records.length === 0 ? 'nothing-recorded' : !clocksSeen ? 'no-clock' : 'no-labels',
240
+ });
241
+ } else if (!labelUsd.has(label)) {
242
+ // The log records labels and has never seen this one this month. That
243
+ // is a measured empty history — but a position of $0 with no days
244
+ // behind it would print the healthiest possible line for a label that
245
+ // may simply have been renamed, so it is named instead.
246
+ unmeasured.push({ scope: 'label', label, limitUsd, why: 'label-unseen' });
247
+ } else {
248
+ positions.push(
249
+ standing('label', label, limitUsd, labelUsd.get(label)!, monthWindow, daysIn(labelDays.get(label)!), elapsedDays, true),
250
+ );
251
+ }
252
+ }
253
+
254
+ const cannotSay: string[] = [];
255
+ if (config.limits?.sessionUsd !== undefined) {
256
+ cannotSay.push(
257
+ 'limits.sessionUsd is judged per call at the doors. A session is not a calendar scope, and a "session position for the month" would be an average wearing a limit\'s name.',
258
+ );
259
+ }
260
+ if (monthly === undefined && config.limits?.dayUsd === undefined && Object.keys(config.limits?.byLabel ?? {}).length === 0) {
261
+ cannotSay.push(
262
+ 'No monthly budget and no limits are configured, so there is no ceiling to state a position against. spend.monthlyUsd and the limits block are where ceilings live.',
263
+ );
264
+ }
265
+
266
+ return {
267
+ schemaVersion: 1,
268
+ source: 'usage-log',
269
+ month,
270
+ positions,
271
+ unmeasured,
272
+ cannotSay,
273
+ unpricedRecords,
274
+ };
275
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The measured side of the limits policy: what a usage log says each scope
3
+ * has already spent.
4
+ *
5
+ * `judgeLimits` judges; this measures. The split is the product's oldest
6
+ * rule — the judging function must be pure and instant, so whatever reads
7
+ * and prices records happens once, here, and the doors keep the result.
8
+ *
9
+ * **Absence is `null`, never zero.** A log with no clock cannot say what
10
+ * today has cost; a log that records no sessions cannot say what a session
11
+ * has spent. Both come back `null`, and `judgeLimits` turns a `null` into
12
+ * `cannot-tell` rather than an approval. The one deliberate asymmetry: a log
13
+ * that *does* record sessions and has never seen this one answers `0` — the
14
+ * history of a conversation that has not started is complete and empty,
15
+ * which is a measurement, not an absence.
16
+ *
17
+ * **Session keys never leave this module.** The index groups by them — that
18
+ * is the whole job — but the map lives in door memory, `positionAt` returns
19
+ * only dollar figures, and nothing here is serialised. The guarantee the
20
+ * usage module states (a session key is somebody's conversation and is never
21
+ * printed) holds through this door too.
22
+ */
23
+
24
+ import { costOf } from './session-cost.js';
25
+ import type { UsageRecord } from './usage.js';
26
+ import type { PricingCatalogue } from './pricing.js';
27
+ import type { MeasuredPosition } from './judgement.js';
28
+
29
+ const DAY_MS = 24 * 60 * 60 * 1000;
30
+
31
+ /**
32
+ * Everything a door needs to answer `positionAt` in constant time, built
33
+ * once from the log it was pointed at.
34
+ */
35
+ export interface MeasuredIndex {
36
+ /** Spend inside the current UTC day. Null when no record carries a clock. */
37
+ dayUsd: number | null;
38
+ /** The UTC day the figure covers. Null exactly when `dayUsd` is. */
39
+ dayWindow: { fromMs: number; toMs: number } | null;
40
+ /** Whether any record carried a label / a session at all. */
41
+ labelsSeen: boolean;
42
+ sessionsSeen: boolean;
43
+ /** Priced spend per label. Keys are labels, which do print. */
44
+ labels: ReadonlyMap<string, number>;
45
+ /** Priced spend per session. Keys are session identifiers — never printed. */
46
+ sessions: ReadonlyMap<string, number>;
47
+ /** Whether the log held any records at all. */
48
+ any: boolean;
49
+ /** Records whose model the catalogue cannot price — money nobody can see. */
50
+ unpriced: number;
51
+ }
52
+
53
+ /**
54
+ * Prices and groups a parsed usage log, once.
55
+ *
56
+ * An unpriced record contributes nothing to any figure and is **counted**
57
+ * instead of dropped silently: a door that reports "measured $3" over a log
58
+ * with a thousand unpriced records is wrong by an amount nobody can see, in
59
+ * the flattering direction, and `unpriced` is how the door says so.
60
+ */
61
+ export function indexUsage(
62
+ records: readonly UsageRecord[],
63
+ options: { catalogue: PricingCatalogue; on?: Date },
64
+ ): MeasuredIndex {
65
+ const { catalogue, on = new Date() } = options;
66
+ const dayFromMs = Math.floor(on.getTime() / DAY_MS) * DAY_MS;
67
+ const dayToMs = dayFromMs + DAY_MS;
68
+
69
+ const labels = new Map<string, number>();
70
+ const sessions = new Map<string, number>();
71
+ let labelsSeen = false;
72
+ let sessionsSeen = false;
73
+ let clocksSeen = false;
74
+ let dayUsd = 0;
75
+ let unpriced = 0;
76
+
77
+ for (const record of records) {
78
+ if (record.label !== null) labelsSeen = true;
79
+ if (record.session !== null) sessionsSeen = true;
80
+ if (record.ts !== null) clocksSeen = true;
81
+
82
+ const usd = costOf(record, catalogue, on);
83
+ if (usd === null) {
84
+ unpriced += 1;
85
+ continue;
86
+ }
87
+ if (record.label !== null) labels.set(record.label, (labels.get(record.label) ?? 0) + usd);
88
+ if (record.session !== null) sessions.set(record.session, (sessions.get(record.session) ?? 0) + usd);
89
+ if (record.ts !== null && record.ts >= dayFromMs && record.ts < dayToMs) dayUsd += usd;
90
+ }
91
+
92
+ return {
93
+ dayUsd: clocksSeen ? dayUsd : null,
94
+ dayWindow: clocksSeen ? { fromMs: dayFromMs, toMs: dayToMs } : null,
95
+ labelsSeen,
96
+ sessionsSeen,
97
+ labels,
98
+ sessions,
99
+ any: records.length > 0,
100
+ unpriced,
101
+ };
102
+ }
103
+
104
+ /**
105
+ * The measured position for one proposed call, from an index built once.
106
+ *
107
+ * A scope the log cannot see is `null`; a scope it can see and has nothing
108
+ * recorded for is `0`. The difference is the difference between "unknown"
109
+ * and "a conversation that has not started yet", and collapsing them is how
110
+ * a dead log approves a live spend.
111
+ */
112
+ export function positionAt(
113
+ index: MeasuredIndex,
114
+ call: { label?: string; session?: string },
115
+ ): MeasuredPosition {
116
+ if (!index.any) {
117
+ return { dayUsd: null, sessionUsd: null, labelUsd: null };
118
+ }
119
+ return {
120
+ dayUsd: index.dayUsd,
121
+ dayWindow: index.dayWindow,
122
+ sessionUsd:
123
+ call.session !== undefined && index.sessionsSeen ? (index.sessions.get(call.session) ?? 0) : null,
124
+ labelUsd: call.label !== undefined && index.labelsSeen ? (index.labels.get(call.label) ?? 0) : null,
125
+ };
126
+ }
package/src/schemas.ts CHANGED
@@ -142,6 +142,15 @@ export const CONTRACT_SCHEMAS: Record<ContractName, Record<string, unknown>> = {
142
142
  missing: array,
143
143
  measured: objectOrNull,
144
144
  }),
145
+ position: doc('position', {
146
+ // The document's own signature: no other contract names its source.
147
+ source: { const: 'usage-log' },
148
+ month: object,
149
+ positions: array,
150
+ unmeasured: array,
151
+ cannotSay: array,
152
+ unpricedRecords: number,
153
+ }),
145
154
  };
146
155
 
147
156
  /** The schema for one named contract — the object `trazum schema` prints. */
@@ -72,7 +72,7 @@ export interface SessionCostTracker {
72
72
  }
73
73
 
74
74
  /** Every billed dollar of one call, at its own model's rates. */
75
- function costOf(record: UsageRecord, catalogue: PricingCatalogue, on: Date): number | null {
75
+ export function costOf(record: UsageRecord, catalogue: PricingCatalogue, on: Date): number | null {
76
76
  const model = catalogue.byId.get(record.model);
77
77
  if (!model) return null;
78
78
  const { inputPerMTok, outputPerMTok } = effectivePricing(model, on);