@harrym1707/sdk 0.0.0-stage → 0.1.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 (58) hide show
  1. package/LICENSE +96 -0
  2. package/README.md +48 -2
  3. package/bin/mesh-demo.mjs +105 -0
  4. package/bin/mesh-proxy.mjs +39 -0
  5. package/bin/mesh-quote.mjs +45 -0
  6. package/bin/mesh-report.mjs +47 -0
  7. package/index.cjs +4923 -0
  8. package/index.js +4850 -0
  9. package/package.json +39 -4
  10. package/types/blind-features.d.ts +28 -0
  11. package/types/cache-ttl-advisor.d.ts +31 -0
  12. package/types/cache-volatility-guard.d.ts +17 -0
  13. package/types/core/cache-simulator.d.ts +271 -0
  14. package/types/core/confidence.d.ts +36 -0
  15. package/types/core/cost.d.ts +16 -0
  16. package/types/core/evaluator.d.ts +6 -0
  17. package/types/core/gateway.d.ts +75 -0
  18. package/types/core/geo-visibility.d.ts +25 -0
  19. package/types/core/helicone.d.ts +6 -0
  20. package/types/core/index.d.ts +26 -0
  21. package/types/core/langfuse.d.ts +7 -0
  22. package/types/core/litellm.d.ts +15 -0
  23. package/types/core/local-tier.d.ts +82 -0
  24. package/types/core/model-prices.d.ts +25 -0
  25. package/types/core/output-diagnostics.d.ts +39 -0
  26. package/types/core/price-catalogue.d.ts +168 -0
  27. package/types/core/provider-usage.d.ts +84 -0
  28. package/types/core/quote-report.d.ts +54 -0
  29. package/types/core/replay-runner.d.ts +11 -0
  30. package/types/core/replay.d.ts +2 -0
  31. package/types/core/router.d.ts +9 -0
  32. package/types/core/routing-simulation.d.ts +24 -0
  33. package/types/core/savings-ledger.d.ts +349 -0
  34. package/types/core/savings-model.d.ts +132 -0
  35. package/types/core/stripe-billing.d.ts +67 -0
  36. package/types/core/stripe-sink.d.ts +77 -0
  37. package/types/core/theo-coverage.d.ts +49 -0
  38. package/types/core/token-reduction.d.ts +208 -0
  39. package/types/core/tool-schema.d.ts +64 -0
  40. package/types/core/traffic.d.ts +182 -0
  41. package/types/core/triage.d.ts +70 -0
  42. package/types/core/types.d.ts +138 -0
  43. package/types/evaluation-capture.d.ts +11 -0
  44. package/types/exact-cache.d.ts +20 -0
  45. package/types/graders.d.ts +53 -0
  46. package/types/index.d.ts +26 -0
  47. package/types/openai.d.ts +23 -0
  48. package/types/proxy.d.ts +63 -0
  49. package/types/reduce-request.d.ts +247 -0
  50. package/types/replay-gate.d.ts +120 -0
  51. package/types/report.d.ts +33 -0
  52. package/types/routing.d.ts +11 -0
  53. package/types/savings-ledger.d.ts +12 -0
  54. package/types/semantic-compaction.d.ts +84 -0
  55. package/types/telemetry.d.ts +6 -0
  56. package/types/theo-policy.d.ts +119 -0
  57. package/types/types.d.ts +263 -0
  58. package/types/wrap.d.ts +52 -0
@@ -0,0 +1,349 @@
1
+ import { type PriceCatalogue } from "./price-catalogue.js";
2
+ /**
3
+ * The savings ledger: the append-only record MESH bills from, and the pure
4
+ * functions that turn it back into an invoice.
5
+ *
6
+ * MESH charges a percentage of VERIFIED savings, so the ledger is designed to
7
+ * be recomputed by the customer, not trusted:
8
+ *
9
+ * - Every event carries the provider-verbatim token usage and the content hash
10
+ * of the price catalogue it was priced against. Anyone holding the same
11
+ * catalogue can re-derive every USD figure with zero tolerance.
12
+ * - Events are hash-chained (seq, prevHash, eventHash), so a perturbed or
13
+ * removed event is detectable, and the exact position is named.
14
+ * - `recomputeInvoice` is deterministic and idempotent by requestId: replaying
15
+ * the same spool twice, late, or shuffled yields a byte-identical invoice.
16
+ * - Only verified components bill: price-mode deltas on actual tokens, MESH's
17
+ * own exact-cache avoidance at the originally measured cost, provider-cache
18
+ * economics on prefixes MESH itself placed, and lossy levers whose replay
19
+ * gate verdict is "approved". Savings the customer already had (provider
20
+ * cache on appended history they placed or got by default, gateway caches)
21
+ * are recorded for transparency and never billed. Token-reduction levers may
22
+ * bill from an estimated baseline anchored to provider-verbatim usage, and
23
+ * every such figure is labelled "estimated-baseline" on the lever and the
24
+ * invoice line item — an estimate is never passed off as a measurement.
25
+ * - Negative components are netted, never clamped: a 1h cache-write surcharge
26
+ * that never earned its reads shows up AGAINST MESH on the invoice, and a
27
+ * net-non-positive period produces the "do_not_charge" verdict.
28
+ */
29
+ export type LedgerExecutionMode = "standard" | "flex" | "batch";
30
+ export type LedgerLeverKind =
31
+ /** Transform that cannot change the answer (schema compaction, dedupe). */
32
+ "lossless"
33
+ /** Behaviour-changing lever; bills only with an approved replay-gate verdict. */
34
+ | "lossy"
35
+ /** Execution-tier price delta (flex/batch) on actual tokens. */
36
+ | "tier"
37
+ /** MESH's own exact response cache: a request never sent. */
38
+ | "exact_cache"
39
+ /** Provider prompt-cache economics on cache_control MESH itself placed. */
40
+ | "provider_cache";
41
+ /** Reference to the replay-gate run that approved or rejected a lossy lever. */
42
+ export type LedgerGateVerdict = {
43
+ ref: string;
44
+ verdict: "approved" | "rejected";
45
+ };
46
+ export type LedgerLever = {
47
+ leverId: string;
48
+ kind: LedgerLeverKind;
49
+ /**
50
+ * Verified USD this lever saved on THIS request. MAY be negative (netted on
51
+ * the invoice, never clamped). Omitted means the lever was applied but has no
52
+ * per-request verified measurement; it is then recorded and never billed.
53
+ */
54
+ savedUsd?: number;
55
+ /**
56
+ * How savedUsd was derived. "measured" (the default when absent) means it
57
+ * came entirely from provider-verbatim deltas. "estimated-baseline" means
58
+ * the tokens this lever removed were counted BEFORE send by MESH's own
59
+ * counter, anchored to the provider-verbatim input total by ratio, and
60
+ * valued at this event's realized blended input rate — a conservative
61
+ * under-claim on cache-heavy traffic, labelled as an estimate everywhere
62
+ * it appears, including the invoice line item.
63
+ */
64
+ basis?: "measured" | "estimated-baseline";
65
+ gateVerdict?: LedgerGateVerdict;
66
+ detail?: string;
67
+ };
68
+ export type LedgerUsage = {
69
+ inputTokens: number;
70
+ outputTokens: number;
71
+ cachedInputTokens: number;
72
+ /** TOTAL cache writes, inclusive of any TTL-split share below. */
73
+ cacheWriteInputTokens: number;
74
+ /**
75
+ * Provider-reported TTL split of the cache writes, present as a PAIR only
76
+ * when the provider reported one (Anthropic usage.cache_creation). The two
77
+ * buckets must sum exactly to cacheWriteInputTokens or the event is unpriced.
78
+ * Absent means the split is UNKNOWN: writes on a MESH-placed cache_control
79
+ * use the TTL stamped by MESH when it is recorded (otherwise the 1h premium,
80
+ * dispute-safe and counted against MESH), never assumed to be 5m writes.
81
+ */
82
+ cacheWrite5mInputTokens?: number;
83
+ cacheWrite1hInputTokens?: number;
84
+ };
85
+ /** One append-only billable event, written once per completed request. */
86
+ export type BillableEvent = {
87
+ schemaVersion: 1;
88
+ /** End-to-end idempotency key; duplicates are ignored at invoice time. */
89
+ requestId: string;
90
+ applicationId: string;
91
+ /** Correlation to a multi-turn task, so a failed task's turns can be excluded. */
92
+ taskId?: string;
93
+ turnIndex?: number;
94
+ /** YYYY-MM, fixed from `timestamp` at write time so late replays land in the same period. */
95
+ invoicePeriod: string;
96
+ timestamp: string;
97
+ provider: string;
98
+ model: string;
99
+ /** Taken from the provider RESPONSE (service_tier / batch), never the request. */
100
+ executionMode: LedgerExecutionMode;
101
+ pricingStatus: "priced" | "unpriced";
102
+ pricingReason?: string;
103
+ /** Content hash of the catalogue the USD figures were computed against. */
104
+ catalogueVersion?: string;
105
+ /** Provider-verbatim normalised token usage. */
106
+ usage?: LedgerUsage;
107
+ /** Catalogue-priced cost of this request at its actual execution mode. */
108
+ actualUsd?: number;
109
+ /** Measured counterfactual (standard tier, no levers), when a measurement path supplies one. */
110
+ baselineUsd?: number;
111
+ /** The caller's own pricing of the request, informational only. */
112
+ reportedCostUsd?: number;
113
+ levers: LedgerLever[];
114
+ /**
115
+ * Evidence behind any estimated-baseline lever on this event: MESH's own
116
+ * pre-send token counts. Informational — the invoice never reads it; it
117
+ * exists so an auditor can re-derive every estimated savedUsd from the
118
+ * event alone (removedFraction = removed / before, baseline input =
119
+ * usage.inputTokens / (1 - removedFraction), valued at actual input cost
120
+ * divided by actual input tokens).
121
+ */
122
+ estimatedReduction?: {
123
+ estimatedInputTokensBefore: number;
124
+ estimatedInputTokensRemoved: number;
125
+ };
126
+ /**
127
+ * Output-side waste metering (never billed, never mutated): how much of
128
+ * this completion was verbatim re-emission of lines already in the request
129
+ * context, and whether this request byte-duplicated an earlier one. Pure
130
+ * diagnostics for the statement's waste view; token counts only.
131
+ */
132
+ outputDiagnostics?: {
133
+ inspectedOutputTokens: number;
134
+ reEmittedOutputTokens: number;
135
+ reEmittedCodeTokens: number;
136
+ };
137
+ /** This request was byte-identical to an earlier one from the same app. */
138
+ duplicateOfRequestId?: string;
139
+ /** Savings the customer already had. Recorded for transparency, NEVER billed. */
140
+ excluded?: {
141
+ providerCacheAlreadyOwnedUsd?: number;
142
+ gatewayCacheUsd?: number;
143
+ };
144
+ status: "succeeded" | "failed";
145
+ };
146
+ export declare const LEDGER_GENESIS_HASH: string;
147
+ export type LedgerRecord = {
148
+ seq: number;
149
+ prevHash: string;
150
+ eventHash: string;
151
+ event: BillableEvent;
152
+ };
153
+ /** Hash of one chained event; covers its position, its predecessor and its content. */
154
+ export declare function ledgerEventHash(seq: number, prevHash: string, event: BillableEvent): string;
155
+ /** Chain one event onto the previous record (or onto genesis). */
156
+ export declare function chainLedgerRecord(event: BillableEvent, previous?: LedgerRecord): LedgerRecord;
157
+ export type LedgerChainVerification = {
158
+ ok: true;
159
+ length: number;
160
+ } | {
161
+ ok: false;
162
+ seq: number;
163
+ reason: string;
164
+ };
165
+ /**
166
+ * Verify a spool end to end. A perturbed usage field, a reordered record, or a
167
+ * missing record is reported with the exact sequence number where the chain breaks.
168
+ */
169
+ export declare function verifyLedgerChain(records: readonly LedgerRecord[]): LedgerChainVerification;
170
+ export type LedgerPricingInput = {
171
+ provider: string;
172
+ /** Raw API model identifier, resolved against the catalogue. */
173
+ model: string;
174
+ /** ISO calendar date the request was billed on. */
175
+ at: string;
176
+ executionMode: LedgerExecutionMode;
177
+ usage: LedgerUsage;
178
+ /**
179
+ * True when MESH itself placed the cache_control (the cache-ttl lever applies
180
+ * only when the caller had none), so the request's cache economics -- reads
181
+ * at the cached rate MINUS the write surcharge -- attribute to MESH. False
182
+ * means the customer already owned those economics; they are then excluded.
183
+ */
184
+ meshPlacedCacheControl: boolean;
185
+ /**
186
+ * The TTL MESH stamped, when meshPlacedCacheControl is true. Decides how an
187
+ * ABSENT provider TTL split prices the writes: a "5m" stamp can only have
188
+ * produced 5m writes (1.25x), while "1h" or unspecified prices every write
189
+ * at the 1h premium (2x) — the dispute-safe reading for an hour-long stamp.
190
+ */
191
+ meshPlacedTtl?: "5m" | "1h";
192
+ };
193
+ export type LedgerPricing = {
194
+ pricingStatus: "priced";
195
+ actualUsd: number;
196
+ /** Input-side share of actualUsd (actual mode, cache usage included, output excluded). */
197
+ inputUsd: number;
198
+ /** Standard-mode minus actual-mode cost on the same tokens; set only when the mode differs. */
199
+ tierSavedUsd?: number;
200
+ /** Cache economics attributable to MESH; MAY be negative (write surcharge unearned by reads). */
201
+ cacheAttributedUsd?: number;
202
+ /** Cache economics the customer already had; informational, never billed. */
203
+ providerCacheAlreadyOwnedUsd?: number;
204
+ } | {
205
+ pricingStatus: "unpriced";
206
+ reason: string;
207
+ };
208
+ /**
209
+ * Decompose one request's catalogue cost into auditable parts:
210
+ *
211
+ * actualUsd = fullRateStandardUsd - cacheDeltaUsd - tierSavedUsd
212
+ *
213
+ * where fullRateStandardUsd prices every input token at the standard full rate,
214
+ * cacheDeltaUsd is what the prompt cache changed (negative when writes outweigh
215
+ * reads), and tierSavedUsd is the flex/batch price delta on the actual tokens.
216
+ * Unpriced is returned rather than zero whenever a needed rate is missing.
217
+ */
218
+ export declare function priceLedgerUsage(catalogue: PriceCatalogue, input: LedgerPricingInput): LedgerPricing;
219
+ export type LedgerPricingAudit = {
220
+ status: "verified";
221
+ } | {
222
+ status: "catalogue_version_mismatch";
223
+ eventVersion?: string;
224
+ catalogueVersion: string;
225
+ } | {
226
+ status: "unpriced";
227
+ reason: string;
228
+ } | {
229
+ status: "mismatch";
230
+ field: "actualUsd";
231
+ storedUsd?: number;
232
+ recomputedUsd: number;
233
+ };
234
+ /**
235
+ * Recompute one event's stored cost from its provider-verbatim usage and the
236
+ * given catalogue, with zero tolerance. The catalogue must be the exact version
237
+ * the event was priced against; auditing against a bumped catalogue is reported
238
+ * as a version mismatch rather than a false pricing error.
239
+ */
240
+ export declare function auditEventPricing(event: BillableEvent, catalogue: PriceCatalogue): LedgerPricingAudit;
241
+ export type InvoiceOptions = {
242
+ /** Restrict to one invoice period (YYYY-MM), matched against each event's own stamp. */
243
+ period?: string;
244
+ /**
245
+ * Override gate verdicts by lever id WITHOUT mutating any event: flipping a
246
+ * lever to "rejected" drops its savings from the invoice on the next recompute.
247
+ */
248
+ gateVerdictOverrides?: Record<string, "approved" | "rejected">;
249
+ /** Tasks known to have failed quality out-of-band; all their turns' savings are excluded. */
250
+ failedTaskIds?: readonly string[];
251
+ /** MESH's contracted share of net verified savings, 0-100. Omitted: no fee line. */
252
+ feePercent?: number;
253
+ /**
254
+ * Verified-savings deficit carried in from prior periods (the ESPC G.5
255
+ * mechanic): a period that lost money does not just bill zero — its
256
+ * deficit offsets future fees, so aggregate fees can never exceed
257
+ * aggregate verified savings. Non-negative USD.
258
+ */
259
+ carryForwardDeficitUsd?: number;
260
+ };
261
+ export type InvoiceLineItem = {
262
+ leverId: string;
263
+ kind: LedgerLeverKind;
264
+ events: number;
265
+ savedUsd: number;
266
+ savedCents: number;
267
+ /** Present when ANY contributing lever's savedUsd was estimated-baseline rather than fully measured. */
268
+ basis?: "estimated-baseline";
269
+ gateVerdictRefs: string[];
270
+ };
271
+ export type InvoiceUnbilledItem = {
272
+ leverId: string;
273
+ kind: LedgerLeverKind;
274
+ events: number;
275
+ reason: string;
276
+ };
277
+ export type Invoice = {
278
+ schemaVersion: 1;
279
+ period: string | null;
280
+ catalogueVersions: string[];
281
+ eventsConsidered: number;
282
+ eventsBilled: number;
283
+ failedTaskIds: string[];
284
+ eventsExcludedForFailedTasks: number;
285
+ unpricedEvents: number;
286
+ lineItems: InvoiceLineItem[];
287
+ /** Levers that were applied but carry no billable per-request measurement. */
288
+ recordedUnbilled: InvoiceUnbilledItem[];
289
+ /** Savings the customer already had; shown so the exclusion is checkable, never billed. */
290
+ excludedAlreadyOwned: {
291
+ providerCacheOnAppendedHistoryUsd: number;
292
+ gatewayCacheUsd: number;
293
+ };
294
+ /** Sum of billable components; negatives are netted, never clamped. */
295
+ netVerifiedSavingsUsd: number;
296
+ netVerifiedSavingsCents: number;
297
+ /** Deficit applied from prior periods, when the option was supplied. */
298
+ carryForwardDeficitInUsd?: number;
299
+ /** Deficit to carry into the NEXT period (this period's shortfall after netting). */
300
+ carryForwardDeficitOutUsd?: number;
301
+ verdict: "charge" | "do_not_charge";
302
+ feePercent?: number;
303
+ amountDueUsd?: number;
304
+ amountDueCents?: number;
305
+ };
306
+ /**
307
+ * Why one lever's savings may NOT bill, or undefined when they may. The single
308
+ * rule the invoice and every projection of it (for example the Stripe meter
309
+ * sink) share, so no downstream artifact can ever bill a lever the invoice
310
+ * would refuse: unmeasured levers never bill, and lossy levers bill only with
311
+ * an approved replay-gate verdict.
312
+ */
313
+ export declare function leverUnbilledReason(lever: LedgerLever, gateVerdictOverrides?: Record<string, "approved" | "rejected">): string | undefined;
314
+ /**
315
+ * The shared selection pipeline: validate, sort, dedupe by requestId, filter
316
+ * to one period, and void every turn of a failed task. Extracted so the
317
+ * invoice and its projections apply IDENTICAL filters; recomputeInvoice's
318
+ * output bytes are unchanged by the extraction.
319
+ */
320
+ export declare function selectBillableEvents(events: readonly BillableEvent[], options?: Pick<InvoiceOptions, "period" | "failedTaskIds">): {
321
+ /** Deduplicated events inside the period, before task-failure exclusion. */
322
+ consideredEvents: BillableEvent[];
323
+ /** Events whose levers may bill: succeeded, on no failed task. */
324
+ billableEvents: BillableEvent[];
325
+ failedTaskIds: Set<string>;
326
+ eventsExcludedForFailedTasks: number;
327
+ duplicatesIgnored: number;
328
+ };
329
+ /**
330
+ * Recompute the invoice from raw events. Pure and deterministic: events are
331
+ * sorted and deduplicated by requestId before anything is summed, so the same
332
+ * spool replayed twice, a day late, or shuffled produces byte-identical output.
333
+ */
334
+ export type LedgerAudit = {
335
+ /** Events dropped as requestId replays before anything was summed. */
336
+ duplicatesIgnored: number;
337
+ };
338
+ /**
339
+ * The canonical, customer-recomputable invoice. Deliberately does NOT include
340
+ * replay metadata: whether a spool was transmitted once or three times must not
341
+ * change a single byte of the billing artifact, or "recompute it yourself"
342
+ * stops being a guarantee and becomes a dispute. Replay counts are audit
343
+ * telemetry and come back separately from recomputeInvoiceWithAudit.
344
+ */
345
+ export declare function recomputeInvoice(events: readonly BillableEvent[], options?: InvoiceOptions): Invoice;
346
+ export declare function recomputeInvoiceWithAudit(events: readonly BillableEvent[], options?: InvoiceOptions): {
347
+ invoice: Invoice;
348
+ audit: LedgerAudit;
349
+ };
@@ -0,0 +1,132 @@
1
+ import { type TokenPrice } from "./cost.js";
2
+ /**
3
+ * Composable cost-reduction model.
4
+ *
5
+ * A single lever looks unimpressive. Model routing on LLMRouterBench's MMLU-Pro
6
+ * returned 9.73% and bought it with quality. The levers below are different in
7
+ * two ways: most of them do not touch the answer, and they attack disjoint parts
8
+ * of a request, so they compose rather than compete.
9
+ *
10
+ * A request is modelled as segments, because each lever only reaches some of
11
+ * them. Tool-schema minification cannot help a RAG prompt with no tools, and
12
+ * prefix caching cannot help the one segment that changes every request. Summing
13
+ * headline percentages across levers double-counts; applying them to the
14
+ * segments they actually target does not.
15
+ *
16
+ * Order matters and is fixed: reducers shrink segments first, then caching prices
17
+ * whatever stable tokens remain. Minifying a tool catalogue and then caching it
18
+ * must charge the cache rate on the minified size, not the original.
19
+ *
20
+ * Every lever carries the published evidence for its reduction factor. Those
21
+ * factors come from their authors' benchmarks, not from MESH measuring them on
22
+ * your traffic, so a projection from this model is a hypothesis to verify by
23
+ * replay, never a realised saving. Realised savings come from provider-reported
24
+ * usage priced through the catalogue.
25
+ */
26
+ export type WorkloadSegment = "toolSchemas" | "systemPrompt" | "retrievedContext" | "history" | "userTurn" | "output";
27
+ export declare const INPUT_SEGMENTS: readonly WorkloadSegment[];
28
+ /**
29
+ * How confident a saving is before it is measured on the customer's own traffic.
30
+ *
31
+ * - `deterministic`: the request is provably equivalent, or the provider bills
32
+ * the same tokens at a lower rate. Nothing about the answer can change.
33
+ * - `needs-verification`: the prompt or the output budget changes, so quality
34
+ * has to be shown to hold by replay before the lever is enabled.
35
+ */
36
+ export type LeverRisk = "deterministic" | "needs-verification";
37
+ export type LeverEvidence = {
38
+ /** Where the reduction factor comes from. */
39
+ source: string;
40
+ /** What that source measured, in its own terms. */
41
+ claim: string;
42
+ };
43
+ export type Lever = {
44
+ id: string;
45
+ description: string;
46
+ risk: LeverRisk;
47
+ /** Segments this lever can reach; it has no effect on any other. */
48
+ targets: readonly WorkloadSegment[];
49
+ /** Share of targeted tokens removed, between 0 and 1. */
50
+ reduction: number;
51
+ /**
52
+ * How this lever changes the number of calls a task takes. 1 leaves it
53
+ * unchanged, 1.5 adds half a round trip per existing one, 0.3 removes most of
54
+ * them. Above 1 can make a lever net negative however much it trims per
55
+ * prompt, which is the whole reason this field exists: a published bench found
56
+ * progressive disclosure modelled at ~77% delivering ~13%, because the router
57
+ * it adds costs one extra round trip per novel tool call.
58
+ */
59
+ roundTripMultiplier?: number;
60
+ evidence: LeverEvidence;
61
+ };
62
+ export type WorkloadProfile = {
63
+ name: string;
64
+ /** Requests the projection covers; caching needs more than one to pay off. */
65
+ requests: number;
66
+ /** Mean tokens per request in each segment. */
67
+ segments: Record<WorkloadSegment, number>;
68
+ /**
69
+ * Segments byte-identical across requests, so a provider's prefix cache can
70
+ * serve them. Order is the prompt order: caching stops at the first segment
71
+ * that changes, so anything listed after a volatile segment cannot cache.
72
+ */
73
+ stableSegments: readonly WorkloadSegment[];
74
+ };
75
+ export type LeverContribution = {
76
+ lever: string;
77
+ risk: LeverRisk;
78
+ tokensRemoved: number;
79
+ costRemovedUsd: number;
80
+ /** Share of the baseline bill this lever alone removes, given the levers before it. */
81
+ sharePercent: number;
82
+ evidence: LeverEvidence;
83
+ };
84
+ export type SavingsProjection = {
85
+ workload: string;
86
+ requests: number;
87
+ baselineCostUsd: number;
88
+ projectedCostUsd: number;
89
+ savingUsd: number;
90
+ savingPercent: number;
91
+ /** The share achievable without any possibility of changing an answer. */
92
+ deterministicSavingPercent: number;
93
+ /** The additional share that requires a replay check before rollout. */
94
+ needsVerificationSavingPercent: number;
95
+ contributions: LeverContribution[];
96
+ inputTokensBefore: number;
97
+ inputTokensAfter: number;
98
+ outputTokensBefore: number;
99
+ outputTokensAfter: number;
100
+ cachedInputTokens: number;
101
+ /** Calls per task before any lever. */
102
+ roundTripsBefore: number;
103
+ /** Calls per task after every lever's effect on call count. */
104
+ roundTripsAfter: number;
105
+ warnings: string[];
106
+ };
107
+ /**
108
+ * Published levers, with the evidence for each factor.
109
+ *
110
+ * Factors are deliberately set at or below the conservative end of what each
111
+ * source reports. A model that projects a vendor's best-case number is the thing
112
+ * this project exists to argue against.
113
+ */
114
+ export declare const PUBLISHED_LEVERS: Record<string, Lever>;
115
+ /**
116
+ * Project the cost of a workload after a set of levers.
117
+ *
118
+ * Caching is applied last and only to stable segments that remain contiguous
119
+ * from the start of the prompt, because providers match on an exact prefix: the
120
+ * first segment that varies ends the cacheable region regardless of what follows.
121
+ */
122
+ export declare function projectSavings(profile: WorkloadProfile, levers: Lever[], price: TokenPrice, options?: {
123
+ minimumCacheableTokens?: number;
124
+ }): SavingsProjection;
125
+ /**
126
+ * Workload shapes the levers behave very differently on. The headline number a
127
+ * customer sees depends far more on which of these they are than on anything
128
+ * MESH does, which is why one global percentage would be misleading.
129
+ */
130
+ export declare const WORKLOAD_ARCHETYPES: Record<string, WorkloadProfile>;
131
+ /** Levers applicable to a profile, in the order they should be applied. */
132
+ export declare function leversFor(profile: WorkloadProfile): Lever[];
@@ -0,0 +1,67 @@
1
+ import type { Invoice } from "./savings-ledger.js";
2
+ /**
3
+ * Turning a recomputed MESH invoice into a Stripe charge — the honest way.
4
+ *
5
+ * This module is PURE: it converts an `Invoice` (the output of
6
+ * `recomputeInvoice`, itself a pure function over the customer's own
7
+ * hash-chained ledger) into a `StripeInvoicePlan` — the exact set of Stripe API
8
+ * calls that would bill it. No network here; the executor (mesh-bill script)
9
+ * runs the plan. Keeping it pure means the billing arithmetic is unit-tested
10
+ * without touching Stripe, and the plan can be shown to a human before anything
11
+ * is created.
12
+ *
13
+ * The invariants that matter for a verified-savings vendor:
14
+ * - A broken/unverified ledger NEVER bills. verdict carries DO_NOT_BILL.
15
+ * - A non-positive net period bills nothing (do_not_charge), and a carried
16
+ * deficit is surfaced, never hidden.
17
+ * - The amount is 1% (or the contracted feePercent) of NET verified savings,
18
+ * taken straight from the invoice — this module does not recompute savings,
19
+ * it only formats the already-verified number for Stripe.
20
+ * - The line-item description traces to the recomputable statement, so the
21
+ * customer can check the charge against their own ledger.
22
+ * - Every create call carries an idempotency key keyed on customer+period, so
23
+ * re-running a month cannot double-bill.
24
+ */
25
+ export type StripeBillingOptions = {
26
+ /** Stripe customer id (cus_…) the fee is billed to. */
27
+ stripeCustomerId: string;
28
+ /** Currency for the invoice. MESH fees are USD-denominated. */
29
+ currency?: string;
30
+ /**
31
+ * Whether to finalize+send the invoice or leave it as a reviewable DRAFT.
32
+ * Default "draft": nothing is ever charged without a human finalizing it.
33
+ */
34
+ mode?: "draft" | "finalize";
35
+ /** Label for the customer's statement, e.g. the spool set or app id. */
36
+ customerLabel?: string;
37
+ };
38
+ export type StripeInvoicePlan = {
39
+ action: "bill";
40
+ /** cus_… the invoice item + invoice attach to. */
41
+ customerId: string;
42
+ /** Integer minor units (cents) — Stripe never takes floats. */
43
+ amountCents: number;
44
+ currency: string;
45
+ /** Human-readable, traces to the recomputable statement. */
46
+ description: string;
47
+ /** Keyed on customer+period so a re-run cannot double-bill. */
48
+ idempotencyKey: string;
49
+ finalize: boolean;
50
+ /** Carried into the explanatory metadata on the Stripe objects. */
51
+ metadata: Record<string, string>;
52
+ } | {
53
+ action: "do_not_bill";
54
+ /** Why nothing is billed: do_not_charge, deficit carried, or chain broken. */
55
+ reason: string;
56
+ /** True only when the ledger failed verification — the hard stop. */
57
+ chainUnverified: boolean;
58
+ };
59
+ /**
60
+ * Build the Stripe plan for one recomputed invoice.
61
+ *
62
+ * `chainVerified` is passed in (not read from the invoice) because chain
63
+ * verification is the ledger layer's job: the caller verifies the spool and
64
+ * tells us. An unverified chain is a hard DO_NOT_BILL — a statement over an
65
+ * unverifiable ledger is not an invoice.
66
+ */
67
+ export declare function buildStripeInvoicePlan(invoice: Invoice, chainVerified: boolean, options: StripeBillingOptions): StripeInvoicePlan;
@@ -0,0 +1,77 @@
1
+ import { type BillableEvent, type InvoiceOptions } from "./savings-ledger.js";
2
+ /**
3
+ * The LOCAL Stripe meter sink: a pure projection from ledger events to Stripe
4
+ * Billing Meters event rows, written to a local JSONL file. No network calls,
5
+ * no API keys, no Stripe account - this is the file a billing integration
6
+ * would transmit, produced where the customer can read it first.
7
+ *
8
+ * Honesty properties, inherited rather than re-promised:
9
+ * - The projection selects and bills events through the SAME shared pipeline
10
+ * as recomputeInvoice (selectBillableEvents + leverUnbilledReason): deduped
11
+ * by requestId, failed tasks voided in full, unmeasured levers never
12
+ * counted, lossy levers only with approved gate verdicts, negatives netted.
13
+ * - Idempotent by construction: a doubled spool deduplicates to the same
14
+ * events, the same hourly windows, the same identifiers and the same values,
15
+ * so re-projection emits ZERO duplicate meter events - the output file is
16
+ * byte-identical. The identifier doubles as the Stripe-side idempotency key.
17
+ * - The canonical billing artifact remains the invoice. The projection's total
18
+ * equals the invoice's net verified savings over the same options (same
19
+ * floats, grouped hourly instead of by lever), and `totalCents` is exposed
20
+ * so the reconciliation is a one-line check.
21
+ */
22
+ export type StripeMeterEventRow = {
23
+ /** Stripe Billing Meter event name; one meter per deployment. */
24
+ event_name: string;
25
+ /**
26
+ * Deterministic idempotency identifier: sha256 of applicationId + window
27
+ * start. Stripe rejects duplicate identifiers within the dedupe horizon,
28
+ * which is exactly the re-transmission guard a replayed spool needs.
29
+ */
30
+ identifier: string;
31
+ /** Hour-window start, ISO UTC. */
32
+ timestamp: string;
33
+ payload: {
34
+ /**
35
+ * Customer mapping for the Stripe meter. Defaults to the applicationId
36
+ * verbatim; a real integration passes customerIdOf to map onto cus_ ids.
37
+ */
38
+ stripe_customer_id: string;
39
+ /** Net verified savings for the window, USD as a decimal string (6 dp). */
40
+ value: string;
41
+ };
42
+ };
43
+ export type StripeMeterProjectionOptions = Pick<InvoiceOptions, "period" | "gateVerdictOverrides" | "failedTaskIds"> & {
44
+ /** Meter event name. Default "mesh_net_verified_savings_usd". */
45
+ eventName?: string;
46
+ /** Map an applicationId to the Stripe customer id. Default: identity. */
47
+ customerIdOf?: (applicationId: string) => string;
48
+ };
49
+ export type StripeMeterProjection = {
50
+ rows: StripeMeterEventRow[];
51
+ /** Deduplicated events considered (inside the period, if one was given). */
52
+ eventsConsidered: number;
53
+ /** Events that contributed at least one billable lever to a row. */
54
+ eventsBilled: number;
55
+ duplicatesIgnored: number;
56
+ /** Events whose timestamp could not be bucketed into an hour window. */
57
+ eventsSkippedBadTimestamp: number;
58
+ /** Sum across rows, for reconciliation against the invoice. */
59
+ totalUsd: number;
60
+ totalCents: number;
61
+ };
62
+ /** Deterministic row identifier: hash(applicationId + window start). */
63
+ export declare function stripeMeterIdentifier(applicationId: string, windowStart: string): string;
64
+ /**
65
+ * Project ledger events onto hourly pre-aggregated Stripe meter rows. Pure:
66
+ * same events and options in, byte-identical rows out, however many times the
67
+ * spool was replayed or shuffled.
68
+ */
69
+ export declare function projectLedgerEventsToStripeMeterRows(events: readonly BillableEvent[], options?: StripeMeterProjectionOptions): StripeMeterProjection;
70
+ /**
71
+ * Write the projection to a local JSONL file, one meter row per line. A full
72
+ * deterministic rewrite, never an append: re-projecting the same spool writes
73
+ * the identical bytes, which is what makes a doubled spool emit zero duplicate
74
+ * meter events. Local only - nothing here (or anywhere in this module) opens a
75
+ * network connection or reads a key.
76
+ */
77
+ export declare function writeStripeMeterSink(path: string, rows: readonly StripeMeterEventRow[]): void;
@@ -0,0 +1,49 @@
1
+ import { type TokenPrice } from "./cost.js";
2
+ import { type LeverRisk, type WorkloadProfile } from "./savings-model.js";
3
+ export type LeverCoverage = {
4
+ leverId: string;
5
+ description: string;
6
+ risk: LeverRisk;
7
+ /** The lever targets at least one segment this workload actually has. */
8
+ applicable: boolean;
9
+ /** Theo applies it to this workload today (it is in leversFor). */
10
+ applied: boolean;
11
+ /**
12
+ * Projected saving from this lever alone on this workload, in USD and as a
13
+ * share of the baseline. For an applied lever this is its marginal saving in
14
+ * Theo's real stack; for an unapplied one it is the standalone projection. Both
15
+ * are hypotheses from the lever's published evidence — never a realised saving.
16
+ */
17
+ projectedSavingUsd: number;
18
+ projectedSavingPercent: number;
19
+ /** Why an applicable lever is not applied. Absent when applied, or not applicable. */
20
+ reason?: string;
21
+ };
22
+ export type CoverageReport = {
23
+ workload: string;
24
+ baselineCostUsd: number;
25
+ /** Theo's actual stacked projection on this workload (what leversFor delivers). */
26
+ realizedSavingUsd: number;
27
+ realizedSavingPercent: number;
28
+ /** The part of the realized saving that cannot change an answer — live immediately. */
29
+ realizedDeterministicPercent: number;
30
+ /** The part that needs a replay proof within the quality ceiling before it is enabled. */
31
+ realizedNeedsVerificationPercent: number;
32
+ /** Catalogue levers that can touch this workload (N). */
33
+ applicableLevers: number;
34
+ /** Of those, how many Theo applies (M). */
35
+ appliedLevers: number;
36
+ /** M / N as a percentage — the headline coverage figure. */
37
+ leverCoveragePercent: number;
38
+ /** Every catalogue lever, applied or not, sorted by projected headroom descending. */
39
+ levers: LeverCoverage[];
40
+ /** Applicable levers Theo does not apply, each with a reason. Sorted by headroom. */
41
+ gaps: LeverCoverage[];
42
+ };
43
+ /**
44
+ * Measure how much of the lever catalogue Theo reaches on one workload profile.
45
+ *
46
+ * Deterministic: the same profile, price and catalogue always produce the same
47
+ * report, so it is safe to diff across builds and to assert on in tests.
48
+ */
49
+ export declare function coverageForProfile(profile: WorkloadProfile, price: TokenPrice): CoverageReport;