import { Q as HexString, F as FiberRpcClient, n as ChannelState } from './resolve-B7MJYzSy.js'; export { A as AUTH_TAG_LENGTH, a as AbandonChannelParams, b as AcceptChannelParams, c as AcceptChannelResult, d as Attribute, B as BuildRouterParams, e as BuildRouterResult, f as CancelInvoiceParams, g as CancelInvoiceResult, h as CchInvoice, i as CchOrderStatus, j as CellDep, k as CellOutput, l as Channel, m as ChannelId, o as ChannelStateFlags, p as ChannelUpdateInfo, q as CkbInvoice, r as CkbInvoiceStatus, s as CkbTransaction, t as ConnectPeerParams, u as ConnectPeerResult, C as Currency, D as DEFAULT_CKB_ASSET, v as DisconnectPeerParams, E as ENCRYPTED_MAGIC, w as FiberRpcError, x as FormattedChannelBalances, G as GetInvoiceParams, y as GetInvoiceResult, z as GetPaymentParams, H as GetPaymentResult, I as GraphChannelInfo, J as GraphChannelsParams, K as GraphChannelsResult, L as GraphNodeInfo, M as GraphNodesParams, N as GraphNodesResult, O as Hash256, P as HashAlgorithm, R as HopHint, S as HopRequire, T as Htlc, U as IFiberClient, V as IV_LENGTH, W as InvoiceData, X as InvoiceSignature, Y as JsonRpcError, Z as JsonRpcRequest, _ as JsonRpcResponse, $ as KEY_LENGTH, a0 as ListChannelsParams, a1 as ListChannelsResult, a2 as ListPaymentsParams, a3 as ListPaymentsResult, a4 as ListPeersResult, a5 as Multiaddr, a6 as NewInvoiceParams, a7 as NewInvoiceResult, a8 as NodeInfo, a9 as NodeInfoResult, aa as OpenChannelParams, ab as OpenChannelResult, ac as OpenChannelWithExternalFundingParams, ad as OpenChannelWithExternalFundingResult, ae as OutPoint, af as ParseInvoiceParams, ag as ParseInvoiceResult, ah as PaymentCustomRecords, ai as PaymentHash, aj as PaymentInfo, ak as PaymentStatus, al as PeerId, am as PeerInfo, an as Privkey, ao as Pubkey, ap as RemoveTlcReason, aq as ResolveUdtAssetOptions, ar as RevocationData, as as RouterHop, at as SALT_LENGTH, au as SCRYPT_N, av as SCRYPT_P, aw as SCRYPT_R, ax as Script, ay as SendPaymentParams, az as SendPaymentResult, aA as SendPaymentWithRouterParams, aB as SessionRoute, aC as SessionRouteNode, aD as SettleInvoiceParams, aE as SettlementData, aF as SettlementTlc, aG as ShutdownChannelParams, aH as SubmitSignedFundingTxParams, aI as SubmitSignedFundingTxResult, aJ as TLCId, aK as TlcStatus, aL as TransportType, aM as UdtArgInfo, aN as UdtAsset, aO as UdtCellDep, aP as UdtCfgInfos, aQ as UdtDep, aR as UdtScript, aS as UdtTypeScript, aT as UpdateChannelParams, aU as areUdtTypeScriptsEqual, aV as buildMultiaddr, aW as buildMultiaddrFromNodeId, aX as buildMultiaddrFromRpcUrl, aY as ckbHash, aZ as ckbToShannons, a_ as decryptKey, a$ as derivePublicKey, b0 as ensureHexPrefix, b1 as formatAssetName, b2 as formatChannelBalances, b3 as fromHex, b4 as generatePreimage, b5 as generatePrivateKey, b6 as hashPreimage, b7 as isEncryptedKey, b8 as nodeIdToPeerId, b9 as normalizeChannel, ba as normalizeChannelStateName, bb as parseFundingAmount, bc as parsePaymentAmount, bd as parseUdtTypeScript, be as randomBytes32, bf as resolveUdtAsset, bg as scriptToAddress, bh as serializeUdtTypeScript, bi as sha256Hash, bj as shannonsToCkb, bk as toHex, bl as validateUdtTypeScript, bm as verifyPreimageHash } from './resolve-B7MJYzSy.js'; import { z } from 'zod'; /** * Security Policy Types * Configuration for AI agent spending limits and guardrails */ declare const SpendingLimitSchema: z.ZodObject<{ maxPerTransaction: z.ZodString; maxPerWindow: z.ZodString; windowSeconds: z.ZodNumber; currentSpent: z.ZodOptional; windowStart: z.ZodOptional; }, z.core.$strip>; type SpendingLimit = z.infer; declare const RecipientPolicySchema: z.ZodObject<{ allowlist: z.ZodOptional>; blocklist: z.ZodOptional>; allowUnknown: z.ZodDefault; }, z.core.$strip>; type RecipientPolicy = z.infer; declare const RateLimitSchema: z.ZodObject<{ maxTransactions: z.ZodNumber; windowSeconds: z.ZodNumber; cooldownSeconds: z.ZodDefault; currentCount: z.ZodOptional; windowStart: z.ZodOptional; lastTransaction: z.ZodOptional; }, z.core.$strip>; type RateLimit = z.infer; declare const ChannelPolicySchema: z.ZodObject<{ allowOpen: z.ZodDefault; allowClose: z.ZodDefault; allowForceClose: z.ZodDefault; maxFundingAmount: z.ZodOptional; minFundingAmount: z.ZodOptional; maxChannels: z.ZodOptional; }, z.core.$strip>; type ChannelPolicy = z.infer; declare const SecurityPolicySchema: z.ZodObject<{ name: z.ZodString; version: z.ZodDefault; enabled: z.ZodDefault; spending: z.ZodOptional; windowStart: z.ZodOptional; }, z.core.$strip>>; recipients: z.ZodOptional>; blocklist: z.ZodOptional>; allowUnknown: z.ZodDefault; }, z.core.$strip>>; rateLimit: z.ZodOptional; currentCount: z.ZodOptional; windowStart: z.ZodOptional; lastTransaction: z.ZodOptional; }, z.core.$strip>>; channels: z.ZodOptional; allowClose: z.ZodDefault; allowForceClose: z.ZodDefault; maxFundingAmount: z.ZodOptional; minFundingAmount: z.ZodOptional; maxChannels: z.ZodOptional; }, z.core.$strip>>; confirmationThreshold: z.ZodOptional; auditLogging: z.ZodDefault; metadata: z.ZodOptional>; }, z.core.$strip>; type SecurityPolicy = z.infer; type ViolationType = 'SPENDING_LIMIT_PER_TX' | 'SPENDING_LIMIT_PER_WINDOW' | 'RATE_LIMIT_EXCEEDED' | 'RATE_LIMIT_COOLDOWN' | 'RECIPIENT_NOT_ALLOWED' | 'RECIPIENT_BLOCKED' | 'CHANNEL_OPEN_NOT_ALLOWED' | 'CHANNEL_CLOSE_NOT_ALLOWED' | 'CHANNEL_FORCE_CLOSE_NOT_ALLOWED' | 'CHANNEL_FUNDING_EXCEEDS_MAX' | 'CHANNEL_FUNDING_BELOW_MIN' | 'MAX_CHANNELS_REACHED' | 'REQUIRES_CONFIRMATION'; interface PolicyViolation { type: ViolationType; message: string; details: { requested?: string; limit?: string; recipient?: string; remaining?: string; cooldownRemaining?: number; }; } interface PolicyCheckResult { allowed: boolean; violations: PolicyViolation[]; requiresConfirmation: boolean; } type AuditAction = 'PAYMENT_SENT' | 'PAYMENT_RECEIVED' | 'INVOICE_CREATED' | 'INVOICE_VALIDATED' | 'HOLD_INVOICE_CREATED' | 'HOLD_INVOICE_SETTLED' | 'CHANNEL_OPENED' | 'CHANNEL_CLOSED' | 'POLICY_VIOLATION' | 'POLICY_UPDATED' | 'NODE_STARTED' | 'NODE_STOPPED'; interface AuditLogEntry { timestamp: number; action: AuditAction; success: boolean; details: Record; policyViolations?: PolicyViolation[]; sessionId?: string; agentId?: string; } interface KeyConfig { /** Base directory for key storage */ baseDir: string; /** Password for key encryption (should come from secure source) */ encryptionPassword?: string; /** Whether to generate keys if they don't exist */ autoGenerate: boolean; } interface KeyInfo { /** Public key (hex) */ publicKey: HexString; /** Whether the key is encrypted */ encrypted: boolean; /** Key file path */ path: string; /** Key creation timestamp */ createdAt?: number; } interface AgentSession { /** Unique session ID */ sessionId: string; /** Agent identifier */ agentId: string; /** Session start time */ startedAt: number; /** Session expiry time */ expiresAt?: number; /** Session-specific policy overrides */ policyOverrides?: Partial; /** Session metadata */ metadata?: Record; } declare const DEFAULT_SECURITY_POLICY: SecurityPolicy; /** * Fund Management & Liquidity Analyzer * Analyzes channel health, identifies liquidity gaps, and provides funding recommendations */ /** * Channel health score breakdown */ interface ChannelHealthMetrics { channelId: string; pubkey: string; localBalanceCkb: number; remoteBalanceCkb: number; totalCapacityCkb: number; utilizationPercent: number; balanceRatioPercent: number; isBalanced: boolean; pendingLocalCkb: number; pendingRemoteCkb: number; availableToSendCkb: number; availableToReceiveCkb: number; healthScore: number; state: ChannelState; } interface LiquidityGap { amount: number; reason: string; severity: 'low' | 'medium' | 'high'; affectedChannels: string[]; } interface RebalanceRecommendation { from: string; to: string; amountCkb: number; reason: string; benefit: string; estimatedRoutingFeeCkb: number; priority: number; } interface FundingNeed { amount: number; reason: string; optimalChannelPubkey?: string; urgency: 'low' | 'normal' | 'high'; estimatedTimeToDepletion?: number; } interface LiquidityReport { timestamp: number; balance: { totalCkb: number; availableToSendCkb: number; availableToReceiveCkb: number; lockedInChannelsCkb: number; }; channels: { count: number; health: ChannelHealthMetrics[]; averageHealthScore: number; balancedCount: number; imbalancedCount: number; }; liquidity: { gaps: LiquidityGap[]; hasCriticalGaps: boolean; runway: { daysAtCurrentRate?: number; estimatedDailySpendCkb?: number; }; }; recommendations: { rebalances: RebalanceRecommendation[]; funding: FundingNeed[]; }; summary: string; } declare class LiquidityAnalyzer { private rpc; constructor(rpc: FiberRpcClient); /** * Comprehensive liquidity analysis */ analyzeLiquidity(): Promise; /** * Analyze individual channel health */ private analyzeChannelHealth; /** * Identify liquidity shortfalls and gaps */ private identifyLiquidityGaps; /** * Generate rebalance recommendations between channels */ private generateRebalanceRecommendations; /** * Estimate funding needs for future operations */ private estimateFundingNeeds; /** * Estimate runway (days until liquidity depleted at current spending rate) */ private estimateRunway; /** * Generate human-readable summary */ private generateSummary; /** * Get missing liquidity for a specific amount */ getMissingLiquidityForAmount(targetCkb: number): Promise<{ canSend: boolean; shortfallCkb: number; recommendation: string; }>; } /** * Biscuit policy helpers for Fiber RPC. * * These helpers model the upstream RPC authorization rules and generate * token-side permission facts like `read("peers");` and `write("payments");`. * * The RULES table mirrors fnn v0.9.0 `build_rules()` * (crates/fiber-lib/src/rpc/biscuit.rs @ v0.9.0, also documented in upstream * docs/biscuit-auth.md), with two deliberate omissions: * * - `subscribe_store_changes`: upstream requires `internal("store_changes")`, * a node-internal scope that user-minted tokens must not carry. * - `backup_now`: upstream registers the rule under the key `backup_now` * while the RPC method is named `backup`, so authenticated calls are * fail-closed regardless of token contents ("no rules for method"). * * Biscuit `read` and `write` do not imply each other, so * `collectBiscuitPermissions` by default also grants `read("cch")` whenever * `write("cch")` is collected: on fnn v0.9.0 a write-only cch token cannot * call `get_cch_order`, and on pre-v0.9.0 nodes `receive_btc` still requires * `read("cch")`. Pass `{ cchReadCompat: false }` to opt out. */ type BiscuitAction = 'read' | 'write'; interface BiscuitPermission { action: BiscuitAction; resource: string; } interface BiscuitMethodRule { permissions: BiscuitPermission[]; requiresChannelRight: boolean; } interface CollectBiscuitPermissionsOptions { /** * Also grant `read("cch")` whenever `write("cch")` is collected. * * Defaults to true so that cch-mutating tokens can still query their own * orders via `get_cch_order` (requires `read("cch")` on every fnn version) * and keep working for `receive_btc` on pre-v0.9.0 nodes. */ cchReadCompat?: boolean; } declare function getBiscuitRuleForMethod(method: string): BiscuitMethodRule | undefined; declare function collectBiscuitPermissions(methods: string[], options?: CollectBiscuitPermissionsOptions): BiscuitPermission[]; declare function renderBiscuitPermissionFacts(permissions: BiscuitPermission[]): string; declare function renderBiscuitFactsForMethods(methods: string[], options?: CollectBiscuitPermissionsOptions): string; declare function listSupportedBiscuitMethods(): string[]; /** * Policy Engine * Enforces spending limits, rate limits, and other security policies * This operates at the SDK level and cannot be bypassed via prompts */ declare class PolicyEngine { private policy; private auditLog; private spendingState; private rateLimitState; constructor(policy: SecurityPolicy); /** * Check if a payment is allowed by the policy */ checkPayment(params: { amount: string; recipient?: string; }): PolicyCheckResult; /** * Check if a channel operation is allowed */ checkChannelOperation(params: { operation: 'open' | 'close' | 'force_close'; fundingAmount?: string; currentChannelCount?: number; }): PolicyCheckResult; /** * Record a successful payment (updates spending and rate limit state) */ recordPayment(amount: string): void; /** * Add an entry to the audit log */ addAuditEntry(action: AuditAction, success: boolean, details: Record, violations?: PolicyViolation[]): void; /** * Get the audit log */ getAuditLog(options?: { limit?: number; since?: number; }): AuditLogEntry[]; /** * Get remaining spending allowance */ getRemainingAllowance(): { perTransaction: bigint; perWindow: bigint; }; /** * Update the policy */ updatePolicy(newPolicy: Partial): void; /** * Get the current policy */ getPolicy(): SecurityPolicy; private refreshSpendingWindow; private refreshRateLimitWindow; } /** * Invoice Verification Engine * Validates invoice legitimacy, format, cryptographic correctness, and peer connectivity * This ensures the agent only pays valid invoices */ /** * Invoice verification result */ interface InvoiceVerificationResult { /** Overall validity (true = safe to pay) */ valid: boolean; /** Invoice parsed details */ details: { paymentHash: string; amountCkb: number; expiresAt: number; description?: string; isExpired: boolean; }; /** Peer information */ peer: { nodeId?: string; isConnected: boolean; trustScore: number; }; /** Validation checks performed */ checks: { validFormat: boolean; notExpired: boolean; validAmount: boolean; peerConnected: boolean; }; /** Issues found */ issues: VerificationIssue[]; /** Recommendation for agent */ recommendation: 'proceed' | 'warn' | 'reject'; /** Human-readable reason for recommendation */ reason: string; } interface VerificationIssue { type: 'warning' | 'critical'; code: string; message: string; } declare class InvoiceVerifier { private rpc; constructor(rpc: FiberRpcClient); /** * Fully validate an invoice before payment */ verifyInvoice(invoiceString: string): Promise; /** * Quick format validation (regex-based, before RPC call) */ private validateInvoiceFormat; /** * Validate amount is positive and reasonable */ private validateAmount; /** * Check if invoice has expired */ private isInvoiceExpired; /** * Get expiry timestamp in milliseconds */ private getExpiryTimestamp; private getAttributeU64; private getDescription; /** * Try to extract payee node public key from invoice attributes * The payee public key is embedded in the invoice as a payee_public_key attribute. */ private extractNodeIdFromInvoice; /** * Calculate trust score (0-100) based on various factors */ private calculateTrustScore; } export { type AgentSession, type AuditAction, type AuditLogEntry, type BiscuitAction, type BiscuitMethodRule, type BiscuitPermission, type ChannelPolicy, ChannelPolicySchema, ChannelState, type CollectBiscuitPermissionsOptions, DEFAULT_SECURITY_POLICY, FiberRpcClient, HexString, type InvoiceVerificationResult, InvoiceVerifier, type KeyConfig, type KeyInfo, LiquidityAnalyzer, type LiquidityReport, type PolicyCheckResult, PolicyEngine, type PolicyViolation, type RateLimit, RateLimitSchema, type RecipientPolicy, RecipientPolicySchema, type SecurityPolicy, SecurityPolicySchema, type SpendingLimit, SpendingLimitSchema, type ViolationType, collectBiscuitPermissions, getBiscuitRuleForMethod, listSupportedBiscuitMethods, renderBiscuitFactsForMethods, renderBiscuitPermissionFacts };