@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,84 @@
1
+ import { type TokenCounter } from "./core/index.js";
2
+ import { type MeshReductionChange, type MeshReductionSummary, type MeshTokenReductionConfig } from "./reduce-request.js";
3
+ import type { LedgerGateVerdict } from "./core/index.js";
4
+ /**
5
+ * The pluggable adapter. The customer supplies a LOCAL model behind this
6
+ * interface; MESH bundles none. `compact` may be sync or async — a pre-pass can
7
+ * await either. It is called ONLY to compress stale context, never model output
8
+ * and never the live user turn (this module enforces that; the compactor itself
9
+ * only ever sees the text MESH decided was eligible).
10
+ */
11
+ export type SemanticCompactor = {
12
+ compact(input: {
13
+ /** The stale body text to compress. */
14
+ text: string;
15
+ /** Target ceiling for the compressed result, in MESH's approximate tokens. */
16
+ maxTokens: number;
17
+ /** What kind of body this is, so a compactor can prompt itself accordingly. */
18
+ kind: "tool-result";
19
+ }): Promise<string> | string;
20
+ };
21
+ export type SemanticCompactionConfig = {
22
+ /** The customer's LOCAL compactor. Absent => the lever is off (no-op). */
23
+ compactor?: SemanticCompactor;
24
+ /**
25
+ * Replay-gate verdict for the `semantic-compaction` lever. REQUIRED and must
26
+ * be "approved" for the pre-pass to touch ANY content. Absent or "rejected"
27
+ * => the pre-pass is a byte-identical no-op and records why. This is the
28
+ * reducer-level half of the double gate; the ledger still independently
29
+ * refuses to bill the lever without an approved verdict.
30
+ */
31
+ gateVerdict?: LedgerGateVerdict;
32
+ /**
33
+ * Target ceiling for a compacted body, approximate tokens. Default 500.
34
+ *
35
+ * Calibrated from real agent trajectories (docs/rnd/knowledge/
36
+ * 2026-10-27-dataset-findings.md): tool-result median is ~270–302 tok across
37
+ * SWE-rebench/SWE-smith/tau-bench, so the old 200 floor flagged 58–68% of ALL
38
+ * tool-results — compacting the typical observation, not the oversized tail.
39
+ * 500 fires on only the genuinely-oversized 3.5–34.5% tail. This lever runs
40
+ * only on multi-turn agent-shaped conversations (minimumTurns gate), so the
41
+ * agent-trajectory distribution is the right calibration population.
42
+ */
43
+ maxTokens?: number;
44
+ /** Only compact once the conversation has at least this many user turns. Default 3. */
45
+ minimumTurns?: number;
46
+ /** The most recent user turns whose content is always left verbatim. Default 2. */
47
+ keepRecentTurns?: number;
48
+ /** MESH's token counter; defaults to the shared approximate counter. */
49
+ countTokens?: TokenCounter;
50
+ };
51
+ export type SemanticCompactionResult = {
52
+ request: unknown;
53
+ /** The lossy change record when compaction ran; absent when nothing changed. */
54
+ change?: MeshReductionChange;
55
+ /** MESH's approximate input-token count of the targeted fields, before and after. */
56
+ tokensBefore: number;
57
+ tokensAfter: number;
58
+ /** Set when the pre-pass was a no-op, saying why (off, no verdict, nothing stale). */
59
+ skippedReason?: string;
60
+ };
61
+ /**
62
+ * The async PRE-PASS. Compacts stale tool-result bodies with the customer's
63
+ * local compactor and returns a new request, leaving the original untouched.
64
+ *
65
+ * Hard guard: without an APPROVED gate verdict in the config, this returns the
66
+ * request byte-identical and records why — it refuses to call the compactor at
67
+ * all. A compacted body that is not actually shorter is discarded (the original
68
+ * bytes are kept), so compaction can never make a request larger.
69
+ */
70
+ export declare function compactStaleContext(request: unknown, config?: SemanticCompactionConfig): Promise<SemanticCompactionResult>;
71
+ /**
72
+ * Async entry point: the semantic-compaction PRE-PASS followed by the
73
+ * untouched synchronous reduceRequest, with the compaction change merged into
74
+ * the summary so before/after spans the whole pipeline.
75
+ *
76
+ * This is the only place the async lever meets the sync core. reduceRequest
77
+ * itself stays pure and synchronous (see the design note at the top of this
78
+ * file); callers that do not use semantic compaction keep calling reduceRequest
79
+ * directly and never take on a promise.
80
+ */
81
+ export declare function reduceRequestAsync(request: unknown, config?: MeshTokenReductionConfig, semantic?: SemanticCompactionConfig): Promise<{
82
+ request: unknown;
83
+ summary: MeshReductionSummary;
84
+ }>;
@@ -0,0 +1,6 @@
1
+ import type { MeshRequestEvent, MeshTelemetryConfig } from "./types.js";
2
+ export declare class TelemetryClient {
3
+ private readonly config;
4
+ constructor(config?: MeshTelemetryConfig);
5
+ emit(event: MeshRequestEvent): Promise<void>;
6
+ }
@@ -0,0 +1,119 @@
1
+ import type { MeshTokenReductionConfig } from "./reduce-request.js";
2
+ /**
3
+ * Theo's per-user policy — the control mechanism between Theo and MESH.
4
+ *
5
+ * Theo never sits in the request path. His ONLY action is to publish a new version
6
+ * of this document; the proxy reads it and enforces it synchronously. A policy is
7
+ * self-documenting: every lossy lever carries the gate proof (measured saving + the
8
+ * measured quality delta Y + the grader) that justifies it.
9
+ *
10
+ * The load-bearing safety property is in `policyToReductionConfig`: a lossy lever is
11
+ * applied ONLY if it carries a passing gate proof within the route's quality ceiling.
12
+ * A policy therefore CANNOT enable a saving Theo has not proven — the "never degrade
13
+ * the product" rule is enforced here, in code, not by trust.
14
+ *
15
+ * Pure and dependency-free (no node:*), so it loads in any JavaScript runtime.
16
+ */
17
+ export type TheoLeverClass = "lossless" | "lossy";
18
+ /** The gate proof for a lossy lever: measured on the user's OWN traffic. */
19
+ export type TheoGateProof = {
20
+ /** Measured saving on the user's traffic, from provider-reported usage. */
21
+ savingPercent: number;
22
+ /** Measured quality delta Y (<= 0; e.g. -0.3 = a 0.3% drop). */
23
+ qualityDeltaPercent: number;
24
+ /** What graded quality: "task-completion" | "tests" | "behavioural" | a custom name. */
25
+ grader: string;
26
+ provenAt: string;
27
+ };
28
+ export type TheoLever = {
29
+ /** The reducer lever id (e.g. "tool-schema-compaction", "cache-ttl-5m", "output-effort-low"). */
30
+ lever: string;
31
+ class: TheoLeverClass;
32
+ /** Required for a lossy lever before it can be enforced; absent for lossless. */
33
+ gate?: TheoGateProof;
34
+ /** Lever-specific params (e.g. { maximumTokens: 600 }, { maximumDescriptionTokens: 40 }). */
35
+ params?: Record<string, unknown>;
36
+ };
37
+ export type TheoPolicy = {
38
+ schemaVersion: 1;
39
+ user: string;
40
+ /** Optional per-route policy; a default route when omitted. */
41
+ route?: string;
42
+ /** Monotonic — publishing a new version is Theo's only action. Rollback = publish a prior one. */
43
+ version: number;
44
+ /** Max quality drop (percent) this route tolerates. Default STRICT; loosened only by the user. */
45
+ qualityCeilingPercent: number;
46
+ levers: TheoLever[];
47
+ updatedAt: string;
48
+ };
49
+ /** Why a lever in the policy is NOT currently enforced — for Theo's transparency to the user. */
50
+ export type WithheldLever = {
51
+ lever: string;
52
+ reason: string;
53
+ };
54
+ /**
55
+ * Turn a policy into the reduction config the proxy enforces.
56
+ *
57
+ * Lossless levers apply unconditionally (they cannot change the answer). A lossy
58
+ * lever applies ONLY if it carries a gate proof whose measured quality delta is
59
+ * within the route's ceiling; otherwise it is silently withheld. This is the
60
+ * enforcement point of "never enable a saving we have not proven within budget."
61
+ */
62
+ export declare function policyToReductionConfig(policy: TheoPolicy): MeshTokenReductionConfig;
63
+ /** The lossy levers present in the policy but NOT enforced, with the reason — for Theo's UX. */
64
+ export declare function withheldLevers(policy: TheoPolicy): WithheldLever[];
65
+ /**
66
+ * Publish a lever into a policy, returning a NEW version (never mutating the input).
67
+ * A lossless lever is added as-is; a lossy lever must carry a gate proof. The version
68
+ * bumps and updatedAt is set by the caller's clock (passed in, so this stays pure).
69
+ */
70
+ export declare function publishLever(policy: TheoPolicy, lever: TheoLever, at: string): TheoPolicy;
71
+ /** A fresh, STRICT default policy for a new user — lossless-only until Theo proves more. */
72
+ export declare function defaultPolicy(user: string, at: string): TheoPolicy;
73
+ /** The reducer-lever ids Theo can enforce. */
74
+ export declare function knownLeverIds(): string[];
75
+ export type EnforceableLever = {
76
+ id: string;
77
+ label: string;
78
+ members: readonly string[];
79
+ };
80
+ /**
81
+ * The levers the proxy can enforce, grouped so mutually-exclusive variants count
82
+ * once: a policy cannot run output-effort-low AND output-effort-high, nor both
83
+ * cache TTLs, so counting each id separately would understate coverage. Every id
84
+ * in knownLeverIds() belongs to exactly one group here, and vice versa — the test
85
+ * `ENFORCEABLE_LEVERS stays in sync with knownLeverIds` holds the two together.
86
+ */
87
+ export declare const ENFORCEABLE_LEVERS: readonly EnforceableLever[];
88
+ /**
89
+ * Where an enforceable lever stands for this user right now:
90
+ * - `active`: Theo is enforcing it (lossless, or lossy with a proof within the ceiling).
91
+ * - `held`: it is in the policy but a lossy proof does not yet clear the ceiling.
92
+ * - `available`: Theo can enforce it but has not adopted it yet — a candidate for the live gate.
93
+ */
94
+ export type LeverStandState = "active" | "held" | "available";
95
+ export type LeverStand = {
96
+ lever: string;
97
+ label: string;
98
+ state: LeverStandState;
99
+ class?: TheoLeverClass;
100
+ reason?: string;
101
+ };
102
+ export type PolicyCoverage = {
103
+ /** Enforceable levers in the repertoire (grouped). */
104
+ enforceableCount: number;
105
+ activeCount: number;
106
+ heldCount: number;
107
+ availableCount: number;
108
+ /** activeCount / enforceableCount * 100 — the share of the repertoire live right now. */
109
+ activeCoveragePercent: number;
110
+ stands: LeverStand[];
111
+ };
112
+ /**
113
+ * How much of the proxy's enforceable repertoire Theo is actually using for this
114
+ * user. The honest denominator for the live dashboard: it shows not just the
115
+ * levers Theo applies and holds, but every lever he COULD apply and has not
116
+ * adopted yet — so a user can see how complete the coverage is, not only what is
117
+ * on. Pure: the same policy always yields the same coverage.
118
+ */
119
+ export declare function policyCoverage(policy: TheoPolicy): PolicyCoverage;
@@ -0,0 +1,263 @@
1
+ import type { LedgerGateVerdict } from "../../core/dist/src/savings-ledger.js";
2
+ import type { PriceCatalogue } from "../../core/dist/src/price-catalogue.js";
3
+ import type { MeshReductionSummary, MeshTokenReductionConfig } from "./reduce-request.js";
4
+ export type MeshTelemetryConfig = {
5
+ /**
6
+ * Where to POST usage metadata. Unset (the default) means telemetry is OFF
7
+ * and nothing is ever sent anywhere. There is no mode that sends content:
8
+ * events carry usage numbers and lever names, never prompts, and provider
9
+ * error text is masked before send.
10
+ */
11
+ endpoint?: string;
12
+ };
13
+ export type MeshRequestEvent = {
14
+ /** What reduction removed from this request, when reduction is configured. */
15
+ reduction?: MeshReductionSummary;
16
+ requestId: string;
17
+ applicationId: string;
18
+ provider: string;
19
+ model: string;
20
+ requestedModel?: string;
21
+ taskClass?: string;
22
+ workflow?: string;
23
+ difficulty?: "low" | "medium" | "high";
24
+ riskLevel?: "low" | "medium" | "high";
25
+ contextProfileId?: string;
26
+ contextProfileVersion?: string;
27
+ routePolicyId?: string;
28
+ routeReason?: string;
29
+ estimatedCostSavingsPercent?: number;
30
+ modelsAttempted?: string[];
31
+ fallbackUsed?: boolean;
32
+ fallbackReason?: "quality_rejected" | "quality_check_error" | "candidate_error" | "context_transform_unavailable" | "context_transform_error" | "context_profile_mismatch";
33
+ qualityCheckPassed?: boolean;
34
+ cacheHit?: boolean;
35
+ tokensAvoided?: number;
36
+ costAvoidedUsd?: number;
37
+ inputTokens?: number;
38
+ outputTokens?: number;
39
+ uncachedInputTokens?: number;
40
+ cachedInputTokens?: number;
41
+ cacheWriteInputTokens?: number;
42
+ /** Output-waste metering: re-emission of request context in the completion (tokens only, never billed). */
43
+ outputDiagnostics?: {
44
+ inspectedOutputTokens: number;
45
+ reEmittedOutputTokens: number;
46
+ reEmittedCodeTokens: number;
47
+ };
48
+ /** This request was byte-identical to an earlier one from the same app. */
49
+ duplicateOfRequestId?: string;
50
+ /**
51
+ * Provider-reported TTL split of the cache writes (Anthropic
52
+ * usage.cache_creation). Present as a PAIR only when the provider reported
53
+ * the split; absent means unknown, and billing uses MESH's stamped TTL when
54
+ * available (otherwise the 1h premium, dispute-safe), never assumes 5m.
55
+ */
56
+ cacheWrite5mInputTokens?: number;
57
+ cacheWrite1hInputTokens?: number;
58
+ costUsd?: number;
59
+ /**
60
+ * service_tier as reported on the final RESPONSE, never the requested one: a
61
+ * flex request that 429s and falls back to standard bills standard and earns
62
+ * zero tier savings. Absent when the provider reports none.
63
+ */
64
+ responseServiceTier?: string;
65
+ /** Response service_tier per attempt, aligned with modelsAttempted; null where unreported. */
66
+ attemptServiceTiers?: Array<string | null>;
67
+ latencyMs: number;
68
+ status: "succeeded" | "failed";
69
+ error?: string;
70
+ timestamp: string;
71
+ };
72
+ export type MeshRoutingEvidence = {
73
+ baselineModel: string;
74
+ candidateModel: string;
75
+ eligibleForReview: boolean;
76
+ sampleSize: number;
77
+ candidateAccuracyLower95: number;
78
+ accuracyDrop: number;
79
+ baselineCostUsd: number;
80
+ candidateCostUsd: number;
81
+ };
82
+ export type MeshRoutingCandidate = {
83
+ model: string;
84
+ /** Share of requests assigned to this candidate, from 0 to 1. */
85
+ trafficShare: number;
86
+ /** Explicit human approval after reviewing the offline replay report. */
87
+ approved: boolean;
88
+ evidence: MeshRoutingEvidence;
89
+ /** Optional lower output-token cap for this candidate. The baseline request is unchanged on fallback. */
90
+ maxOutputTokens?: number;
91
+ /** Versioned deterministic context-reduction transform evaluated in replay. */
92
+ contextProfileId?: string;
93
+ };
94
+ export type MeshRoutingPolicy = {
95
+ id: string;
96
+ taskClass: string;
97
+ workflow?: string;
98
+ difficulty?: "low" | "medium" | "high";
99
+ riskLevel?: "low" | "medium" | "high";
100
+ baselineModel: string;
101
+ minimumSamples: number;
102
+ minimumCandidateAccuracyLower95: number;
103
+ maximumAccuracyDrop: number;
104
+ candidates: MeshRoutingCandidate[];
105
+ };
106
+ export type MeshRoutingConfig = {
107
+ policies: MeshRoutingPolicy[];
108
+ /** Return a stable, non-sensitive key such as tenant/user or job ID. */
109
+ getRequestKey: (request: unknown) => string | undefined;
110
+ };
111
+ export type MeshExactCacheConfig = {
112
+ /** Maximum completed responses retained in this client process. */
113
+ maxEntries: number;
114
+ /** Cache entry lifetime in milliseconds. */
115
+ ttlMs: number;
116
+ /** Return an isolation scope such as tenant ID; returning undefined disables caching for that request. */
117
+ getScopeKey: (request: unknown) => string | undefined;
118
+ };
119
+ export type MeshEvaluationCaptureAttempt = {
120
+ model: string;
121
+ contextProfileId?: string;
122
+ maxOutputTokens?: number;
123
+ request: unknown;
124
+ response?: unknown;
125
+ error?: string;
126
+ inputTokens?: number;
127
+ outputTokens?: number;
128
+ costUsd?: number;
129
+ score?: number;
130
+ };
131
+ /** Content-bearing local evaluation record. Enable only with an explicit redactor. */
132
+ export type MeshEvaluationCaptureRecord = {
133
+ schemaVersion: 1;
134
+ id: string;
135
+ caseId: string;
136
+ /** Optional stable, non-sensitive group ID used to keep related prompts in one split. */
137
+ groupId?: string;
138
+ applicationId: string;
139
+ requestedModel: string;
140
+ finalModel: string;
141
+ taskClass?: string;
142
+ workflow?: string;
143
+ difficulty?: "low" | "medium" | "high";
144
+ riskLevel?: "low" | "medium" | "high";
145
+ request: unknown;
146
+ expected?: unknown;
147
+ attempts: MeshEvaluationCaptureAttempt[];
148
+ cacheHit?: boolean;
149
+ routeReason?: string;
150
+ status: "succeeded" | "failed";
151
+ timestamp: string;
152
+ };
153
+ export type MeshEvaluationCaptureConfig = {
154
+ /** Stable ID across deliberate replays of the same application test case. */
155
+ getCaseId?: (request: unknown) => string | undefined;
156
+ /** Optional stable group key, ideally a one-way hash of the normalized input. */
157
+ getGroupId?: (request: unknown) => string | undefined;
158
+ /** Optional trusted answer/label from a test fixture or application outcome. */
159
+ getExpected?: (request: unknown) => unknown;
160
+ /** Task-specific scorer returning a normalized value in [0, 1]. */
161
+ score?: (expected: unknown, response: unknown, meta: {
162
+ model: string;
163
+ workflow?: string;
164
+ taskClass?: string;
165
+ }) => number;
166
+ /** Required privacy boundary: return a sanitized copy, or undefined to discard the record. */
167
+ redact: (record: MeshEvaluationCaptureRecord) => MeshEvaluationCaptureRecord | undefined;
168
+ /** Write sanitized records locally or to an explicitly chosen sink. */
169
+ write: (record: MeshEvaluationCaptureRecord) => void | Promise<void>;
170
+ };
171
+ /**
172
+ * Opt-in savings ledger: an append-only, hash-chained JSONL spool of billable
173
+ * events, one per request, written synchronously from the event path. Off by
174
+ * default; every write is wrapped so a full disk or bad path can never throw
175
+ * into the request path. The spool is the billing source of truth a customer
176
+ * recomputes themselves with `recomputeInvoice`.
177
+ */
178
+ export type MeshSavingsLedgerConfig = {
179
+ /** Append-only JSONL file; parent directories are created on first write. */
180
+ path: string;
181
+ /** Provider key used to resolve rates in the catalogue. Default "openai". */
182
+ provider?: string;
183
+ /** Rates to pin event pricing against. Default: the published catalogue. */
184
+ catalogue?: PriceCatalogue;
185
+ /**
186
+ * Replay-gate verdict reference per lossy lever id. A lossy lever's savings
187
+ * bill only when its verdict here is "approved"; unknown lossy levers are
188
+ * recorded and never billed.
189
+ */
190
+ gateVerdicts?: Record<string, LedgerGateVerdict>;
191
+ /** Optional task correlation so a failed task's turns are excluded from the invoice. */
192
+ getCorrelation?: (event: MeshRequestEvent) => {
193
+ taskId?: string;
194
+ turnIndex?: number;
195
+ } | undefined;
196
+ /**
197
+ * Optional measured counterfactual cost (standard tier, no levers) in USD for
198
+ * this request, from a replay/counterfactual measurement path. Stored on the
199
+ * event; the measured token-reduction delta bills only when it is present.
200
+ */
201
+ getBaselineUsd?: (event: MeshRequestEvent) => number | undefined;
202
+ };
203
+ export type MeshRequestContext = {
204
+ taskClass?: string;
205
+ workflow?: string;
206
+ difficulty?: "low" | "medium" | "high";
207
+ riskLevel?: "low" | "medium" | "high";
208
+ };
209
+ /** A deterministic, versioned context transformation that can be replayed before rollout. */
210
+ export type MeshContextProfile = {
211
+ id: string;
212
+ version: string;
213
+ /** Optional guard; every supplied field must exactly match the request's trusted context. */
214
+ match?: Partial<Pick<MeshRequestContext, "taskClass" | "workflow" | "difficulty" | "riskLevel">>;
215
+ /** Transform synchronously to avoid adding another model call to the inference path. */
216
+ transform: (request: unknown, context: MeshRequestContext) => unknown;
217
+ };
218
+ export type MeshOptions = {
219
+ applicationId: string;
220
+ pricing?: {
221
+ inputPerMillion: number;
222
+ cachedInputPerMillion?: number;
223
+ cacheWriteInputPerMillion?: number;
224
+ /** 1h-TTL cache writes bill at their own premium (Anthropic: 2x base input). */
225
+ cacheWrite1hInputPerMillion?: number;
226
+ outputPerMillion: number;
227
+ };
228
+ pricingByModel?: Record<string, {
229
+ inputPerMillion: number;
230
+ cachedInputPerMillion?: number;
231
+ cacheWriteInputPerMillion?: number;
232
+ /** 1h-TTL cache writes bill at their own premium (Anthropic: 2x base input). */
233
+ cacheWrite1hInputPerMillion?: number;
234
+ outputPerMillion: number;
235
+ }>;
236
+ telemetry?: MeshTelemetryConfig;
237
+ classify?: (request: unknown) => string | undefined;
238
+ getContext?: (request: unknown) => MeshRequestContext;
239
+ /**
240
+ * Token reduction applied to every request, independent of routing. Omit to
241
+ * leave requests untouched.
242
+ */
243
+ tokenReduction?: MeshTokenReductionConfig;
244
+ contextProfiles?: readonly MeshContextProfile[];
245
+ /** @deprecated Use versioned contextProfiles for replayable context transformations. */
246
+ contextTransforms?: Record<string, (request: unknown, context: MeshRequestContext) => unknown>;
247
+ routing?: MeshRoutingConfig;
248
+ /** Return false or throw to retry a routed candidate request on the baseline model. */
249
+ qualityCheck?: (input: {
250
+ request: unknown;
251
+ response: unknown;
252
+ taskClass?: string;
253
+ context?: MeshRequestContext;
254
+ candidateModel: string;
255
+ }) => boolean | Promise<boolean>;
256
+ /** Opt-in, in-memory exact response cache. Tool/conversation/streaming requests are bypassed. */
257
+ exactCache?: MeshExactCacheConfig;
258
+ /** Off by default. Captures request/response content only when explicitly configured. */
259
+ evaluationCapture?: MeshEvaluationCaptureConfig;
260
+ /** Off by default. Appends hash-chained billable events to a local JSONL spool. */
261
+ ledger?: MeshSavingsLedgerConfig;
262
+ onEvent?: (event: MeshRequestEvent) => void;
263
+ };
@@ -0,0 +1,52 @@
1
+ import type { MeshTokenReductionConfig } from "./reduce-request.js";
2
+ /**
3
+ * wrapMesh — the one-line drop-in for an existing provider client.
4
+ *
5
+ * import OpenAI from "openai";
6
+ * import { wrapMesh } from "@harrym1707/sdk";
7
+ * const openai = wrapMesh(new OpenAI()); // <- the only change
8
+ * // ...use `openai` exactly as before...
9
+ * console.log(openai.mesh.savings()); // { requests, savedUsd, ... }
10
+ *
11
+ * This is `withMesh` with sane, zero-config defaults for someone who just wants
12
+ * their AI app to spend less without learning the proxy, the ledger, or any
13
+ * options object. The client's response shapes are preserved, its own key is
14
+ * used, prompts never leave the machine, and reduction is LOSSLESS-ONLY by
15
+ * default — so there is no quality risk to switching one import.
16
+ *
17
+ * The savings number is the real measured one: every request appends a
18
+ * hash-chained ledger event priced from provider-reported usage, and
19
+ * `mesh.savings()` recomputes the invoice from that spool — the same audit a
20
+ * customer runs. It is never MESH's own token estimate.
21
+ */
22
+ export type WrapMeshOptions = {
23
+ /** Names this app on the ledger + invoice. Default "app". */
24
+ app?: string;
25
+ /** Where the hash-chained savings ledger is written. Default ./.mesh/<app>.jsonl */
26
+ ledgerPath?: string;
27
+ /** Catalogue provider key for pricing. Auto-detected from the client; override if needed. */
28
+ provider?: string;
29
+ /** Override reduction. Default: lossless-only (safe, no quality gate needed). */
30
+ tokenReduction?: MeshTokenReductionConfig;
31
+ /** Opt into the Anthropic prompt-cache stamp on multi-turn traffic ("5m" | "1h"). */
32
+ cacheTtl?: "5m" | "1h";
33
+ };
34
+ export type MeshSavingsSummary = {
35
+ /** Requests metered through MESH for this app. */
36
+ requests: number;
37
+ /** Net verified savings in USD (never MESH's token estimate; from provider usage). */
38
+ savedUsd: number;
39
+ /** MESH's fee at 1% of verified savings. */
40
+ feeUsd: number;
41
+ verdict: "charge" | "do_not_charge";
42
+ ledgerPath: string;
43
+ };
44
+ export type MeshHandle = {
45
+ /** Recompute the measured savings from the ledger spool. */
46
+ savings(): MeshSavingsSummary;
47
+ /** The ledger spool path, for `recomputeInvoice` / `mesh-report`. */
48
+ ledgerPath: string;
49
+ };
50
+ export declare function wrapMesh<T extends object>(client: T, options?: WrapMeshOptions): T & {
51
+ mesh: MeshHandle;
52
+ };