/** * AgentCFO — spend control for AI agents making x402 payments. * * Wraps `fetch` and intercepts x402 (402 Payment Required) responses. * Before paying, checks policy → budget → decides. After paying, * logs to ledger → updates budget. Provides analytics on demand. * * Usage: * const agent = new AgentCFO({ * wallet: { pay: async (req) => paymentHeader }, * budget: { hourly: 5, daily: 50 }, * policy: { maxPerRequest: 2.00 }, * }); * const res = await agent.fetch('https://api.chaindata.xyz/v1/prices'); */ import { type BudgetLimits, type BudgetStatus } from './budget.js'; import { type LedgerEntry } from './ledger.js'; import { type PolicyRules } from './policy.js'; import { type SpendSummary } from './analytics.js'; import { type SyncConfig } from './sync.js'; import { AgentEvents, type AnomalyMode } from './events.js'; import { AnomalyDetector, type AnomalyDetectorConfig, type CostEstimate } from './anomaly.js'; import type { StorageAdapter } from './storage.js'; /** Structured result of the last payment decision. */ export interface LastDecision { /** Whether the payment was allowed. */ allowed: boolean; /** Which gate made the decision. */ gate: 'policy' | 'anomaly' | 'budget' | 'paid' | 'failed' | 'review'; /** Human-readable reason for the decision. */ reason: string; /** URL that was evaluated. */ url: string; /** Amount that was requested. */ amount: number; /** HTTP status code seen (402 for challenges). */ statusCodeSeen: number; /** ISO timestamp of the decision. */ timestamp: string; } /** x402 payment requirement from a 402 response. */ export interface X402PaymentRequirement { scheme: string; network: string; maxAmountRequired: string; resource: string; description: string; payTo: string; asset: string; } /** x402 challenge from a 402 response body. */ export interface X402Challenge { x402Version: number; accepts: X402PaymentRequirement[]; challengeId?: string; error?: string; } /** Wallet interface — implement this to connect to any payment provider. */ export interface AgentWallet { /** * Sign and submit payment for an x402 challenge. * Returns the value for the X-PAYMENT header. */ pay(params: { requirement: X402PaymentRequirement; challengeId?: string; }): Promise; } export interface AgentCFOConfig { /** Wallet that can sign x402 payments. */ wallet: AgentWallet; /** Budget limits. */ budget?: BudgetLimits; /** Cost policy rules. */ policy?: PolicyRules; /** Sync to hosted dashboard (paid feature). */ sync?: SyncConfig; /** Persistent storage adapter for ledger data. */ storage?: StorageAdapter; /** Budget warning threshold (0-1). Default: 0.8 (80%). */ warningThreshold?: number; /** Anomaly detection tuning. */ anomaly?: AnomalyDetectorConfig; /** * Anomaly detection mode. Default: 'enforce' * - 'enforce': anomalies block payment before it happens * - 'review': anomalies are flagged but payment proceeds * - 'off': no anomaly checking */ anomalyMode?: AnomalyMode; /** Custom fetch implementation (defaults to globalThis.fetch). */ fetchImpl?: typeof fetch; } export declare class AgentCFO { private wallet; private budget; private policy; private ledger; private analytics; private sync; private storage; private warningThreshold; private fetchImpl; private anomalyMode; /** Cumulative amount blocked by anomaly detection (proof metric). */ private _protectedSpend; /** Most recent payment decision — structured local signal for callers. */ private _lastDecision; /** Typed event emitter — subscribe to payment, budget, and anomaly events. */ events: AgentEvents; /** Statistical anomaly detector (EWMA + Welford's + z-score). */ private anomalyDetector; constructor(config: AgentCFOConfig); /** * Drop-in fetch replacement. Automatically handles x402 payment flows: * 1. Makes the initial request * 2. If 402 → parses challenge → checks policy → checks budget → pays → retries * 3. If not 402 → returns response as-is */ fetch(url: string | URL, init?: RequestInit): Promise; /** Get current budget status. */ spent(): BudgetStatus; /** Get spend analytics summary. */ summary(): SpendSummary; /** * Get the most recent payment decision. * Returns a structured object describing which gate decided, why, and for what URL/amount. * Use this to distinguish "server 402" from "locally blocked by policy/anomaly/budget". * Returns null before the first fetch() call. */ lastDecision(): LastDecision | null; /** Get the full audit ledger. */ audit(): readonly LedgerEntry[]; /** Export ledger as JSON. */ exportJSON(): string; /** Export ledger as CSV. */ exportCSV(): string; /** * Estimate the cost of calling a URL based on historical data. * Returns percentile-based statistics (p50, p75, p95, p99) using * Welford's online algorithm and circular buffer sampling. * Returns null if insufficient history exists. */ estimateCost(url: string): CostEstimate | null; /** * Get the full anomaly detector for advanced usage. * Exposes global estimates, per-host stats, and configuration. */ get detector(): AnomalyDetector; /** Stop dashboard sync and event handlers (call on agent shutdown). */ stop(): void; private extractHost; private checkBudgetWarnings; /** Get cumulative protected spend (amount blocked by anomaly + policy + budget). */ get protectedSpend(): number; private logPaid; private logDenied; private logFailed; } //# sourceMappingURL=controller.d.ts.map