@harrym1707/sdk 0.1.1 → 0.2.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@harrym1707/sdk",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Cut LLM API costs on Claude and OpenAI: one-URL proxy or one-line SDK wrapper that reduces each request losslessly and meters VERIFIED savings into an append-only, customer-recomputable ledger. Pay only a share of verified savings.",
5
5
  "license": "BUSL-1.1",
6
6
  "repository": {
@@ -1,17 +1,31 @@
1
1
  export type CacheStampDecision = {
2
+ /** False withholds every breakpoint. */
2
3
  stamp: boolean;
3
- /** Present when stamp is false: why this conversation is not being stamped. */
4
+ /**
5
+ * False withholds only the breakpoint on the newest message; the system
6
+ * breakpoint may still be placed. Absent means the same as `stamp`.
7
+ */
8
+ messageBreakpoint?: boolean;
9
+ /** Present when anything is withheld: why. */
4
10
  reason?: string;
5
11
  };
12
+ export type CacheStampContext = {
13
+ /**
14
+ * The content the system breakpoint would cover on this request, after
15
+ * MESH's levers and without any cache_control markers. Only hashed.
16
+ */
17
+ stampedPrefix?: unknown;
18
+ };
6
19
  export declare class CachePrefixVolatilityGuard {
7
20
  private readonly maxConversations;
8
21
  /** Insertion-ordered; re-inserted on touch, so the first key is the LRU. */
9
22
  private readonly conversations;
10
23
  constructor(maxConversations?: number);
11
24
  /**
12
- * Record this request and decide whether its conversation has earned a
13
- * cache stamp. Call once per request, with the raw (unreduced) request.
25
+ * Record this request and decide which cache breakpoints its conversation
26
+ * has earned. Call once per request, with the raw (unreduced) request and,
27
+ * when known, the content the system breakpoint would cover.
14
28
  */
15
- observe(request: unknown): CacheStampDecision;
29
+ observe(request: unknown, context?: CacheStampContext): CacheStampDecision;
16
30
  private evict;
17
31
  }
@@ -0,0 +1,7 @@
1
+ import { AccountStore } from "./accounts.js";
2
+ /**
3
+ * Open (or create) a file-backed account store. The returned store persists
4
+ * every mutation synchronously before the mutating call returns, so a crash
5
+ * after signup can never lose the account a customer was just handed a key for.
6
+ */
7
+ export declare function openFileAccountStore(path: string): AccountStore;
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The self-serve account model — who MESH bills, and the Mesh account key that
3
+ * authenticates their metering.
4
+ *
5
+ * Two keys are deliberately kept apart and must never be confused:
6
+ * - The PROVIDER key (Anthropic x-api-key / OpenAI bearer) only ever passes
7
+ * THROUGH the proxy to the provider. MESH never stores it, and nothing in
8
+ * this module touches it.
9
+ * - The MESH ACCOUNT KEY identifies an account to the metering API. It is
10
+ * generated here, shown to the customer exactly once at signup, and stored
11
+ * only as a salted-free SHA-256 hash — a leaked store never yields a usable
12
+ * key, and a presented key is matched by hashing it the same way.
13
+ *
14
+ * The store itself is an in-memory Map keyed by account id, with secondary
15
+ * indexes by GitHub id and by account-key hash. It is pure and synchronous so
16
+ * the whole account lifecycle is unit-testable without a database; the
17
+ * file-backed persistence layer (./account-store.js) wraps one of these.
18
+ */
19
+ /** How a customer pays the MESH fee. Chosen by the customer, stored per account. */
20
+ export type PaymentChoice =
21
+ /** Stripe pulls the fee automatically against a saved mandate (ACH/BACS/SEPA). */
22
+ "direct_debit"
23
+ /** MESH finalizes an invoice and the customer pays it by bank transfer themselves. */
24
+ | "bank_transfer";
25
+ export type DirectDebitMandate = {
26
+ /** The Stripe SetupIntent that collected the mandate. */
27
+ setupIntentId?: string;
28
+ /** The saved payment method the fee is pulled from. */
29
+ paymentMethodId?: string;
30
+ /** "pending" until the mandate is confirmed; "active" once it can be charged. */
31
+ status: "pending" | "active";
32
+ };
33
+ export type Account = {
34
+ /** Stable internal id, acct_…, never derived from anything guessable. */
35
+ id: string;
36
+ /** GitHub's numeric user id — stable across username changes, the real identity. */
37
+ githubId: number;
38
+ /** GitHub login at last sign-in, for display and the admin list. */
39
+ githubLogin: string;
40
+ /** Primary verified email from GitHub, when the user shared one. */
41
+ email?: string;
42
+ /** Stripe customer (cus_…), created once at signup; absent only if Stripe was unreachable. */
43
+ stripeCustomerId?: string;
44
+ /** SHA-256 hex of the live account key. The key itself is never stored. */
45
+ accountKeyHash: string;
46
+ /**
47
+ * The non-secret leading segment of the key (e.g. mesh_sk_ab12cd34), kept so
48
+ * the admin API and the customer can identify WHICH key is live without ever
49
+ * seeing or storing the secret tail.
50
+ */
51
+ accountKeyPrefix: string;
52
+ /** direct_debit | bank_transfer, once the customer has chosen. */
53
+ paymentChoice?: PaymentChoice;
54
+ /** Mandate state when paymentChoice is direct_debit. */
55
+ directDebitMandate?: DirectDebitMandate;
56
+ /** MESH's contracted share of net verified savings, 0–100. Default 1. */
57
+ feePercent: number;
58
+ createdAt: string;
59
+ updatedAt: string;
60
+ };
61
+ /** The default MESH fee: 1% of net verified savings. */
62
+ export declare const DEFAULT_FEE_PERCENT = 1;
63
+ /** Hash an account key exactly as it is stored and looked up. */
64
+ export declare function hashAccountKey(key: string): string;
65
+ /** The non-secret display prefix of a key (scheme + first 8 chars of the secret). */
66
+ export declare function accountKeyPrefixOf(key: string): string;
67
+ /**
68
+ * Generate a fresh account key. Returns the plaintext key (shown to the
69
+ * customer ONCE) plus the hash and prefix that are safe to persist.
70
+ */
71
+ export declare function generateAccountKey(): {
72
+ key: string;
73
+ hash: string;
74
+ prefix: string;
75
+ };
76
+ /** Constant-time compare of two SHA-256 hex digests (key lookup must not leak timing). */
77
+ export declare function accountKeyHashEquals(a: string, b: string): boolean;
78
+ /** A view of an account that is safe to return over the API — never the key hash. */
79
+ export type PublicAccount = {
80
+ id: string;
81
+ githubLogin: string;
82
+ email?: string;
83
+ stripeCustomerId?: string;
84
+ accountKeyPrefix: string;
85
+ paymentChoice?: PaymentChoice;
86
+ directDebitMandateStatus?: DirectDebitMandate["status"];
87
+ feePercent: number;
88
+ createdAt: string;
89
+ updatedAt: string;
90
+ };
91
+ /** Strip the secret-adjacent fields so an account can be safely serialized to a client. */
92
+ export declare function redactAccount(account: Account): PublicAccount;
93
+ export type GithubIdentity = {
94
+ githubId: number;
95
+ githubLogin: string;
96
+ email?: string;
97
+ };
98
+ /**
99
+ * In-memory account store with the three lookups the API needs (by id, by
100
+ * GitHub id, by account-key hash). Pure and synchronous. A persistence layer
101
+ * supplies the initial records and observes mutations via `onChange`.
102
+ */
103
+ export declare class AccountStore {
104
+ private readonly onChange?;
105
+ private readonly byId;
106
+ private readonly idByGithub;
107
+ private readonly idByKeyHash;
108
+ constructor(seed?: readonly Account[], onChange?: ((account: Account) => void) | undefined);
109
+ private index;
110
+ list(): Account[];
111
+ get(id: string): Account | undefined;
112
+ findByGithubId(githubId: number): Account | undefined;
113
+ /** Resolve an account from a presented plaintext account key. */
114
+ findByAccountKey(key: string): Account | undefined;
115
+ private save;
116
+ /**
117
+ * Find the account for this GitHub identity, or create one. On creation a
118
+ * fresh account key is issued and returned in plaintext (the ONLY time it is
119
+ * available); on an existing account the login/email are refreshed and no key
120
+ * is returned. The caller attaches the Stripe customer id separately.
121
+ */
122
+ upsertFromGithub(identity: GithubIdentity, now?: string): {
123
+ account: Account;
124
+ created: boolean;
125
+ accountKey?: string;
126
+ };
127
+ /** Rotate an account's key, invalidating the old one. Returns the new plaintext key. */
128
+ rotateAccountKey(id: string, now?: string): {
129
+ account: Account;
130
+ accountKey: string;
131
+ } | undefined;
132
+ /** Apply a partial update to an account (Stripe id, payment choice, mandate, fee). */
133
+ patch(id: string, patch: Partial<Pick<Account, "stripeCustomerId" | "paymentChoice" | "directDebitMandate" | "feePercent" | "email">>, now?: string): Account | undefined;
134
+ }
@@ -0,0 +1,113 @@
1
+ import type { Account, PaymentChoice } from "./accounts.js";
2
+ import { type Invoice, type LedgerRecord } from "./savings-ledger.js";
3
+ import type { BillingStripe } from "./stripe-client.js";
4
+ /**
5
+ * The automated per-account billing worker — the operator-run mesh-bill logic
6
+ * promoted to run unattended, once per account, with every safety rail intact:
7
+ *
8
+ * - A broken/unverified ledger chain is a hard stop: DO NOT BILL.
9
+ * - A non-positive net period bills nothing (do_not_charge).
10
+ * - Idempotency keys on customer+period+amount, so a re-run is a no-op at
11
+ * Stripe, never a double charge.
12
+ * - TEST MODE only: the worker takes a {@link BillingStripe}; the real client
13
+ * refuses a live key unless explicitly allowed, which the worker never does.
14
+ * - No prompt content is read — only the usage-derived invoice totals.
15
+ *
16
+ * The customer's stored payment choice decides the rail:
17
+ * - direct_debit: Stripe pulls the fee against the saved mandate
18
+ * (charge_automatically + the mandate's payment method), after an advance
19
+ * "upcoming charge" notice carrying the recompute-it-yourself receipt —
20
+ * because the amount varies period to period.
21
+ * - bank_transfer: Stripe finalizes and SENDS the invoice; the customer pays
22
+ * it themselves. No mandate, no auto-pull.
23
+ *
24
+ * The decision is a pure function (unit-tested without Stripe); the executor
25
+ * performs the Stripe calls for whichever rail the decision selected.
26
+ */
27
+ /**
28
+ * Recompute one account's invoice from its stored ledger records, with the
29
+ * chain verified. The single path the worker and the admin API share, so a
30
+ * preview and the real run can never disagree about what an account owes.
31
+ */
32
+ export declare function invoiceForAccount(account: Account, records: readonly LedgerRecord[], period?: string): {
33
+ invoice: Invoice;
34
+ chainVerified: boolean;
35
+ };
36
+ /** The advance notice a variable-amount charge sends before it is pulled. */
37
+ export type AdvanceChargeNotice = {
38
+ accountId: string;
39
+ period: string;
40
+ rail: PaymentChoice;
41
+ feePercent: number;
42
+ netVerifiedSavingsUsd: number;
43
+ amountDueCents: number;
44
+ currency: string;
45
+ /** How the customer re-derives the charge from their own hash-chained ledger. */
46
+ recompute: {
47
+ command: string;
48
+ note: string;
49
+ };
50
+ };
51
+ export type BillingDecision = {
52
+ action: "skip";
53
+ reason: string;
54
+ chainUnverified: boolean;
55
+ } | {
56
+ action: "bill";
57
+ rail: PaymentChoice;
58
+ customerId: string;
59
+ amountCents: number;
60
+ currency: string;
61
+ description: string;
62
+ idempotencyKey: string;
63
+ metadata: Record<string, string>;
64
+ /** The mandate's payment method, present (and required) only for direct_debit. */
65
+ mandatePaymentMethodId?: string;
66
+ notice: AdvanceChargeNotice;
67
+ };
68
+ export type DecideBillingOptions = {
69
+ /** Currency for the fee invoice. Default usd. */
70
+ currency?: string;
71
+ };
72
+ /**
73
+ * Decide how (and whether) to bill one account for a recomputed invoice. Pure.
74
+ * Branches on the stored payment choice; refuses to bill a direct-debit account
75
+ * whose mandate is not active, and refuses entirely before a choice is made.
76
+ */
77
+ export declare function decideBilling(account: Account, invoice: Invoice, chainVerified: boolean, options?: DecideBillingOptions): BillingDecision;
78
+ export type AccountBillingOutcome = {
79
+ status: "skipped";
80
+ reason: string;
81
+ chainUnverified: boolean;
82
+ } | {
83
+ status: "noticed";
84
+ rail: PaymentChoice;
85
+ notice: AdvanceChargeNotice;
86
+ } | {
87
+ status: "billed";
88
+ rail: PaymentChoice;
89
+ invoiceId: string;
90
+ invoiceStatus: string;
91
+ amountCents: number;
92
+ currency: string;
93
+ hostedInvoiceUrl?: string;
94
+ notice: AdvanceChargeNotice;
95
+ };
96
+ export type RunBillingOptions = DecideBillingOptions & {
97
+ /**
98
+ * "advance_notice" produces the upcoming-charge notice and performs NO Stripe
99
+ * calls (sent N days before a variable-amount pull). "charge" (default)
100
+ * creates and settles the invoice via the chosen rail.
101
+ */
102
+ mode?: "advance_notice" | "charge";
103
+ /** Days a bank-transfer invoice is payable. Default 14. */
104
+ daysUntilDue?: number;
105
+ /** Statement description prefix on the Stripe invoice. */
106
+ statementPrefix?: string;
107
+ };
108
+ /**
109
+ * Run billing for one account against a recomputed invoice. The decision is
110
+ * pure; this performs the Stripe side-effects for the selected rail with the
111
+ * plan's idempotency key, so a re-run never double-charges.
112
+ */
113
+ export declare function runAccountBilling(stripe: BillingStripe, account: Account, invoice: Invoice, chainVerified: boolean, options?: RunBillingOptions): Promise<AccountBillingOutcome>;
@@ -0,0 +1,216 @@
1
+ import type { InferenceEvent, ModelTarget } from "./types.js";
2
+ /**
3
+ * Agent budget control (Stage 9).
4
+ *
5
+ * An agent run is a sequence of steps and tool-calls, each of which spends
6
+ * money, tokens, and turns. Left alone a loop can run away — retrying, re-reading
7
+ * context, fanning out tool-calls — and the bill is only visible once it has
8
+ * already happened. The budget controller is the governor on that loop: it
9
+ * accumulates usage across the run and, at each step, decides deterministically
10
+ * what the configured policy says to do when a cap is approached or exceeded.
11
+ *
12
+ * Four caps are enforced (any subset may be set; an unset cap is not enforced):
13
+ *
14
+ * - `maxCostUsd` — total realized spend for the run
15
+ * - `maxTokens` — total tokens (input + output) across the run
16
+ * - `maxSteps` — agent/planner iterations
17
+ * - `maxToolCalls` — tool invocations
18
+ *
19
+ * When a cap is reached the policy maps the severity to one of five actions:
20
+ *
21
+ * - `continue` — carry on (the default while under budget)
22
+ * - `switch_model` — fall back to a cheaper target
23
+ * - `compress_context` — shrink the prompt/history before the next step
24
+ * - `stop` — halt the run now
25
+ * - `escalate` — hand off to a human / higher authority
26
+ *
27
+ * Two of those — `switch_model` and `compress_context` — are NOT implemented
28
+ * here. Routing lives in the Stage 6 Router and context transforms in the
29
+ * Stage 7 context-optimisation work; reimplementing either here would fork that
30
+ * logic. Instead the controller emits them as INTENTS (`BudgetIntent`): a typed
31
+ * request carrying what is left of each cap, for the Router or the context
32
+ * optimiser to fulfil. The controller's job is the decision, not the remedy.
33
+ *
34
+ * The decision function is pure and total: the same usage and policy always
35
+ * yield the same `BudgetDecision`, independent of how the usage accumulated.
36
+ * `BudgetTracker` is the thin stateful wrapper that accumulates deltas across a
37
+ * run and records each actionable decision through a telemetry sink, projecting
38
+ * onto the shared `InferenceEvent` so budget decisions ride the same pipe as
39
+ * routing decisions and provider calls.
40
+ */
41
+ export type BudgetDimension = "cost" | "tokens" | "steps" | "toolCalls";
42
+ /** Canonical dimension order; every list and record of dimensions uses it. */
43
+ export declare const BUDGET_DIMENSIONS: readonly BudgetDimension[];
44
+ export type BudgetAction = "continue" | "switch_model" | "compress_context" | "stop" | "escalate";
45
+ /** Severity of the run's usage against its caps. */
46
+ export type BudgetStatus = "ok" | "approaching" | "exceeded";
47
+ export type BudgetLimits = {
48
+ maxCostUsd?: number;
49
+ maxTokens?: number;
50
+ maxSteps?: number;
51
+ maxToolCalls?: number;
52
+ };
53
+ export type BudgetPolicy = {
54
+ limits: BudgetLimits;
55
+ /**
56
+ * Fraction of a cap (0 < t <= 1) at which usage counts as "approaching" that
57
+ * cap but has not yet exceeded it. Defaults to 0.8.
58
+ */
59
+ warnThreshold?: number;
60
+ /** Action when usage crosses the warn threshold but is still under the cap. Defaults to "continue". */
61
+ onApproaching?: BudgetAction;
62
+ /** Action when usage reaches or passes a cap. Defaults to "stop". */
63
+ onExceeded?: BudgetAction;
64
+ };
65
+ /** Accumulated usage of an agent run. */
66
+ export type BudgetUsage = {
67
+ costUsd: number;
68
+ tokens: number;
69
+ steps: number;
70
+ toolCalls: number;
71
+ };
72
+ /** A single step/tool-call's contribution to the run's usage. All fields optional. */
73
+ export type BudgetDelta = Partial<BudgetUsage>;
74
+ /** How much of each capped dimension is left (never negative); unset dimensions are omitted. */
75
+ export type BudgetRemaining = {
76
+ costUsd?: number;
77
+ tokens?: number;
78
+ steps?: number;
79
+ toolCalls?: number;
80
+ };
81
+ /**
82
+ * A request emitted for the Router (Stage 6) or context optimiser (Stage 7) to
83
+ * fulfil. The controller never performs the remedy itself; it describes what is
84
+ * left of the budget and which caps forced the decision.
85
+ */
86
+ export type BudgetIntent = {
87
+ kind: "switch_model";
88
+ triggeredBy: BudgetDimension[];
89
+ remaining: BudgetRemaining;
90
+ /** The target currently in use, when the run supplied one. */
91
+ currentTarget?: ModelTarget;
92
+ reason: string;
93
+ } | {
94
+ kind: "compress_context";
95
+ triggeredBy: BudgetDimension[];
96
+ remaining: BudgetRemaining;
97
+ reason: string;
98
+ };
99
+ export type BudgetDecision = {
100
+ status: BudgetStatus;
101
+ action: BudgetAction;
102
+ /** Dimensions at the decisive severity level, in canonical order. */
103
+ triggeredBy: BudgetDimension[];
104
+ /** Snapshot of accumulated usage the decision was made against. */
105
+ usage: BudgetUsage;
106
+ /** used/limit per dimension; null for a dimension with no cap. */
107
+ fractions: Record<BudgetDimension, number | null>;
108
+ remaining: BudgetRemaining;
109
+ reason: string;
110
+ /**
111
+ * The remedy to attempt, set whenever a remedy (`switch_model` /
112
+ * `compress_context`) was configured for this status. It stays present even
113
+ * when the action has fallen back to `stop` because the cap was already
114
+ * exceeded (see `remedyExhausted`): it names the remedy an orchestrator may
115
+ * apply before starting a fresh run.
116
+ */
117
+ intent?: BudgetIntent;
118
+ /**
119
+ * True when the configured remedy (`switch_model` / `compress_context`) was
120
+ * chosen for an ALREADY-EXCEEDED cap and so cannot recover the overrun: the
121
+ * action falls back to `stop` and the run must halt. This is the explicit
122
+ * "remedy cannot help past the cap" terminal path.
123
+ */
124
+ remedyExhausted?: boolean;
125
+ /** True for `stop` / `escalate`: the run must not continue automatically. */
126
+ terminal: boolean;
127
+ };
128
+ /** `stop` and `escalate` halt the run; the other three let it proceed. */
129
+ export declare function isTerminalAction(action: BudgetAction): boolean;
130
+ export declare const ZERO_BUDGET_USAGE: BudgetUsage;
131
+ /** Validate a policy up front so every later decision is total and NaN-free. */
132
+ export declare function assertValidBudgetPolicy(policy: BudgetPolicy): void;
133
+ /**
134
+ * Decide the budget action for an accumulated usage against a policy. Pure and
135
+ * deterministic: a dimension is "exceeded" when used >= its cap and
136
+ * "approaching" when used/cap >= the warn threshold but below the cap. The run's
137
+ * status is the most severe dimension; the action is the policy's mapping of
138
+ * that status. `switch_model`/`compress_context` carry a fulfilment intent.
139
+ */
140
+ export declare function evaluateBudget(usage: BudgetUsage, policy: BudgetPolicy): BudgetDecision;
141
+ /** Who/what an agent run is, so its budget decisions can be correlated. */
142
+ export type BudgetRunContext = {
143
+ requestId: string;
144
+ applicationId: string;
145
+ taskId?: string;
146
+ taskClass?: string;
147
+ /** The model the run is using, carried into `switch_model` intents and telemetry. */
148
+ currentTarget?: ModelTarget;
149
+ };
150
+ /** A recorded budget decision: the native telemetry record for the budget path. */
151
+ export type BudgetDecisionEvent = {
152
+ requestId: string;
153
+ applicationId: string;
154
+ taskId?: string;
155
+ taskClass?: string;
156
+ status: BudgetStatus;
157
+ action: BudgetAction;
158
+ triggeredBy: BudgetDimension[];
159
+ usage: BudgetUsage;
160
+ reason: string;
161
+ intentKind?: BudgetIntent["kind"];
162
+ timestamp: string;
163
+ };
164
+ export interface BudgetEventSink {
165
+ record(event: BudgetDecisionEvent): void;
166
+ }
167
+ /** Collects budget decision events in memory; stands in for the real telemetry sink in tests. */
168
+ export declare class InMemoryBudgetSink implements BudgetEventSink {
169
+ readonly events: BudgetDecisionEvent[];
170
+ record(event: BudgetDecisionEvent): void;
171
+ }
172
+ /** Map a decision + run context to its telemetry record. */
173
+ export declare function budgetDecisionEvent(decision: BudgetDecision, context: BudgetRunContext, timestamp: string): BudgetDecisionEvent;
174
+ /**
175
+ * Project a budget decision event onto the shared `InferenceEvent`, so budget
176
+ * decisions flow through the same telemetry/ledger pipe as routing decisions
177
+ * and provider calls. `routeReason` carries the budget verdict; the provider /
178
+ * model name the run's current target, or the budget controller itself.
179
+ */
180
+ export declare function budgetInferenceEvent(event: BudgetDecisionEvent, currentTarget?: ModelTarget): InferenceEvent;
181
+ export type BudgetTrackerOptions = {
182
+ context?: BudgetRunContext;
183
+ /** Where actionable decisions are recorded. Needs `context` to carry correlation ids. */
184
+ sink?: BudgetEventSink;
185
+ /** Timestamp source for recorded events; defaults to the wall clock. */
186
+ clock?: () => string;
187
+ };
188
+ /**
189
+ * Accumulates usage across the steps and tool-calls of one agent run and decides
190
+ * the budget action after each. Thin and stateful: the decision itself is the
191
+ * pure `evaluateBudget`; the tracker only adds accumulation and telemetry.
192
+ *
193
+ * Every decision whose action is not `continue` is recorded through the sink (a
194
+ * budget decision worth keeping is one that changed what the run does), both as
195
+ * the native `BudgetDecisionEvent` and — when the run has a target — projectable
196
+ * onto the shared `InferenceEvent`.
197
+ */
198
+ export declare class BudgetTracker {
199
+ private readonly policy;
200
+ private readonly context?;
201
+ private readonly sink?;
202
+ private readonly clock;
203
+ private current;
204
+ constructor(policy: BudgetPolicy, options?: BudgetTrackerOptions);
205
+ /** A copy of the accumulated usage; the internal total is never handed out. */
206
+ get usage(): BudgetUsage;
207
+ /** Decide against the current usage without accumulating anything or recording. */
208
+ peek(): BudgetDecision;
209
+ /** Accumulate a usage delta, then decide and (if actionable) record. */
210
+ record(delta: BudgetDelta): BudgetDecision;
211
+ /** Record one agent step (steps += 1) plus any spend/tokens/tool-calls it incurred. */
212
+ recordStep(delta?: Omit<BudgetDelta, "steps">): BudgetDecision;
213
+ /** Record one tool call (toolCalls += 1) plus any spend/tokens it incurred. */
214
+ recordToolCall(delta?: Omit<BudgetDelta, "toolCalls">): BudgetDecision;
215
+ private emit;
216
+ }
@@ -1,4 +1,14 @@
1
1
  import type { EvaluationInput, Evaluator, QualityPolicy, QualityResult } from "./types.js";
2
+ /**
3
+ * Apply a quality policy to a measured result, returning the result with
4
+ * `passed` narrowed to whether every requirement is met.
5
+ *
6
+ * The error-rate and latency ceilings are fail-closed: a ceiling the result
7
+ * does not actually measure cannot be certified as met, so an unmeasured
8
+ * `maxErrorRate` or `maxLatencyMs` fails the gate rather than silently passing.
9
+ * This closes the "never silently reduce quality" hole where a candidate gated
10
+ * on error rate or latency would otherwise clear a gate it never proved.
11
+ */
2
12
  export declare function applyQualityPolicy(result: QualityResult, policy: QualityPolicy): QualityResult;
3
13
  export declare class ExactMatchEvaluator implements Evaluator {
4
14
  name: string;
@@ -0,0 +1,41 @@
1
+ import type { GithubIdentity } from "./accounts.js";
2
+ /**
3
+ * GitHub OAuth — the one identity step in signup. First login auto-creates the
4
+ * account (no approval), so this module only needs to (a) build the authorize
5
+ * URL, (b) issue and verify a stateless CSRF `state`, and (c) exchange the
6
+ * returned code for a stable GitHub identity.
7
+ *
8
+ * The `state` is an HMAC-signed `nonce.timestamp` rather than server-side
9
+ * session storage, so the API stays stateless and horizontally scalable. The
10
+ * fetch calls are injectable so the whole exchange is unit-testable with no
11
+ * network.
12
+ *
13
+ * Only identity is read: numeric GitHub id (stable across renames), login, and
14
+ * a verified primary email when the user has shared one. The short-lived access
15
+ * token is used for those two reads and then discarded — never stored.
16
+ */
17
+ export type GithubOAuthConfig = {
18
+ clientId: string;
19
+ clientSecret: string;
20
+ /** Where GitHub redirects back with the code; must match the OAuth app setting. */
21
+ redirectUri: string;
22
+ /** Secret for signing the stateless `state` token. */
23
+ stateSecret: string;
24
+ /** Scopes requested. Default: read:user user:email (identity + email only). */
25
+ scope?: string;
26
+ };
27
+ /** Mint a signed, time-stamped CSRF state token. */
28
+ export declare function createOAuthState(secret: string, now?: number): string;
29
+ /** Verify a state token's signature and freshness (constant-time on the signature). */
30
+ export declare function verifyOAuthState(secret: string, state: string, now?: number, maxAgeMs?: number): boolean;
31
+ /** Build the GitHub authorize URL a browser is redirected to. Pure. */
32
+ export declare function buildAuthorizeUrl(config: GithubOAuthConfig, state: string): string;
33
+ export type OAuthFetch = typeof fetch;
34
+ /**
35
+ * Exchange an authorization code for a GitHub identity: swap code → access
36
+ * token, then read the user and their verified primary email. The token never
37
+ * leaves this function.
38
+ */
39
+ export declare function exchangeCodeForIdentity(config: GithubOAuthConfig, code: string, deps?: {
40
+ fetch?: OAuthFetch;
41
+ }): Promise<GithubIdentity>;
@@ -1,5 +1,6 @@
1
1
  export * from "./types.js";
2
2
  export * from "./router.js";
3
+ export * from "./routing.js";
3
4
  export * from "./evaluator.js";
4
5
  export * from "./cost.js";
5
6
  export * from "./confidence.js";
@@ -10,6 +11,7 @@ export * from "./tool-schema.js";
10
11
  export * from "./savings-model.js";
11
12
  export * from "./theo-coverage.js";
12
13
  export * from "./savings-ledger.js";
14
+ export * from "./workflow-sessions.js";
13
15
  export * from "./quote-report.js";
14
16
  export * from "./traffic.js";
15
17
  export * from "./triage.js";
@@ -24,3 +26,11 @@ export * from "./stripe-sink.js";
24
26
  export * from "./geo-visibility.js";
25
27
  export * from "./output-diagnostics.js";
26
28
  export * from "./stripe-billing.js";
29
+ export * from "./budget.js";
30
+ export * from "./security/index.js";
31
+ export * from "./accounts.js";
32
+ export * from "./account-store.js";
33
+ export * from "./ledger-store.js";
34
+ export * from "./github-oauth.js";
35
+ export * from "./stripe-client.js";
36
+ export * from "./billing-worker.js";
@@ -0,0 +1,62 @@
1
+ import { type LedgerRecord } from "./savings-ledger.js";
2
+ /**
3
+ * Server-side ledger storage with chain-verification-on-ingest.
4
+ *
5
+ * The proxy/SDK mirrors each hash-chained record it writes locally to the Mesh
6
+ * API; this is where the API stores it, per account, in an append-only JSONL
7
+ * spool. The one rule that makes "recompute it yourself" a guarantee rather
8
+ * than a promise: a record is stored ONLY if it is self-consistent AND
9
+ * continues the account's existing chain. A perturbed, forked, or gapped batch
10
+ * is a hard reject — it is never partially stored and never silently repaired.
11
+ *
12
+ * The mirror is fire-and-forget with retry, so the same records arrive more
13
+ * than once. Ingestion is therefore idempotent: records at or below the stored
14
+ * tail are recognised as replays and skipped (with a fork check against the
15
+ * tail), and only the genuine continuation is appended.
16
+ */
17
+ /** The last stored record's position, all the store needs to extend the chain. */
18
+ export type LedgerTail = {
19
+ seq: number;
20
+ eventHash: string;
21
+ };
22
+ export type IngestVerification = {
23
+ ok: true;
24
+ /** Records beyond the current tail that should be appended, in order. */
25
+ newRecords: LedgerRecord[];
26
+ /** Leading records recognised as already-stored replays. */
27
+ skipped: number;
28
+ /** The tail after appending newRecords. */
29
+ tail: LedgerTail;
30
+ } | {
31
+ ok: false;
32
+ reason: string;
33
+ seq: number;
34
+ };
35
+ /**
36
+ * Verify that `records` form a valid continuation of `tail` (undefined = empty
37
+ * chain, starting at genesis). Pure: no I/O, so the whole accept/replay/reject
38
+ * decision is unit-testable. Allows a leading overlap of already-stored
39
+ * sequences (idempotent retries) and rejects any gap, fork, or tampered hash.
40
+ */
41
+ export declare function verifyIngestBatch(tail: LedgerTail | undefined, records: readonly LedgerRecord[]): IngestVerification;
42
+ export type LedgerIngestResult = {
43
+ ok: true;
44
+ stored: number;
45
+ skipped: number;
46
+ tailSeq: number;
47
+ } | {
48
+ ok: false;
49
+ reason: string;
50
+ seq: number;
51
+ };
52
+ export interface LedgerStore {
53
+ append(accountId: string, records: readonly LedgerRecord[]): LedgerIngestResult;
54
+ readRecords(accountId: string): LedgerRecord[];
55
+ tail(accountId: string): LedgerTail | undefined;
56
+ }
57
+ /**
58
+ * File-backed ledger store: one append-only JSONL spool per account under
59
+ * `<dir>/<accountId>.jsonl`. Tails are cached in memory and lazily resumed from
60
+ * the spool, so a server restart picks the chain up where it left off.
61
+ */
62
+ export declare function openFileLedgerStore(dir: string): LedgerStore;