@blockrun/clawrouter 0.11.13 → 0.12.0

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/dist/index.d.ts CHANGED
@@ -147,6 +147,7 @@ type RoutingDecision = {
147
147
  costEstimate: number;
148
148
  baselineCost: number;
149
149
  savings: number;
150
+ agenticScore?: number;
150
151
  };
151
152
  type TierConfig = {
152
153
  primary: string;
@@ -463,6 +464,48 @@ declare class BalanceMonitor {
463
464
  private buildInfo;
464
465
  }
465
466
 
467
+ /**
468
+ * Solana USDC Balance Monitor
469
+ *
470
+ * Checks USDC balance on Solana mainnet with caching.
471
+ * Absorbed from @blockrun/clawwallet's solana-adapter.ts (balance portion only).
472
+ */
473
+ type SolanaBalanceInfo = {
474
+ balance: bigint;
475
+ balanceUSD: string;
476
+ isLow: boolean;
477
+ isEmpty: boolean;
478
+ walletAddress: string;
479
+ };
480
+ /** Result from checkSufficient() */
481
+ type SolanaSufficiencyResult = {
482
+ sufficient: boolean;
483
+ info: SolanaBalanceInfo;
484
+ shortfall?: string;
485
+ };
486
+ declare class SolanaBalanceMonitor {
487
+ private readonly rpc;
488
+ private readonly walletAddress;
489
+ private cachedBalance;
490
+ private cachedAt;
491
+ constructor(walletAddress: string, rpcUrl?: string);
492
+ checkBalance(): Promise<SolanaBalanceInfo>;
493
+ deductEstimated(amountMicros: bigint): void;
494
+ invalidate(): void;
495
+ refresh(): Promise<SolanaBalanceInfo>;
496
+ /**
497
+ * Check if balance is sufficient for an estimated cost.
498
+ */
499
+ checkSufficient(estimatedCostMicros: bigint): Promise<SolanaSufficiencyResult>;
500
+ /**
501
+ * Format USDC amount (in micros) as "$X.XX".
502
+ */
503
+ formatUSDC(amountMicros: bigint): string;
504
+ getWalletAddress(): string;
505
+ private fetchBalance;
506
+ private buildInfo;
507
+ }
508
+
466
509
  /**
467
510
  * Session Persistence Store
468
511
  *
@@ -476,6 +519,9 @@ type SessionEntry = {
476
519
  createdAt: number;
477
520
  lastUsedAt: number;
478
521
  requestCount: number;
522
+ recentHashes: string[];
523
+ strikes: number;
524
+ escalated: boolean;
479
525
  };
480
526
  type SessionConfig = {
481
527
  /** Enable session persistence (default: false) */
@@ -529,6 +575,21 @@ declare class SessionStore {
529
575
  * Clean up expired sessions.
530
576
  */
531
577
  private cleanup;
578
+ /**
579
+ * Record a request content hash and detect repetitive patterns.
580
+ * Returns true if escalation should be triggered (3+ consecutive similar requests).
581
+ */
582
+ recordRequestHash(sessionId: string, hash: string): boolean;
583
+ /**
584
+ * Escalate session to next tier. Returns the new model/tier or null if already at max.
585
+ */
586
+ escalateSession(sessionId: string, tierConfigs: Record<string, {
587
+ primary: string;
588
+ fallback: string[];
589
+ }>): {
590
+ model: string;
591
+ tier: string;
592
+ } | null;
532
593
  /**
533
594
  * Stop the cleanup interval.
534
595
  */
@@ -538,6 +599,12 @@ declare class SessionStore {
538
599
  * Generate a session ID from request headers or create a default.
539
600
  */
540
601
  declare function getSessionId(headers: Record<string, string | string[] | undefined>, headerName?: string): string | undefined;
602
+ /**
603
+ * Generate a short hash fingerprint from request content.
604
+ * Captures: last user message text + tool call names (if any).
605
+ * Normalizes whitespace to avoid false negatives from minor formatting diffs.
606
+ */
607
+ declare function hashRequestContent(lastUserContent: string, toolCallNames?: string[]): string;
541
608
 
542
609
  /**
543
610
  * Local x402 Proxy Server
@@ -560,6 +627,9 @@ declare function getSessionId(headers: Record<string, string | string[] | undefi
560
627
  * - Usage logging: log every request as JSON line to ~/.openclaw/blockrun/logs/
561
628
  */
562
629
 
630
+ /** Union type for chain-agnostic balance monitoring */
631
+ type AnyBalanceMonitor = BalanceMonitor | SolanaBalanceMonitor;
632
+
563
633
  /**
564
634
  * Get the proxy port from pre-loaded configuration.
565
635
  * Port is validated at module load time, this just returns the cached value.
@@ -641,7 +711,7 @@ type ProxyHandle = {
641
711
  baseUrl: string;
642
712
  walletAddress: string;
643
713
  solanaAddress?: string;
644
- balanceMonitor: BalanceMonitor;
714
+ balanceMonitor: AnyBalanceMonitor;
645
715
  close: () => Promise<void>;
646
716
  };
647
717
  /**
@@ -690,6 +760,8 @@ type WalletResolution = {
690
760
  source: "saved" | "env" | "generated";
691
761
  mnemonic?: string;
692
762
  solanaPrivateKeyBytes?: Uint8Array;
763
+ /** Legacy (secp256k1) Solana key bytes, present when migration is needed. */
764
+ legacySolanaKeyBytes?: Uint8Array;
693
765
  };
694
766
  /**
695
767
  * Set up Solana wallet for existing EVM-only users.
@@ -765,6 +837,13 @@ type BlockRunModel = {
765
837
  vision?: boolean;
766
838
  /** Models optimized for agentic workflows (multi-step autonomous tasks) */
767
839
  agentic?: boolean;
840
+ /**
841
+ * Model supports OpenAI-compatible structured function/tool calling.
842
+ * Models without this flag output tool invocations as plain text JSON,
843
+ * which leaks raw {"command":"..."} into visible chat messages.
844
+ * Default: false (must opt-in to prevent silent regressions on new models).
845
+ */
846
+ toolCalling?: boolean;
768
847
  };
769
848
  declare const BLOCKRUN_MODELS: BlockRunModel[];
770
849
  /**
@@ -810,6 +889,8 @@ type UsageEntry = {
810
889
  baselineCost: number;
811
890
  savings: number;
812
891
  latencyMs: number;
892
+ /** Input (prompt) tokens reported by the provider */
893
+ inputTokens?: number;
813
894
  /** Partner service ID (e.g., "x_users_lookup") — only set for partner API calls */
814
895
  partnerId?: string;
815
896
  /** Partner service name (e.g., "AttentionVC") — only set for partner API calls */
@@ -854,34 +935,6 @@ declare class RequestDeduplicator {
854
935
  private prune;
855
936
  }
856
937
 
857
- /**
858
- * Solana USDC Balance Monitor
859
- *
860
- * Checks USDC balance on Solana mainnet with caching.
861
- * Absorbed from @blockrun/clawwallet's solana-adapter.ts (balance portion only).
862
- */
863
- type SolanaBalanceInfo = {
864
- balance: bigint;
865
- balanceUSD: string;
866
- isLow: boolean;
867
- isEmpty: boolean;
868
- walletAddress: string;
869
- };
870
- declare class SolanaBalanceMonitor {
871
- private readonly rpc;
872
- private readonly walletAddress;
873
- private cachedBalance;
874
- private cachedAt;
875
- constructor(walletAddress: string, rpcUrl?: string);
876
- checkBalance(): Promise<SolanaBalanceInfo>;
877
- deductEstimated(amountMicros: bigint): void;
878
- invalidate(): void;
879
- refresh(): Promise<SolanaBalanceInfo>;
880
- getWalletAddress(): string;
881
- private fetchBalance;
882
- private buildInfo;
883
- }
884
-
885
938
  /**
886
939
  * Spend Control - Time-windowed spending limits
887
940
  *
@@ -999,6 +1052,9 @@ declare function formatDuration(seconds: number): string;
999
1052
  *
1000
1053
  * BIP-39 mnemonic generation + BIP-44 HD key derivation for EVM and Solana.
1001
1054
  * Absorbed from @blockrun/clawwallet. No file I/O here - auth.ts handles persistence.
1055
+ *
1056
+ * Solana uses SLIP-10 Ed25519 derivation (Phantom/Solflare/Backpack compatible).
1057
+ * EVM uses standard BIP-32 secp256k1 derivation.
1002
1058
  */
1003
1059
  interface DerivedKeys {
1004
1060
  mnemonic: string;
@@ -1023,15 +1079,58 @@ declare function deriveEvmKey(mnemonic: string): {
1023
1079
  address: string;
1024
1080
  };
1025
1081
  /**
1026
- * Derive 32-byte Solana private key from a BIP-39 mnemonic.
1027
- * Path: m/44'/501'/0'/0' (standard Solana derivation)
1082
+ * Derive 32-byte Solana private key using SLIP-10 Ed25519 derivation.
1083
+ * Path: m/44'/501'/0'/0' (Phantom / Solflare / Backpack compatible)
1084
+ *
1085
+ * Algorithm (SLIP-0010 for Ed25519):
1086
+ * 1. Master: HMAC-SHA512(key="ed25519 seed", data=bip39_seed) → IL=key, IR=chainCode
1087
+ * 2. For each hardened child index:
1088
+ * HMAC-SHA512(key=chainCode, data=0x00 || key || ser32(index)) → split again
1089
+ * 3. Final IL (32 bytes) = Ed25519 private key seed
1028
1090
  */
1029
1091
  declare function deriveSolanaKeyBytes(mnemonic: string): Uint8Array;
1092
+ /**
1093
+ * Legacy Solana key derivation using secp256k1 BIP-32 (incorrect for Solana).
1094
+ * Kept for migration: sweeping funds from wallets derived with the old method.
1095
+ */
1096
+ declare function deriveSolanaKeyBytesLegacy(mnemonic: string): Uint8Array;
1030
1097
  /**
1031
1098
  * Derive both EVM and Solana keys from a single mnemonic.
1032
1099
  */
1033
1100
  declare function deriveAllKeys(mnemonic: string): DerivedKeys;
1034
1101
 
1102
+ /**
1103
+ * Solana Wallet Sweep — migrate USDC from legacy (secp256k1) to new (SLIP-10) wallet.
1104
+ *
1105
+ * Used when upgrading from the old BIP-32 secp256k1 derivation to correct
1106
+ * SLIP-10 Ed25519 derivation. Transfers all USDC from the old address to the new one.
1107
+ *
1108
+ * Uses raw instruction encoding to avoid @solana-program/token dependency.
1109
+ */
1110
+ type SweepResult = {
1111
+ transferred: string;
1112
+ transferredMicros: bigint;
1113
+ txSignature: string;
1114
+ oldAddress: string;
1115
+ newAddress: string;
1116
+ };
1117
+ type SweepError = {
1118
+ error: string;
1119
+ oldAddress: string;
1120
+ newAddress?: string;
1121
+ solBalance?: bigint;
1122
+ usdcBalance?: bigint;
1123
+ };
1124
+ /**
1125
+ * Sweep all USDC from old (legacy secp256k1) wallet to new (SLIP-10) wallet.
1126
+ *
1127
+ * @param oldKeyBytes - 32-byte private key from legacy derivation
1128
+ * @param newAddress - Solana address of the new (correct) wallet
1129
+ * @param rpcUrl - Optional RPC URL override
1130
+ * @returns SweepResult on success, SweepError on failure
1131
+ */
1132
+ declare function sweepSolanaWallet(oldKeyBytes: Uint8Array, newAddress: string, rpcUrl?: string): Promise<SweepResult | SweepError>;
1133
+
1035
1134
  /**
1036
1135
  * Typed Error Classes for ClawRouter
1037
1136
  *
@@ -1277,4 +1376,4 @@ declare function buildPartnerTools(proxyBaseUrl: string): PartnerToolDefinition[
1277
1376
 
1278
1377
  declare const plugin: OpenClawPluginDefinition;
1279
1378
 
1280
- export { type AggregatedStats, BALANCE_THRESHOLDS, BLOCKRUN_MODELS, type BalanceInfo, BalanceMonitor, type CachedLLMResponse, type CachedResponse, type CheckResult, DEFAULT_RETRY_CONFIG, DEFAULT_ROUTING_CONFIG, DEFAULT_SESSION_CONFIG, type DailyStats, type DerivedKeys, EmptyWalletError, FileSpendControlStorage, InMemorySpendControlStorage, InsufficientFundsError, type InsufficientFundsInfo, type LowBalanceInfo, MODEL_ALIASES, OPENCLAW_MODELS, PARTNER_SERVICES, type PartnerServiceDefinition, type PartnerToolDefinition, type PaymentChain, type ProxyHandle, type ProxyOptions, RequestDeduplicator, ResponseCache, type ResponseCacheConfig, type RetryConfig, type RoutingConfig, type RoutingDecision, RpcError, type SessionConfig, type SessionEntry, SessionStore, type SolanaBalanceInfo, SolanaBalanceMonitor, SpendControl, type SpendControlOptions, type SpendControlStorage, type SpendLimits, type SpendRecord, type SpendWindow, type SpendingStatus, type SufficiencyResult, type Tier, type UsageEntry, type WalletConfig, type WalletResolution, blockrunProvider, buildPartnerTools, buildProviderModels, calculateModelCost, plugin as default, deriveAllKeys, deriveEvmKey, deriveSolanaKeyBytes, fetchWithRetry, formatDuration, formatStatsAscii, generateWalletMnemonic, getAgenticModels, getFallbackChain, getFallbackChainFiltered, getModelContextWindow, getPartnerService, getProxyPort, getSessionId, getStats, isAgenticModel, isBalanceError, isEmptyWalletError, isInsufficientFundsError, isRetryable, isRpcError, isValidMnemonic, loadPaymentChain, logUsage, resolveModelAlias, resolvePaymentChain, route, savePaymentChain, setupSolana, startProxy };
1379
+ export { type AggregatedStats, BALANCE_THRESHOLDS, BLOCKRUN_MODELS, type BalanceInfo, BalanceMonitor, type CachedLLMResponse, type CachedResponse, type CheckResult, DEFAULT_RETRY_CONFIG, DEFAULT_ROUTING_CONFIG, DEFAULT_SESSION_CONFIG, type DailyStats, type DerivedKeys, EmptyWalletError, FileSpendControlStorage, InMemorySpendControlStorage, InsufficientFundsError, type InsufficientFundsInfo, type LowBalanceInfo, MODEL_ALIASES, OPENCLAW_MODELS, PARTNER_SERVICES, type PartnerServiceDefinition, type PartnerToolDefinition, type PaymentChain, type ProxyHandle, type ProxyOptions, RequestDeduplicator, ResponseCache, type ResponseCacheConfig, type RetryConfig, type RoutingConfig, type RoutingDecision, RpcError, type SessionConfig, type SessionEntry, SessionStore, type SolanaBalanceInfo, SolanaBalanceMonitor, SpendControl, type SpendControlOptions, type SpendControlStorage, type SpendLimits, type SpendRecord, type SpendWindow, type SpendingStatus, type SufficiencyResult, type SweepError, type SweepResult, type Tier, type UsageEntry, type WalletConfig, type WalletResolution, blockrunProvider, buildPartnerTools, buildProviderModels, calculateModelCost, plugin as default, deriveAllKeys, deriveEvmKey, deriveSolanaKeyBytes, deriveSolanaKeyBytesLegacy, fetchWithRetry, formatDuration, formatStatsAscii, generateWalletMnemonic, getAgenticModels, getFallbackChain, getFallbackChainFiltered, getModelContextWindow, getPartnerService, getProxyPort, getSessionId, getStats, hashRequestContent, isAgenticModel, isBalanceError, isEmptyWalletError, isInsufficientFundsError, isRetryable, isRpcError, isValidMnemonic, loadPaymentChain, logUsage, resolveModelAlias, resolvePaymentChain, route, savePaymentChain, setupSolana, startProxy, sweepSolanaWallet };