usertrust
API Reference

Types

Core TypeScript types exported by usertrust.

All types are exported from the usertrust package entry point. The SDK uses TypeScript 5.9 strict mode with noUncheckedIndexedAccess and exactOptionalPropertyTypes.

Client Types

TrustOpts

Options passed to trust(). See trust() for full documentation.

interface TrustOpts {
  configPath?: string;
  proxy?: string;
  key?: string;
  budget?: number;
  tier?: string;
  dryRun?: boolean;
  vaultBase?: string;
}

TrustedClient<T>

The governed client returned by trust(). Same shape as the original LLM client plus destroy().

type TrustedClient<T> = T & { destroy(): Promise<void> };

TrustedResponse<T>

The return type of every intercepted LLM call.

interface TrustedResponse<T> {
  response: T;
  receipt: TrustReceipt;
}

TrustReceipt

Governance metadata returned with every LLM call. See trust() for field descriptions.

interface TrustReceipt {
  transferId: string;
  cost: number;
  /** Present only when the settle POST was capped at the reserved hold. */
  postedCost?: number;
  budgetRemaining: number;
  auditHash: string;
  chainPath: string;
  receiptUrl: string | null;
  settled: boolean;
  model: string;
  provider: string;
  timestamp: string;
  auditDegraded?: boolean;
  usageSource?: "provider" | "estimated";
  /** Four-tier disjoint token split. Present iff usageSource === "provider". */
  usage?: ReceiptUsage;
  chunksDelivered?: number;
  actionKind?: ActionKind;
  endpoint?: { class: EndpointClass; runtime: LocalRuntime };
  meter?: {
    costBasis: CostBasis;
    rateSource: RateSource;
    computeMs?: number;
  };
  /** The rate half of the reconciliation surface. Frozen; every LLM settle emits it. */
  pricing?: {
    /** The four resolved per-1k rates the cost was computed with. */
    appliedRates: AppliedRates;
    /** Date-stamped PRICING_TABLE version the rates came from. */
    tableVersion: string;
  };
  budget?: { costCenter: string; remaining: number; fraction?: number };
}

pricing is a root-level sibling of meter, not a member of it. That placement is deliberate: receipt.v1.schema.json declares meter with additionalProperties: false while leaving the receipt root open, so growing meter would make every v1 validator reject every receipt usertrust emits — and v1 is frozen. Adding at the root keeps v1 validators green and costs recomputability nothing.

pricing.appliedRates is frozen, and each record surface (the receipt, the llm_call chain event, a stream's pre-settle handle) gets its own copy. Mutating what you were handed cannot make the rates recorded in the audit chain diverge from the rates your cost was computed with.

ReceiptUsage

The four-tier disjoint token split a settle was metered from (spec D5). Present on TrustReceipt.usage and llm_call audit events only when usage was provider-reported — never zero-filled for an estimated settle.

interface ReceiptUsage {
  inputTokens: number;      // fresh (non-cached) prompt tokens
  outputTokens: number;     // completion tokens, incl. provider-billed thinking
  cacheReadTokens: number;  // cache-hit prompt tokens
  cacheWriteTokens: number; // cache-creation prompt tokens
}

AppliedRates

The four RESOLVED per-1k rates a settle was metered with — i.e. after the cache-rate fallback invariant, so an absent cache tier appears here as inputPer1k, never as undefined or 0. Together with ReceiptUsage this is the whole reconciliation surface: ceil(sum(counts × rates / 1000)), floored at 1, reproduces TrustReceipt.cost exactly, from the record alone.

interface AppliedRates {
  inputPer1k: number;
  outputPer1k: number;
  cacheReadPer1k: number;
  cacheWritePer1k: number;
}

TrustReceipt's other inline field types: ActionKind is "llm_call" | "tool_use" | "file_access" | "shell_command" | "api_request"; EndpointClass is "local" | "cloud"; LocalRuntime is "ollama" | "vllm" | "lmstudio" | "openai-compat" | "unknown"; CostBasis is "usd-proxy" | "nominal"; RateSource is "table" | "custom" | "local-model" | "local-default" | "fallback".

LLMClientKind

The three supported provider types, detected via duck typing.

type LLMClientKind = "anthropic" | "openai" | "google";

Config Types

TrustConfig

The full configuration schema. See Configuration for field-level documentation.

type TrustConfig = {
  budget: number;
  tier: "free" | "mini" | "pro" | "mega" | "ultra";
  proxy?: string;
  key?: string;
  policies: string;
  pii: "redact" | "warn" | "block" | "off";
  circuitBreaker: {
    failureThreshold: number;
    resetTimeout: number;
  };
  patterns: {
    enabled: boolean;
    feedProxy: boolean;
  };
  audit: {
    rotation: "daily" | "weekly" | "none";
    indexLimit: number;
  };
  tigerbeetle: {
    addresses: string[];
    clusterId: number;
  };
};

Policy Types

PolicyRule

A single policy rule evaluated by the gate engine.

interface PolicyRule {
  name: string;
  effect: PolicyEffect;
  enforcement: PolicyEnforcement;
  severity?: PolicySeverity;
  conditions: FieldCondition[];
}

FieldCondition

A single condition within a policy rule. Uses dot-notation field resolution and one of 12 operators.

interface FieldCondition {
  field: string;
  operator: FieldOperator;
  value?: unknown;
}

FieldOperator

The 12 field operators supported by the policy gate.

type FieldOperator =
  | "exists"
  | "not_exists"
  | "eq"
  | "neq"
  | "gt"
  | "gte"
  | "lt"
  | "lte"
  | "in"
  | "not_in"
  | "contains"
  | "regex";
OperatorDescriptionExample Value
existsField is present and not undefined(none)
not_existsField is absent or undefined(none)
eqStrict equality"gpt-4o"
neqNot equal"test"
gtGreater than (numeric)1000
gteGreater than or equal500
ltLess than (numeric)100
lteLess than or equal50
inValue is in the given array["gpt-4o", "gpt-4o-mini"]
not_inValue is not in the given array["deprecated-model"]
containsString contains substring"password"
regexMatches regular expression"^claude-.*"

PolicyEffect

type PolicyEffect = "deny" | "warn";
  • deny -- Block the request and throw a PolicyDeniedError.
  • warn -- Allow the request but attach a warning to the receipt.

PolicyEnforcement

type PolicyEnforcement = "hard" | "soft";
  • hard -- The rule is enforced strictly. A deny effect blocks the call.
  • soft -- The rule generates warnings but does not block.

PolicySeverity

type PolicySeverity = "critical" | "high" | "medium" | "low" | "info";

Severity level for policy rules.


Audit Types

AuditEvent

A single entry in the SHA-256 hash-chained audit log.

interface AuditEvent {
  id: string;                         // Unique event ID
  timestamp: string;                  // ISO 8601 timestamp
  previousHash: string;               // Hash of the previous event (or GENESIS_HASH)
  hash: string;                       // SHA-256 hash of this event
  kind: string;                       // Event type (e.g., "spend", "settlement_ambiguous")
  actor: string;                      // Actor identifier
  data: Record<string, unknown>;      // Event-specific payload
}

Each event's hash covers the previousHash, forming an append-only chain. The first event chains from GENESIS_HASH (64 zero characters). Tampering with any event breaks all subsequent hashes.


Streaming Types

GovernedStream<T>

An async iterable that wraps the native LLM stream, adding a receipt promise that resolves when the stream completes.

interface GovernedStream<T> extends AsyncIterable<T> {
  receipt: Promise<TrustReceipt>;
}

Usage:

const { response } = await client.messages.create({
  model: "claude-fable-5",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Hello" }],
  stream: true,
});

for await (const chunk of response) {
  // Process chunks as usual
}

// Governance receipt resolves after the stream finishes
const receipt = await response.receipt;

StreamUsage

Internal token accumulation from stream chunks — the four DISJOINT tiers of spec D2. inputTokens is fresh prompt tokens only: for providers whose prompt count is inclusive of the cache tiers (OpenAI, Gemini), the cached tokens are already subtracted back out by the extractors; for Anthropic, whose SDK counters are disjoint at the source, nothing is subtracted. Summing all four fields gives the billable total with nothing double-counted.

interface StreamUsage {
  inputTokens: number;
  outputTokens: number;
  cacheReadTokens: number;
  cacheWriteTokens: number;
}