@zonastery/bursar 0.0.1

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 (70) hide show
  1. package/README.md +375 -0
  2. package/dist/allowance.d.ts +48 -0
  3. package/dist/allowance.d.ts.map +1 -0
  4. package/dist/allowance.js +140 -0
  5. package/dist/allowance.js.map +1 -0
  6. package/dist/breakdown.d.ts +27 -0
  7. package/dist/breakdown.d.ts.map +1 -0
  8. package/dist/breakdown.js +27 -0
  9. package/dist/breakdown.js.map +1 -0
  10. package/dist/config.d.ts +23 -0
  11. package/dist/config.d.ts.map +1 -0
  12. package/dist/config.js +278 -0
  13. package/dist/config.js.map +1 -0
  14. package/dist/engine.d.ts +44 -0
  15. package/dist/engine.d.ts.map +1 -0
  16. package/dist/engine.js +172 -0
  17. package/dist/engine.js.map +1 -0
  18. package/dist/errors.d.ts +55 -0
  19. package/dist/errors.d.ts.map +1 -0
  20. package/dist/errors.js +55 -0
  21. package/dist/errors.js.map +1 -0
  22. package/dist/expr.d.ts +65 -0
  23. package/dist/expr.d.ts.map +1 -0
  24. package/dist/expr.js +681 -0
  25. package/dist/expr.js.map +1 -0
  26. package/dist/index.d.ts +20 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +14 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/load-pricing-file.d.ts +12 -0
  31. package/dist/load-pricing-file.d.ts.map +1 -0
  32. package/dist/load-pricing-file.js +45 -0
  33. package/dist/load-pricing-file.js.map +1 -0
  34. package/dist/manager.d.ts +421 -0
  35. package/dist/manager.d.ts.map +1 -0
  36. package/dist/manager.js +1112 -0
  37. package/dist/manager.js.map +1 -0
  38. package/dist/metrics.d.ts +19 -0
  39. package/dist/metrics.d.ts.map +1 -0
  40. package/dist/metrics.js +2 -0
  41. package/dist/metrics.js.map +1 -0
  42. package/dist/node.d.ts +15 -0
  43. package/dist/node.d.ts.map +1 -0
  44. package/dist/node.js +15 -0
  45. package/dist/node.js.map +1 -0
  46. package/dist/stores/credit-store.d.ts +171 -0
  47. package/dist/stores/credit-store.d.ts.map +1 -0
  48. package/dist/stores/credit-store.js +52 -0
  49. package/dist/stores/credit-store.js.map +1 -0
  50. package/dist/stores/events.d.ts +63 -0
  51. package/dist/stores/events.d.ts.map +1 -0
  52. package/dist/stores/events.js +68 -0
  53. package/dist/stores/events.js.map +1 -0
  54. package/dist/stores/memory-store.d.ts +178 -0
  55. package/dist/stores/memory-store.d.ts.map +1 -0
  56. package/dist/stores/memory-store.js +1833 -0
  57. package/dist/stores/memory-store.js.map +1 -0
  58. package/dist/stores/postgres-store.d.ts +95 -0
  59. package/dist/stores/postgres-store.d.ts.map +1 -0
  60. package/dist/stores/postgres-store.js +872 -0
  61. package/dist/stores/postgres-store.js.map +1 -0
  62. package/dist/stores/supabase-store.d.ts +76 -0
  63. package/dist/stores/supabase-store.d.ts.map +1 -0
  64. package/dist/stores/supabase-store.js +865 -0
  65. package/dist/stores/supabase-store.js.map +1 -0
  66. package/dist/types.d.ts +462 -0
  67. package/dist/types.d.ts.map +1 -0
  68. package/dist/types.js +2 -0
  69. package/dist/types.js.map +1 -0
  70. package/package.json +82 -0
package/README.md ADDED
@@ -0,0 +1,375 @@
1
+ # @zonastery/bursar
2
+
3
+ [![CI](https://github.com/Zonastery/bursar/actions/workflows/ci.yml/badge.svg)](https://github.com/Zonastery/bursar/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/@zonastery/bursar)](https://www.npmjs.com/package/@zonastery/bursar)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/Zonastery/bursar/blob/main/LICENSE)
6
+
7
+ Add usage-based credits to your AI SaaS in minutes — not weeks.
8
+
9
+ bursar is a drop-in credit calculation engine. Define pricing as math expressions
10
+ (per-model, per-tool, search/RAG, cache, fixed jobs), connect a database, and
11
+ start deducting credits. Pricing lives in your DB — update it live without redeploys.
12
+
13
+ ```typescript
14
+ import { CreditManager } from "@zonastery/bursar";
15
+ import { MemoryStore } from "@zonastery/bursar/node"; // Node-only (uses `crypto`)
16
+
17
+ const store = new MemoryStore();
18
+ const manager = new CreditManager(store);
19
+
20
+ await manager.publishPricingFromDict({
21
+ version: 1,
22
+ models: { "_default": "input_tokens * (0.01 / 1000) + output_tokens * (0.03 / 1000)" },
23
+ plans: {
24
+ free: { id: "free", name: "Free Tier", freeAllowance: 50000 },
25
+ pro: { id: "pro", name: "Pro Plan", freeAllowance: 500000 },
26
+ },
27
+ });
28
+
29
+ await manager.addCredits("user_abc", 1000); // number or decimal.js Decimal
30
+ ```
31
+
32
+ Works in Node.js 18+, Bun, and Deno. ESM-only.
33
+
34
+ ## Features
35
+
36
+ - **Safe expression engine** — Recursive descent parser with strict allowlist. `min`, `max`, `if`, `tier`, `clamp`, `ceil`, `floor`, `round`, `percentile`. No eval/Function().
37
+ - **Plan-based pricing** — Subscription plans with free monthly allowances and rate overrides. Allowance consumed before balance.
38
+ - **Refunds** — Full and partial credit reversals with duplicate detection.
39
+ - **Credit expiry / TTL** — Time-bound credits with `expiresAt` on `addCredits`. Sweep with dry-run mode.
40
+ - **Team / shared balances** — Separate team credit pools with per-member spend caps.
41
+ - **Spend caps** — Per-user daily/monthly limits with `deny`, `warn`, `notify` actions. Per-model caps supported.
42
+ - **Usage analytics** — `spendByUser`, `spendByModel`, `topUsers`, `dailySpend`, `aggregateStats` across time windows.
43
+ - **Event hooks** — Typed pub/sub for `credits.deducted`, `credits.added`, `credits.refunded`, `credits.expired`, `credits.cap_reached`, `credits.cap_warning`, `credits.low_balance`.
44
+ - **Database-backed pricing** — Live updates without redeploys. Dict loading for testing.
45
+ - **Multi-dimensional** — Per-model (with `_default` fallback), per-tool overrides, search/RAG, cache discounts, fixed-cost jobs.
46
+ - **Pluggable storage** — One atomic, idempotency-keyed `deductWithAllowance` per `CreditStore`: Supabase (native fetch, zero deps), PostgreSQL (`pg`), or in-memory. The two-phase reserve-then-deduct API is also available.
47
+ - **Safe defaults** — `minBalance` floor, idempotent deductions, concurrent-deduction protection.
48
+ - **Exact decimal money** — All credit amounts are [`decimal.js`](https://github.com/MikeMcl/decimal.js) `Decimal` values, quantized to 4 dp (`ROUND_HALF_UP`). No binary-float rounding or truncation of sub-credit costs.
49
+ - **Auditable** — Structured `CostBreakdown` with per-dimension costs.
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ npm install @zonastery/bursar
55
+
56
+ # PostgreSQL store (optional)
57
+ npm install pg
58
+
59
+ # YAML pricing loading (optional)
60
+ npm install js-yaml
61
+ ```
62
+
63
+ Requires Node.js 18+ (native `fetch` for Supabase store).
64
+
65
+ ## Full docs
66
+
67
+ **[zonastery.github.io/bursar](https://zonastery.github.io/bursar/)** — JS API reference, expressions, configuration, examples.
68
+
69
+ ## Quick Start
70
+
71
+ ### Calculation only (no database)
72
+
73
+ ```typescript
74
+ import { PricingEngine } from "@zonastery/bursar";
75
+
76
+ const engine = PricingEngine.fromDict({
77
+ version: 1,
78
+ models: {
79
+ "gpt-4": "input_tokens * (0.01 / 1000) + output_tokens * (0.03 / 1000)",
80
+ "_default": "input_tokens * (0.001 / 1000) + output_tokens * (0.003 / 1000)",
81
+ },
82
+ });
83
+
84
+ const cost = engine.calculate({
85
+ model: "gpt-4",
86
+ inputTokens: 500,
87
+ outputTokens: 200,
88
+ });
89
+ // cost.total is a decimal.js `Decimal` (quantized to 4 dp, ROUND_HALF_UP)
90
+ console.log(`Total: ${cost.total.toString()}`); // 0.0110
91
+ ```
92
+
93
+ ### Full credit lifecycle (in-memory)
94
+
95
+ ```typescript
96
+ import { CreditManager } from "@zonastery/bursar";
97
+ import { MemoryStore } from "@zonastery/bursar/node"; // Node-only (uses `crypto`)
98
+ import Decimal from "decimal.js";
99
+
100
+ const store = new MemoryStore();
101
+ const manager = new CreditManager(store);
102
+
103
+ // publishPricingFromDict is async — it syncs the config to the store.
104
+ await manager.publishPricingFromDict({
105
+ version: 1,
106
+ models: { "_default": "input_tokens * (0.01 / 1000) + output_tokens * (0.03 / 1000)" },
107
+ plans: {
108
+ free: { id: "free", name: "Free Tier", freeAllowance: 50000 },
109
+ pro: { id: "pro", name: "Pro Plan", freeAllowance: 500000 },
110
+ },
111
+ });
112
+
113
+ // Money amounts accept a plain `number` or a `decimal.js` Decimal.
114
+ await manager.addCredits("user_abc", new Decimal(1000));
115
+ const result = await manager.deduct(
116
+ "user_abc",
117
+ { model: "gpt-4", inputTokens: 500, outputTokens: 200 },
118
+ "idempotency-key-123",
119
+ );
120
+ console.log(`Charged: ${result.amount.toString()}`); // Decimal
121
+ console.log(`Remaining balance: ${(await manager.getBalance("user_abc")).balance.toString()}`);
122
+ ```
123
+
124
+ ### Production with Supabase
125
+
126
+ ```typescript
127
+ import { CreditManager } from "@zonastery/bursar";
128
+ import { HttpxSupabaseStore } from "@zonastery/bursar";
129
+
130
+ const store = new HttpxSupabaseStore(
131
+ "https://your-project.supabase.co",
132
+ "service_role_key"
133
+ );
134
+ const manager = new CreditManager(store);
135
+ await manager.loadPricingFromStore();
136
+ await manager.addCredits("user_abc", 5000);
137
+ ```
138
+
139
+ ### Plan-based pricing
140
+
141
+ ```typescript
142
+ import { CreditManager } from "@zonastery/bursar";
143
+ import { MemoryStore } from "@zonastery/bursar/node"; // Node-only (uses `crypto`)
144
+
145
+ const store = new MemoryStore();
146
+ const manager = new CreditManager(store);
147
+
148
+ await manager.publishPricingFromDict({
149
+ version: 1,
150
+ models: { "_default": "input_tokens * 1" },
151
+ plans: {
152
+ free: { id: "free", name: "Free Tier", freeAllowance: 50000 },
153
+ },
154
+ });
155
+ await store.setUserPlan("user-1", "free");
156
+ await manager.addCredits("user-1", 10);
157
+
158
+ // First 50000 credits are free — no balance deduction
159
+ const result = await manager.deduct("user-1", { inputTokens: 5 });
160
+ console.log(result.amount.toString()); // "0" — covered by allowance
161
+ ```
162
+
163
+ ## Feature Examples
164
+
165
+ ### Refunds
166
+
167
+ ```typescript
168
+ const tx = await manager.deduct("user-1", { model: "gpt-4", inputTokens: 100 });
169
+ const refund = await manager.refundCredits(tx.transactionId); // full refund
170
+ const partial = await manager.refundCredits(tx.transactionId, 5); // partial
171
+ ```
172
+
173
+ ### Credit expiry
174
+
175
+ ```typescript
176
+ await manager.addCredits("user-1", 100, "purchase", null, new Date("2025-01-01"));
177
+ const result = await manager.sweepExpiredCredits(); // sweep
178
+ const report = await manager.sweepExpiredCredits(true); // preview only
179
+ ```
180
+
181
+ ### Team / shared balances
182
+
183
+ ```typescript
184
+ const team = await store.createTeam("Engineering", 5000);
185
+ await store.addTeamMember(team.teamId, "user-1", "admin", 1000);
186
+ const result = await manager.deductTeam(team.teamId, "user-1", { model: "gpt-4", inputTokens: 500 });
187
+ ```
188
+
189
+ ### Spend caps
190
+
191
+ ```typescript
192
+ store.setSpendCap({ userId: "user-1", type: "daily", limit: 100, action: "deny" });
193
+ ```
194
+
195
+ ### Financial safety (leases)
196
+
197
+ Because bursar charges *after* the AI call, the safe pattern is an atomic **lease** taken *before* the work: `reserve` a worst-case hold against `available = balance − Σ(active holds)`, do the work, then `settle` the **actual** cost (de-clamped) or `release` to cancel. `reserve` is the only admission gate. Two presets: `strict_prepaid` (default; floor ≥ 0, structurally zero debt) and `overdraft` (negative floor; bills full actual; for paid users with auto-reload).
198
+
199
+ ```typescript
200
+ import Decimal from "decimal.js";
201
+
202
+ const manager = new CreditManager(store, null, null, { policy: "strict_prepaid" }); // or { policy: "overdraft", overdraftFloor: new Decimal(-50) }
203
+ const lease = await manager.reserve("user-1", new Decimal(40)); // worst-case hold
204
+ const deduction = await manager.settle("user-1", lease.leaseId, new Decimal(11)); // actual cost; de-clamped
205
+ // on failure: await manager.release("user-1", lease.leaseId); // idempotent
206
+ ```
207
+
208
+ ### Usage analytics
209
+
210
+ ```typescript
211
+ const now = new Date();
212
+ const start = new Date(now.getTime() - 30 * 86400000);
213
+ await manager.spendByUser(start, now); // per-user totals
214
+ await manager.spendByModel(start, now); // per-model spend
215
+ await manager.topUsers(10, start, now); // top 10 users
216
+ await manager.dailySpend(start, now); // daily buckets
217
+ await manager.aggregateStats(start, now); // aggregate summary
218
+ ```
219
+
220
+ ### Events
221
+
222
+ ```typescript
223
+ import { CreditEventEmitter } from "@zonastery/bursar";
224
+ const emitter = new CreditEventEmitter();
225
+ const manager = new CreditManager(store, null, emitter);
226
+ emitter.on("credits.deducted", (e) => console.log(`User ${e.userId} spent credits`));
227
+ emitter.on("credits.low_balance", (e) => sendAlert(e.userId, e.data?.balance));
228
+ ```
229
+
230
+ ## Pricing Configuration
231
+
232
+ Basic example:
233
+
234
+ ```json
235
+ {
236
+ "version": 1,
237
+ "models": {
238
+ "gpt-4": "input_tokens * (0.01 / 1000) + output_tokens * (0.03 / 1000)",
239
+ "_default": "input_tokens * (0.001 / 1000) + output_tokens * (0.003 / 1000)"
240
+ },
241
+ "tools": { "_default": "tool_calls * 5 / 1000" },
242
+ "search": { "costs": "search_queries * 0.5 + search_results * 0.05" },
243
+ "cache": { "discount": "-cache_read_tokens * (0.001 / 1000)" },
244
+ "fixed": { "batch_train": 100 },
245
+ "minBalance": 5
246
+ }
247
+ ```
248
+
249
+ ### Expression syntax
250
+
251
+ | Feature | Example |
252
+ |---------|---------|
253
+ | Arithmetic | `+`, `-`, `*`, `/`, `//`, `%` |
254
+ | Comparisons | `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`, `not in` |
255
+ | Boolean | `and`, `or`, `not` |
256
+ | Ternary | `X if cond else Y` |
257
+ | Functions | `ceil`, `floor`, `round`, `min`, `max`, `if(cond,t,f)`, `tier(v,t1,r1,t2,r2,...)`, `clamp(x,lo,hi)`, `percentile(p,v1,v2,...)` |
258
+
259
+ > Exponentiation (`**`) is **not allowed** in pricing expressions — it is rejected
260
+ > at config-load time (`ExpressionError`) as a sandbox-safety measure. Division and
261
+ > modulo by zero, and any non-finite result, are rejected the same way.
262
+
263
+ ### Loading from file
264
+
265
+ `loadPricingFile` reads Node's filesystem, so it ships from the `@zonastery/bursar/node`
266
+ subpath (not the root entry point). YAML files require the optional `js-yaml` peer
267
+ dependency; if it is missing, an `ImportError` is thrown.
268
+
269
+ ```typescript
270
+ import { PricingEngine } from "@zonastery/bursar";
271
+ import { loadPricingFile } from "@zonastery/bursar/node";
272
+
273
+ const data = await loadPricingFile("./pricing.yaml");
274
+ const engine = PricingEngine.fromDict(data);
275
+ ```
276
+
277
+ ### Available metrics
278
+
279
+ | Variable | Source | Type |
280
+ |----------|--------|------|
281
+ | `input_tokens` | `metrics.inputTokens` | `number` |
282
+ | `output_tokens` | `metrics.outputTokens` | `number` |
283
+ | `cache_read_tokens` | `metrics.cacheReadTokens` | `number` |
284
+ | `cache_write_tokens` | `metrics.cacheWriteTokens` | `number` |
285
+ | `tool_calls` | `metrics.toolCalls.length` | `number` |
286
+ | `search_queries` | `metrics.searchQueries` | `number` |
287
+ | `search_results` | `metrics.searchResults` | `number` |
288
+ | `web_search_calls` | `metrics.webSearchCalls` | `number` |
289
+ | `code_exec_calls` | `metrics.codeExecCalls` | `number` |
290
+
291
+ ## Store adapters
292
+
293
+ | Store | Import | Deps | Use case |
294
+ |-------|--------|------|----------|
295
+ | `MemoryStore` | `@zonastery/bursar/node` | None (uses Node `crypto`) | Testing, development |
296
+ | `HttpxSupabaseStore` | `@zonastery/bursar` | Node 18+ (`fetch`) | Supabase production |
297
+ | `PostgresStore` | `@zonastery/bursar` | `pg` (optional peer) | Direct PostgreSQL |
298
+
299
+ `PostgresStore` requires the optional `pg` peer dependency (`npm install pg`); it
300
+ is dynamically imported and throws if missing.
301
+
302
+ ## API
303
+
304
+ ### `PricingEngine`
305
+
306
+ ```typescript
307
+ PricingEngine.fromDict(data): PricingEngine
308
+ engine.calculate(metrics: UsageMetrics): CostBreakdown // CostBreakdown.total is a Decimal
309
+ engine.calculateBatch(metrics: UsageMetrics[]): CostBreakdown[]
310
+ engine.resolveModel(modelVersion: string): string | null
311
+ engine.hasModel(modelName: string): boolean
312
+ engine.getFixedCost(jobName: string): Decimal | null
313
+ engine.pricingSchema(): PricingConfigData
314
+ engine.knownVariables: Set<string>
315
+ engine.minBalance: number
316
+ ```
317
+
318
+ ### `CreditManager`
319
+
320
+ All money parameters (`amount`, `minBalance`) accept a plain `number` or a
321
+ `decimal.js` `Decimal`. All money fields on returned results (`amount`,
322
+ `balance`, `balanceAfter`, `newBalance`, `allowanceConsumed`, …) are `Decimal`.
323
+
324
+ ```typescript
325
+ new CreditManager(store: CreditStore, engine?, emitter?, options?: CreditManagerOptions)
326
+
327
+ // Setup / pricing
328
+ manager.setup(): Promise<SetupResult>
329
+ manager.publishPricingFromDict(data): Promise<void>
330
+ manager.loadPricingFromStore(): Promise<void>
331
+ manager.publishPricing(config, label?): Promise<void>
332
+
333
+ // Balance ops
334
+ manager.getBalance(userId): Promise<BalanceResult>
335
+ manager.addCredits(userId, amount: Decimal | number, type?, metadata?, expiresAt?): Promise<AddCreditsResult>
336
+ manager.reserveCredits(userId, amount: Decimal | number, opType?, metadata?, minBalance?): Promise<ReserveResult>
337
+ manager.deduct(userId, metrics, idempotencyKey?, metadata?): Promise<DeductionResult>
338
+ manager.deductFixed(userId, jobName, idempotencyKey?, metadata?): Promise<DeductionResult> // throws ConfigError on unknown job
339
+
340
+ // Plans
341
+ manager.getUserPlan(userId): Promise<GetUserPlanResult>
342
+ manager.checkFeature(userId, feature): Promise<CheckFeatureResult>
343
+
344
+ // Refunds
345
+ manager.refundCredits(transactionId, amount?: Decimal | number, reason?, metadata?): Promise<RefundResult>
346
+
347
+ // Expiry
348
+ manager.sweepExpiredCredits(dryRun?): Promise<SweepResult>
349
+
350
+ // Teams
351
+ manager.deductTeam(teamId, userId, metrics, idempotencyKey?, metadata?): Promise<TeamDeductionResult>
352
+
353
+ // Analytics
354
+ manager.spendByUser(start, end): Promise<SpendByUserRow[]>
355
+ manager.spendByModel(start, end): Promise<SpendByModelRow[]>
356
+ manager.topUsers(limit, start, end): Promise<TopUserRow[]>
357
+ manager.dailySpend(start, end): Promise<DailySpendRow[]>
358
+ manager.aggregateStats(start, end): Promise<AggregateStats>
359
+ manager.listUserTransactions(userId, options?): Promise<PaginatedTransactions>
360
+ manager.listUsageEvents(userId, options?): Promise<PaginatedTransactions>
361
+
362
+ // Events
363
+ const emitter = new CreditEventEmitter();
364
+ emitter.on("credits.deducted", handler);
365
+ emitter.on("credits.low_balance", handler);
366
+ // ... credits.added, credits.refunded, credits.expired, credits.cap_reached,
367
+ // credits.cap_warning, credits.deduct_failed, credits.refund_failed
368
+
369
+ // Properties
370
+ manager.pricingEngine: PricingEngine | null
371
+ ```
372
+
373
+ ## License
374
+
375
+ MIT
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Configurable free-allowance reset window resolver (WS9a).
3
+ *
4
+ * Pure, UTC-only, DATE-granularity (time-of-day is discarded) window resolver.
5
+ * MUST exactly match the Python resolver: this is the cross-language parity
6
+ * baseline for `allowancePeriod` handling. All computation uses UTC methods
7
+ * exclusively (`getUTCFullYear`, `Date.UTC`, ...) — never local-timezone
8
+ * Date methods.
9
+ *
10
+ * `resolveCalendarWindow` is a separate, anchor-free resolver used by
11
+ * per-feature invocation-count limits (`PlanDefinition.featureLimits`). It
12
+ * supports `"daily"`/`"weekly"`/`"monthly"`/`"yearly"` cadences, all
13
+ * calendar-aligned (every user resets at the same instant) rather than
14
+ * anchored to a per-user timestamp — MUST exactly match
15
+ * `bursar.allowance.resolve_calendar_window` in the Python SDK.
16
+ */
17
+ /** Supported free-allowance reset window modes. */
18
+ export type AllowancePeriod = "calendar_month" | "rolling_30d" | "anniversary";
19
+ /** Supported per-feature invocation-count limit cadences. */
20
+ export type FeatureLimitPeriod = "daily" | "weekly" | "monthly" | "yearly";
21
+ /**
22
+ * Resolve the free-allowance reset window containing `now` for the given
23
+ * `period` mode, anchored (where applicable) at `anchor` (typically the
24
+ * plan-assignment timestamp).
25
+ *
26
+ * `start`/`end` are UTC-midnight `Date`s at DATE granularity; `end` is
27
+ * EXCLUSIVE (the window is `[start, end)`).
28
+ */
29
+ export declare function resolveAllowanceWindow(now: Date, period: AllowancePeriod, anchor: Date | null): {
30
+ start: Date;
31
+ end: Date;
32
+ };
33
+ /**
34
+ * Resolve the calendar-aligned `[start, end)` window for a per-feature
35
+ * invocation-count limit cadence (`FeatureLimit.period`).
36
+ *
37
+ * Unlike {@link resolveAllowanceWindow}, this resolver takes no anchor: every
38
+ * user resets at the same UTC instant. `start`/`end` are UTC-midnight `Date`s
39
+ * at DATE granularity; `end` is EXCLUSIVE (the window is `[start, end)`).
40
+ *
41
+ * MUST exactly match `bursar.allowance.resolve_calendar_window` in Python
42
+ * (same Monday-start ISO week, same year boundary).
43
+ */
44
+ export declare function resolveCalendarWindow(now: Date, period: FeatureLimitPeriod): {
45
+ start: Date;
46
+ end: Date;
47
+ };
48
+ //# sourceMappingURL=allowance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allowance.d.ts","sourceRoot":"","sources":["../src/allowance.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,mDAAmD;AACnD,MAAM,MAAM,eAAe,GAAG,gBAAgB,GAAG,aAAa,GAAG,aAAa,CAAC;AAE/E,6DAA6D;AAC7D,MAAM,MAAM,kBAAkB,GAAG,OAAO,GAAG,QAAQ,GAAG,SAAS,GAAG,QAAQ,CAAC;AA4E3E;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,GAAG,EAAE,IAAI,EACT,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,IAAI,GAAG,IAAI,GAClB;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,GAAG,EAAE,IAAI,CAAA;CAAE,CAW5B;AAyBD;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,IAAI,EACT,MAAM,EAAE,kBAAkB,GACzB;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,GAAG,EAAE,IAAI,CAAA;CAAE,CAa5B"}
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Configurable free-allowance reset window resolver (WS9a).
3
+ *
4
+ * Pure, UTC-only, DATE-granularity (time-of-day is discarded) window resolver.
5
+ * MUST exactly match the Python resolver: this is the cross-language parity
6
+ * baseline for `allowancePeriod` handling. All computation uses UTC methods
7
+ * exclusively (`getUTCFullYear`, `Date.UTC`, ...) — never local-timezone
8
+ * Date methods.
9
+ *
10
+ * `resolveCalendarWindow` is a separate, anchor-free resolver used by
11
+ * per-feature invocation-count limits (`PlanDefinition.featureLimits`). It
12
+ * supports `"daily"`/`"weekly"`/`"monthly"`/`"yearly"` cadences, all
13
+ * calendar-aligned (every user resets at the same instant) rather than
14
+ * anchored to a per-user timestamp — MUST exactly match
15
+ * `bursar.allowance.resolve_calendar_window` in the Python SDK.
16
+ */
17
+ const MS_PER_DAY = 86_400_000;
18
+ /** Truncate a `Date` to UTC midnight (DATE granularity, discards time-of-day). */
19
+ function utcMidnight(d) {
20
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
21
+ }
22
+ /** Number of days in the given UTC year/month (0-indexed month, like `Date.UTC`). */
23
+ function daysInUtcMonth(year, month) {
24
+ // Day 0 of "next month" is the last day of `month`.
25
+ return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
26
+ }
27
+ /**
28
+ * The `day`-th day of the UTC month `(year, month)`, clamped to that month's
29
+ * actual length (e.g. day 31 in a 28-day February clamps to the 28th).
30
+ */
31
+ function clampedDayInMonth(year, month, day) {
32
+ const lastDay = daysInUtcMonth(year, month);
33
+ return new Date(Date.UTC(year, month, Math.min(day, lastDay)));
34
+ }
35
+ /** First day of the UTC month containing `d`, at midnight UTC. */
36
+ function calendarMonthStart(d) {
37
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1));
38
+ }
39
+ function resolveCalendarMonth(now) {
40
+ const start = calendarMonthStart(now);
41
+ const end = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 1));
42
+ return { start, end };
43
+ }
44
+ function resolveRolling30d(now, anchor) {
45
+ if (anchor === null)
46
+ return resolveCalendarMonth(now);
47
+ const anchorMidnight = utcMidnight(anchor);
48
+ const nowMidnight = utcMidnight(now);
49
+ const elapsedDays = Math.floor((nowMidnight.getTime() - anchorMidnight.getTime()) / MS_PER_DAY);
50
+ const windowIndex = Math.floor(elapsedDays / 30);
51
+ const start = new Date(anchorMidnight.getTime() + windowIndex * 30 * MS_PER_DAY);
52
+ const end = new Date(start.getTime() + 30 * MS_PER_DAY);
53
+ return { start, end };
54
+ }
55
+ function resolveAnniversary(now, anchor) {
56
+ if (anchor === null)
57
+ return resolveCalendarMonth(now);
58
+ const anchorMidnight = utcMidnight(anchor);
59
+ const nowMidnight = utcMidnight(now);
60
+ const resetDay = anchorMidnight.getUTCDate();
61
+ // Candidate reset date in the same UTC year/month as `now`, clamped.
62
+ const candidate = clampedDayInMonth(nowMidnight.getUTCFullYear(), nowMidnight.getUTCMonth(), resetDay);
63
+ let start;
64
+ if (candidate.getTime() <= nowMidnight.getTime()) {
65
+ start = candidate;
66
+ }
67
+ else {
68
+ // The clamped reset date this month is still ahead of `now` — the current
69
+ // window started last month.
70
+ start = clampedDayInMonth(nowMidnight.getUTCFullYear(), nowMidnight.getUTCMonth() - 1, resetDay);
71
+ }
72
+ const end = clampedDayInMonth(start.getUTCFullYear(), start.getUTCMonth() + 1, resetDay);
73
+ return { start, end };
74
+ }
75
+ /**
76
+ * Resolve the free-allowance reset window containing `now` for the given
77
+ * `period` mode, anchored (where applicable) at `anchor` (typically the
78
+ * plan-assignment timestamp).
79
+ *
80
+ * `start`/`end` are UTC-midnight `Date`s at DATE granularity; `end` is
81
+ * EXCLUSIVE (the window is `[start, end)`).
82
+ */
83
+ export function resolveAllowanceWindow(now, period, anchor) {
84
+ switch (period) {
85
+ case "calendar_month":
86
+ return resolveCalendarMonth(now);
87
+ case "rolling_30d":
88
+ return resolveRolling30d(now, anchor);
89
+ case "anniversary":
90
+ return resolveAnniversary(now, anchor);
91
+ default:
92
+ throw new Error(`unrecognized allowance period: ${String(period)}`);
93
+ }
94
+ }
95
+ /** `[now, now + 1 day)` at UTC midnight. */
96
+ function dayWindow(now) {
97
+ const start = utcMidnight(now);
98
+ return { start, end: new Date(start.getTime() + MS_PER_DAY) };
99
+ }
100
+ /** Monday-start ISO week window: `[Monday, next Monday)`. */
101
+ function isoWeekWindow(now) {
102
+ const midnight = utcMidnight(now);
103
+ // getUTCDay(): 0=Sunday..6=Saturday. Days since the most recent Monday.
104
+ const dayOfWeek = midnight.getUTCDay();
105
+ const daysSinceMonday = (dayOfWeek + 6) % 7;
106
+ const start = new Date(midnight.getTime() - daysSinceMonday * MS_PER_DAY);
107
+ return { start, end: new Date(start.getTime() + 7 * MS_PER_DAY) };
108
+ }
109
+ /** `[Jan 1, next Jan 1)` of `now`'s UTC year. */
110
+ function yearWindow(now) {
111
+ const start = new Date(Date.UTC(now.getUTCFullYear(), 0, 1));
112
+ const end = new Date(Date.UTC(now.getUTCFullYear() + 1, 0, 1));
113
+ return { start, end };
114
+ }
115
+ /**
116
+ * Resolve the calendar-aligned `[start, end)` window for a per-feature
117
+ * invocation-count limit cadence (`FeatureLimit.period`).
118
+ *
119
+ * Unlike {@link resolveAllowanceWindow}, this resolver takes no anchor: every
120
+ * user resets at the same UTC instant. `start`/`end` are UTC-midnight `Date`s
121
+ * at DATE granularity; `end` is EXCLUSIVE (the window is `[start, end)`).
122
+ *
123
+ * MUST exactly match `bursar.allowance.resolve_calendar_window` in Python
124
+ * (same Monday-start ISO week, same year boundary).
125
+ */
126
+ export function resolveCalendarWindow(now, period) {
127
+ switch (period) {
128
+ case "daily":
129
+ return dayWindow(now);
130
+ case "weekly":
131
+ return isoWeekWindow(now);
132
+ case "monthly":
133
+ return resolveCalendarMonth(now);
134
+ case "yearly":
135
+ return yearWindow(now);
136
+ default:
137
+ throw new Error(`unrecognized feature-limit period: ${String(period)}`);
138
+ }
139
+ }
140
+ //# sourceMappingURL=allowance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allowance.js","sourceRoot":"","sources":["../src/all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AC;IAC5E,CAAC;AACH,CAAC"}
@@ -0,0 +1,27 @@
1
+ import Decimal from "decimal.js";
2
+ /**
3
+ * Granular credit cost report for a usage event.
4
+ *
5
+ * All money fields are `Decimal` (never binary `number`) and are quantized to
6
+ * 4dp ROUND_HALF_UP. `total` is the single source of truth: it is recomputed
7
+ * from the components (clamped at 0) and quantized — there is NO implicit
8
+ * integer truncation of the total (that was the revenue-leak bug).
9
+ */
10
+ export interface CostBreakdown {
11
+ modelCredits: Decimal;
12
+ toolCredits: Decimal;
13
+ searchCredits: Decimal;
14
+ cacheSavings: Decimal;
15
+ fixedCredits: Decimal;
16
+ total: Decimal;
17
+ breakdown: Record<string, unknown>;
18
+ }
19
+ export declare function makeCostBreakdown(partial?: {
20
+ modelCredits?: Decimal;
21
+ toolCredits?: Decimal;
22
+ searchCredits?: Decimal;
23
+ cacheSavings?: Decimal;
24
+ fixedCredits?: Decimal;
25
+ breakdown?: Record<string, unknown>;
26
+ }): CostBreakdown;
27
+ //# sourceMappingURL=breakdown.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"breakdown.d.ts","sourceRoot":"","sources":["../src/breakdown.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAGjC;;;;;;;GAOG;AACH,MAAM,WAAW,aAAa;IAC5B,YAAY,EAAE,OAAO,CAAC;IACtB,WAAW,EAAE,OAAO,CAAC;IACrB,aAAa,EAAE,OAAO,CAAC;IACvB,YAAY,EAAE,OAAO,CAAC;IACtB,YAAY,EAAE,OAAO,CAAC;IACtB,KAAK,EAAE,OAAO,CAAC;IACf,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,wBAAgB,iBAAiB,CAAC,OAAO,CAAC,EAAE;IAC1C,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACrC,GAAG,aAAa,CAyBhB"}
@@ -0,0 +1,27 @@
1
+ import Decimal from "decimal.js";
2
+ import { quantizeMoney } from "./expr.js";
3
+ export function makeCostBreakdown(partial) {
4
+ const modelCredits = quantizeMoney(partial?.modelCredits ?? new Decimal(0));
5
+ const toolCredits = quantizeMoney(partial?.toolCredits ?? new Decimal(0));
6
+ const searchCredits = quantizeMoney(partial?.searchCredits ?? new Decimal(0));
7
+ const cacheSavings = quantizeMoney(partial?.cacheSavings ?? new Decimal(0));
8
+ const fixedCredits = quantizeMoney(partial?.fixedCredits ?? new Decimal(0));
9
+ // Single source of truth for the total: sum of components, clamped at 0,
10
+ // quantized to 4dp HALF_UP.
11
+ const rawTotal = modelCredits
12
+ .plus(toolCredits)
13
+ .plus(searchCredits)
14
+ .plus(fixedCredits)
15
+ .plus(cacheSavings);
16
+ const total = quantizeMoney(Decimal.max(new Decimal(0), rawTotal));
17
+ return {
18
+ modelCredits,
19
+ toolCredits,
20
+ searchCredits,
21
+ cacheSavings,
22
+ fixedCredits,
23
+ total,
24
+ breakdown: partial?.breakdown ?? {},
25
+ };
26
+ }
27
+ //# sourceMappingURL=breakdown.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"breakdown.js","sourceRoot":"","sources":["../src/breakdown.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAoB1C,MAAM,UAAU,iBAAiB,CAAC,OAOjC;IACC,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,WAAW,GAAG,aAAa,CAAC,OAAO,EAAE,WAAW,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1E,MAAM,aAAa,GAAG,aAAa,CAAC,OAAO,EAAE,aAAa,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9E,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAE5E,yEAAyE;IACzE,4BAA4B;IAC5B,MAAM,QAAQ,GAAG,YAAY;SAC1B,IAAI,CAAC,WAAW,CAAC;SACjB,IAAI,CAAC,aAAa,CAAC;SACnB,IAAI,CAAC,YAAY,CAAC;SAClB,IAAI,CAAC,YAAY,CAAC,CAAC;IACtB,MAAM,KAAK,GAAG,aAAa,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;IAEnE,OAAO;QACL,YAAY;QACZ,WAAW;QACX,aAAa;QACb,YAAY;QACZ,YAAY;QACZ,KAAK;QACL,SAAS,EAAE,OAAO,EAAE,SAAS,IAAI,EAAE;KACpC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { PlanDefinition, TierDefinition } from "./types.js";
2
+ /**
3
+ * Canonical metric-variable set — MUST mirror `PricingEngine.buildVariables`
4
+ * exactly. Expressions may only reference these names (or allowed functions).
5
+ * Passed into `validateExpression` so typos like `inputtokens` fail at
6
+ * config-load, not at first runtime use (M5).
7
+ */
8
+ export declare const KNOWN_VARIABLES: ReadonlySet<string>;
9
+ /** Internal validated pricing configuration. */
10
+ export interface PricingConfig {
11
+ models: Record<string, string>;
12
+ tools: Record<string, string>;
13
+ search?: string | null;
14
+ cache?: string | null;
15
+ minBalance: number;
16
+ signupBonus?: number | null;
17
+ fixed: Record<string, number>;
18
+ plans?: Record<string, PlanDefinition> | null;
19
+ tiers?: Record<string, TierDefinition> | null;
20
+ }
21
+ /** Load and validate a pricing config from a raw dictionary. */
22
+ export declare function loadConfigFromDict(data: Record<string, unknown>): PricingConfig;
23
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAgB,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAoB/E;;;;;GAKG;AACH,eAAO,MAAM,eAAe,EAAE,WAAW,CAAC,MAAM,CAU9C,CAAC;AAEH,gDAAgD;AAChD,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,GAAG,IAAI,CAAC;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,GAAG,IAAI,CAAC;CAC/C;AA0HD,gEAAgE;AAChE,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,aAAa,CAoJ/E"}