@blockrun/clawrouter 0.12.324 → 0.12.326
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/README.md +2 -1
- package/dist/cli.js +5 -5
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -5
- package/dist/router/index.js +1 -1
- package/package.json +2 -2
- package/skills/clawrouter/SKILL.md +1 -1
- package/src/top-models.json +1 -0
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __blockrun_createRequire } from 'node:module'; const require = __blockrun_createRequire(import.meta.url);
|
|
3
3
|
var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __esm=(fn,res,err)=>function(){if(err)throw err[0];try{return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res}catch(e7){throw err=[e7],e7}};var __commonJS=(cb,mod5)=>function(){try{return mod5||(0,cb[__getOwnPropNames(cb)[0]])((mod5={exports:{}}).exports,mod5),mod5.exports}catch(e7){throw mod5=0,e7}};var __export=(target,all4)=>{for(var name in all4)__defProp(target,name,{get:all4[name],enumerable:!0})},__copyProps=(to2,from28,except,desc)=>{if(from28&&typeof from28=="object"||typeof from28=="function")for(let key3 of __getOwnPropNames(from28))!__hasOwnProp.call(to2,key3)&&key3!==except&&__defProp(to2,key3,{get:()=>from28[key3],enumerable:!(desc=__getOwnPropDesc(from28,key3))||desc.enumerable});return to2};var __toESM=(mod5,isNodeMode,target)=>(target=mod5!=null?__create(__getProtoOf(mod5)):{},__copyProps(isNodeMode||!mod5||!mod5.__esModule?__defProp(target,"default",{value:mod5,enumerable:!0}):target,mod5)),__toCommonJS=mod5=>__copyProps(__defProp({},"__esModule",{value:!0}),mod5);var snapshot_v1_default,init_snapshot_v1=__esm({"node_modules/@blockrun/model-catalog/dist/snapshot.v1.json"(){snapshot_v1_default={catalog:{schema_version:1,catalog_version:"2026.11.12.2",observed_at:"2026-11-12T20:53:46.000Z",sources:{base:"https://blockrun.ai/api/v1/models?format=json",solana:"https://sol.blockrun.ai/api/v1/models?format=json"},models:[{id:"anthropic/claude-fable-5",name:"Claude Fable 5",provider:"anthropic",description:"Mythos-class tier above Opus, for the most demanding reasoning and long-horizon agentic work. 1M context, 128K output, always-on thinking",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:10,output:50,cache_read:1,cache_write:12.5},context_window:1e6,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:10,output:50},context_window:1e6,max_output:128e3}}},{id:"anthropic/claude-fable-5.1",name:"Claude Fable 5.1",provider:"anthropic",description:"Anthropic's most capable model \u2014 successor to Fable 5 in the same tier at the same price, for the most demanding reasoning and long-horizon agentic work. 1M context, 128K output, always-on thinking",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:10,output:50,cache_read:.25,cache_write:12.5},context_window:1e6,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:10,output:50},context_window:1e6,max_output:128e3}}},{id:"anthropic/claude-fable-5.2",name:"Claude Fable 5.2",provider:"anthropic",description:"Anthropic's most capable model \u2014 successor to Fable 5.1 at a lower price, for the most demanding reasoning and long-horizon agentic work. 1M context, 128K output, always-on thinking. Anthropic retains requests to this model for 30 days.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:8,output:40,cache_read:.2,cache_write:10},context_window:1e6,max_output:128e3},solana:{listed:!1,categories:[],billing_mode:"unavailable",pricing:{}}}},{id:"anthropic/claude-haiku-4.5",name:"Claude Haiku 4.5",provider:"anthropic",description:"Fastest and most efficient Claude, near-frontier intelligence",lifecycle:"active",declared_capabilities:["chat","coding","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:1,output:5,cache_read:.1,cache_write:1.25},context_window:2e5,max_output:64e3},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:1,output:5},context_window:2e5,max_output:64e3}}},{id:"anthropic/claude-opus-4.5",name:"Claude Opus 4.5",provider:"anthropic",description:"Claude Opus 4.5 \u2014 enhanced reasoning and creativity",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:5,output:25,cache_read:.5,cache_write:6.25},context_window:2e5,max_output:64e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:5,output:25},context_window:2e5,max_output:64e3}}},{id:"anthropic/claude-opus-4.7",name:"Claude Opus 4.7",provider:"anthropic",description:"Powerful Claude Opus for complex reasoning and agentic coding. 1M context, 128k output, adaptive thinking",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:5,output:25,cache_read:.5,cache_write:6.25},context_window:1e6,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:5,output:25},context_window:1e6,max_output:128e3}}},{id:"anthropic/claude-opus-4.8",name:"Claude Opus 4.8",provider:"anthropic",description:"Most capable Claude 4-series Opus for complex reasoning and agentic coding. 1M context, 128k output, adaptive thinking",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:5,output:25,cache_read:.5,cache_write:6.25},context_window:1e6,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:5,output:25},context_window:1e6,max_output:128e3}}},{id:"anthropic/claude-opus-5",name:"Claude Opus 5",provider:"anthropic",description:"Opus 5 \u2014 step-change over Opus 4.8 for deep reasoning and agentic coding at the same price. 1M context, 128k output, adaptive thinking",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:5,output:25,cache_read:.5,cache_write:6.25},context_window:1e6,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:5,output:25},context_window:1e6,max_output:128e3}}},{id:"anthropic/claude-opus-5.5",name:"Claude Opus 5.5",provider:"anthropic",description:"Newest Opus \u2014 Opus-class deep reasoning and agentic coding at a lower price than Opus 5. 1M context, 128k output, always-on adaptive thinking, vision",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:4,output:20,cache_read:.2,cache_write:5},context_window:1e6,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:4,output:20},context_window:1e6,max_output:128e3}}},{id:"anthropic/claude-sonnet-4.5",name:"Claude Sonnet 4.5",provider:"anthropic",description:"Sonnet 4.5 \u2014 strong coding and agentic performance, vision",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:3,output:15,cache_read:.3,cache_write:3.75},context_window:2e5,max_output:64e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:3,output:15},context_window:2e5,max_output:64e3}}},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",provider:"anthropic",description:"Sonnet 4.6 \u2014 a balance of intelligence, speed, and cost",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:3,output:15,cache_read:.3,cache_write:3.75},context_window:1e6,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:3,output:15},context_window:1e6,max_output:128e3}}},{id:"anthropic/claude-sonnet-5",name:"Claude Sonnet 5",provider:"anthropic",description:"Sonnet 5 \u2014 near-Opus coding/agentic quality at Sonnet cost. 1M context, 128k output, adaptive thinking, vision",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10,cache_read:.2,cache_write:2.5},context_window:1e6,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10},context_window:1e6,max_output:128e3}}},{id:"anthropic/claude-sonnet-5.5",name:"Claude Sonnet 5.5",provider:"anthropic",description:"Newest Sonnet \u2014 fast, capable everyday coding and agent work at Sonnet cost. 1M context, 128k output, adaptive thinking, vision",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10,cache_read:.2,cache_write:2.5},context_window:1e6,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10},context_window:1e6,max_output:128e3}}},{id:"azure/sora-2",name:"Sora 2",provider:"azure",description:"OpenAI Sora 2 via Azure AI Foundry \u2014 text-to-video AND image-to-video at 720p with synchronized audio. 4s default; 4, 8, or 12s. Portrait or landscape. Image-to-video takes a non-human reference image (human faces are rejected upstream \u2014 use Seedance + RealFace for real people). $0.10/sec.",lifecycle:"deprecated",declared_capabilities:["video"],aliases:[],redirects:[],networks:{base:{listed:!1,categories:["video"],billing_mode:"per_second",pricing:{per_second:.105,per_call_surcharge:0,transaction_fee:.001,default_duration_seconds:4,max_duration_seconds:12}},solana:{listed:!1,categories:[],billing_mode:"unavailable",pricing:{}}}},{id:"bytedance/seed-audio-1.0",name:"Seed Audio 1.0",provider:"bytedance",description:"ByteDance's Seed Audio 1.0 \u2014 prompt-directed audio creation: describe the voice, emotion, and sound staging in natural language. Up to 120s output, mp3/wav. Billed by audio duration ($0.003/second, estimated from input length).",lifecycle:"active",declared_capabilities:["speech","tts"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["speech","tts"],billing_mode:"per_character",pricing:{per_1k_chars:.315,transaction_fee:.001,max_input_chars:3e3,max_output_seconds:120}},solana:{listed:!0,categories:["speech","tts"],billing_mode:"per_character",pricing:{per_1k_chars:.315,max_input_chars:3e3}}}},{id:"bytedance/seedance-1.5-pro",name:"Seedance 1.5 Pro",provider:"bytedance",description:"ByteDance Seedance 1.5 Pro \u2014 budget text/image-to-video at 720p with synced audio, 5s default. Does NOT support RealFace assets.",lifecycle:"active",declared_capabilities:["video"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.070783146,per_call_surcharge:0,transaction_fee:.001,default_duration_seconds:5,max_duration_seconds:12}},solana:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.070783146,per_call_surcharge:0,default_duration_seconds:5,max_duration_seconds:12}}}},{id:"bytedance/seedance-2.0",name:"Seedance 2.0 Pro",provider:"bytedance",description:"ByteDance Seedance 2.0 Pro \u2014 premium quality text/image-to-video at 720p with synced audio, 5s default. Supports BytePlus RealFace assets \u2014 see /docs/video/real-person-ip for enrollment.",lifecycle:"active",declared_capabilities:["video"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.22709592675,per_call_surcharge:0,transaction_fee:.001,default_duration_seconds:5,max_duration_seconds:15}},solana:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.22709592675,per_call_surcharge:0,default_duration_seconds:5,max_duration_seconds:15}}}},{id:"bytedance/seedance-2.0-fast",name:"Seedance 2.0 Fast",provider:"bytedance",description:"ByteDance Seedance 2.0 Fast \u2014 fast video at 720p with synced audio, 5s default. ~60-80s to generate. Supports BytePlus RealFace assets \u2014 see /docs/video/real-person-ip for enrollment.",lifecycle:"active",declared_capabilities:["video"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.165160674,per_call_surcharge:0,transaction_fee:.001,default_duration_seconds:5,max_duration_seconds:15}},solana:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.165160674,per_call_surcharge:0,default_duration_seconds:5,max_duration_seconds:15}}}},{id:"bytedance/seedance-2.0-mini",name:"Seedance 2.0 Mini",provider:"bytedance",description:"ByteDance Seedance 2.0 Mini \u2014 720p video with synced audio at half the flagship rate, 5s default. 480p and 720p (no 1080p/4K). Supports BytePlus RealFace assets \u2014 see /docs/video/real-person-ip for enrollment.",lifecycle:"active",declared_capabilities:["video"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.07971075,per_call_surcharge:0,transaction_fee:.001,default_duration_seconds:5,max_duration_seconds:15}},solana:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.07971075,per_call_surcharge:0,default_duration_seconds:5,max_duration_seconds:15}}}},{id:"bytedance/seedance-2.5",name:"Seedance 2.5",provider:"bytedance",description:"ByteDance Seedance 2.5 \u2014 Long-form video up to 30s at 720p, with first/last-frame control, up to 30 reference images, and reference video/audio clips up to 30s each (billed per reference second). For 1080p or 4K use Seedance 2.0 Pro.",lifecycle:"active",declared_capabilities:["video"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.31557485925,per_call_surcharge:0,transaction_fee:.001,default_duration_seconds:5,max_duration_seconds:30}},solana:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.31557485925,per_call_surcharge:0,default_duration_seconds:5,max_duration_seconds:30}}}},{id:"bytedance/seedream-5-pro",name:"Seedream 5.0 Pro",provider:"bytedance",description:"ByteDance's Seedream 5.0 Pro \u2014 flagship image generation and editing, up to 4K-class resolution with reference-image support",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.04725,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.04725}}}},{id:"cohere/north-mini-code",name:"Cohere North Mini Code (Free)",provider:"cohere",description:"Cohere's North Mini Code, free. Compact coding model, 256K context, sub-second responses.",lifecycle:"active",declared_capabilities:["chat","coding"],aliases:[],redirects:[],networks:{base:{listed:!1,categories:["chat","coding"],billing_mode:"free",pricing:{input:0,output:0},context_window:256e3,max_output:16384},solana:{listed:!0,categories:["chat","coding"],billing_mode:"free",pricing:{input:0,output:0},context_window:256e3,max_output:16384}}},{id:"deepseek/deepseek-chat",name:"DeepSeek Chat (V4.1 Flash)",provider:"deepseek",description:"Compatibility id for DeepSeek V4.1 Flash in non-thinking mode ($0.14 in / $0.28 out) \u2014 same model, price and routing as deepseek/deepseek-v4.1-flash. Production-grade reliability and 5MB request bodies.",lifecycle:"active",declared_capabilities:["chat","coding","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.14,output:.28,cache_read:.006},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.14,output:.28,cache_read:.006,cache_read_schemes:["batch-settlement"]},context_window:1048576,max_output:65536}}},{id:"deepseek/deepseek-reasoner",name:"DeepSeek Reasoner (V4.1 Flash)",provider:"deepseek",description:"Compatibility id for DeepSeek V4.1 Flash in thinking mode for reasoning tasks ($0.14 in / $0.28 out). Same upstream as deepseek/deepseek-v4.1-flash but with thinking enabled by default.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.14,output:.28,cache_read:.006},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.14,output:.28,cache_read:.006,cache_read_schemes:["batch-settlement"]},context_window:1048576,max_output:65536}}},{id:"deepseek/deepseek-v4-flash-vision-exp",name:"DeepSeek V4 Flash Vision",provider:"deepseek",description:"DeepSeek V4 Flash Vision \u2014 1M context with text and image input. Experimental multimodal tier of the V4 Flash family.",lifecycle:"active",declared_capabilities:["chat","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","reasoning","vision"],billing_mode:"paid",pricing:{input:.3,output:1.2,cache_read:.006},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","reasoning","vision"],billing_mode:"paid",pricing:{input:.3,output:1.2,cache_read:.006,cache_read_schemes:["batch-settlement"]},context_window:1048576,max_output:65536}}},{id:"deepseek/deepseek-v4-pro",name:"DeepSeek V4 Pro",provider:"deepseek",description:"DeepSeek V4 flagship \u2014 1.6T MoE / 49B active, 1M context. Strongest open-weight reasoner. Thinking mode default.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.32,output:3.96,cache_read:.044},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.32,output:3.96,cache_read:.044,cache_read_schemes:["batch-settlement"]},context_window:1048576,max_output:65536}}},{id:"deepseek/deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",provider:"deepseek",description:"DeepSeek V4.1 Flash in non-thinking mode \u2014 1M context at $0.14 in / $0.28 out. Production-grade reliability and 5MB request bodies.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.14,output:.28,cache_read:.006},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.14,output:.28,cache_read:.006,cache_read_schemes:["batch-settlement"]},context_window:1048576,max_output:65536}}},{id:"elevenlabs/flash-v2.5",name:"ElevenLabs Flash v2.5",provider:"elevenlabs",description:"Ultra-low-latency (~75ms) speech synthesis for real-time voice agents. 32 languages.",lifecycle:"active",declared_capabilities:["speech","tts"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["speech","tts"],billing_mode:"per_character",pricing:{per_1k_chars:.0525,transaction_fee:.001,max_input_chars:4e4}},solana:{listed:!0,categories:["speech","tts"],billing_mode:"per_character",pricing:{per_1k_chars:.0525,max_input_chars:4e4}}}},{id:"elevenlabs/multilingual-v2",name:"ElevenLabs Multilingual v2",provider:"elevenlabs",description:"Highest-consistency voice for long-form narration, audiobooks, and voiceover. 29 languages.",lifecycle:"active",declared_capabilities:["speech","tts"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["speech","tts"],billing_mode:"per_character",pricing:{per_1k_chars:.105,transaction_fee:.001,max_input_chars:1e4}},solana:{listed:!0,categories:["speech","tts"],billing_mode:"per_character",pricing:{per_1k_chars:.105,max_input_chars:1e4}}}},{id:"elevenlabs/sound-effects",name:"ElevenLabs Sound Effects",provider:"elevenlabs",description:"Generate cinematic sound effects and audio textures from a text prompt (up to 22s).",lifecycle:"active",declared_capabilities:["sound_effect"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["sound_effect"],billing_mode:"per_generation",pricing:{per_generation:.0525,transaction_fee:.001,max_duration_seconds:22}},solana:{listed:!0,categories:["sound_effect"],billing_mode:"per_generation",pricing:{per_generation:.0525,max_duration_seconds:22}}}},{id:"elevenlabs/turbo-v2.5",name:"ElevenLabs Turbo v2.5",provider:"elevenlabs",description:"Balanced quality and latency (~250ms) for interactive use cases. 32 languages.",lifecycle:"active",declared_capabilities:["speech","tts"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["speech","tts"],billing_mode:"per_character",pricing:{per_1k_chars:.0525,transaction_fee:.001,max_input_chars:4e4}},solana:{listed:!0,categories:["speech","tts"],billing_mode:"per_character",pricing:{per_1k_chars:.0525,max_input_chars:4e4}}}},{id:"elevenlabs/v3",name:"ElevenLabs v3",provider:"elevenlabs",description:"Maximum expressiveness and emotional range for creative applications. 70+ languages.",lifecycle:"active",declared_capabilities:["speech","tts"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["speech","tts"],billing_mode:"per_character",pricing:{per_1k_chars:.105,transaction_fee:.001,max_input_chars:5e3}},solana:{listed:!0,categories:["speech","tts"],billing_mode:"per_character",pricing:{per_1k_chars:.105,max_input_chars:5e3}}}},{id:"google/gemini-2.5-flash",name:"Gemini 2.5 Flash",provider:"google",description:"Fast and efficient Gemini model with vision support",lifecycle:"active",declared_capabilities:["chat","coding","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.3,output:2.5,cache_read:.03},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.3,output:2.5},context_window:1048576,max_output:65536}}},{id:"google/gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",provider:"google",description:"Most economical Gemini model - ultra-fast and lightweight (requires new SDK)",lifecycle:"active",declared_capabilities:["chat","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat"],billing_mode:"paid",pricing:{input:.1,output:.4,cache_read:.01},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","vision"],billing_mode:"paid",pricing:{input:.1,output:.4},context_window:1048576,max_output:65536}}},{id:"google/gemini-2.5-pro",name:"Gemini 2.5 Pro",provider:"google",description:"Gemini 2.5 Pro \u2014 strong reasoning, coding, and mathematics",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.25,output:10,cache_read:.125,long_context:[{threshold:2e5,inclusive:!1,input:2.5,output:15,cache_read:.25}]},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.25,output:10,long_context:[{threshold:2e5,inclusive:!1,input:2.5,output:15}]},context_window:1048576,max_output:65536}}},{id:"google/gemini-3-flash-preview",name:"Gemini 3 Flash Preview",provider:"google",description:"Frontier-class performance with Pro-level intelligence at Flash speed and pricing. Includes thinking mode (requires new SDK)",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.5,output:3},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.5,output:3},context_window:1048576,max_output:65536}}},{id:"google/gemini-3.1-flash-lite",name:"Gemini 3.1 Flash Lite",provider:"google",description:"Ultra-fast and lightweight Gemini 3.1 model with thinking mode for high-throughput tasks",lifecycle:"active",declared_capabilities:["chat","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","reasoning"],billing_mode:"paid",pricing:{input:.25,output:1.5,cache_read:.025},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","reasoning"],billing_mode:"paid",pricing:{input:.25,output:1.5},context_window:1048576,max_output:65536}}},{id:"google/gemini-3.1-pro",name:"Gemini 3.1 Pro",provider:"google",description:"Gemini 3.1 Pro with improved thinking, token efficiency, and agentic capabilities. Optimized for software engineering (requires new SDK)",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:12,cache_read:.2,long_context:[{threshold:2e5,inclusive:!1,input:4,output:18,cache_read:.4}]},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:12,long_context:[{threshold:2e5,inclusive:!1,input:4,output:18}]},context_window:1048576,max_output:65536}}},{id:"google/gemini-3.5-flash",name:"Gemini 3.5 Flash",provider:"google",description:"Gemini 3.5 Flash with built-in thinking mode \u2014 frontier-class quality at Flash speed",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.5,output:9,cache_read:.15},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.5,output:9},context_window:1048576,max_output:65536}}},{id:"google/gemini-3.5-flash-lite",name:"Gemini 3.5 Flash Lite",provider:"google",description:"Latest Flash Lite \u2014 ultra-fast, lightweight Gemini with thinking mode for high-throughput tasks",lifecycle:"active",declared_capabilities:["chat","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","reasoning"],billing_mode:"paid",pricing:{input:.3,output:2.5,cache_read:.03},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","reasoning"],billing_mode:"paid",pricing:{input:.3,output:2.5},context_window:1048576,max_output:65536}}},{id:"google/gemini-3.6-flash",name:"Gemini 3.6 Flash",provider:"google",description:"Gemini 3.6 Flash with built-in thinking mode \u2014 frontier-class quality at Flash speed",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.75,output:3.75,cache_read:.075},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.75,output:3.75},context_window:1048576,max_output:65536}}},{id:"google/gemini-3.8-flash",name:"Gemini 3.8 Flash",provider:"google",description:"Newest-generation Flash with built-in thinking mode \u2014 frontier-class quality at Flash speed",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.75,output:3.75,cache_read:.075},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.75,output:3.75},context_window:1048576,max_output:65536}}},{id:"google/gemini-4-argon",name:"Gemini 4 Argon",provider:"google",description:"Google's efficient Gemini 4 model: Gemini 4 intelligence with faster responses and fewer tokens per turn than Carbon",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10,cache_read:.1},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10},context_window:1048576,max_output:65536}}},{id:"google/gemini-4-carbon",name:"Gemini 4 Carbon",provider:"google",description:"Google's most capable reasoning model, built for complex software engineering, deep math and science, and long autonomous agent work",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10,cache_read:.1},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10},context_window:1048576,max_output:65536}}},{id:"google/nano-banana",name:"Nano Banana",provider:"google",description:"Google's Gemini 2.5 Flash image generation - fast and efficient",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.0525,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.0525}}}},{id:"google/nano-banana-2",name:"Nano Banana 2",provider:"google",description:"Google's Gemini 3.1 Flash image generation - pro-level quality at Flash speed",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.0945,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.0945}}}},{id:"google/nano-banana-pro",name:"Nano Banana Pro",provider:"google",description:"Google's Gemini 3 Pro image generation - highest quality up to 4K",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.105,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.105}}}},{id:"meta/muse-spark-1.3",name:"Muse Spark 1.3",provider:"meta",description:"Meta's Muse Spark 1.3, Meta's current general model. 1M context, image + text input, tool calling, always reasons (reasoning_effort minimal to max).",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!1,categories:[],billing_mode:"unavailable",pricing:{}},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.25,output:4.25},context_window:1048576,max_output:131072}}},{id:"meta/muse-wonder-1.0",name:"Muse Wonder 1.0",provider:"meta",description:"Meta's Muse Wonder 1.0 (preview), Meta's frontier model for agents and coding. 1M context, image + text input, tool calling, always reasons (reasoning_effort minimal to max).",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!1,categories:[],billing_mode:"unavailable",pricing:{}},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:4,output:20},context_window:1048576,max_output:131072}}},{id:"minimax/minimax-m2.7",name:"MiniMax M2.7",provider:"minimax",description:"MiniMax's M2.7 reasoning model with recursive self-improvement. Great value for complex tasks (~60 tps)",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:.3,output:1.2},context_window:204800,max_output:16384},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:.3,output:1.2},context_window:204800,max_output:16384}}},{id:"minimax/minimax-m3",name:"MiniMax M3",provider:"minimax",description:"MiniMax's M3 flagship \u2014 1M context, strong reasoning + coding.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:.3,output:1.2},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:.3,output:1.2},context_window:1048576,max_output:65536}}},{id:"minimax/music-2.5+",name:"MiniMax Music 2.5+",provider:"minimax",description:"MiniMax's flagship music generation model. Supports lyrics, instrumental, and style prompts. ~3 min output.",lifecycle:"active",declared_capabilities:["music"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["music"],billing_mode:"per_track",pricing:{per_track:.199,transaction_fee:.001}},solana:{listed:!0,categories:["music"],billing_mode:"per_track",pricing:{per_track:.2}}}},{id:"mistral/mistral-large-4",name:"Mistral Large 4",provider:"mistral",description:"Mistral's flagship \u2014 multimodal reasoning model for coding and agentic work. 512K context, image input.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.36,output:4.18},context_window:524288,max_output:262144},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.36,output:4.18},context_window:524288,max_output:262144}}},{id:"moonshot/kimi-k3",name:"Kimi K3",provider:"moonshot",description:"Moonshot's flagship \u2014 a 2.8-trillion-parameter open MoE with 1M context, image + text input, returning reasoning_content. Live-verified 2026-07-17 (chat, tools, vision).",lifecycle:"deprecated",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!1,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:3,output:15,cache_read:.3},context_window:1048576,max_output:65536},solana:{listed:!1,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:3,output:15},context_window:1048576,max_output:65536}}},{id:"moonshot/kimi-k3.1-pro",name:"Kimi K3.1 Pro",provider:"moonshot",description:"Moonshot's flagship \u2014 post-trained successor to Kimi K3 for long-horizon coding and agents. 1M context, image + text input, returns reasoning_content.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10,cache_read:.2},context_window:1048576,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10},context_window:1048576,max_output:65536}}},{id:"nvidia/llama-3.2-11b-vision",name:"Llama 3.2 11B Vision (Free)",provider:"nvidia",description:"Meta's Llama 3.2 11B Vision hosted free by NVIDIA. Accepts images; 128K context.",lifecycle:"deprecated",declared_capabilities:["chat","vision"],aliases:[],redirects:[],networks:{base:{listed:!1,categories:["chat","vision"],billing_mode:"free",pricing:{input:0,output:0},context_window:128e3,max_output:16384},solana:{listed:!1,categories:["chat","vision"],billing_mode:"free",pricing:{input:0,output:0},context_window:128e3,max_output:16384}}},{id:"nvidia/minimax-m3.1-flash",name:"MiniMax M3.1 Flash (Free)",provider:"nvidia",description:"MiniMax's M3.1 Flash hosted free by NVIDIA. Reasons before it answers, calls tools, and takes a 1M context, usually in a few seconds.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!1,categories:["chat","coding","reasoning"],billing_mode:"free",pricing:{input:0,output:0},context_window:1048576,max_output:16384},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"free",pricing:{input:0,output:0},context_window:1048576,max_output:16384}}},{id:"nvidia/muse-glimmer-30b",name:"Muse Glimmer 30B (Free)",provider:"nvidia",description:"Meta's Muse Glimmer 30B \u2014 Apache 2.0, 29.6B dense, hosted free by NVIDIA. Meta's open line after Llama.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!1,categories:["chat","coding","reasoning"],billing_mode:"free",pricing:{input:0,output:0},context_window:131072,max_output:16384},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"free",pricing:{input:0,output:0},context_window:131072,max_output:16384}}},{id:"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning",name:"Nemotron 3 Nano Omni (Free)",provider:"nvidia",description:"NVIDIA's multimodal reasoning Nemotron Nano Omni, free. 31B / 3.2B active MoE. Accepts text, images, video, audio. ChartQA 90.3, DocVQA 95.6, MMMU 70.8 \u2014 the only free model in our catalog that takes video and audio as well as images",lifecycle:"active",declared_capabilities:["chat","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!1,categories:["chat","reasoning","vision"],billing_mode:"free",pricing:{input:0,output:0},context_window:256e3,max_output:16384},solana:{listed:!0,categories:["chat","reasoning","vision"],billing_mode:"free",pricing:{input:0,output:0},context_window:256e3,max_output:16384}}},{id:"nvidia/nemotron-3-super-120b",name:"Nemotron 3.5 Super 120B (Free)",provider:"nvidia",description:"NVIDIA Nemotron 3.5 Super VL: MoE model (12B active params) with thinking mode. Reads images, fast and capable reasoning",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"free",pricing:{input:0,output:0},context_window:131072,max_output:16384},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"free",pricing:{input:0,output:0},context_window:131072,max_output:16384}}},{id:"nvidia/nemotron-3-ultra-550b",name:"Nemotron 3 Ultra 550B (Free)",provider:"nvidia",description:"NVIDIA Nemotron 3 Ultra 550B-A55B, free. 550B total / 55B active MoE with a 1M-token context \u2014 the largest free model in the catalog.",lifecycle:"active",declared_capabilities:["chat","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","reasoning"],billing_mode:"free",pricing:{input:0,output:0},context_window:1e6,max_output:16384},solana:{listed:!0,categories:["chat","reasoning"],billing_mode:"free",pricing:{input:0,output:0},context_window:1e6,max_output:16384}}},{id:"nvidia/nemotron-3.5-bolt",name:"Nemotron 3.5 Bolt (Free)",provider:"nvidia",description:"NVIDIA's small, fast Nemotron 3.5 hosted free by NVIDIA. Answers in about a second, reads images and calls tools; no thinking pass. 131K context",lifecycle:"active",declared_capabilities:["chat","coding","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","vision"],billing_mode:"free",pricing:{input:0,output:0},context_window:131072,max_output:16384},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"free",pricing:{input:0,output:0},context_window:131072,max_output:16384}}},{id:"nvidia/nemotron-3.5-lightning",name:"Nemotron 3.5 Lightning (Free)",provider:"nvidia",description:"NVIDIA Nemotron 3.5 Lightning 30B-A3B, free. Thinking-mode reasoning with a 1M-token context.",lifecycle:"active",declared_capabilities:["chat","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","reasoning"],billing_mode:"free",pricing:{input:0,output:0},context_window:1e6,max_output:16384},solana:{listed:!0,categories:["chat","reasoning"],billing_mode:"free",pricing:{input:0,output:0},context_window:1e6,max_output:16384}}},{id:"openai/chat-latest",name:"ChatGPT Instant (GPT-5.5)",provider:"openai",description:"ChatGPT's default model \u2014 the rolling `chat-latest` alias, currently GPT-5.5 Instant. Tuned for speed and concision, same price as GPT-5.5",lifecycle:"active",declared_capabilities:["chat","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","vision"],billing_mode:"paid",pricing:{input:5,output:30,cache_read:.5},context_window:128e3,max_output:128e3},solana:{listed:!0,categories:["chat","vision"],billing_mode:"paid",pricing:{input:5,output:30},context_window:128e3,max_output:128e3}}},{id:"openai/gpt-4.1",name:"GPT-4.1",provider:"openai",description:"Latest GPT-4 generation model",lifecycle:"active",declared_capabilities:["chat","coding","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:2,output:8,cache_read:.5},context_window:128e3,max_output:32768},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:2,output:8},context_window:128e3,max_output:32768}}},{id:"openai/gpt-4.1-mini",name:"GPT-4.1 Mini",provider:"openai",description:"Fast and affordable GPT-4.1 model",lifecycle:"active",declared_capabilities:["chat","coding","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding"],billing_mode:"paid",pricing:{input:.4,output:1.6,cache_read:.1},context_window:128e3,max_output:32768},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.4,output:1.6},context_window:128e3,max_output:32768}}},{id:"openai/gpt-4.1-nano",name:"GPT-4.1 Nano",provider:"openai",description:"Ultra-fast and cost-effective GPT-4.1",lifecycle:"deprecated",declared_capabilities:["chat","vision"],aliases:[],redirects:[],networks:{base:{listed:!1,categories:["chat"],billing_mode:"paid",pricing:{input:.1,output:.4,cache_read:.025},context_window:128e3,max_output:32768},solana:{listed:!1,categories:["chat","vision"],billing_mode:"paid",pricing:{input:.1,output:.4},context_window:128e3,max_output:32768}}},{id:"openai/gpt-4o",name:"GPT-4o",provider:"openai",description:"Multimodal model with vision and audio",lifecycle:"active",declared_capabilities:["chat","coding","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:2.5,output:10,cache_read:1.25},context_window:128e3,max_output:16384},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:2.5,output:10},context_window:128e3,max_output:16384}}},{id:"openai/gpt-4o-mini",name:"GPT-4o Mini",provider:"openai",description:"Fast and affordable GPT-4o model",lifecycle:"active",declared_capabilities:["chat","coding","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding"],billing_mode:"paid",pricing:{input:.15,output:.6,cache_read:.075},context_window:128e3,max_output:16384},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.15,output:.6},context_window:128e3,max_output:16384}}},{id:"openai/gpt-5-mini",name:"GPT-5 Mini",provider:"openai",description:"Cost-optimized reasoning and chat",lifecycle:"active",declared_capabilities:["chat","coding","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding"],billing_mode:"paid",pricing:{input:.25,output:2,cache_read:.025},context_window:2e5,max_output:128e3},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.25,output:2},context_window:2e5,max_output:128e3}}},{id:"openai/gpt-5.1",name:"GPT-5.1",provider:"openai",description:"Frontier model with 400K context and configurable reasoning effort",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.25,output:10,cache_read:.125},context_window:4e5,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.25,output:10},context_window:4e5,max_output:128e3}}},{id:"openai/gpt-5.2",name:"GPT-5.2",provider:"openai",description:"Frontier model with 400K context and adaptive reasoning",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.75,output:14,cache_read:.175},context_window:4e5,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.75,output:14},context_window:4e5,max_output:128e3}}},{id:"openai/gpt-5.2-pro",name:"GPT-5.2 Pro",provider:"openai",description:"Uses more compute for consistently better answers",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:21,output:168},context_window:4e5,max_output:128e3},solana:{listed:!0,categories:["coding","reasoning"],billing_mode:"paid",pricing:{input:21,output:168},context_window:4e5,max_output:128e3}}},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",provider:"openai",description:"Industry-leading agentic coding model. 400K context, reasoning, tool use, and complex execution",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.75,output:14,cache_read:.175},context_window:4e5,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.75,output:14},context_window:4e5,max_output:128e3}}},{id:"openai/gpt-5.4",name:"GPT-5.4",provider:"openai",description:"GPT-5.4 frontier model with 1M context, native computer use, and thinking mode",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2.5,output:15,cache_read:.25,long_context:[{threshold:272e3,inclusive:!1,input:5,output:22.5,cache_read:.5}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2.5,output:15,long_context:[{threshold:272e3,inclusive:!1,input:5,output:22.5}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-5.4-mini",name:"GPT-5.4 Mini",provider:"openai",description:"Strongest mini model for coding, computer use, and subagents with GPT-5.4 capabilities",lifecycle:"active",declared_capabilities:["chat","coding","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.75,output:4.5,cache_read:.075},context_window:4e5,max_output:128e3},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.75,output:4.5},context_window:4e5,max_output:128e3}}},{id:"openai/gpt-5.4-nano",name:"GPT-5.4 Nano",provider:"openai",description:"Fastest and most affordable GPT-5.4 model for high-throughput tasks",lifecycle:"active",declared_capabilities:["chat","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat"],billing_mode:"paid",pricing:{input:.2,output:1.25,cache_read:.02},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","vision"],billing_mode:"paid",pricing:{input:.2,output:1.25},context_window:4e5,max_output:128e3}}},{id:"openai/gpt-5.4-pro",name:"GPT-5.4 Pro",provider:"openai",description:"Premium GPT-5.4 with maximum compute for the hardest problems",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:30,output:180,long_context:[{threshold:272e3,inclusive:!1,input:60,output:270}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["coding","reasoning"],billing_mode:"paid",pricing:{input:30,output:180,long_context:[{threshold:272e3,inclusive:!1,input:60,output:270}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-5.5",name:"GPT-5.5",provider:"openai",description:"First fully retrained base since GPT-4.5. 1M context, 128K output, native agent + computer use",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:5,output:30,cache_read:.5,long_context:[{threshold:272e3,inclusive:!1,input:10,output:45,cache_read:1}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:5,output:30,long_context:[{threshold:272e3,inclusive:!1,input:10,output:45}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-5.5-pro",name:"GPT-5.5 Pro",provider:"openai",description:"Premium GPT-5.5 with maximum compute for the hardest problems",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:30,output:180,long_context:[{threshold:272e3,inclusive:!1,input:60,output:270}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["coding","reasoning"],billing_mode:"paid",pricing:{input:30,output:180,long_context:[{threshold:272e3,inclusive:!1,input:60,output:270}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-5.6-luna",name:"GPT-5.6 Luna",provider:"openai",description:"Cost-efficient GPT-5.6 tier for high-volume, latency-sensitive chat and lightweight agentic workflows. 1M context",lifecycle:"active",declared_capabilities:["chat","coding","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.2,output:1.2,cache_read:.02,cache_write:.25,long_context:[{threshold:272e3,inclusive:!1,input:.4,output:1.8,cache_read:.04,cache_write:.5}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","vision"],billing_mode:"paid",pricing:{input:.2,output:1.2,long_context:[{threshold:272e3,inclusive:!1,input:.4,output:1.8}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-5.6-luna-pro",name:"GPT-5.6 Luna Pro",provider:"openai",description:"GPT-5.6 Luna with pro reasoning mode \u2014 budget tier with deeper reasoning for high-volume workloads. 1M context",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.2,output:1.2,cache_read:.02,cache_write:.25,long_context:[{threshold:272e3,inclusive:!1,input:.4,output:1.8,cache_read:.04,cache_write:.5}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.2,output:1.2,long_context:[{threshold:272e3,inclusive:!1,input:.4,output:1.8}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-5.6-sol",name:"GPT-5.6 Sol",provider:"openai",description:"Top GPT-5.6 tier \u2014 deepest reasoning for complex coding, agentic workflows, and long-horizon problems. 1M context",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:4,output:20,cache_read:.4,cache_write:5,long_context:[{threshold:272e3,inclusive:!1,input:8,output:30,cache_read:.8,cache_write:10}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:4,output:20,long_context:[{threshold:272e3,inclusive:!1,input:8,output:30}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-5.6-sol-pro",name:"GPT-5.6 Sol Pro",provider:"openai",description:"Highest-capability GPT-5.6 \u2014 Sol with pro reasoning mode for the hardest problems and long-running agentic work. 1M context",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:4,output:20,cache_read:.4,cache_write:5,long_context:[{threshold:272e3,inclusive:!1,input:8,output:30,cache_read:.8,cache_write:10}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:4,output:20,long_context:[{threshold:272e3,inclusive:!1,input:8,output:30}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-5.6-terra",name:"GPT-5.6 Terra",provider:"openai",description:"Balanced GPT-5.6 tier \u2014 everyday coding, reasoning, and agentic tasks at half the flagship price. 1M context",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:12,cache_read:.2,cache_write:2.5,long_context:[{threshold:272e3,inclusive:!1,input:4,output:18,cache_read:.4,cache_write:5}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:12,long_context:[{threshold:272e3,inclusive:!1,input:4,output:18}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-5.6-terra-pro",name:"GPT-5.6 Terra Pro",provider:"openai",description:"GPT-5.6 Terra with pro reasoning mode \u2014 deeper responses on complex tasks at half the standard Terra rate. 1M context",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:12,cache_read:.2,cache_write:2.5,long_context:[{threshold:272e3,inclusive:!1,input:4,output:18,cache_read:.4,cache_write:5}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:12,long_context:[{threshold:272e3,inclusive:!1,input:4,output:18}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-6-astra",name:"GPT-6 Astra",provider:"openai",description:"OpenAI flagship \u2014 GPT-6 generation, tuned for long-horizon agentic work and computer use. 1M context",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:10,output:50,cache_read:1,cache_write:12.5,long_context:[{threshold:272e3,inclusive:!1,input:20,output:75,cache_read:2,cache_write:25}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:10,output:50,long_context:[{threshold:272e3,inclusive:!1,input:20,output:75}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-6-luna",name:"GPT-6 Luna",provider:"openai",description:"Fast, low-cost GPT-6 tier \u2014 high-volume chat, classification and lightweight agentic work. 1M context",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.1,output:.5,cache_read:.01,cache_write:.125,long_context:[{threshold:272e3,inclusive:!1,input:.2,output:.75,cache_read:.02,cache_write:.25}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.1,output:.5,long_context:[{threshold:272e3,inclusive:!1,input:.2,output:.75}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-6-luna-decisions",name:"GPT-6 Luna Decisions",provider:"openai",description:"Typed judgments over text or images: predicate (yes/no with a probability), choice (one of your values, with per-value probabilities) or score (an ordered rubric). OpenAI Decisions-compatible \u2014 POST /v1/decisions, not /v1/chat/completions. Billed on input tokens only, plus the transaction fee per call; with an API key from https://user.blockrun.ai, https://api.blockrun.ai/v1/decisions bills them from credit.",lifecycle:"active",declared_capabilities:["judgment"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["judgment"],billing_mode:"per_token",pricing:{input:.1,output:0,transaction_fee:.001,long_context:{threshold:272e3,input:.2}}},solana:{listed:!0,categories:["judgment"],billing_mode:"per_token",pricing:{input:.1,output:0,long_context_threshold:272e3,long_context_input:.2,per_call_fee_exact:.001,per_call_fee_batch:0,service_fee:0}}}},{id:"openai/gpt-6-sol",name:"GPT-6 Sol",provider:"openai",description:"Cost-efficient GPT-6 tier \u2014 complex coding and agentic workflows below the Astra flagship. 1M context",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10,cache_read:.2,cache_write:2.5,long_context:[{threshold:272e3,inclusive:!1,input:4,output:15,cache_read:.4,cache_write:5}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10,long_context:[{threshold:272e3,inclusive:!1,input:4,output:15}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-6.1-sol",name:"GPT-6.1 Sol",provider:"openai",description:"Refreshed GPT-6 Sol \u2014 complex coding and agentic workflows below the Astra flagship, April 2026 knowledge. 1M context",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10,cache_read:.1,cache_write:2.5,long_context:[{threshold:272e3,inclusive:!1,input:4,output:15,cache_read:.2,cache_write:5}]},context_window:105e4,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:2,output:10,long_context:[{threshold:272e3,inclusive:!1,input:4,output:15}]},context_window:105e4,max_output:128e3}}},{id:"openai/gpt-image-1",name:"GPT Image 1",provider:"openai",description:"Native image generation in GPT-4o",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.021,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.021}}}},{id:"openai/gpt-image-2",name:"ChatGPT Images 2.0",provider:"openai",description:"OpenAI's GPT Image 2 \u2014 reasoning-driven image generation with multilingual text rendering, character consistency, and high-fidelity edits",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.063,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.063}}}},{id:"openai/gpt-image-2.5-flare",name:"GPT Image 2.5 Flare",provider:"openai",description:"OpenAI GPT Image 2.5 fast model for high-quality everyday image generation",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.294,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.294}}}},{id:"openai/gpt-image-2.5-sunburst",name:"GPT Image 2.5 Sunburst",provider:"openai",description:"OpenAI GPT Image 2.5 most capable model for image generation and high-precision editing",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.294,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.294}}}},{id:"openai/o1",name:"o1",provider:"openai",description:"Advanced reasoning model for complex tasks",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:15,output:60,cache_read:7.5},context_window:2e5,max_output:1e5},solana:{listed:!0,categories:["coding","reasoning"],billing_mode:"paid",pricing:{input:15,output:60},context_window:2e5,max_output:1e5}}},{id:"openai/o3",name:"o3",provider:"openai",description:"o-series reasoning model with improved performance",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:2,output:8,cache_read:.5},context_window:2e5,max_output:1e5},solana:{listed:!0,categories:["coding","reasoning"],billing_mode:"paid",pricing:{input:2,output:8},context_window:2e5,max_output:1e5}}},{id:"openai/o3-mini",name:"o3-mini",provider:"openai",description:"Efficient reasoning model for STEM tasks",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.1,output:4.4,cache_read:.55},context_window:128e3,max_output:1e5},solana:{listed:!0,categories:["coding","reasoning"],billing_mode:"paid",pricing:{input:1.1,output:4.4},context_window:128e3,max_output:1e5}}},{id:"openai/o4-mini",name:"o4-mini",provider:"openai",description:"Efficient o4-generation reasoning model",lifecycle:"active",declared_capabilities:["coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["coding","reasoning"],billing_mode:"paid",pricing:{input:1.1,output:4.4,cache_read:.275},context_window:128e3,max_output:1e5},solana:{listed:!0,categories:["coding","reasoning"],billing_mode:"paid",pricing:{input:1.1,output:4.4},context_window:128e3,max_output:1e5}}},{id:"poolside/laguna-s-2.1",name:"Laguna S 2.1",provider:"poolside",description:"Poolside's Laguna S 2.1 \u2014 118B open-weight coding model, 1M context, very cheap per token.",lifecycle:"active",declared_capabilities:["chat","coding"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding"],billing_mode:"paid",pricing:{input:.09,output:.18},context_window:1048576,max_output:131072},solana:{listed:!0,categories:["chat","coding"],billing_mode:"paid",pricing:{input:.09,output:.18},context_window:1048576,max_output:131072}}},{id:"poolside/laguna-xs-2.1",name:"Poolside Laguna XS 2.1 (Free)",provider:"nvidia",description:"Poolside Laguna XS 2.1 hosted free by NVIDIA. Fast compact coding model (~161 tok/s).",lifecycle:"active",declared_capabilities:["chat","coding"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding"],billing_mode:"free",pricing:{input:0,output:0},context_window:131072,max_output:16384},solana:{listed:!0,categories:["chat","coding"],billing_mode:"free",pricing:{input:0,output:0},context_window:131072,max_output:16384}}},{id:"qwen/qwen3.7-flash",name:"Qwen3.7 Flash",provider:"qwen",description:"Alibaba's fastest Qwen tier \u2014 1M context reasoning for high-volume, latency-sensitive workloads",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:.03,output:.13,long_context:[{threshold:32e3,inclusive:!0,input:.1,output:.4},{threshold:256e3,inclusive:!0,input:.2,output:.8}]},context_window:1e6,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:.03,output:.13},context_window:1e6,max_output:65536}}},{id:"qwen/qwen3.7-max",name:"Qwen3.7 Max",provider:"qwen",description:"Alibaba's Qwen3.7 Max tier. 1M context, strong reasoning, coding, and agentic tool use. Live-verified 2026-07-20.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.475,output:4.425},context_window:1e6,max_output:65536},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.475,output:4.425},context_window:1e6,max_output:65536}}},{id:"qwen/qwen3.7-plus",name:"Qwen3.7 Plus",provider:"qwen",description:"Alibaba's balanced Qwen tier \u2014 1M context with reasoning, coding, and agentic tool use at a fraction of the Max price",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:.32,output:1.28,long_context:[{threshold:256e3,inclusive:!0,input:.96,output:3.84}]},context_window:1e6,max_output:131072},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:.32,output:1.28},context_window:1e6,max_output:131072}}},{id:"qwen/qwen3.8-flash",name:"Qwen3.8 Flash",provider:"qwen",description:"Alibaba's Qwen3.8 Flash \u2014 125B MoE with hybrid attention, 1M context, image input. Outperforms the Qwen3.7 Plus tier at a lower price.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.15,output:.47},context_window:1e6,max_output:131072},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.15,output:.47},context_window:1e6,max_output:131072}}},{id:"qwen/qwen3.8-max",name:"Qwen3.8 Max",provider:"qwen",description:"Alibaba's Qwen3.8 Max \u2014 current flagship of the Qwen line. 1M context, 131K output.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:2,output:6},context_window:1e6,max_output:131072},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:2,output:6},context_window:1e6,max_output:131072}}},{id:"reflection/beam-1.0-501b-a23b",name:"Beam 1.0",provider:"reflection",description:"Reflection's Beam 1.0 \u2014 open-weight 501B MoE (23B active) reasoning model for coding and long-horizon agents. 1M context, tool calling, reasoning_effort low-max.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!1,categories:[],billing_mode:"unavailable",pricing:{}},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:.25,output:1},context_window:1048576,max_output:131072}}},{id:"tencent/hy4-preview",name:"Tencent Hy4 Preview",provider:"tencent",description:"Tencent's Hy4 \u2014 770B mixture-of-experts, Apache 2.0, 1M context. A large open flagship at a fraction of closed-model pricing.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:.834,output:2.501},context_window:1048576,max_output:64e3},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:.834,output:2.501},context_window:1048576,max_output:64e3}}},{id:"xai/grok-4.3",name:"Grok 4.3",provider:"xai",description:"xAI's Grok 4.3 reasoning model. 1M context, vision-capable, tuned for agentic workflows and instruction-following.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.25,output:2.5,cache_read:.2,long_context:[{threshold:2e5,inclusive:!0,input:2.5,output:5,cache_read:.4}]},context_window:1e6,max_output:16384},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:1.25,output:2.5,long_context:[{threshold:2e5,inclusive:!0,input:2.5,output:5}]},context_window:1e6,max_output:16384}}},{id:"xai/grok-4.5",name:"Grok 4.5",provider:"xai",description:"xAI's Grok 4.5 \u2014 500K context, vision-capable, chain-of-thought reasoning. Supports Live Search (+$0.30 per call)",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","search","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","search","vision"],billing_mode:"paid",pricing:{input:2,output:6,cache_read:.3,long_context:[{threshold:2e5,inclusive:!0,input:4,output:12,cache_read:.6}]},context_window:5e5,max_output:16384},solana:{listed:!0,categories:["chat","coding","reasoning","search","vision"],billing_mode:"paid",pricing:{input:2,output:6,long_context:[{threshold:2e5,inclusive:!0,input:4,output:12}]},context_window:5e5,max_output:16384}}},{id:"xai/grok-4.6",name:"Grok 4.6",provider:"xai",description:"xAI's Grok 4.6 \u2014 500K context, chain-of-thought reasoning with selectable effort. Supports Live Search (+$0.30 per call)",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","search","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","search","vision"],billing_mode:"paid",pricing:{input:2,output:6,cache_read:.5,long_context:[{threshold:2e5,inclusive:!0,input:4,output:12,cache_read:1}]},context_window:5e5,max_output:16384},solana:{listed:!0,categories:["chat","coding","reasoning","search","vision"],billing_mode:"paid",pricing:{input:2,output:6,long_context:[{threshold:2e5,inclusive:!0,input:4,output:12}]},context_window:5e5,max_output:16384}}},{id:"xai/grok-4.7",name:"Grok 4.7",provider:"xai",description:"xAI's flagship Grok 4.7 \u2014 500K context, vision, always-on reasoning with selectable effort (low to xhigh). Supports Live Search (+$0.30 per call)",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","search","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","search","vision"],billing_mode:"paid",pricing:{input:2,output:6,cache_read:.5,long_context:[{threshold:2e5,inclusive:!0,input:4,output:12,cache_read:1}]},context_window:5e5,max_output:16384},solana:{listed:!0,categories:["chat","coding","reasoning","search","vision"],billing_mode:"paid",pricing:{input:2,output:6,long_context:[{threshold:2e5,inclusive:!0,input:4,output:12}]},context_window:5e5,max_output:16384}}},{id:"xai/grok-build-0.1",name:"Grok Build 0.1",provider:"xai",description:"xAI's fast agentic coding model, trained for interactive software-engineering workflows. 256K context, text + image input.",lifecycle:"active",declared_capabilities:["chat","coding"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding"],billing_mode:"paid",pricing:{input:1,output:2,cache_read:.2,long_context:[{threshold:2e5,inclusive:!0,input:2,output:4,cache_read:.4}]},context_window:256e3,max_output:16384},solana:{listed:!0,categories:["chat","coding"],billing_mode:"paid",pricing:{input:1,output:2,long_context:[{threshold:2e5,inclusive:!0,input:2,output:4}]},context_window:256e3,max_output:16384}}},{id:"xai/grok-imagine-image",name:"Grok Imagine",provider:"xai",description:"xAI's Grok Imagine image generation. Fast, 300 RPM.",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.021,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.021}}}},{id:"xai/grok-imagine-image-2.0",name:"Grok Imagine 2.0",provider:"xai",description:"xAI's Grok Imagine 2.0 image generation at low quality. Sits between Grok Imagine and Grok Imagine Pro on price.",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.042,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.042}}}},{id:"xai/grok-imagine-image-pro",name:"Grok Imagine Pro",provider:"xai",description:"xAI's Grok Imagine 2.0 image generation at medium quality: finer detail than Grok Imagine 2.0. 30 RPM.",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.063,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.063}}}},{id:"xai/grok-imagine-video",name:"Grok Imagine Video",provider:"xai",description:"xAI's Grok Imagine video generation. Text or image to video, configurable 1\u201315s clips. $0.05/sec at 480p (default), $0.07/sec at 720p \u2014 official per-second rates, plus $0.002 per input image and a flat $0.001 per generation.",lifecycle:"active",declared_capabilities:["video"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.05,per_call_surcharge:.001,per_input_image:.002,transaction_fee:.001,default_duration_seconds:8,max_duration_seconds:15}},solana:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.05,per_call_surcharge:.001,per_input_image:.002,default_duration_seconds:8,max_duration_seconds:15}}}},{id:"xai/grok-imagine-video-1.5",name:"Grok Imagine Video 1.5",provider:"xai",description:"xAI's flagship Grok Imagine Video 1.5 \u2014 text or image to video with native synced audio, 1\u201315s clips. $0.08/sec at 480p (default), $0.14/sec at 720p, $0.25/sec at 1080p \u2014 official per-second rates, plus $0.01 per input image and a flat $0.001 per generation. First-and-last-frame at 480p and 720p.",lifecycle:"active",declared_capabilities:["video"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.08,per_call_surcharge:.001,per_input_image:.01,transaction_fee:.001,default_duration_seconds:8,max_duration_seconds:15}},solana:{listed:!0,categories:["video"],billing_mode:"per_second",pricing:{per_second:.08,per_call_surcharge:.001,per_input_image:.01,default_duration_seconds:8,max_duration_seconds:15}}}},{id:"xiaomi/mimo-v2.5",name:"MiMo V2.5",provider:"xiaomi",description:"Xiaomi's MiMo V2.5 \u2014 310B sparse MoE, natively multimodal, 1M context. Accepts text and images.",lifecycle:"active",declared_capabilities:["chat","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","reasoning","vision"],billing_mode:"paid",pricing:{input:.14,output:.28},context_window:1048576,max_output:131072},solana:{listed:!0,categories:["chat","reasoning","vision"],billing_mode:"paid",pricing:{input:.14,output:.28},context_window:1048576,max_output:131072}}},{id:"xiaomi/mimo-v2.5-pro",name:"Xiaomi MiMo-V2.5 Pro",provider:"xiaomi",description:"Xiaomi's MiMo-V2.5 Pro \u2014 1M context reasoning model, priced well below the frontier tier.",lifecycle:"active",declared_capabilities:["chat","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","reasoning"],billing_mode:"paid",pricing:{input:.435,output:.87},context_window:1048576,max_output:131072},solana:{listed:!0,categories:["chat","reasoning"],billing_mode:"paid",pricing:{input:.435,output:.87},context_window:1048576,max_output:131072}}},{id:"zai/cogview-4",name:"CogView-4",provider:"zai",description:"Zhipu AI's CogView-4 image generation model \u2014 high quality, supports up to 1440x1440",lifecycle:"active",declared_capabilities:["image"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.01575,transaction_fee:.001}},solana:{listed:!0,categories:["image"],billing_mode:"per_image",pricing:{per_image:.01575}}}},{id:"zai/glm-5",name:"GLM-5",provider:"zai",description:"Z.AI's foundation model with 200K context. Strong reasoning and agentic capabilities",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1,output:3.2,cache_read:.2},context_window:2e5,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1,output:3.2},context_window:2e5,max_output:128e3}}},{id:"zai/glm-5-turbo",name:"GLM-5 Turbo",provider:"zai",description:"Optimized GLM-5 variant with faster inference",lifecycle:"active",declared_capabilities:["chat","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","reasoning"],billing_mode:"paid",pricing:{input:1.2,output:4},context_window:2e5,max_output:128e3},solana:{listed:!0,categories:["chat","reasoning"],billing_mode:"paid",pricing:{input:1.2,output:4},context_window:2e5,max_output:128e3}}},{id:"zai/glm-5.1",name:"GLM-5.1",provider:"zai",description:"Z.AI's GLM-5.1 \u2014 #1 open source on SWE-Bench Pro, 8-hour autonomous execution. 200K context",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.4,output:4.4,cache_read:.26},context_window:2e5,max_output:128e3},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.4,output:4.4},context_window:2e5,max_output:128e3}}},{id:"zai/glm-5.2",name:"GLM-5.2",provider:"zai",description:"Z.AI GLM-5.2 \u2014 1M-token context, strong open-source long-horizon coding. Verified live on Z.AI.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.4,output:4.4,cache_read:.26},context_window:1e6,max_output:131072},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.4,output:4.4},context_window:1e6,max_output:131072}}},{id:"zai/glm-5.3",name:"GLM-5.3",provider:"zai",description:"Z.AI's flagship \u2014 1M-token context with always-on reasoning, strong at long-horizon coding. Verified live on Z.AI.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.4,output:4.4,cache_read:.26},context_window:1e6,max_output:131072},solana:{listed:!0,categories:["chat","coding","reasoning"],billing_mode:"paid",pricing:{input:1.4,output:4.4},context_window:1e6,max_output:131072}}},{id:"zai/glm-5.3-flash",name:"GLM-5.3 Flash",provider:"zai",description:"Z.AI's first natively multimodal GLM-5 \u2014 320B/18B MoE with image input, 1M-token context, and always-on reasoning at value-tier pricing. Verified live on Z.AI.",lifecycle:"active",declared_capabilities:["chat","coding","reasoning","vision"],aliases:[],redirects:[],networks:{base:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.15,output:.5,cache_read:.03},context_window:1e6,max_output:131072},solana:{listed:!0,categories:["chat","coding","reasoning","vision"],billing_mode:"paid",pricing:{input:.15,output:.5},context_window:1e6,max_output:131072}}}]},picker_policy:{schema_version:1,policy_version:"2026.11.12.2",catalog_version:"2026.11.12.2",default_network:"solana",compatibility_shortcuts:{"opus-4.6":"anthropic/claude-opus-4.6","haiku-4.5":"anthropic/claude-haiku-4.5-20251001","gpt-5.4-pro":"openai/gpt-5.4-pro","gpt-5.3":"openai/gpt-5.3","gpt-5.2-pro":"openai/gpt-5.2-pro",o3:"openai/o3",o4:"openai/o4-mini","o4-mini":"openai/o4-mini",o1:"openai/o1","grok-3":"xai/grok-3","grok-4":"xai/grok-4-0709","grok-fast":"xai/grok-4-1-fast-reasoning","grok-4.1":"xai/grok-4-1-fast-reasoning",r1:"deepseek/deepseek-reasoner","deepseek-v4":"deepseek/deepseek-v4.1-flash","deepseek-v4-flash":"deepseek/deepseek-v4.1-flash",dsv4:"deepseek/deepseek-v4.1-flash","deepseek-v3.2":"deepseek/deepseek-v4.1-flash","deepseek-v3":"deepseek/deepseek-v4.1-flash","k2.6":"moonshot/kimi-k2.6","kimi-k2.5":"moonshot/kimi-k2.6","k2.5":"moonshot/kimi-k2.6"},views:{default_chat:{description:"ClawRouter recommendations, filtered to live Solana chat; remaining active models are always discoverable.",virtual_entries:["blockrun/auto","blockrun/free"],model_ids:["anthropic/claude-fable-5","anthropic/claude-opus-5","anthropic/claude-opus-4.8","anthropic/claude-opus-4.7","anthropic/claude-sonnet-5","anthropic/claude-sonnet-4.6","anthropic/claude-haiku-4.5","openai/gpt-5.6-terra","openai/gpt-5.6-sol","openai/gpt-5.6-luna","openai/gpt-5.5","openai/gpt-5.4","openai/gpt-5.4-mini","openai/gpt-5.4-nano","openai/gpt-5.3-codex","google/gemini-3.1-pro","google/gemini-3.8-flash","google/gemini-3.6-flash","google/gemini-3.5-flash","google/gemini-3.5-flash-lite","google/gemini-3.1-flash-lite","google/gemini-3-flash-preview","xai/grok-4.5","xai/grok-4.3","xai/grok-build-0.1","zai/glm-5.3","zai/glm-5.3-flash","zai/glm-5.2","zai/glm-5.1","zai/glm-5-turbo","zai/glm-5","xiaomi/mimo-v2.5","xiaomi/mimo-v2.5-pro","minimax/minimax-m3","minimax/minimax-m2.7","moonshot/kimi-k3.1-pro","qwen/qwen3.7-max","qwen/qwen3.8-flash","deepseek/deepseek-v4-flash-vision-exp","deepseek/deepseek-v4-pro","deepseek/deepseek-v4.1-flash","nvidia/nemotron-3.5-lightning","poolside/laguna-xs-2.1","cohere/north-mini-code","nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","nvidia/nemotron-3-ultra-550b","nvidia/nemotron-3-super-120b","nvidia/nemotron-3.5-bolt"],groups:[{id:"recommended",title:"Recommended",model_ids:["anthropic/claude-fable-5","anthropic/claude-opus-5","anthropic/claude-opus-4.8","anthropic/claude-opus-4.7","anthropic/claude-sonnet-5","anthropic/claude-sonnet-4.6","anthropic/claude-haiku-4.5","openai/gpt-5.6-terra","openai/gpt-5.6-sol","openai/gpt-5.6-luna","openai/gpt-5.5","openai/gpt-5.4","openai/gpt-5.4-mini","openai/gpt-5.4-nano","openai/gpt-5.3-codex","google/gemini-3.1-pro","google/gemini-3.8-flash","google/gemini-3.6-flash","google/gemini-3.5-flash","google/gemini-3.5-flash-lite","google/gemini-3.1-flash-lite","google/gemini-3-flash-preview","xai/grok-4.5","xai/grok-4.3","xai/grok-build-0.1","zai/glm-5.3","zai/glm-5.3-flash","zai/glm-5.2","zai/glm-5.1","zai/glm-5-turbo","zai/glm-5","xiaomi/mimo-v2.5","xiaomi/mimo-v2.5-pro","minimax/minimax-m3","minimax/minimax-m2.7","moonshot/kimi-k3.1-pro","qwen/qwen3.7-max","qwen/qwen3.8-flash","deepseek/deepseek-v4-flash-vision-exp","deepseek/deepseek-v4-pro","deepseek/deepseek-v4.1-flash"]},{id:"free",title:"Free (no USDC needed)",model_ids:["nvidia/nemotron-3.5-lightning","poolside/laguna-xs-2.1","cohere/north-mini-code","nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","nvidia/nemotron-3-ultra-550b","nvidia/nemotron-3-super-120b","nvidia/nemotron-3.5-bolt"]}],shortcuts:{auto:"blockrun/auto",smart:"blockrun/auto",eco:"blockrun/auto",premium:"blockrun/auto",sonnet:"anthropic/claude-sonnet-5.5",claude:"anthropic/claude-sonnet-5.5","sonnet-4.6":"anthropic/claude-sonnet-4.6",opus:"anthropic/claude-opus-5.5","opus-4.8":"anthropic/claude-opus-4.8","opus-4.7":"anthropic/claude-opus-4.7",haiku:"anthropic/claude-haiku-4.5",gpt:"openai/gpt-6-astra",gpt5:"openai/gpt-5.6-terra","gpt-5":"openai/gpt-5.5","gpt-5.5":"openai/gpt-5.5","gpt-5.4":"openai/gpt-5.4","gpt-5.2":"openai/gpt-5.2","gpt-4.1":"openai/gpt-4.1",codex:"openai/gpt-5.3-codex",nano:"openai/gpt-5.4-nano",mini:"openai/gpt-4o-mini",gemini:"google/gemini-2.5-pro","gemini-2.5":"google/gemini-2.5-pro",flash:"google/gemini-2.5-flash","gemini-3":"google/gemini-3.1-pro","gemini-3.1":"google/gemini-3.1-pro",grok:"xai/grok-4.7","grok-4.3":"xai/grok-4.3","grok-build":"xai/grok-build-0.1",deepseek:"deepseek/deepseek-v4.1-flash","deepseek-v4-pro":"nvidia/nemotron-3.5-lightning","dsv4-pro":"deepseek/deepseek-v4-pro","v4-pro":"nvidia/nemotron-3.5-lightning",free:"blockrun/free",glm4:"nvidia/nemotron-3.5-lightning","deepseek-free":"nvidia/nemotron-3.5-lightning","qwen-coder":"nvidia/nemotron-3.5-lightning","qwen-think":"nvidia/nemotron-3.5-lightning",maverick:"nvidia/nemotron-3.5-lightning","gpt-oss":"nvidia/nemotron-3.5-lightning","gpt-oss-small":"nvidia/nemotron-3.5-lightning","mistral-small":"nvidia/nemotron-3.5-lightning",nemotron:"nvidia/nemotron-3.5-lightning",devstral:"nvidia/nemotron-3.5-lightning",minimax:"minimax/minimax-m3",m3:"minimax/minimax-m3","m2.7":"minimax/minimax-m2.7",glm:"zai/glm-5.3","glm-5":"zai/glm-5","glm-turbo":"zai/glm-5-turbo",glm5:"zai/glm-5.1",kimi:"moonshot/kimi-k3.1-pro","br-sonnet":"anthropic/claude-sonnet-4.6","sonnet-4":"anthropic/claude-sonnet-4.6","sonnet-4-6":"anthropic/claude-sonnet-4.6","sonnet-5":"anthropic/claude-sonnet-5","sonnet-5.0":"anthropic/claude-sonnet-5","sonnet-5-0":"anthropic/claude-sonnet-5","sonnet-4.5":"anthropic/claude-sonnet-4.5","sonnet-4-5":"anthropic/claude-sonnet-4.5","anthropic/claude-sonnet-4-5":"anthropic/claude-sonnet-4.5",fable:"anthropic/claude-fable-5","fable-5":"anthropic/claude-fable-5","fable-5.0":"anthropic/claude-fable-5","opus-5":"anthropic/claude-opus-5","opus-5.0":"anthropic/claude-opus-5","opus-5-0":"anthropic/claude-opus-5","opus-4":"anthropic/claude-opus-4.8","opus-4-8":"anthropic/claude-opus-4.8","opus-4-7":"anthropic/claude-opus-4.7","anthropic/sonnet":"anthropic/claude-sonnet-4.6","anthropic/fable":"anthropic/claude-fable-5","anthropic/claude-fable-5.0":"anthropic/claude-fable-5","anthropic/opus":"anthropic/claude-opus-5","anthropic/claude-opus-5.0":"anthropic/claude-opus-5","anthropic/claude-opus-5-0":"anthropic/claude-opus-5","anthropic/haiku":"anthropic/claude-haiku-4.5","anthropic/claude":"anthropic/claude-sonnet-4.6","anthropic/claude-sonnet-4":"anthropic/claude-sonnet-4.6","anthropic/claude-sonnet-4-6":"anthropic/claude-sonnet-4.6","anthropic/claude-opus-4":"anthropic/claude-opus-4.8","anthropic/claude-opus-4-8":"anthropic/claude-opus-4.8","anthropic/claude-opus-4-7":"anthropic/claude-opus-4.7","anthropic/claude-opus-4-5":"anthropic/claude-opus-4.5","anthropic/claude-haiku-4":"anthropic/claude-haiku-4.5","anthropic/claude-haiku-4-5":"anthropic/claude-haiku-4.5",gpt4:"openai/gpt-4o","gpt-5.6":"openai/gpt-5.6-terra","openai/gpt-5.6":"openai/gpt-5.6-terra","gpt-5.6-sol":"openai/gpt-5.6-sol","gpt-5.6-terra":"openai/gpt-5.6-terra","gpt-5.6-luna":"openai/gpt-5.6-luna","gpt-5.6-sol-pro":"openai/gpt-5.6-sol-pro","gpt-5.6-terra-pro":"openai/gpt-5.6-terra-pro","gpt-5.6-luna-pro":"openai/gpt-5.6-luna-pro","sol-pro":"openai/gpt-5.6-sol-pro","terra-pro":"openai/gpt-5.6-terra-pro","luna-pro":"openai/gpt-5.6-luna-pro","chat-latest":"openai/chat-latest",chatgpt:"openai/chat-latest","gpt-5.4-nano":"openai/gpt-5.4-nano","gpt-5-nano":"openai/gpt-5.4-nano","openai-codex/gpt-5.4-mini":"openai/gpt-5.4-mini","gpt-5.4-mini":"openai/gpt-5.4-mini","deepseek-chat":"deepseek/deepseek-chat","kimi-k3":"moonshot/kimi-k3.1-pro","qwen3.7-max":"qwen/qwen3.7-max","qwen3.8-flash":"qwen/qwen3.8-flash","qwen3-8-flash":"qwen/qwen3.8-flash","qwen-vision":"qwen/qwen3.8-flash","deepseek-vision":"deepseek/deepseek-v4-flash-vision-exp","v4-flash-vision":"deepseek/deepseek-v4-flash-vision-exp","mimo-vision":"xiaomi/mimo-v2.5","qwen-3.7-max":"qwen/qwen3.7-max","qwen3-7-max":"qwen/qwen3.7-max","qwen3.7-plus":"qwen/qwen3.7-plus","qwen-3.7-plus":"qwen/qwen3.7-plus","qwen3.7-flash":"qwen/qwen3.7-flash","qwen-3.7-flash":"qwen/qwen3.7-flash",mimo:"xiaomi/mimo-v2.5-pro","mimo-v2.5-pro":"xiaomi/mimo-v2.5-pro","mimo-v2.5":"xiaomi/mimo-v2.5",xiaomi:"xiaomi/mimo-v2.5-pro","google/gemini-3-pro-preview":"google/gemini-3.1-pro","gemini-3-pro-preview":"google/gemini-3.1-pro","gemini-pro":"google/gemini-3.1-pro","gemini-3-pro":"google/gemini-3.1-pro","gemini-3.1-pro":"google/gemini-3.1-pro","gemini-3.1-pro-preview":"google/gemini-3.1-pro","google/gemini-3.1-pro-preview":"google/gemini-3.1-pro","gemini-3.6-flash":"google/gemini-3.6-flash","gemini-3.6":"google/gemini-3.6-flash","gemini-3.5-flash":"google/gemini-3.5-flash","gemini-3.5-flash-lite":"google/gemini-3.5-flash-lite","gemini-3.1-flash-lite":"google/gemini-3.1-flash-lite","gemini-2.5-flash-lite":"google/gemini-2.5-flash-lite","grok-4.5":"xai/grok-4.5","grok-4-5":"xai/grok-4.5","grok-code":"xai/grok-build-0.1","grok-code-fast-1":"deepseek/deepseek-chat","xai/grok-code-fast-1":"deepseek/deepseek-chat",nvidia:"nvidia/nemotron-3.5-lightning","nvidia/deepseek-v3.2":"nvidia/nemotron-3.5-lightning","free/deepseek-v3.2":"nvidia/nemotron-3.5-lightning","nvidia/deepseek-v4-pro":"nvidia/nemotron-3.5-lightning","free/deepseek-v4-pro":"nvidia/nemotron-3.5-lightning","nvidia/nemotron-3-nano-omni-30b-a3b-reasoning":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","nvidia/nemotron-ultra-253b":"nvidia/nemotron-3.5-lightning","nvidia/devstral-2-123b":"nvidia/nemotron-3.5-lightning","free/nemotron-ultra-253b":"nvidia/nemotron-3.5-lightning","free/devstral-2-123b":"nvidia/nemotron-3.5-lightning","mistral-free":"nvidia/nemotron-3.5-lightning","glm-free":"nvidia/nemotron-3.5-lightning","llama-free":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","qwen-coder-free":"nvidia/nemotron-3.5-lightning","qwen-thinking":"nvidia/nemotron-3.5-lightning","coder-free":"cohere/north-mini-code","nemotron-nano-9b":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-nano":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-nano-vl":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","nano-vl":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-omni":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","nano-omni":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","vision-free":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-ultra":"nvidia/nemotron-3.5-lightning","nemotron-253b":"nvidia/nemotron-3.5-lightning","nemotron-super":"nvidia/nemotron-3.5-lightning","nemotron-49b":"nvidia/nemotron-3.5-lightning","nemotron-120b":"nvidia/nemotron-3.5-lightning","devstral-2":"nvidia/nemotron-3.5-lightning","nvidia/nemotron-3.5-lightning":"nvidia/nemotron-3.5-lightning","nvidia/nemotron-3-nano-30b":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","nvidia/nemotron-3-ultra-550b":"nvidia/nemotron-3-ultra-550b","nvidia/llama-3.2-11b-vision":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","cohere/north-mini-code":"cohere/north-mini-code","poolside/laguna-xs-2.1":"poolside/laguna-xs-2.1",lightning:"nvidia/nemotron-3.5-lightning","nemotron-lightning":"nvidia/nemotron-3.5-lightning","nemotron-3.5-lightning":"nvidia/nemotron-3.5-lightning","nano-30b":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-nano-30b":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","ultra-550b":"nvidia/nemotron-3-ultra-550b","nemotron-ultra-550b":"nvidia/nemotron-3-ultra-550b","llama-vision":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","llama-3.2-vision":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","north-mini":"cohere/north-mini-code","north-mini-code":"cohere/north-mini-code",laguna:"poolside/laguna-xs-2.1","laguna-xs":"poolside/laguna-xs-2.1","minimax-m3":"minimax/minimax-m3","minimax-m2.7":"minimax/minimax-m2.7","glm-5.3":"zai/glm-5.3","glm-5-3":"zai/glm-5.3","glm-5.3-flash":"zai/glm-5.3-flash","glm-5-3-flash":"zai/glm-5.3-flash","glm-flash":"zai/glm-5.3-flash","glm-5.2":"zai/glm-5.2","glm-5.1":"zai/glm-5.1","glm-5-turbo":"zai/glm-5-turbo","gpt-fast":"openai/gpt-6-luna","gpt-balanced":"openai/gpt-6-sol",qwen:"qwen/qwen3.8-max","free-code":"cohere/north-mini-code","free-fast":"nvidia/nemotron-3.5-lightning","free-vision":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","claude-sonnet-4.5":"anthropic/claude-sonnet-4.5","gpt-5-mini":"openai/gpt-5-mini","gemini-2.5-pro":"google/gemini-2.5-pro","claude-haiku-4.5":"anthropic/claude-haiku-4.5","gpt-4.1-mini":"openai/gpt-4.1-mini","claude-sonnet-5.5":"anthropic/claude-sonnet-5.5","claude-sonnet-5":"anthropic/claude-sonnet-5","claude-opus-4.8":"anthropic/claude-opus-4.8","gpt-4o":"openai/gpt-4o","grok-4.7":"xai/grok-4.7","laguna-xs-2.1":"poolside/laguna-xs-2.1","nemotron-3-nano-omni-30b-a3b-reasoning":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","gpt-6-sol":"openai/gpt-6-sol","laguna-s-2.1":"poolside/laguna-s-2.1","grok-build-0.1":"xai/grok-build-0.1","claude-opus-4.5":"anthropic/claude-opus-4.5","qwen3.8-max":"qwen/qwen3.8-max","deepseek-v4-flash-vision-exp":"deepseek/deepseek-v4-flash-vision-exp","claude-opus-5":"anthropic/claude-opus-5","gemini-2.5-flash":"google/gemini-2.5-flash","muse-glimmer-30b":"nvidia/muse-glimmer-30b","gpt-6-luna":"openai/gpt-6-luna","grok-4.6":"xai/grok-4.6","claude-sonnet-4.6":"anthropic/claude-sonnet-4.6","llama-3.2-11b-vision":"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","hy4-preview":"tencent/hy4-preview","gpt-4o-mini":"openai/gpt-4o-mini","claude-opus-4.7":"anthropic/claude-opus-4.7","claude-opus-5.5":"anthropic/claude-opus-5.5","gemini-3.8-flash":"google/gemini-3.8-flash","gemini-4-argon":"google/gemini-4-argon","nemotron-3-ultra-550b":"nvidia/nemotron-3-ultra-550b","gpt-5.1":"openai/gpt-5.1","claude-fable-5":"anthropic/claude-fable-5","gemini-3-flash-preview":"google/gemini-3-flash-preview","claude-fable-5.1":"anthropic/claude-fable-5.1","gpt-6-astra":"openai/gpt-6-astra","gpt-4.1-nano":"openai/gpt-5.4-nano","gpt-5.3-codex":"openai/gpt-5.3-codex","gpt-6.1-sol":"openai/gpt-6.1-sol","mistral-large-4":"mistral/mistral-large-4","deepseek-v4.1-flash":"deepseek/deepseek-v4.1-flash","gemini-4-carbon":"google/gemini-4-carbon","kimi-k3.1-pro":"moonshot/kimi-k3.1-pro","kimi-k3.1":"moonshot/kimi-k3.1-pro","nemotron-3.5-bolt":"nvidia/nemotron-3.5-bolt","nemotron-bolt":"nvidia/nemotron-3.5-bolt","nemotron-3-super":"nvidia/nemotron-3-super-120b","minimax-m3.1-flash":"nvidia/minimax-m3.1-flash"}}}},router_policy:{schema_version:1,policy_version:"2026.11.12.2",catalog_version:"2026.11.12.2",default_network:"solana",status:"draft",description:"Prototype model-specific policy for Router Core. Do not consume in production until benchmark review is complete.",candidate_sets:{simple:["qwen/qwen3.7-flash","google/gemini-3.5-flash-lite","minimax/minimax-m3","cohere/north-mini-code"],medium:["openai/gpt-5.6-luna","google/gemini-3.6-flash","moonshot/kimi-k3.1-pro","qwen/qwen3.8-flash"],complex:["openai/gpt-5.6-terra","openai/gpt-5.6-sol","anthropic/claude-sonnet-5","anthropic/claude-opus-5"],reasoning:["xai/grok-4.5","deepseek/deepseek-v4-pro","google/gemini-3.1-pro","openai/gpt-5.6-sol"],agentic:["openai/gpt-5.6-terra","anthropic/claude-sonnet-5","xai/grok-4.5","moonshot/kimi-k3.1-pro"]},free_candidate_sets:{coding:["cohere/north-mini-code","poolside/laguna-xs-2.1","nvidia/nemotron-3.5-lightning"],general:["nvidia/nemotron-3.5-lightning","nvidia/nemotron-3-ultra-550b"],vision:["nvidia/nemotron-3-nano-omni-30b-a3b-reasoning"]},classifier_model:"nvidia/nemotron-3.5-lightning"}}}});function isReleaseDate(value){if(typeof value!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(value))return!1;let date5=new Date(`${value}T00:00:00Z`);return Number.isFinite(date5.getTime())&&date5.toISOString().slice(0,10)===value}var init_ordering=__esm({"node_modules/@blockrun/model-catalog/runtime/ordering.js"(){"use strict"}});import{createHash}from"crypto";import{readFile}from"fs/promises";function validateAll(catalog,pickerPolicy,routerPolicy){let errors=[],record2=value=>value!==null&&typeof value=="object"&&!Array.isArray(value),strings=value=>Array.isArray(value)&&value.every(item=>typeof item=="string");if(!record2(pickerPolicy?.views)||!record2(pickerPolicy.views.default_chat))return["picker policy views.default_chat must be an object"];for(let[name,view]of Object.entries(pickerPolicy.views)){if(!record2(view)){errors.push(`picker view ${name} must be an object`);continue}for(let field of["model_ids","virtual_entries"])strings(view[field])||errors.push(`picker view ${name}.${field} must be an array of strings`);if((!record2(view.shortcuts)||!Object.values(view.shortcuts).every(target=>typeof target=="string"))&&errors.push(`picker view ${name}.shortcuts must map names to strings`),!Array.isArray(view.groups))errors.push(`picker view ${name}.groups must be an array`);else for(let group of view.groups)(!record2(group)||typeof group.id!="string"||typeof group.title!="string"||!strings(group.model_ids))&&errors.push(`picker view ${name} has a malformed group`)}if(errors.length)return errors;catalog.schema_version!==1&&errors.push("catalog.schema_version must be 1"),/^\d{4}\.\d{2}\.\d{2}\.[1-9]\d*$/.test(catalog.catalog_version??"")||errors.push("catalog.catalog_version must use YYYY.MM.DD.N"),Number.isNaN(Date.parse(catalog.observed_at))&&errors.push("catalog.observed_at must be an ISO date-time"),(!Array.isArray(catalog.models)||catalog.models.length===0)&&errors.push("catalog.models must be non-empty");let ids=new Set,aliases=new Set;for(let[index2,model]of(catalog.models??[]).entries()){let at=`catalog.models[${index2}]`;(typeof model.id!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9._+/-]*$/.test(model.id))&&errors.push(`${at}.id must be a public model identifier`),ids.has(model.id)&&errors.push(`duplicate model id: ${model.id}`),ids.add(model.id),(typeof model.name!="string"||model.name.length===0)&&errors.push(`${at}.name must be non-empty`),model.release_date!==void 0&&!isReleaseDate(model.release_date)&&errors.push(`${at}.release_date must be a valid YYYY-MM-DD date`),["active","preview","deprecated","sunset"].includes(model.lifecycle)||errors.push(`${at}.lifecycle is invalid`),Array.isArray(model.declared_capabilities)||errors.push(`${at}.declared_capabilities must be an array`);for(let network of["base","solana"]){let entry=model.networks?.[network];if(!entry){errors.push(`${at}.networks.${network} is required`);continue}Array.isArray(entry.categories)||errors.push(`${at}.networks.${network}.categories must be an array`),(typeof entry.billing_mode!="string"||entry.billing_mode.length===0)&&errors.push(`${at}.networks.${network}.billing_mode is required`),(typeof entry.pricing!="object"||entry.pricing===null||Array.isArray(entry.pricing))&&errors.push(`${at}.networks.${network}.pricing must be an object`)}for(let alias of model.aliases??[])aliases.has(alias)&&errors.push(`duplicate alias: ${alias}`),ids.has(alias)&&errors.push(`alias collides with model id: ${alias}`),aliases.add(alias)}for(let model of catalog.models??[])for(let target of model.redirects??[])ids.has(target)||errors.push(`${model.id} redirects to missing model ${target}`),target===model.id&&errors.push(`${model.id} redirects to itself`);let byId=new Map((catalog.models??[]).map(model=>[model.id,model])),virtualEntries=new Set;for(let view of Object.values(pickerPolicy.views??{}))for(let id2 of view.virtual_entries??[])virtualEntries.add(id2);let isSolanaChat=id2=>{let network=byId.get(id2)?.networks?.solana;return!!(network?.listed&&network.categories.includes("chat"))};pickerPolicy.default_network!=="solana"&&errors.push("picker policy default_network must be solana");for(let[name,view]of Object.entries(pickerPolicy.views??{})){let seen=new Set;for(let id2 of view.model_ids??[])ids.has(id2)||errors.push(`picker view ${name} references missing model ${id2}`),seen.has(id2)&&errors.push(`picker view ${name} repeats ${id2}`),seen.add(id2),ids.has(id2)&&!isSolanaChat(id2)&&errors.push(`picker view ${name} references model unavailable for Solana chat: ${id2}`);let grouped=new Set;for(let group of view.groups??[])for(let id2 of group.model_ids??[])seen.has(id2)||errors.push(`picker group ${group.id} references model outside view ${name}: ${id2}`),grouped.has(id2)&&errors.push(`picker view ${name} groups repeat ${id2}`),grouped.add(id2);if((view.groups??[]).length>0)for(let id2 of seen)grouped.has(id2)||errors.push(`picker view ${name} does not group ${id2}`);for(let[shortcut,target]of Object.entries(view.shortcuts??{}))!isSolanaChat(target)&&!virtualEntries.has(target)&&errors.push(`picker shortcut ${shortcut} has invalid target ${target}`)}routerPolicy.default_network!=="solana"&&errors.push("router policy default_network must be solana");for(let[name,candidates]of Object.entries(routerPolicy.candidate_sets??{})){let seen=new Set;for(let id2 of candidates)ids.has(id2)||errors.push(`router candidate set ${name} references missing model ${id2}`),seen.has(id2)&&errors.push(`router candidate set ${name} repeats ${id2}`),ids.has(id2)&&!isSolanaChat(id2)&&errors.push(`router candidate set ${name} references model unavailable for Solana chat: ${id2}`),seen.add(id2)}for(let[name,candidates]of Object.entries(routerPolicy.free_candidate_sets??{})){let seen=new Set;for(let id2 of candidates){let model=byId.get(id2);model||errors.push(`free router candidate set ${name} references missing model ${id2}`),seen.has(id2)&&errors.push(`free router candidate set ${name} repeats ${id2}`),model&&!isSolanaChat(id2)&&errors.push(`free router candidate set ${name} references model unavailable for Solana chat: ${id2}`),model?.networks?.solana?.billing_mode!=="free"&&errors.push(`free router candidate set ${name} references paid model ${id2}`),seen.add(id2)}}isSolanaChat(routerPolicy.classifier_model)||errors.push(`router classifier_model is unavailable for Solana chat: ${routerPolicy.classifier_model}`);for(let[name,policy]of[["picker",pickerPolicy],["router",routerPolicy]])policy.schema_version!==1&&errors.push(`${name} policy schema_version must be 1`),policy.catalog_version!==catalog.catalog_version&&errors.push(`${name} policy catalog_version must match catalog`);return errors}var init_lib=__esm({"node_modules/@blockrun/model-catalog/scripts/lib.mjs"(){"use strict";init_ordering()}});function validateModels(rows){if(!Array.isArray(rows)||!rows.length)throw new Error("Empty or malformed model catalog");let ids=new Set;for(let row of rows){if(!row||typeof row.id!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9._+/-]*$/.test(row.id)||ids.has(row.id))throw new Error("Invalid or duplicate model ID");if(ids.add(row.id),typeof row.name!="string"||!row.name||!Array.isArray(row.categories)||!row.categories.every(x=>typeof x=="string"))throw new Error(`Invalid metadata: ${row.id}`);if(!row.pricing||typeof row.pricing!="object"||Array.isArray(row.pricing)||typeof row.billing_mode!="string")throw new Error(`Invalid pricing: ${row.id}`);if(row.billing_mode==="paid"&&(!isNumber(row.pricing.input)||!isNumber(row.pricing.output)))throw new Error(`Invalid token price: ${row.id}`);if(row.billing_mode==="flat"&&!isNumber(row.pricing.flat))throw new Error(`Invalid flat price: ${row.id}`);if(row.billing_mode==="free"&&((row.pricing.input??0)!==0||(row.pricing.output??0)!==0))throw new Error(`Nonzero free price: ${row.id}`);for(let key3 of["context_window","max_output"])if(row[key3]!==void 0&&(!Number.isInteger(row[key3])||row[key3]<=0))throw new Error(`Invalid ${key3}: ${row.id}`);if(row.release_date!==void 0&&!isReleaseDate(row.release_date))throw new Error(`Invalid release_date: ${row.id}`)}return rows}function validateSnapshot(value){if(!value?.catalog||!value.picker_policy||!value.router_policy)throw new Error("Incomplete catalog snapshot");let errors=validateAll(value.catalog,value.picker_policy,value.router_policy);if(errors.length)throw new Error(errors.join("; "));return value}function snapshotModels(snapshot2,network){return validateModels(snapshot2.catalog.models.filter(m=>["active","preview"].includes(m.lifecycle)&&m.networks[network]?.listed).map(m=>({id:m.id,name:m.name,owned_by:m.provider,description:m.description,...m.release_date!==void 0?{release_date:m.release_date}:{},...m.networks[network]})))}function projectCatalog(models,policy){let chat=models.filter(m=>m.categories.includes("chat")&&m.available!==!1),byId=new Map(chat.map(m=>[m.id,m])),view=policy.views.default_chat,used=new Set,groups=(view.groups??[]).map(group=>({id:group.id,title:group.title,models:group.model_ids.filter(id2=>byId.has(id2)&&!used.has(id2)&&used.add(id2)).map(id2=>byId.get(id2))})).filter(group=>group.models.length),remaining=chat.filter(m=>!used.has(m.id)),free=remaining.filter(m=>m.billing_mode==="free"),paid=remaining.filter(m=>m.billing_mode!=="free");if(free.length){let group=groups.find(g=>g.id==="free");group?group.models.push(...free):groups.push({id:"free",title:"Free (no USDC needed)",models:free})}paid.length&&groups.push({id:"other",title:"All other available models",models:paid});let virtual=new Set(view.virtual_entries),shortcuts=Object.fromEntries(Object.entries(view.shortcuts).filter(([,target])=>byId.has(target)||virtual.has(target)));for(let model of chat)shortcuts[model.id]=model.id;let pricing=Object.fromEntries(models.flatMap(m=>m.available===!1?[]:m.billing_mode==="free"?[[m.id,{input:0,output:0}]]:m.billing_mode==="paid"?[[m.id,{input:m.pricing.input,output:m.pricing.output}]]:m.billing_mode==="flat"?[[m.id,{input:0,output:0,perCall:m.pricing.flat}]]:[]));return{groups,shortcuts,pricing,virtualEntries:[...virtual]}}function createCatalogClient(options={}){let network=options.network??"solana";if(!(network in gateways))throw new Error(`Unknown catalog network: ${network}`);let snapshot2=validateSnapshot(options.snapshot??snapshot_v1_default),models=snapshotModels(snapshot2,network),source="bundled",lastError,expiresAt=0,inflight,etag,now2=options.now??Date.now,fetcher=options.fetch??globalThis.fetch,listeners=new Set,current=()=>({network,version:snapshot2.catalog.catalog_version,models,source,lastError,...projectCatalog(models,snapshot2.picker_policy)});async function json2(url3,headers={}){let response=await fetcher(url3,{headers:{Accept:"application/json",...headers},signal:AbortSignal.timeout(options.timeoutMs??4e3)});if(response.status===304)return{unchanged:!0};if(!response.ok)throw new Error(`Catalog HTTP ${response.status}`);return{body:await response.json(),etag:response.headers.get("etag")}}return{current,subscribe(listener){return listeners.add(listener),()=>listeners.delete(listener)},refresh({force=!1}={}){return inflight||(!force&&now2()<expiresAt?Promise.resolve(current()):(inflight=(async()=>{try{let[policy,gateway]=await Promise.allSettled([options.catalogUrl?json2(options.catalogUrl,etag?{"If-None-Match":etag}:{}).then(result=>result.unchanged?{snapshot:snapshot2,etag}:{snapshot:validateSnapshot(result.body),etag:result.etag}):Promise.resolve({snapshot:snapshot2,etag}),json2(options.gatewayUrl??gateways[network])]);if(gateway.status==="rejected")throw gateway.reason;if(gateway.value.unchanged)throw new Error("Unexpected gateway 304");let candidateSnapshot=policy.status==="fulfilled"?policy.value.snapshot:snapshot2,releaseDates=new Map(candidateSnapshot.catalog.models.map(m=>[m.id,m.release_date])),nextModels=validateModels(gateway.value.body?.data).filter(m=>m.available!==!1).map(m=>{let releaseDate=m.release_date??releaseDates.get(m.id);return releaseDate===void 0?m:{...m,release_date:releaseDate}});if(!nextModels.length)throw new Error("No available models");if(projectCatalog(nextModels,policy.status==="fulfilled"?policy.value.snapshot.picker_policy:snapshot2.picker_policy),models=nextModels,source="live",policy.status==="fulfilled")snapshot2=policy.value.snapshot,etag=policy.value.etag,lastError=void 0,expiresAt=now2()+(options.ttlMs??3e5);else{let reason=policy.reason;lastError=`Catalog policy: ${reason instanceof Error?reason.message:String(reason)}`,expiresAt=now2()+Math.min(options.ttlMs??3e5,15e3)}}catch(error62){lastError=error62 instanceof Error?error62.message:String(error62),expiresAt=now2()+Math.min(options.ttlMs??3e5,15e3)}let value=current();for(let listener of listeners)listener(value);return value})().finally(()=>{inflight=void 0}),inflight))}}}var gateways,isNumber,init_runtime=__esm({"node_modules/@blockrun/model-catalog/runtime/index.js"(){"use strict";init_snapshot_v1();init_lib();init_ordering();init_ordering();gateways={solana:"https://sol.blockrun.ai/api/v1/models?format=json",base:"https://blockrun.ai/api/v1/models?format=json"},isNumber=value=>typeof value=="number"&&Number.isFinite(value)&&value>=0}});import{open}from"fs/promises";import{openSync,readSync,closeSync,fstatSync}from"fs";async function readTextFile(filePath){let fh=await open(filePath,"r");try{let size4=(await fh.stat()).size,buf=Buffer.alloc(size4),offset=0;for(;offset<size4;){let{bytesRead}=await fh.read(buf,offset,size4-offset,offset);if(bytesRead===0)break;offset+=bytesRead}return buf.subarray(0,offset).toString("utf-8")}finally{await fh.close()}}function readTextFileSync(filePath){let fd=openSync(filePath,"r");try{let size4=fstatSync(fd).size,buf=Buffer.alloc(size4),offset=0;for(;offset<size4;){let bytesRead=readSync(fd,buf,offset,size4-offset,offset);if(bytesRead===0)break;offset+=bytesRead}return buf.subarray(0,offset).toString("utf-8")}finally{closeSync(fd)}}var init_fs_read=__esm({"src/fs-read.ts"(){"use strict"}});import{writeFile,mkdir,rm}from"fs/promises";import{join}from"path";import{homedir}from"os";function isValidApiKey(value){return typeof value!="string"?!1:/^brk_[A-Za-z0-9_-]{8,}$/.test(value.trim())}function maskApiKey(key3){let trimmed=key3.trim();return trimmed.length<=18?`${trimmed.slice(0,8)}\u2026`:`${trimmed.slice(0,14)}\u2026${trimmed.slice(-4)}`}async function readOptional(path8){try{return(await readTextFile(path8)).trim()||void 0}catch(error62){if(error62.code==="ENOENT")return;throw new Error(`Cannot read BlockRun API key file ${path8}; refusing to fall back to another account or wallet.`,{cause:error62})}}async function resolveApiKey(){let envKey=process.env.BLOCKRUN_API_KEY?.trim();if(envKey){if(isValidApiKey(envKey))return{key:envKey,source:"env"};throw new Error(`BLOCKRUN_API_KEY is malformed (expected brk_\u2026). Mint one at ${PORTAL_KEYS_URL}, or unset it to pay from the wallet. Refusing to fall back silently.`)}for(let[path8,source]of[[CORE_API_KEY_FILE,"core"],[API_KEY_FILE,"saved"]]){let stored=await readOptional(path8);if(stored!==void 0){if(isValidApiKey(stored))return{key:stored,source};throw new Error(`${path8} does not contain a BlockRun key (expected brk_\u2026). Run "clawrouter login" with a valid key, or "clawrouter logout" to return to wallet billing. Refusing to fall back silently: the next source could bill a different account or spend from a wallet.`)}}}async function saveApiKey(key3){let trimmed=key3.trim();if(!isValidApiKey(trimmed))throw new Error(`Not a BlockRun API key: expected it to start with "brk_". Mint one at ${PORTAL_KEYS_URL}`);return await mkdir(join(homedir(),".blockrun"),{recursive:!0}),await writeFile(CORE_API_KEY_FILE,trimmed+`
|
|
4
|
-
`,{mode:384}),CORE_API_KEY_FILE}async function clearApiKey(){let removed=[];for(let path8 of[CORE_API_KEY_FILE,API_KEY_FILE])await readOptional(path8)!==void 0&&(await rm(path8,{force:!0}),removed.push(path8));return{removed,envStillSet:!!process.env.BLOCKRUN_API_KEY?.trim()}}async function fetchCreditBalance(apiKey,timeoutMs=5e3){try{let controller=new AbortController,timer2=setTimeout(()=>controller.abort(),timeoutMs),res=await fetch(`${BLOCKRUN_API_KEY_API}/v1/credits`,{headers:{authorization:`Bearer ${apiKey}`},signal:controller.signal});if(clearTimeout(timer2),!res.ok)return;let b=await res.json(),num2=v=>typeof v=="number"?v:null;return{accountId:typeof b.account_id=="string"?b.account_id:void 0,billingMode:typeof b.billing_mode=="string"?b.billing_mode:void 0,currency:typeof b.currency=="string"?b.currency:"USD",grantedUsd:num2(b.granted_usd),spentUsd:num2(b.spent_usd),remainingUsd:num2(b.remaining_usd),blocked:b.blocked===!0,blockedReason:typeof b.blocked_reason=="string"?b.blocked_reason:void 0}}catch{return}}function formatCreditBalance(b){let money=v=>v===null?void 0:`$${v.toFixed(v<.01&&v>0?6:2)}`,remaining=money(b.remainingUsd),spent=money(b.spentUsd);if(remaining)return`${remaining} remaining${spent?` (spent ${spent})`:""}`;let mode2=b.billingMode==="ungated"?"no prepaid limit":b.billingMode??"unknown";return`${spent?`spent ${spent}`:"unknown"} \u2014 ${mode2}`}async function fetchUsagePage(apiKey,opts={}){let params=new URLSearchParams;opts.from&¶ms.set("from",opts.from),opts.to&¶ms.set("to",opts.to),opts.limit&¶ms.set("limit",String(opts.limit)),opts.cursor&¶ms.set("cursor",opts.cursor);let query=params.toString();try{let res=await fetch(`${BLOCKRUN_API_KEY_API}/v1/usage${query?`?${query}`:""}`,{headers:{authorization:`Bearer ${apiKey}`},signal:AbortSignal.timeout(3e4)});if(!res.ok)return;let body=await res.json();return{rows:(body.data??[]).map(r2=>({requestId:String(r2.request_id??""),timestamp:String(r2.timestamp??""),endpoint:String(r2.endpoint??""),model:typeof r2.model=="string"?r2.model:null,kind:String(r2.kind??""),inputTokens:typeof r2.input_tokens=="number"?r2.input_tokens:0,outputTokens:typeof r2.output_tokens=="number"?r2.output_tokens:0,costUsd:typeof r2.cost_usd=="number"?r2.cost_usd:null,costState:String(r2.cost_state??""),status:typeof r2.status=="number"?r2.status:0})),nextCursor:body.next_cursor??null,unavailableDays:body.unavailable_days??[]}}catch{return}}function normalizeApiKeyBase(raw){let base4=raw.replace(/\/+$/,"").replace(/\/v1$/,""),url3=new URL(base4);if(url3.username||url3.password||url3.search||url3.hash||url3.protocol!=="https:"&&!(url3.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(url3.hostname)))throw new Error("BlockRun account API URL requires HTTPS (except localhost) and no credentials, query or fragment.");return base4}function createApiKeyFetch(apiKey,baseFetch=fetch,apiBase=BLOCKRUN_API_KEY_API){let base4=new URL(normalizeApiKeyBase(apiBase));return async(input2,init2)=>{let request2=input2 instanceof Request?input2:void 0,url3=new URL(request2?.url??String(input2),`${base4}/`);if(url3.origin!==base4.origin||url3.username||url3.password)throw new Error("Refusing to forward a BlockRun account key to another origin.");base4.pathname==="/"&&url3.pathname.startsWith("/api/v1/")&&(url3.pathname=url3.pathname.slice(4));let headers=new Headers(init2?.headers??request2?.headers);for(let name of[...headers.keys()])(/payment/i.test(name)||name.toLowerCase()==="x-api-key")&&headers.delete(name);headers.set("authorization",`Bearer ${apiKey}`);let response=await baseFetch(request2?new Request(url3,request2):url3.href,{...init2,headers,redirect:"error"});return response.ok?response:explainApiKeyFailure(response)}}async function pollApiKeyJob(response,payFetch,apiBase,signal,intervalMs=2e3){if(response.status!==202)return response;let initial=await response.clone().json();if(!initial.poll_url)throw new Error("Async account response missing poll_url");let pollUrl=new URL(initial.poll_url,`${normalizeApiKeyBase(apiBase)}/`).href,abort=AbortSignal.any([signal,AbortSignal.timeout(15*6e4)]);for(;!abort.aborted;){let polled=await payFetch(pollUrl,{signal:abort});if([502,503,504,522,524].includes(polled.status))await polled.body?.cancel();else{if(!polled.ok)return polled;let data=await polled.clone().json();if(data.status==="completed"||data.status==="failed")return polled;await polled.body?.cancel()}await new Promise(resolve4=>setTimeout(resolve4,intervalMs))}throw new Error("Async account job did not complete before the client aborted or timed out.")}async function explainApiKeyFailure(response){let hint=HINTS[response.status];if(!hint||!(response.headers.get("content-type")??"").includes("json"))return response;let parsed;try{parsed=await response.clone().json()}catch{return response}if(!parsed?.error||typeof parsed.error.message!="string"||response.status===404&&!/unsupported endpoint/i.test(parsed.error.message))return response;parsed.error.message=`${parsed.error.message} ${hint}`;let headers=new Headers(response.headers);return headers.delete("content-length"),new Response(JSON.stringify(parsed),{status:response.status,statusText:response.statusText,headers})}var API_KEY_FILE,CORE_API_KEY_FILE,PORTAL_URL,PORTAL_KEYS_URL,PORTAL_CREDITS_URL,BLOCKRUN_API_KEY_API,HINTS,init_api_key=__esm({"src/api-key.ts"(){"use strict";init_fs_read();API_KEY_FILE=join(homedir(),".openclaw","blockrun","api-key"),CORE_API_KEY_FILE=join(homedir(),".blockrun",".api-key"),PORTAL_URL="https://user.blockrun.ai",PORTAL_KEYS_URL=`${PORTAL_URL}/dashboard/keys`,PORTAL_CREDITS_URL=`${PORTAL_URL}/dashboard/credits`,BLOCKRUN_API_KEY_API=process.env.BLOCKRUN_API_BASE_URL?.replace(/\/+$/,"").replace(/\/v1$/,"")||"https://api.blockrun.ai";HINTS={401:`Check BLOCKRUN_API_KEY, or mint a new key at ${PORTAL_KEYS_URL}.`,402:`Top up your BlockRun credit at ${PORTAL_CREDITS_URL}.`,404:'api.blockrun.ai does not serve this endpoint. Chat, Anthropic-shaped messages, images, speech, video and the partner APIs (Exa, prediction markets, phone lookup) all work on an API key. The wallet-only exceptions are the routes that bind a lease or a position to a payer address \u2014 buying/renewing/releasing phone numbers, and Polymarket trading \u2014 which need a wallet to own the thing being bought. For those, unset BLOCKRUN_API_KEY and run "clawrouter logout".'}}});var top_models_default,init_top_models=__esm({"src/top-models.json"(){top_models_default=["auto","premium","eco","free","anthropic/claude-fable-5.1","anthropic/claude-fable-5","anthropic/claude-opus-5.5","anthropic/claude-opus-5","anthropic/claude-opus-4.8","anthropic/claude-opus-4.7","anthropic/claude-sonnet-5.5","anthropic/claude-sonnet-5","anthropic/claude-sonnet-4.6","anthropic/claude-haiku-4.5","openai/gpt-6-astra","openai/gpt-6-sol","openai/gpt-6.1-sol","openai/gpt-6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","openai/gpt-5.6-luna","openai/gpt-5.6-terra-pro","openai/gpt-5.6-sol-pro","openai/gpt-5.6-luna-pro","openai/gpt-5.5","openai/gpt-5.5-pro","openai/gpt-5.4-pro","openai/gpt-5.4","openai/gpt-5.4-mini","openai/gpt-5.4-nano","openai/gpt-5.1","openai/gpt-5.3-codex","google/gemini-4-argon","google/gemini-3.1-pro","google/gemini-3.8-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","google/gemini-3.1-flash-lite","google/gemini-3-flash-preview","xai/grok-4.7","xai/grok-4.6","xai/grok-4.5","xai/grok-4.3","xai/grok-build-0.1","zai/glm-5.3","zai/glm-5.3-flash","zai/glm-5.2","zai/glm-5.1","zai/glm-5-turbo","zai/glm-5","xiaomi/mimo-v2.5","xiaomi/mimo-v2.5-pro","tencent/hy4-preview","mistral/mistral-large-4","poolside/laguna-s-2.1","minimax/minimax-m3","minimax/minimax-m2.7","moonshot/kimi-k3.1-pro","qwen/qwen3.7-max","qwen/qwen3.8-max","qwen/qwen3.8-flash","deepseek/deepseek-v4-flash-vision-exp","deepseek/deepseek-v4-pro","deepseek/deepseek-v4.1-flash","deepseek/deepseek-chat","deepseek/deepseek-reasoner","free/nemotron-3.5-lightning","free/laguna-xs-2.1","free/nemotron-3-nano-omni-30b-a3b-reasoning","free/nemotron-3-ultra-550b","free/nemotron-3.5-bolt","free/nemotron-3-super-120b","free/muse-glimmer-30b"]}});function loadTopModels(){let parsed=top_models_default;if(!Array.isArray(parsed)||parsed.some(value=>typeof value!="string"||!value.trim()))throw new Error("top-models.json must be a JSON array of non-empty strings");return[...parsed]}var TOP_MODELS,init_top_models2=__esm({"src/top-models.ts"(){"use strict";init_top_models();TOP_MODELS=Object.freeze(loadTopModels())}});function resolveModelAlias(model){let normalized=model.trim().toLowerCase(),resolved=MODEL_ALIASES[normalized];if(resolved)return resolved;if(normalized.startsWith("blockrun/")){let withoutPrefix=normalized.slice(9),resolvedWithoutPrefix=MODEL_ALIASES[withoutPrefix];return resolvedWithoutPrefix||withoutPrefix}if(normalized.startsWith("openai/")){let withoutPrefix=normalized.slice(7),resolvedWithoutPrefix=MODEL_ALIASES[withoutPrefix];if(resolvedWithoutPrefix)return resolvedWithoutPrefix;if(BLOCKRUN_MODELS.some(m=>m.id===withoutPrefix))return withoutPrefix}if(normalized.startsWith("openai-codex/")){let withoutPrefix=normalized.slice(13),resolvedWithoutPrefix=MODEL_ALIASES[withoutPrefix];if(resolvedWithoutPrefix)return resolvedWithoutPrefix;if(BLOCKRUN_MODELS.some(m=>m.id===withoutPrefix))return withoutPrefix}return model}function getActivePromoPrice(model,now2=new Date){if(model.flatPrice!==void 0)return model.flatPrice;if(!model.promo)return;let start=new Date(model.promo.startDate),end=new Date(model.promo.endDate);if(now2>=start&&now2<end)return model.promo.flatPrice}function toOpenClawModel(m){return{id:m.id,name:m.name,api:"openai-completions",reasoning:m.reasoning??!1,input:m.vision?["text","image"]:["text"],cost:{input:m.inputPrice,output:m.outputPrice,cacheRead:0,cacheWrite:0},contextWindow:m.contextWindow,maxTokens:m.maxOutput}}function buildProviderModels(baseUrl){return{baseUrl:`${baseUrl}/v1`,api:"openai-completions",models:VISIBLE_OPENCLAW_MODELS}}function isAgenticModel(modelId){return BLOCKRUN_MODELS.find(m=>m.id===modelId||m.id===modelId.replace("blockrun/",""))?.agentic??!1}function getAgenticModels(){return BLOCKRUN_MODELS.filter(m=>m.agentic).map(m=>m.id)}function getModelContextWindow(modelId){let normalized=modelId.replace("blockrun/","");return BLOCKRUN_MODELS.find(m=>m.id===normalized)?.contextWindow}function isReasoningModel(modelId){let normalized=modelId.replace("blockrun/","");return BLOCKRUN_MODELS.find(m=>m.id===normalized)?.reasoning??!1}var MODEL_ALIASES,BLOCKRUN_MODELS,ALIAS_MODELS,OPENCLAW_MODELS,OPENCLAW_MODEL_BY_ID,VISIBLE_OPENCLAW_MODELS,init_models=__esm({"src/models.ts"(){"use strict";init_top_models2();MODEL_ALIASES={claude:"anthropic/claude-sonnet-4.6","br-sonnet":"anthropic/claude-sonnet-4.6",sonnet:"anthropic/claude-sonnet-4.6","sonnet-4":"anthropic/claude-sonnet-4.6","sonnet-4.6":"anthropic/claude-sonnet-4.6","sonnet-4-6":"anthropic/claude-sonnet-4.6","sonnet-5":"anthropic/claude-sonnet-5","sonnet-5.0":"anthropic/claude-sonnet-5","sonnet-5-0":"anthropic/claude-sonnet-5","sonnet-5.5":"anthropic/claude-sonnet-5.5","sonnet-5-5":"anthropic/claude-sonnet-5.5","anthropic/claude-sonnet-5-5":"anthropic/claude-sonnet-5.5","sonnet-4.5":"anthropic/claude-sonnet-4.5","sonnet-4-5":"anthropic/claude-sonnet-4.5","anthropic/claude-sonnet-4-5":"anthropic/claude-sonnet-4.5",fable:"anthropic/claude-fable-5","fable-5":"anthropic/claude-fable-5","fable-5.0":"anthropic/claude-fable-5","fable-5.1":"anthropic/claude-fable-5.1","fable-5-1":"anthropic/claude-fable-5.1","fable-5.2":"anthropic/claude-fable-5.2","fable-5-2":"anthropic/claude-fable-5.2","anthropic/claude-fable-5-1":"anthropic/claude-fable-5.1",opus:"anthropic/claude-opus-5","opus-5":"anthropic/claude-opus-5","opus-5.0":"anthropic/claude-opus-5","opus-5-0":"anthropic/claude-opus-5","opus-5.5":"anthropic/claude-opus-5.5","opus-5-5":"anthropic/claude-opus-5.5","anthropic/claude-opus-5-5":"anthropic/claude-opus-5.5","opus-4":"anthropic/claude-opus-4.8","opus-4.8":"anthropic/claude-opus-4.8","opus-4-8":"anthropic/claude-opus-4.8","opus-4.7":"anthropic/claude-opus-4.7","opus-4-7":"anthropic/claude-opus-4.7","opus-4.6":"anthropic/claude-opus-4.6","opus-4-6":"anthropic/claude-opus-4.6",haiku:"anthropic/claude-haiku-4.5","anthropic/sonnet":"anthropic/claude-sonnet-4.6","anthropic/fable":"anthropic/claude-fable-5","anthropic/claude-fable-5.0":"anthropic/claude-fable-5","anthropic/opus":"anthropic/claude-opus-5","anthropic/claude-opus-5.0":"anthropic/claude-opus-5","anthropic/claude-opus-5-0":"anthropic/claude-opus-5","anthropic/haiku":"anthropic/claude-haiku-4.5","anthropic/claude":"anthropic/claude-sonnet-4.6","anthropic/claude-sonnet-4":"anthropic/claude-sonnet-4.6","anthropic/claude-sonnet-4-6":"anthropic/claude-sonnet-4.6","anthropic/claude-opus-4":"anthropic/claude-opus-4.8","anthropic/claude-opus-4-8":"anthropic/claude-opus-4.8","anthropic/claude-opus-4-7":"anthropic/claude-opus-4.7","anthropic/claude-opus-4-6":"anthropic/claude-opus-4.6","anthropic/claude-opus-4-5":"anthropic/claude-opus-4.5","anthropic/claude-haiku-4":"anthropic/claude-haiku-4.5","anthropic/claude-haiku-4-5":"anthropic/claude-haiku-4.5",gpt:"openai/gpt-4o",gpt4:"openai/gpt-4o",gpt5:"openai/gpt-5.6-terra","gpt-5.6":"openai/gpt-5.6-terra","openai/gpt-5.6":"openai/gpt-5.6-terra","gpt-5.6-sol":"openai/gpt-5.6-sol","gpt-5.6-terra":"openai/gpt-5.6-terra","gpt-5.6-luna":"openai/gpt-5.6-luna","gpt-5.6-sol-pro":"openai/gpt-5.6-sol-pro","gpt-5.6-terra-pro":"openai/gpt-5.6-terra-pro","gpt-5.6-luna-pro":"openai/gpt-5.6-luna-pro","sol-pro":"openai/gpt-5.6-sol-pro","terra-pro":"openai/gpt-5.6-terra-pro","luna-pro":"openai/gpt-5.6-luna-pro","gpt-6-astra":"openai/gpt-6-astra","gpt-6-sol":"openai/gpt-6-sol","gpt-6-luna":"openai/gpt-6-luna","gpt-6.1-sol":"openai/gpt-6.1-sol","gpt-6-1-sol":"openai/gpt-6.1-sol","gpt-5.5":"openai/gpt-5.5","gpt-5.5-pro":"openai/gpt-5.5-pro","chat-latest":"openai/chat-latest",chatgpt:"openai/chat-latest","gpt-5.4":"openai/gpt-5.4","gpt-5.1":"openai/gpt-5.1","gpt-5.4-pro":"openai/gpt-5.4-pro","gpt-5.4-nano":"openai/gpt-5.4-nano",nano:"openai/gpt-5.4-nano","gpt-5-nano":"openai/gpt-5-nano",codex:"openai/gpt-5.3-codex",mini:"openai/gpt-4o-mini",o1:"openai/gpt-5.4-mini","openai/o1-mini":"openai/gpt-5.4-mini","o1-mini":"openai/gpt-5.4-mini",o3:"openai/gpt-5.4-mini","openai-codex/gpt-5.4-mini":"openai/gpt-5.4-mini","gpt-5.4-mini":"openai/gpt-5.4-mini",deepseek:"deepseek/deepseek-v4.1-flash","deepseek-chat":"deepseek/deepseek-chat",reasoner:"deepseek/deepseek-reasoner","deepseek-v4.1-flash":"deepseek/deepseek-v4.1-flash","deepseek-v4-1-flash":"deepseek/deepseek-v4.1-flash","v4.1-flash":"deepseek/deepseek-v4.1-flash",kimi:"moonshot/kimi-k2.7",moonshot:"moonshot/kimi-k2.7","kimi-k3":"moonshot/kimi-k3","kimi-k3.1":"moonshot/kimi-k3.1-pro","kimi-k3.1-pro":"moonshot/kimi-k3.1-pro","kimi-k2":"moonshot/kimi-k2.7","kimi-k2.7":"moonshot/kimi-k2.7","kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.5":"moonshot/kimi-k2.5","nvidia/kimi-k2.5":"moonshot/kimi-k2.5","qwen3.7-max":"qwen/qwen3.7-max","qwen3.8-max":"qwen/qwen3.8-max","qwen-3.8-max":"qwen/qwen3.8-max","qwen3-8-max":"qwen/qwen3.8-max","qwen3.8-flash":"qwen/qwen3.8-flash","qwen3-8-flash":"qwen/qwen3.8-flash","qwen-vision":"qwen/qwen3.8-flash","deepseek-vision":"deepseek/deepseek-v4-flash-vision-exp","v4-flash-vision":"deepseek/deepseek-v4-flash-vision-exp","mimo-vision":"xiaomi/mimo-v2.5","qwen-3.7-max":"qwen/qwen3.7-max","qwen3-7-max":"qwen/qwen3.7-max","qwen3.7-plus":"qwen/qwen3.7-plus","qwen-3.7-plus":"qwen/qwen3.7-plus","qwen3.7-flash":"qwen/qwen3.7-flash","qwen-3.7-flash":"qwen/qwen3.7-flash",hy3:"tencent/hy3",tencent:"tencent/hy3",hunyuan:"tencent/hy3",hy4:"tencent/hy4-preview","hy4-preview":"tencent/hy4-preview",mimo:"xiaomi/mimo-v2.5-pro","mimo-v2.5-pro":"xiaomi/mimo-v2.5-pro","mimo-v2.5":"xiaomi/mimo-v2.5",xiaomi:"xiaomi/mimo-v2.5-pro","google/gemini-3-pro-preview":"google/gemini-3.1-pro","gemini-3-pro-preview":"google/gemini-3.1-pro","gemini-pro":"google/gemini-3.1-pro","gemini-3-pro":"google/gemini-3.1-pro","gemini-3.1-pro":"google/gemini-3.1-pro",gemini:"google/gemini-3.8-flash",flash:"google/gemini-3.5-flash-lite","gemini-3.1-pro-preview":"google/gemini-3.1-pro","google/gemini-3.1-pro-preview":"google/gemini-3.1-pro","gemini-3.6-flash":"google/gemini-3.6-flash","gemini-3.6":"google/gemini-3.6-flash","gemini-3.5-flash":"google/gemini-3.6-flash","gemini-3.5-flash-lite":"google/gemini-3.5-flash-lite","gemini-3.1-flash-lite":"google/gemini-3.1-flash-lite","gemini-2.5-flash-lite":"google/gemini-2.5-flash-lite",grok:"xai/grok-4.5","grok-4.5":"xai/grok-4.5","grok-4-5":"xai/grok-4.5","grok-4.7":"xai/grok-4.7","grok-4-7":"xai/grok-4.7","grok-4.6":"xai/grok-4.6","grok-4-6":"xai/grok-4.6","grok-4.3":"xai/grok-4.3","grok-fast":"xai/grok-4-1-fast-reasoning","grok-build":"xai/grok-build-0.1","grok-code":"xai/grok-build-0.1","grok-code-fast-1":"deepseek/deepseek-chat","xai/grok-code-fast-1":"deepseek/deepseek-chat","xai/grok-3-fast":"xai/grok-4-1-fast-reasoning",nvidia:"free/nemotron-3.5-lightning","gpt-120b":"free/gpt-oss-120b","gpt-20b":"free/gpt-oss-20b","nvidia/gpt-oss-120b":"free/gpt-oss-120b","nvidia/gpt-oss-20b":"free/gpt-oss-20b","nvidia/deepseek-v3.2":"free/nemotron-3.5-lightning","free/deepseek-v3.2":"free/nemotron-3.5-lightning","nvidia/deepseek-v4-pro":"free/nemotron-3.5-lightning","free/deepseek-v4-pro":"free/nemotron-3.5-lightning","nvidia/deepseek-v4-flash":"free/nemotron-3.5-lightning","nvidia/nemotron-3-nano-omni-30b-a3b-reasoning":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nvidia/qwen3-coder-480b":"free/qwen3-coder-480b","qwen/qwen3-coder-480b-a35b-instruct":"free/qwen3-coder-480b","nvidia/glm-4.7":"free/glm-4.7","nvidia/llama-4-maverick":"free/llama-4-maverick","nvidia/qwen3-next-80b-a3b-thinking":"free/qwen3-next-80b-a3b-instruct","nvidia/qwen3-next-80b-a3b-instruct":"free/qwen3-next-80b-a3b-instruct","nvidia/seed-oss-36b":"free/seed-oss-36b","nvidia/mistral-nemotron":"free/mistral-nemotron","nvidia/step-3.7-flash":"free/step-3.7-flash","nvidia/nemotron-nano-9b-v2":"free/nemotron-nano-9b-v2","nvidia/nemotron-nano-12b-v2-vl":"free/nemotron-nano-12b-v2-vl","nvidia/nemotron-ultra-253b":"free/nemotron-3.5-lightning","nvidia/mistral-large-3-675b":"free/mistral-large-3-675b","nvidia/qwen3.5-122b-a10b":"free/qwen3.5-122b-a10b","nvidia/devstral-2-123b":"free/nemotron-3.5-lightning","free/nemotron-ultra-253b":"free/nemotron-3.5-lightning","free/devstral-2-123b":"free/nemotron-3.5-lightning","mistral-large":"free/mistral-large-3-675b","mistral-large-3-675b":"free/mistral-large-3-675b","qwen3.5-122b":"free/qwen3.5-122b-a10b","mistral-large-4":"mistral/mistral-large-4","qwen3-122b":"free/qwen3.5-122b-a10b","deepseek-free":"free/nemotron-3.5-lightning","deepseek-v4-pro":"free/nemotron-3.5-lightning","deepseek-v4-flash":"free/nemotron-3.5-lightning","v4-pro":"free/nemotron-3.5-lightning","v4-flash":"free/nemotron-3.5-lightning","mistral-free":"free/nemotron-3.5-lightning","glm-free":"free/nemotron-3.5-lightning","llama-free":"free/muse-glimmer-30b","qwen-coder":"free/nemotron-3.5-lightning","qwen-coder-free":"free/nemotron-3.5-lightning","qwen-thinking":"free/nemotron-3.5-lightning","qwen3-next":"free/qwen3-next-80b-a3b-instruct","qwen3-next-80b":"free/qwen3-next-80b-a3b-instruct","mistral-small":"free/nemotron-3.5-lightning","seed-oss":"free/seed-oss-36b","seed-oss-36b":"free/seed-oss-36b","coder-free":"free/laguna-xs-2.1","mistral-nemotron":"free/mistral-nemotron","step-flash":"free/step-3.7-flash","step-3.7-flash":"free/step-3.7-flash","nemotron-nano-9b":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-nano":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-nano-vl":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nano-vl":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-omni":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nano-omni":"free/nemotron-3-nano-omni-30b-a3b-reasoning","vision-free":"free/nemotron-3.5-bolt",nemotron:"free/nemotron-3.5-lightning","nemotron-ultra":"free/nemotron-3.5-lightning","nemotron-253b":"free/nemotron-3.5-lightning","nemotron-super":"free/nemotron-3-super-120b","nemotron-49b":"free/nemotron-3.5-lightning","nemotron-120b":"free/nemotron-3.5-lightning",devstral:"free/nemotron-3.5-lightning","devstral-2":"free/nemotron-3.5-lightning",maverick:"free/llama-4-maverick","nvidia/nemotron-3.5-lightning":"free/nemotron-3.5-lightning","nvidia/nemotron-3-nano-30b":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nvidia/nemotron-3-ultra-550b":"free/nemotron-3-ultra-550b","nvidia/minimax-m3.1-flash":"free/minimax-m3.1-flash","nvidia/llama-3.2-11b-vision":"free/llama-3.2-11b-vision","cohere/north-mini-code":"free/north-mini-code","poolside/laguna-xs-2.1":"free/laguna-xs-2.1",lightning:"free/nemotron-3.5-lightning","nemotron-lightning":"free/nemotron-3.5-lightning","nemotron-3.5-lightning":"free/nemotron-3.5-lightning","nano-30b":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-nano-30b":"free/nemotron-3-nano-omni-30b-a3b-reasoning","ultra-550b":"free/nemotron-3-ultra-550b","nemotron-ultra-550b":"free/nemotron-3-ultra-550b","minimax-m3.1-flash":"free/minimax-m3.1-flash","llama-vision":"free/llama-3.2-11b-vision","llama-3.2-vision":"free/llama-3.2-11b-vision","north-mini":"free/laguna-xs-2.1","north-mini-code":"free/laguna-xs-2.1",laguna:"free/laguna-xs-2.1","laguna-xs":"free/laguna-xs-2.1","laguna-s":"poolside/laguna-s-2.1","laguna-s-2.1":"poolside/laguna-s-2.1","nvidia/muse-glimmer-30b":"free/muse-glimmer-30b","nvidia/nemotron-3.5-bolt":"free/nemotron-3.5-bolt","nemotron-3.5-bolt":"free/nemotron-3.5-bolt",bolt:"free/nemotron-3.5-bolt","nvidia/nemotron-3-super-120b":"free/nemotron-3-super-120b","nemotron-3-super-120b":"free/nemotron-3-super-120b","super-120b":"free/nemotron-3-super-120b",muse:"free/muse-glimmer-30b","muse-glimmer":"free/muse-glimmer-30b","muse-glimmer-30b":"free/muse-glimmer-30b",free:"free/nemotron-3.5-lightning",minimax:"minimax/minimax-m3","minimax-m3":"minimax/minimax-m3","minimax-m2.7":"minimax/minimax-m2.7","minimax-m2.5":"minimax/minimax-m2.5",glm:"zai/glm-5.3","glm-5.3":"zai/glm-5.3","glm-5-3":"zai/glm-5.3","glm-5.3-flash":"zai/glm-5.3-flash","glm-5-3-flash":"zai/glm-5.3-flash","glm-flash":"zai/glm-5.3-flash","glm-5.2":"zai/glm-5.2","glm-5":"zai/glm-5","glm-5.1":"zai/glm-5.1","glm-5-turbo":"zai/glm-5-turbo","auto-router":"auto",router:"auto",dalle:"openai/gpt-image-2","dall-e":"openai/gpt-image-2","gpt-image":"openai/gpt-image-1","gpt-image-2":"openai/gpt-image-2","nano-banana":"google/nano-banana",banana:"google/nano-banana","banana-pro":"google/nano-banana-pro","nano-banana-pro":"google/nano-banana-pro","nano-banana-2":"google/nano-banana-2","banana-2":"google/nano-banana-2",seedream:"bytedance/seedream-5-pro","grok-imagine":"xai/grok-imagine-image","grok-imagine-pro":"xai/grok-imagine-image-pro",cogview:"zai/cogview-4","grok-video":"xai/grok-imagine-video","grok-video-1.5":"xai/grok-imagine-video-1.5","grok-video-1-5":"xai/grok-imagine-video-1.5",seedance:"bytedance/seedance-1.5-pro","seedance-1.5":"bytedance/seedance-1.5-pro","seedance-2-fast":"bytedance/seedance-2.0-fast","seedance-2":"bytedance/seedance-2.0","seedance-2.5":"bytedance/seedance-2.5","seedance-2-5":"bytedance/seedance-2.5","seedance-2-mini":"bytedance/seedance-2.0-mini","seedance-2.0-mini":"bytedance/seedance-2.0-mini","seedance-mini":"bytedance/seedance-2.0-mini"};BLOCKRUN_MODELS=[{id:"auto",name:"Auto (Smart Router - Balanced)",inputPrice:0,outputPrice:0,contextWindow:105e4,maxOutput:128e3},{id:"free",name:"Free \u2192 Nemotron 3.5 Lightning",inputPrice:0,outputPrice:0,contextWindow:1e6,maxOutput:16384,reasoning:!0},{id:"eco",name:"Eco (Smart Router - Cost Optimized)",inputPrice:0,outputPrice:0,contextWindow:105e4,maxOutput:128e3},{id:"premium",name:"Premium (Smart Router - Best Quality)",inputPrice:0,outputPrice:0,contextWindow:2e6,maxOutput:2e5},{id:"openai/gpt-5.2",name:"GPT-5.2",version:"5.2",inputPrice:1.75,outputPrice:14,contextWindow:4e5,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5-mini",name:"GPT-5 Mini",version:"5.0",inputPrice:.25,outputPrice:2,contextWindow:2e5,maxOutput:128e3,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.6-luna"},{id:"openai/gpt-5-nano",name:"GPT-5 Nano",version:"5.0",inputPrice:.05,outputPrice:.4,contextWindow:128e3,maxOutput:128e3,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-nano"},{id:"openai/gpt-5.2-pro",name:"GPT-5.2 Pro",version:"5.2",inputPrice:21,outputPrice:168,contextWindow:4e5,maxOutput:128e3,reasoning:!0,vision:!0,toolCalling:!0},{id:"openai/gpt-6-astra",name:"GPT-6 Astra",version:"6",inputPrice:10,outputPrice:50,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-6-sol",name:"GPT-6 Sol",version:"6",inputPrice:2,outputPrice:10,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-6.1-sol",name:"GPT-6.1 Sol",version:"6.1",inputPrice:2,outputPrice:10,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-6-luna",name:"GPT-6 Luna",version:"6",inputPrice:.1,outputPrice:.5,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-sol",name:"GPT-5.6 Sol",version:"5.6",inputPrice:4,outputPrice:20,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-terra",name:"GPT-5.6 Terra",version:"5.6",inputPrice:2,outputPrice:12,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-luna",name:"GPT-5.6 Luna",version:"5.6",inputPrice:.2,outputPrice:1.2,contextWindow:105e4,maxOutput:128e3,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-sol-pro",name:"GPT-5.6 Sol Pro",version:"5.6",inputPrice:4,outputPrice:20,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-terra-pro",name:"GPT-5.6 Terra Pro",version:"5.6",inputPrice:2,outputPrice:12,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-luna-pro",name:"GPT-5.6 Luna Pro",version:"5.6",inputPrice:.2,outputPrice:1.2,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.5",name:"GPT-5.5",version:"5.5",inputPrice:5,outputPrice:30,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.5-pro",name:"GPT-5.5 Pro",version:"5.5",inputPrice:30,outputPrice:180,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,toolCalling:!0},{id:"openai/chat-latest",name:"ChatGPT Instant (GPT-5.5)",version:"5.5",inputPrice:5,outputPrice:30,contextWindow:128e3,maxOutput:128e3,vision:!0,toolCalling:!0},{id:"openai/gpt-5.4",name:"GPT-5.4",version:"5.4",inputPrice:2.5,outputPrice:15,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.4-mini",name:"GPT-5.4 Mini",version:"5.4",inputPrice:.75,outputPrice:4.5,contextWindow:4e5,maxOutput:128e3,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.4-pro",name:"GPT-5.4 Pro",version:"5.4",inputPrice:30,outputPrice:180,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,toolCalling:!0},{id:"openai/gpt-5.4-nano",name:"GPT-5.4 Nano",version:"5.4",inputPrice:.2,outputPrice:1.25,contextWindow:105e4,maxOutput:128e3,toolCalling:!0},{id:"openai/gpt-5.1",name:"GPT-5.1",version:"5.1",inputPrice:1.25,outputPrice:10,contextWindow:4e5,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.3",name:"GPT-5.3",version:"5.3",inputPrice:1.75,outputPrice:14,contextWindow:128e3,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.2"},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",version:"5.3",inputPrice:1.75,outputPrice:14,contextWindow:4e5,maxOutput:128e3,agentic:!0,toolCalling:!0},{id:"openai/gpt-4.1",name:"GPT-4.1",version:"4.1",inputPrice:2,outputPrice:8,contextWindow:128e3,maxOutput:32768,vision:!0,toolCalling:!0},{id:"openai/gpt-4.1-mini",name:"GPT-4.1 Mini",version:"4.1",inputPrice:.4,outputPrice:1.6,contextWindow:128e3,maxOutput:32768,toolCalling:!0},{id:"openai/gpt-4.1-nano",name:"GPT-4.1 Nano",version:"4.1",inputPrice:.1,outputPrice:.4,contextWindow:128e3,maxOutput:32768,toolCalling:!0},{id:"openai/gpt-4o",name:"GPT-4o",version:"4o",inputPrice:2.5,outputPrice:10,contextWindow:128e3,maxOutput:16384,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-4o-mini",name:"GPT-4o Mini",version:"4o-mini",inputPrice:.15,outputPrice:.6,contextWindow:128e3,maxOutput:16384,toolCalling:!0},{id:"openai/o1",name:"o1",version:"1",inputPrice:15,outputPrice:60,contextWindow:2e5,maxOutput:1e5,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-mini"},{id:"openai/o1-mini",name:"o1-mini",version:"1-mini",inputPrice:1.1,outputPrice:4.4,contextWindow:128e3,maxOutput:65536,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-mini"},{id:"openai/o3",name:"o3",version:"3",inputPrice:2,outputPrice:8,contextWindow:2e5,maxOutput:1e5,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-mini"},{id:"openai/o3-mini",name:"o3-mini",version:"3-mini",inputPrice:1.1,outputPrice:4.4,contextWindow:128e3,maxOutput:1e5,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-mini"},{id:"openai/o4-mini",name:"o4-mini",version:"4-mini",inputPrice:1.1,outputPrice:4.4,contextWindow:128e3,maxOutput:1e5,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-mini"},{id:"anthropic/claude-haiku-4.5",name:"Claude Haiku 4.5",version:"4.5",inputPrice:1,outputPrice:5,contextWindow:2e5,maxOutput:64e3,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-sonnet-4.5",name:"Claude Sonnet 4.5",version:"4.5",inputPrice:3,outputPrice:15,contextWindow:2e5,maxOutput:64e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",version:"4.6",inputPrice:3,outputPrice:15,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-sonnet-5",name:"Claude Sonnet 5",version:"5",inputPrice:2,outputPrice:10,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-4.5",name:"Claude Opus 4.5",version:"4.5",inputPrice:5,outputPrice:25,contextWindow:2e5,maxOutput:64e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",version:"4.6",inputPrice:5,outputPrice:25,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-fable-5",name:"Claude Fable 5",version:"5",inputPrice:10,outputPrice:50,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-4.7",name:"Claude Opus 4.7",version:"4.7",inputPrice:5,outputPrice:25,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-4.8",name:"Claude Opus 4.8",version:"4.8",inputPrice:5,outputPrice:25,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-5",name:"Claude Opus 5",version:"5",inputPrice:5,outputPrice:25,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-fable-5.1",name:"Claude Fable 5.1",version:"5.1",inputPrice:10,outputPrice:50,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-fable-5.2",name:"Claude Fable 5.2",version:"5.2",inputPrice:8,outputPrice:40,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-5.5",name:"Claude Opus 5.5",version:"5.5",inputPrice:4,outputPrice:20,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-sonnet-5.5",name:"Claude Sonnet 5.5",version:"5.5",inputPrice:2,outputPrice:10,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"google/gemini-3.1-pro",name:"Gemini 3.1 Pro",version:"3.1",inputPrice:2,outputPrice:12,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-3-pro-preview",name:"Gemini 3 Pro Preview",version:"3.0",inputPrice:2,outputPrice:12,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-4-argon",name:"Gemini 4 Argon",version:"4",inputPrice:2,outputPrice:10,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-4-carbon",name:"Gemini 4 Carbon",version:"4",inputPrice:2,outputPrice:10,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-3.8-flash",name:"Gemini 3.8 Flash",version:"3.8",inputPrice:.75,outputPrice:3.75,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-3.6-flash",name:"Gemini 3.6 Flash",version:"3.6",inputPrice:.75,outputPrice:3.75,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-3.5-flash",name:"Gemini 3.5 Flash",version:"3.5",inputPrice:1.5,outputPrice:9,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0,deprecated:!0,fallbackModel:"google/gemini-3.6-flash"},{id:"google/gemini-3.5-flash-lite",name:"Gemini 3.5 Flash Lite",version:"3.5",inputPrice:.3,outputPrice:2.5,contextWindow:1048576,maxOutput:65536,reasoning:!0,toolCalling:!0},{id:"google/gemini-3-flash-preview",name:"Gemini 3 Flash Preview",version:"3.0",inputPrice:.5,outputPrice:3,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0},{id:"google/gemini-2.5-pro",name:"Gemini 2.5 Pro",version:"2.5",inputPrice:1.25,outputPrice:10,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0,deprecated:!0,fallbackModel:"google/gemini-3.8-flash"},{id:"google/gemini-2.5-flash",name:"Gemini 2.5 Flash",version:"2.5",inputPrice:.3,outputPrice:2.5,contextWindow:1048576,maxOutput:65536,vision:!0,toolCalling:!0,deprecated:!0,fallbackModel:"google/gemini-3.5-flash-lite"},{id:"google/gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",version:"2.5",inputPrice:.1,outputPrice:.4,contextWindow:1048576,maxOutput:65536,vision:!0,toolCalling:!0},{id:"google/gemini-3.1-flash-lite",name:"Gemini 3.1 Flash Lite",version:"3.1",inputPrice:.25,outputPrice:1.5,contextWindow:1048576,maxOutput:65536,toolCalling:!0},{id:"deepseek/deepseek-chat",name:"DeepSeek Chat (V4.1 Flash)",version:"4.1-flash",inputPrice:.14,outputPrice:.28,contextWindow:1048576,maxOutput:65536,toolCalling:!0},{id:"deepseek/deepseek-reasoner",name:"DeepSeek Reasoner (V4.1 Flash)",version:"4.1-flash",inputPrice:.14,outputPrice:.28,contextWindow:1048576,maxOutput:65536,reasoning:!0,toolCalling:!0},{id:"deepseek/deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",version:"4.1-flash",inputPrice:.14,outputPrice:.28,contextWindow:1048576,maxOutput:65536,toolCalling:!0},{id:"deepseek/deepseek-v4-pro",name:"DeepSeek V4 Pro",version:"4-pro",inputPrice:1.32,outputPrice:3.96,contextWindow:1048576,maxOutput:65536,reasoning:!0,agentic:!0,toolCalling:!0},{id:"moonshot/kimi-k3.1-pro",name:"Kimi K3.1 Pro",version:"k3.1-pro",inputPrice:2,outputPrice:10,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"moonshot/kimi-k3",name:"Kimi K3",version:"k3",inputPrice:3,outputPrice:15,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"moonshot/kimi-k2.7",name:"Kimi K2.7",version:"k2.7",inputPrice:.95,outputPrice:4,contextWindow:262144,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"qwen/qwen3.7-max",name:"Qwen3.7 Max",version:"3.7-max",inputPrice:1.475,outputPrice:4.425,contextWindow:1e6,maxOutput:65536,reasoning:!0,agentic:!0,toolCalling:!0},{id:"qwen/qwen3.7-plus",name:"Qwen3.7 Plus",version:"3.7-plus",inputPrice:.32,outputPrice:1.28,contextWindow:1e6,maxOutput:131072,reasoning:!0,agentic:!0,toolCalling:!0},{id:"qwen/qwen3.7-flash",name:"Qwen3.7 Flash",version:"3.7-flash",inputPrice:.03,outputPrice:.13,contextWindow:1e6,maxOutput:65536,reasoning:!0,toolCalling:!0},{id:"moonshot/kimi-k2.6",name:"Kimi K2.6",version:"k2.6",inputPrice:.95,outputPrice:4,contextWindow:262144,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"moonshot/kimi-k2.5",name:"Kimi K2.5",version:"k2.5",inputPrice:.6,outputPrice:3,contextWindow:262144,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"nvidia/kimi-k2.5",name:"Kimi K2.5 (NVIDIA, retired)",version:"k2.5",inputPrice:.6,outputPrice:3,contextWindow:262144,maxOutput:16384,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0,deprecated:!0,fallbackModel:"moonshot/kimi-k2.5"},{id:"xai/grok-3",name:"Grok 3",version:"3",inputPrice:3,outputPrice:15,contextWindow:131072,maxOutput:16384,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"xai/grok-4-1-fast-non-reasoning"},{id:"xai/grok-3-mini",name:"Grok 3 Mini",version:"3-mini",inputPrice:.3,outputPrice:.5,contextWindow:131072,maxOutput:16384,toolCalling:!0,deprecated:!0,fallbackModel:"xai/grok-4-1-fast-non-reasoning"},{id:"xai/grok-4-fast-reasoning",name:"Grok 4 Fast Reasoning",version:"4",inputPrice:.2,outputPrice:.5,contextWindow:2e6,maxOutput:16384,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"xai/grok-4-1-fast-reasoning"},{id:"xai/grok-4-fast-non-reasoning",name:"Grok 4 Fast",version:"4",inputPrice:.2,outputPrice:.5,contextWindow:2e6,maxOutput:16384,toolCalling:!0,deprecated:!0,fallbackModel:"xai/grok-4-1-fast-non-reasoning"},{id:"xai/grok-4-1-fast-reasoning",name:"Grok 4.1 Fast Reasoning",version:"4.1",inputPrice:.2,outputPrice:.5,contextWindow:2e6,maxOutput:16384,reasoning:!0,toolCalling:!0},{id:"xai/grok-4-1-fast-non-reasoning",name:"Grok 4.1 Fast",version:"4.1",inputPrice:.2,outputPrice:.5,contextWindow:2e6,maxOutput:16384,toolCalling:!0},{id:"xai/grok-4-0709",name:"Grok 4 (0709)",version:"4-0709",inputPrice:3,outputPrice:15,contextWindow:256e3,maxOutput:16384,reasoning:!0,toolCalling:!0},{id:"xai/grok-2-vision",name:"Grok 2 Vision",version:"2",inputPrice:2,outputPrice:10,contextWindow:32768,maxOutput:16384,vision:!0,toolCalling:!0,deprecated:!0,fallbackModel:"xai/grok-4.3"},{id:"xai/grok-4.20-reasoning",name:"Grok 4.20 Reasoning",version:"4.20",inputPrice:2,outputPrice:6,contextWindow:2e6,maxOutput:16384,reasoning:!0,toolCalling:!0},{id:"xai/grok-4.20-non-reasoning",name:"Grok 4.20",version:"4.20",inputPrice:2,outputPrice:6,contextWindow:2e6,maxOutput:16384,toolCalling:!0},{id:"xai/grok-4.20-multi-agent",name:"Grok 4.20 Multi-Agent",version:"4.20",inputPrice:2,outputPrice:6,contextWindow:2e6,maxOutput:16384,reasoning:!0,toolCalling:!0},{id:"xai/grok-4.5",name:"Grok 4.5",version:"4.5",inputPrice:2,outputPrice:6,contextWindow:5e5,maxOutput:16384,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"xai/grok-4.7",name:"Grok 4.7",version:"4.7",inputPrice:2,outputPrice:6,contextWindow:5e5,maxOutput:16384,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"xai/grok-4.6",name:"Grok 4.6",version:"4.6",inputPrice:2,outputPrice:6,contextWindow:5e5,maxOutput:16384,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"xai/grok-4.3",name:"Grok 4.3",version:"4.3",inputPrice:1.25,outputPrice:2.5,contextWindow:1e6,maxOutput:16384,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"xai/grok-build-0.1",name:"Grok Build 0.1",version:"0.1",inputPrice:1,outputPrice:2,contextWindow:256e3,maxOutput:16384,agentic:!0,toolCalling:!0},{id:"tencent/hy3",name:"Tencent Hy3",version:"hy3",inputPrice:.132,outputPrice:.528,contextWindow:262144,maxOutput:128e3,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"qwen/qwen3.7-flash"},{id:"xiaomi/mimo-v2.5-pro",name:"Xiaomi MiMo-V2.5 Pro",version:"v2.5-pro",inputPrice:.435,outputPrice:.87,contextWindow:1048576,maxOutput:131072,reasoning:!0,toolCalling:!0},{id:"minimax/minimax-m3",name:"MiniMax M3",version:"m3",inputPrice:.3,outputPrice:1.2,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"minimax/minimax-m2.7",name:"MiniMax M2.7",version:"m2.7",inputPrice:.3,outputPrice:1.2,contextWindow:204800,maxOutput:16384,reasoning:!0,agentic:!0,toolCalling:!0},{id:"minimax/minimax-m2.5",name:"MiniMax M2.5",version:"m2.5",inputPrice:.3,outputPrice:1.2,contextWindow:204800,maxOutput:16384,reasoning:!0,agentic:!0,toolCalling:!0,deprecated:!0,fallbackModel:"minimax/minimax-m2.7"},{id:"free/gpt-oss-120b",name:"[Free] GPT-OSS 120B",version:"120b",inputPrice:0,outputPrice:0,contextWindow:128e3,maxOutput:16384},{id:"free/gpt-oss-20b",name:"[Free] GPT-OSS 20B",version:"20b",inputPrice:0,outputPrice:0,contextWindow:128e3,maxOutput:16384},{id:"free/deepseek-v4-flash",name:"[Free] DeepSeek V4 Flash",version:"v4-flash",inputPrice:0,outputPrice:0,contextWindow:1e6,maxOutput:16384,reasoning:!0},{id:"free/qwen3-coder-480b",name:"[Free] Qwen3 Coder 480B",version:"480b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384},{id:"free/glm-4.7",name:"[Free] GLM-4.7",version:"4.7",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/llama-4-maverick",name:"[Free] Llama 4 Maverick",version:"4-maverick",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-3-nano-omni-30b-a3b-reasoning",name:"[Free] Nemotron 3 Nano Omni",version:"30b-a3b-omni-reasoning",inputPrice:0,outputPrice:0,contextWindow:256e3,maxOutput:16384,reasoning:!0},{id:"free/mistral-large-3-675b",name:"[Free] Mistral Large 3 675B",version:"3-675b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/qwen3.5-122b-a10b",name:"[Free] Qwen3.5 122B",version:"3.5-122b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/qwen3-next-80b-a3b-instruct",name:"[Free] Qwen3-Next 80B Instruct",version:"next-80b-a3b",inputPrice:0,outputPrice:0,contextWindow:262144,maxOutput:16384,reasoning:!0},{id:"free/seed-oss-36b",name:"[Free] Seed-OSS 36B",version:"oss-36b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384},{id:"free/mistral-nemotron",name:"[Free] Mistral Nemotron",version:"nemotron",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384},{id:"free/step-3.7-flash",name:"[Free] StepFun Step 3.7 Flash",version:"3.7-flash",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-nano-9b-v2",name:"[Free] Nemotron Nano 9B v2",version:"nano-9b-v2",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-nano-12b-v2-vl",name:"[Free] Nemotron Nano 12B v2 VL",version:"nano-12b-v2-vl",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-3.5-lightning",name:"[Free] Nemotron 3.5 Lightning",version:"3.5-lightning",inputPrice:0,outputPrice:0,contextWindow:1e6,maxOutput:16384,reasoning:!0},{id:"free/nemotron-3-nano-30b",name:"[Free] Nemotron 3 Nano 30B",version:"3-nano-30b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-3-ultra-550b",name:"[Free] Nemotron 3 Ultra 550B",version:"3-ultra-550b",inputPrice:0,outputPrice:0,contextWindow:1e6,maxOutput:16384,reasoning:!0},{id:"free/minimax-m3.1-flash",name:"[Free] MiniMax M3.1 Flash",version:"m3.1-flash",inputPrice:0,outputPrice:0,contextWindow:1048576,maxOutput:16384,reasoning:!0,toolCalling:!0},{id:"free/llama-3.2-11b-vision",name:"[Free] Llama 3.2 11B Vision",version:"3.2-11b-vision",inputPrice:0,outputPrice:0,contextWindow:128e3,maxOutput:16384},{id:"free/north-mini-code",name:"[Free] Cohere North Mini Code",version:"north-mini-code",inputPrice:0,outputPrice:0,contextWindow:256e3,maxOutput:16384,reasoning:!0,deprecated:!0,fallbackModel:"free/laguna-xs-2.1"},{id:"free/laguna-xs-2.1",name:"[Free] Poolside Laguna XS 2.1",version:"xs-2.1",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384},{id:"free/muse-glimmer-30b",name:"[Free] Muse Glimmer 30B",version:"30b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-3.5-bolt",name:"[Free] Nemotron 3.5 Bolt",version:"3.5-bolt",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,vision:!0},{id:"free/nemotron-3-super-120b",name:"[Free] Nemotron 3 Super 120B",version:"3-super-120b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"qwen/qwen3.8-flash",name:"Qwen3.8 Flash",version:"3.8-flash",inputPrice:.15,outputPrice:.47,contextWindow:1e6,maxOutput:131072,reasoning:!0,vision:!0,toolCalling:!0},{id:"deepseek/deepseek-v4-flash-vision-exp",name:"DeepSeek V4 Flash Vision",version:"v4-flash-vision-exp",inputPrice:.3,outputPrice:1.2,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"xiaomi/mimo-v2.5",name:"Xiaomi MiMo V2.5",version:"2.5",inputPrice:.14,outputPrice:.28,contextWindow:1048576,maxOutput:131072,reasoning:!0,vision:!0,toolCalling:!0},{id:"qwen/qwen3.8-max",name:"Qwen3.8 Max",version:"3.8-max",inputPrice:2,outputPrice:6,contextWindow:1e6,maxOutput:131072,reasoning:!0},{id:"tencent/hy4-preview",name:"Tencent Hy4 Preview",version:"hy4-preview",inputPrice:.834,outputPrice:2.501,contextWindow:1048576,maxOutput:64e3,reasoning:!0},{id:"mistral/mistral-large-4",name:"Mistral Large 4",version:"large-4",inputPrice:1.36,outputPrice:4.18,contextWindow:524288,maxOutput:262144,reasoning:!0,vision:!0,toolCalling:!0},{id:"poolside/laguna-s-2.1",name:"Poolside Laguna S 2.1",version:"s-2.1",inputPrice:.09,outputPrice:.18,contextWindow:1048576,maxOutput:131072},{id:"zai/glm-5.3",name:"GLM-5.3",version:"5.3",inputPrice:1.4,outputPrice:4.4,contextWindow:1e6,maxOutput:131072,reasoning:!0,toolCalling:!0},{id:"zai/glm-5.3-flash",name:"GLM-5.3 Flash",version:"5.3-flash",inputPrice:.15,outputPrice:.5,contextWindow:1e6,maxOutput:131072,reasoning:!0,vision:!0,toolCalling:!0},{id:"zai/glm-5.2",name:"GLM-5.2",version:"5.2",inputPrice:1.4,outputPrice:4.4,contextWindow:1e6,maxOutput:131072,reasoning:!0,toolCalling:!0},{id:"zai/glm-5.1",name:"GLM-5.1",version:"5.1",inputPrice:1.4,outputPrice:4.4,contextWindow:2e5,maxOutput:128e3,reasoning:!0,toolCalling:!0,promo:{flatPrice:.001,startDate:"2026-04-01",endDate:"2026-06-05"}},{id:"zai/glm-5",name:"GLM-5",version:"5",inputPrice:1,outputPrice:3.2,contextWindow:2e5,maxOutput:128e3,reasoning:!0,toolCalling:!0},{id:"zai/glm-5-turbo",name:"GLM-5 Turbo",version:"5-turbo",inputPrice:1.2,outputPrice:4,contextWindow:2e5,maxOutput:128e3,reasoning:!0,toolCalling:!0}];ALIAS_MODELS=Object.entries(MODEL_ALIASES).filter(([alias])=>!alias.includes("/")).map(([alias,targetId])=>{let target=BLOCKRUN_MODELS.find(m=>m.id===targetId);return target?toOpenClawModel({...target,id:alias,name:`${alias} \u2192 ${target.name}`}):null}).filter(m=>m!==null),OPENCLAW_MODELS=[...BLOCKRUN_MODELS.filter(m=>!(m.id in MODEL_ALIASES)).map(toOpenClawModel),...ALIAS_MODELS],OPENCLAW_MODEL_BY_ID=new Map(OPENCLAW_MODELS.map(m=>[m.id,m])),VISIBLE_OPENCLAW_MODELS=TOP_MODELS.flatMap(id2=>{let model=OPENCLAW_MODEL_BY_ID.get(id2);return model?[model]:[]})}});function validPercent(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:void 0}function platformFeePercentOf(row){if(row.billing_mode!=="paid")return 0;let pricing=row.pricing&&typeof row.pricing=="object"?row.pricing:void 0;return validPercent(pricing?.platform_fee_percent)??validPercent(row.platform_fee_percent)??0}function withPlatformFee(tokenCostUsd,platformFeePercent){let percent=validPercent(platformFeePercent)??0;return tokenCostUsd*(1+percent/100)}var init_platform_fee=__esm({"src/platform-fee.ts"(){"use strict"}});function fallbackCatalog(){return{models:BLOCKRUN_MODELS,openclaw:OPENCLAW_MODELS,visible:VISIBLE_OPENCLAW_MODELS,freeIds:new Set(BLOCKRUN_MODELS.filter(m=>m.id.startsWith("free/")).map(m=>m.id))}}function upstreamId(id2){return id2==="free/north-mini-code"?"cohere/north-mini-code":id2==="free/laguna-xs-2.1"?"poolside/laguna-xs-2.1":id2.startsWith("free/")?`nvidia/${id2.slice(5)}`:id2}function projectClawCatalog(state){let models=BLOCKRUN_MODELS.map(m=>({...m})),byUpstream=new Map(models.map(m=>[upstreamId(m.id),m])),additions=new Set,freeIds=new Set(fallbackCatalog().freeIds);for(let row of state.models){if(!row.id.includes("/")||row.id.startsWith("blockrun/")||!row.categories.includes("chat")||row.available===!1||!["paid","free","flat"].includes(row.billing_mode))continue;let old=byUpstream.get(row.id);if(old?.id.startsWith("free/")&&row.billing_mode!=="free")throw new Error("Gateway changed billing of a pinned free model");if(!old&&Object.hasOwn(MODEL_ALIASES,row.id))continue;let model=old??{id:row.id,name:row.name,inputPrice:0,outputPrice:0,contextWindow:row.context_window??32768,maxOutput:row.max_output??4096,toolCalling:!1,agentic:!1,reasoning:row.categories.includes("reasoning"),vision:row.categories.includes("vision")};if(row.billing_mode==="flat"&&(typeof row.pricing.flat!="number"||!Number.isFinite(row.pricing.flat)||row.pricing.flat<0))throw new Error("Invalid flat model price");model.name=row.name,model.inputPrice=row.billing_mode==="paid"?row.pricing.input:0,model.outputPrice=row.billing_mode==="paid"?row.pricing.output:0,delete model.promo,delete model.flatPrice,delete model.platformFeePercent,row.billing_mode==="flat"&&(model.flatPrice=row.pricing.flat);let feePercent=platformFeePercentOf(row);feePercent>0&&(model.platformFeePercent=feePercent),row.context_window&&(model.contextWindow=row.context_window),row.max_output&&(model.maxOutput=row.max_output),old||(models.push(model),additions.add(model.id))}let byId=new Map(models.map(m=>[m.id,m])),openclaw=models.filter(m=>!Object.hasOwn(MODEL_ALIASES,m.id)).map(toOpenClawModel);for(let[alias,target]of Object.entries(MODEL_ALIASES)){let model=byId.get(target);!alias.includes("/")&&model&&openclaw.push(toOpenClawModel({...model,id:alias,name:`${alias} \u2192 ${model.name}`}))}let definitions=new Map(openclaw.map(m=>[m.id,m])),visibleIds=new Set(VISIBLE_OPENCLAW_MODELS.map(m=>m.id));for(let group of state.groups)for(let row of group.models)additions.has(row.id)&&visibleIds.add(row.id);let visible=[...visibleIds].flatMap(id2=>definitions.has(id2)?[definitions.get(id2)]:[]);return{models,openclaw,visible,freeIds}}function createClawCatalog(options){let gatewayUrl=`${options.apiBase.replace(/\/$/,"")}/v1/models?format=json`,fetcher=options.fetch??globalThis.fetch,gatewayFetch=options.apiKey?createApiKeyFetch(options.apiKey,fetcher,options.apiBase):fetcher,client=createCatalogClient({network:options.network,gatewayUrl,catalogUrl:options.catalogUrl??process.env.BLOCKRUN_MODEL_CATALOG_URL,timeoutMs:options.timeoutMs??4e3,ttlMs:options.ttlMs??24e4,fetch:(url3,init2)=>String(url3)===gatewayUrl?gatewayFetch(url3,{...init2,redirect:"error"}):fetcher(url3,{...init2,redirect:"error"})}),view=fallbackCatalog(),inflight,lastReported,report=message=>{message!==lastReported&&(lastReported=message,console.warn(`[ClawRouter] Model catalog refresh failed, keeping the last good view: ${message}`))};return{current:()=>view,refresh(){return inflight||(inflight=(async()=>{try{let state=await client.refresh();if(state.lastError&&report(state.lastError),state.source==="live"){let next=projectClawCatalog(state);fingerprint(next)!==fingerprint(view)&&(view=next),state.lastError||(lastReported=void 0)}}catch(err){report(err instanceof Error?err.message:String(err))}return view})().finally(()=>{inflight=void 0}),inflight)}}}function fingerprint(view){return JSON.stringify([view.models.map(m=>[m.id,m.inputPrice,m.outputPrice,m.flatPrice??null,m.platformFeePercent??0,m.contextWindow,m.maxOutput]),view.visible.map(m=>m.id),[...view.freeIds].sort()])}var init_model_catalog=__esm({"src/model-catalog.ts"(){"use strict";init_runtime();init_api_key();init_models();init_platform_fee()}});var version,init_version=__esm({"node_modules/abitype/dist/esm/version.js"(){"use strict";version="1.2.3"}});var BaseError,init_errors=__esm({"node_modules/abitype/dist/esm/errors.js"(){"use strict";init_version();BaseError=class _BaseError extends Error{constructor(shortMessage,args={}){let details=args.cause instanceof _BaseError?args.cause.details:args.cause?.message?args.cause.message:args.details,docsPath9=args.cause instanceof _BaseError&&args.cause.docsPath||args.docsPath,message=[shortMessage||"An error occurred.","",...args.metaMessages?[...args.metaMessages,""]:[],...docsPath9?[`Docs: https://abitype.dev${docsPath9}`]:[],...details?[`Details: ${details}`]:[],`Version: abitype@${version}`].join(`
|
|
4
|
+
`,{mode:384}),CORE_API_KEY_FILE}async function clearApiKey(){let removed=[];for(let path8 of[CORE_API_KEY_FILE,API_KEY_FILE])await readOptional(path8)!==void 0&&(await rm(path8,{force:!0}),removed.push(path8));return{removed,envStillSet:!!process.env.BLOCKRUN_API_KEY?.trim()}}async function fetchCreditBalance(apiKey,timeoutMs=5e3){try{let controller=new AbortController,timer2=setTimeout(()=>controller.abort(),timeoutMs),res=await fetch(`${BLOCKRUN_API_KEY_API}/v1/credits`,{headers:{authorization:`Bearer ${apiKey}`},signal:controller.signal});if(clearTimeout(timer2),!res.ok)return;let b=await res.json(),num2=v=>typeof v=="number"?v:null;return{accountId:typeof b.account_id=="string"?b.account_id:void 0,billingMode:typeof b.billing_mode=="string"?b.billing_mode:void 0,currency:typeof b.currency=="string"?b.currency:"USD",grantedUsd:num2(b.granted_usd),spentUsd:num2(b.spent_usd),remainingUsd:num2(b.remaining_usd),blocked:b.blocked===!0,blockedReason:typeof b.blocked_reason=="string"?b.blocked_reason:void 0}}catch{return}}function formatCreditBalance(b){let money=v=>v===null?void 0:`$${v.toFixed(v<.01&&v>0?6:2)}`,remaining=money(b.remainingUsd),spent=money(b.spentUsd);if(remaining)return`${remaining} remaining${spent?` (spent ${spent})`:""}`;let mode2=b.billingMode==="ungated"?"no prepaid limit":b.billingMode??"unknown";return`${spent?`spent ${spent}`:"unknown"} \u2014 ${mode2}`}async function fetchUsagePage(apiKey,opts={}){let params=new URLSearchParams;opts.from&¶ms.set("from",opts.from),opts.to&¶ms.set("to",opts.to),opts.limit&¶ms.set("limit",String(opts.limit)),opts.cursor&¶ms.set("cursor",opts.cursor);let query=params.toString();try{let res=await fetch(`${BLOCKRUN_API_KEY_API}/v1/usage${query?`?${query}`:""}`,{headers:{authorization:`Bearer ${apiKey}`},signal:AbortSignal.timeout(3e4)});if(!res.ok)return;let body=await res.json();return{rows:(body.data??[]).map(r2=>({requestId:String(r2.request_id??""),timestamp:String(r2.timestamp??""),endpoint:String(r2.endpoint??""),model:typeof r2.model=="string"?r2.model:null,kind:String(r2.kind??""),inputTokens:typeof r2.input_tokens=="number"?r2.input_tokens:0,outputTokens:typeof r2.output_tokens=="number"?r2.output_tokens:0,costUsd:typeof r2.cost_usd=="number"?r2.cost_usd:null,costState:String(r2.cost_state??""),status:typeof r2.status=="number"?r2.status:0})),nextCursor:body.next_cursor??null,unavailableDays:body.unavailable_days??[]}}catch{return}}function normalizeApiKeyBase(raw){let base4=raw.replace(/\/+$/,"").replace(/\/v1$/,""),url3=new URL(base4);if(url3.username||url3.password||url3.search||url3.hash||url3.protocol!=="https:"&&!(url3.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(url3.hostname)))throw new Error("BlockRun account API URL requires HTTPS (except localhost) and no credentials, query or fragment.");return base4}function createApiKeyFetch(apiKey,baseFetch=fetch,apiBase=BLOCKRUN_API_KEY_API){let base4=new URL(normalizeApiKeyBase(apiBase));return async(input2,init2)=>{let request2=input2 instanceof Request?input2:void 0,url3=new URL(request2?.url??String(input2),`${base4}/`);if(url3.origin!==base4.origin||url3.username||url3.password)throw new Error("Refusing to forward a BlockRun account key to another origin.");base4.pathname==="/"&&url3.pathname.startsWith("/api/v1/")&&(url3.pathname=url3.pathname.slice(4));let headers=new Headers(init2?.headers??request2?.headers);for(let name of[...headers.keys()])(/payment/i.test(name)||name.toLowerCase()==="x-api-key")&&headers.delete(name);headers.set("authorization",`Bearer ${apiKey}`);let response=await baseFetch(request2?new Request(url3,request2):url3.href,{...init2,headers,redirect:"error"});return response.ok?response:explainApiKeyFailure(response)}}async function pollApiKeyJob(response,payFetch,apiBase,signal,intervalMs=2e3){if(response.status!==202)return response;let initial=await response.clone().json();if(!initial.poll_url)throw new Error("Async account response missing poll_url");let pollUrl=new URL(initial.poll_url,`${normalizeApiKeyBase(apiBase)}/`).href,abort=AbortSignal.any([signal,AbortSignal.timeout(15*6e4)]);for(;!abort.aborted;){let polled=await payFetch(pollUrl,{signal:abort});if([502,503,504,522,524].includes(polled.status))await polled.body?.cancel();else{if(!polled.ok)return polled;let data=await polled.clone().json();if(data.status==="completed"||data.status==="failed")return polled;await polled.body?.cancel()}await new Promise(resolve4=>setTimeout(resolve4,intervalMs))}throw new Error("Async account job did not complete before the client aborted or timed out.")}async function explainApiKeyFailure(response){let hint=HINTS[response.status];if(!hint||!(response.headers.get("content-type")??"").includes("json"))return response;let parsed;try{parsed=await response.clone().json()}catch{return response}if(!parsed?.error||typeof parsed.error.message!="string"||response.status===404&&!/unsupported endpoint/i.test(parsed.error.message))return response;parsed.error.message=`${parsed.error.message} ${hint}`;let headers=new Headers(response.headers);return headers.delete("content-length"),new Response(JSON.stringify(parsed),{status:response.status,statusText:response.statusText,headers})}var API_KEY_FILE,CORE_API_KEY_FILE,PORTAL_URL,PORTAL_KEYS_URL,PORTAL_CREDITS_URL,BLOCKRUN_API_KEY_API,HINTS,init_api_key=__esm({"src/api-key.ts"(){"use strict";init_fs_read();API_KEY_FILE=join(homedir(),".openclaw","blockrun","api-key"),CORE_API_KEY_FILE=join(homedir(),".blockrun",".api-key"),PORTAL_URL="https://user.blockrun.ai",PORTAL_KEYS_URL=`${PORTAL_URL}/dashboard/keys`,PORTAL_CREDITS_URL=`${PORTAL_URL}/dashboard/credits`,BLOCKRUN_API_KEY_API=process.env.BLOCKRUN_API_BASE_URL?.replace(/\/+$/,"").replace(/\/v1$/,"")||"https://api.blockrun.ai";HINTS={401:`Check BLOCKRUN_API_KEY, or mint a new key at ${PORTAL_KEYS_URL}.`,402:`Top up your BlockRun credit at ${PORTAL_CREDITS_URL}.`,404:'api.blockrun.ai does not serve this endpoint. Chat, Anthropic-shaped messages, images, speech, video and the partner APIs (Exa, prediction markets, phone lookup) all work on an API key. The wallet-only exceptions are the routes that bind a lease or a position to a payer address \u2014 buying/renewing/releasing phone numbers, and Polymarket trading \u2014 which need a wallet to own the thing being bought. For those, unset BLOCKRUN_API_KEY and run "clawrouter logout".'}}});var top_models_default,init_top_models=__esm({"src/top-models.json"(){top_models_default=["auto","premium","eco","free","anthropic/claude-fable-5.1","anthropic/claude-fable-5","anthropic/claude-opus-5.5","anthropic/claude-opus-5","anthropic/claude-opus-4.8","anthropic/claude-opus-4.7","anthropic/claude-sonnet-5.5","anthropic/claude-sonnet-5","anthropic/claude-sonnet-4.6","anthropic/claude-haiku-4.5","openai/gpt-6-astra","openai/gpt-6-sol","openai/gpt-6.1-sol","openai/gpt-6.2-sol","openai/gpt-6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","openai/gpt-5.6-luna","openai/gpt-5.6-terra-pro","openai/gpt-5.6-sol-pro","openai/gpt-5.6-luna-pro","openai/gpt-5.5","openai/gpt-5.5-pro","openai/gpt-5.4-pro","openai/gpt-5.4","openai/gpt-5.4-mini","openai/gpt-5.4-nano","openai/gpt-5.1","openai/gpt-5.3-codex","google/gemini-4-argon","google/gemini-3.1-pro","google/gemini-3.8-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","google/gemini-3.1-flash-lite","google/gemini-3-flash-preview","xai/grok-4.7","xai/grok-4.6","xai/grok-4.5","xai/grok-4.3","xai/grok-build-0.1","zai/glm-5.3","zai/glm-5.3-flash","zai/glm-5.2","zai/glm-5.1","zai/glm-5-turbo","zai/glm-5","xiaomi/mimo-v2.5","xiaomi/mimo-v2.5-pro","tencent/hy4-preview","mistral/mistral-large-4","poolside/laguna-s-2.1","minimax/minimax-m3","minimax/minimax-m2.7","moonshot/kimi-k3.1-pro","qwen/qwen3.7-max","qwen/qwen3.8-max","qwen/qwen3.8-flash","deepseek/deepseek-v4-flash-vision-exp","deepseek/deepseek-v4-pro","deepseek/deepseek-v4.1-flash","deepseek/deepseek-chat","deepseek/deepseek-reasoner","free/nemotron-3.5-lightning","free/laguna-xs-2.1","free/nemotron-3-nano-omni-30b-a3b-reasoning","free/nemotron-3-ultra-550b","free/nemotron-3.5-bolt","free/nemotron-3-super-120b","free/muse-glimmer-30b"]}});function loadTopModels(){let parsed=top_models_default;if(!Array.isArray(parsed)||parsed.some(value=>typeof value!="string"||!value.trim()))throw new Error("top-models.json must be a JSON array of non-empty strings");return[...parsed]}var TOP_MODELS,init_top_models2=__esm({"src/top-models.ts"(){"use strict";init_top_models();TOP_MODELS=Object.freeze(loadTopModels())}});function resolveModelAlias(model){let normalized=model.trim().toLowerCase(),resolved=MODEL_ALIASES[normalized];if(resolved)return resolved;if(normalized.startsWith("blockrun/")){let withoutPrefix=normalized.slice(9),resolvedWithoutPrefix=MODEL_ALIASES[withoutPrefix];return resolvedWithoutPrefix||withoutPrefix}if(normalized.startsWith("openai/")){let withoutPrefix=normalized.slice(7),resolvedWithoutPrefix=MODEL_ALIASES[withoutPrefix];if(resolvedWithoutPrefix)return resolvedWithoutPrefix;if(BLOCKRUN_MODELS.some(m=>m.id===withoutPrefix))return withoutPrefix}if(normalized.startsWith("openai-codex/")){let withoutPrefix=normalized.slice(13),resolvedWithoutPrefix=MODEL_ALIASES[withoutPrefix];if(resolvedWithoutPrefix)return resolvedWithoutPrefix;if(BLOCKRUN_MODELS.some(m=>m.id===withoutPrefix))return withoutPrefix}return model}function getActivePromoPrice(model,now2=new Date){if(model.flatPrice!==void 0)return model.flatPrice;if(!model.promo)return;let start=new Date(model.promo.startDate),end=new Date(model.promo.endDate);if(now2>=start&&now2<end)return model.promo.flatPrice}function toOpenClawModel(m){return{id:m.id,name:m.name,api:"openai-completions",reasoning:m.reasoning??!1,input:m.vision?["text","image"]:["text"],cost:{input:m.inputPrice,output:m.outputPrice,cacheRead:0,cacheWrite:0},contextWindow:m.contextWindow,maxTokens:m.maxOutput}}function buildProviderModels(baseUrl){return{baseUrl:`${baseUrl}/v1`,api:"openai-completions",models:VISIBLE_OPENCLAW_MODELS}}function isAgenticModel(modelId){return BLOCKRUN_MODELS.find(m=>m.id===modelId||m.id===modelId.replace("blockrun/",""))?.agentic??!1}function getAgenticModels(){return BLOCKRUN_MODELS.filter(m=>m.agentic).map(m=>m.id)}function getModelContextWindow(modelId){let normalized=modelId.replace("blockrun/","");return BLOCKRUN_MODELS.find(m=>m.id===normalized)?.contextWindow}function isReasoningModel(modelId){let normalized=modelId.replace("blockrun/","");return BLOCKRUN_MODELS.find(m=>m.id===normalized)?.reasoning??!1}var MODEL_ALIASES,BLOCKRUN_MODELS,ALIAS_MODELS,OPENCLAW_MODELS,OPENCLAW_MODEL_BY_ID,VISIBLE_OPENCLAW_MODELS,init_models=__esm({"src/models.ts"(){"use strict";init_top_models2();MODEL_ALIASES={claude:"anthropic/claude-sonnet-4.6","br-sonnet":"anthropic/claude-sonnet-4.6",sonnet:"anthropic/claude-sonnet-4.6","sonnet-4":"anthropic/claude-sonnet-4.6","sonnet-4.6":"anthropic/claude-sonnet-4.6","sonnet-4-6":"anthropic/claude-sonnet-4.6","sonnet-5":"anthropic/claude-sonnet-5","sonnet-5.0":"anthropic/claude-sonnet-5","sonnet-5-0":"anthropic/claude-sonnet-5","sonnet-5.5":"anthropic/claude-sonnet-5.5","sonnet-5-5":"anthropic/claude-sonnet-5.5","anthropic/claude-sonnet-5-5":"anthropic/claude-sonnet-5.5","sonnet-4.5":"anthropic/claude-sonnet-4.5","sonnet-4-5":"anthropic/claude-sonnet-4.5","anthropic/claude-sonnet-4-5":"anthropic/claude-sonnet-4.5",fable:"anthropic/claude-fable-5","fable-5":"anthropic/claude-fable-5","fable-5.0":"anthropic/claude-fable-5","fable-5.1":"anthropic/claude-fable-5.1","fable-5-1":"anthropic/claude-fable-5.1","fable-5.2":"anthropic/claude-fable-5.2","fable-5-2":"anthropic/claude-fable-5.2","anthropic/claude-fable-5-1":"anthropic/claude-fable-5.1",opus:"anthropic/claude-opus-5","opus-5":"anthropic/claude-opus-5","opus-5.0":"anthropic/claude-opus-5","opus-5-0":"anthropic/claude-opus-5","opus-5.5":"anthropic/claude-opus-5.5","opus-5-5":"anthropic/claude-opus-5.5","anthropic/claude-opus-5-5":"anthropic/claude-opus-5.5","opus-4":"anthropic/claude-opus-4.8","opus-4.8":"anthropic/claude-opus-4.8","opus-4-8":"anthropic/claude-opus-4.8","opus-4.7":"anthropic/claude-opus-4.7","opus-4-7":"anthropic/claude-opus-4.7","opus-4.6":"anthropic/claude-opus-4.6","opus-4-6":"anthropic/claude-opus-4.6",haiku:"anthropic/claude-haiku-4.5","anthropic/sonnet":"anthropic/claude-sonnet-4.6","anthropic/fable":"anthropic/claude-fable-5","anthropic/claude-fable-5.0":"anthropic/claude-fable-5","anthropic/opus":"anthropic/claude-opus-5","anthropic/claude-opus-5.0":"anthropic/claude-opus-5","anthropic/claude-opus-5-0":"anthropic/claude-opus-5","anthropic/haiku":"anthropic/claude-haiku-4.5","anthropic/claude":"anthropic/claude-sonnet-4.6","anthropic/claude-sonnet-4":"anthropic/claude-sonnet-4.6","anthropic/claude-sonnet-4-6":"anthropic/claude-sonnet-4.6","anthropic/claude-opus-4":"anthropic/claude-opus-4.8","anthropic/claude-opus-4-8":"anthropic/claude-opus-4.8","anthropic/claude-opus-4-7":"anthropic/claude-opus-4.7","anthropic/claude-opus-4-6":"anthropic/claude-opus-4.6","anthropic/claude-opus-4-5":"anthropic/claude-opus-4.5","anthropic/claude-haiku-4":"anthropic/claude-haiku-4.5","anthropic/claude-haiku-4-5":"anthropic/claude-haiku-4.5",gpt:"openai/gpt-4o",gpt4:"openai/gpt-4o",gpt5:"openai/gpt-5.6-terra","gpt-5.6":"openai/gpt-5.6-terra","openai/gpt-5.6":"openai/gpt-5.6-terra","gpt-5.6-sol":"openai/gpt-5.6-sol","gpt-5.6-terra":"openai/gpt-5.6-terra","gpt-5.6-luna":"openai/gpt-5.6-luna","gpt-5.6-sol-pro":"openai/gpt-5.6-sol-pro","gpt-5.6-terra-pro":"openai/gpt-5.6-terra-pro","gpt-5.6-luna-pro":"openai/gpt-5.6-luna-pro","sol-pro":"openai/gpt-5.6-sol-pro","terra-pro":"openai/gpt-5.6-terra-pro","luna-pro":"openai/gpt-5.6-luna-pro","gpt-6-astra":"openai/gpt-6-astra","gpt-6-sol":"openai/gpt-6-sol","gpt-6-luna":"openai/gpt-6-luna","gpt-6.1-sol":"openai/gpt-6.1-sol","gpt-6-1-sol":"openai/gpt-6.1-sol","gpt-6.2-sol":"openai/gpt-6.2-sol","gpt-6-2-sol":"openai/gpt-6.2-sol","gpt-5.5":"openai/gpt-5.5","gpt-5.5-pro":"openai/gpt-5.5-pro","chat-latest":"openai/chat-latest",chatgpt:"openai/chat-latest","gpt-5.4":"openai/gpt-5.4","gpt-5.1":"openai/gpt-5.1","gpt-5.4-pro":"openai/gpt-5.4-pro","gpt-5.4-nano":"openai/gpt-5.4-nano",nano:"openai/gpt-5.4-nano","gpt-5-nano":"openai/gpt-5-nano",codex:"openai/gpt-5.3-codex",mini:"openai/gpt-4o-mini",o1:"openai/gpt-5.4-mini","openai/o1-mini":"openai/gpt-5.4-mini","o1-mini":"openai/gpt-5.4-mini",o3:"openai/gpt-5.4-mini","openai-codex/gpt-5.4-mini":"openai/gpt-5.4-mini","gpt-5.4-mini":"openai/gpt-5.4-mini",deepseek:"deepseek/deepseek-v4.1-flash","deepseek-chat":"deepseek/deepseek-chat",reasoner:"deepseek/deepseek-reasoner","deepseek-v4.1-flash":"deepseek/deepseek-v4.1-flash","deepseek-v4-1-flash":"deepseek/deepseek-v4.1-flash","v4.1-flash":"deepseek/deepseek-v4.1-flash",kimi:"moonshot/kimi-k2.7",moonshot:"moonshot/kimi-k2.7","kimi-k3":"moonshot/kimi-k3","kimi-k3.1":"moonshot/kimi-k3.1-pro","kimi-k3.1-pro":"moonshot/kimi-k3.1-pro","kimi-k2":"moonshot/kimi-k2.7","kimi-k2.7":"moonshot/kimi-k2.7","kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.5":"moonshot/kimi-k2.5","nvidia/kimi-k2.5":"moonshot/kimi-k2.5","qwen3.7-max":"qwen/qwen3.7-max","qwen3.8-max":"qwen/qwen3.8-max","qwen-3.8-max":"qwen/qwen3.8-max","qwen3-8-max":"qwen/qwen3.8-max","qwen3.8-flash":"qwen/qwen3.8-flash","qwen3-8-flash":"qwen/qwen3.8-flash","qwen-vision":"qwen/qwen3.8-flash","deepseek-vision":"deepseek/deepseek-v4-flash-vision-exp","v4-flash-vision":"deepseek/deepseek-v4-flash-vision-exp","mimo-vision":"xiaomi/mimo-v2.5","qwen-3.7-max":"qwen/qwen3.7-max","qwen3-7-max":"qwen/qwen3.7-max","qwen3.7-plus":"qwen/qwen3.7-plus","qwen-3.7-plus":"qwen/qwen3.7-plus","qwen3.7-flash":"qwen/qwen3.7-flash","qwen-3.7-flash":"qwen/qwen3.7-flash",hy3:"tencent/hy3",tencent:"tencent/hy3",hunyuan:"tencent/hy3",hy4:"tencent/hy4-preview","hy4-preview":"tencent/hy4-preview",mimo:"xiaomi/mimo-v2.5-pro","mimo-v2.5-pro":"xiaomi/mimo-v2.5-pro","mimo-v2.5":"xiaomi/mimo-v2.5",xiaomi:"xiaomi/mimo-v2.5-pro","google/gemini-3-pro-preview":"google/gemini-3.1-pro","gemini-3-pro-preview":"google/gemini-3.1-pro","gemini-pro":"google/gemini-3.1-pro","gemini-3-pro":"google/gemini-3.1-pro","gemini-3.1-pro":"google/gemini-3.1-pro",gemini:"google/gemini-3.8-flash",flash:"google/gemini-3.5-flash-lite","gemini-3.1-pro-preview":"google/gemini-3.1-pro","google/gemini-3.1-pro-preview":"google/gemini-3.1-pro","gemini-3.6-flash":"google/gemini-3.6-flash","gemini-3.6":"google/gemini-3.6-flash","gemini-3.5-flash":"google/gemini-3.6-flash","gemini-3.5-flash-lite":"google/gemini-3.5-flash-lite","gemini-3.1-flash-lite":"google/gemini-3.1-flash-lite","gemini-2.5-flash-lite":"google/gemini-2.5-flash-lite",grok:"xai/grok-4.5","grok-4.5":"xai/grok-4.5","grok-4-5":"xai/grok-4.5","grok-4.7":"xai/grok-4.7","grok-4-7":"xai/grok-4.7","grok-4.6":"xai/grok-4.6","grok-4-6":"xai/grok-4.6","grok-4.3":"xai/grok-4.3","grok-fast":"xai/grok-4-1-fast-reasoning","grok-build":"xai/grok-build-0.1","grok-code":"xai/grok-build-0.1","grok-code-fast-1":"deepseek/deepseek-chat","xai/grok-code-fast-1":"deepseek/deepseek-chat","xai/grok-3-fast":"xai/grok-4-1-fast-reasoning",nvidia:"free/nemotron-3.5-lightning","gpt-120b":"free/gpt-oss-120b","gpt-20b":"free/gpt-oss-20b","nvidia/gpt-oss-120b":"free/gpt-oss-120b","nvidia/gpt-oss-20b":"free/gpt-oss-20b","nvidia/deepseek-v3.2":"free/nemotron-3.5-lightning","free/deepseek-v3.2":"free/nemotron-3.5-lightning","nvidia/deepseek-v4-pro":"free/nemotron-3.5-lightning","free/deepseek-v4-pro":"free/nemotron-3.5-lightning","nvidia/deepseek-v4-flash":"free/nemotron-3.5-lightning","nvidia/nemotron-3-nano-omni-30b-a3b-reasoning":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nvidia/qwen3-coder-480b":"free/qwen3-coder-480b","qwen/qwen3-coder-480b-a35b-instruct":"free/qwen3-coder-480b","nvidia/glm-4.7":"free/glm-4.7","nvidia/llama-4-maverick":"free/llama-4-maverick","nvidia/qwen3-next-80b-a3b-thinking":"free/qwen3-next-80b-a3b-instruct","nvidia/qwen3-next-80b-a3b-instruct":"free/qwen3-next-80b-a3b-instruct","nvidia/seed-oss-36b":"free/seed-oss-36b","nvidia/mistral-nemotron":"free/mistral-nemotron","nvidia/step-3.7-flash":"free/step-3.7-flash","nvidia/nemotron-nano-9b-v2":"free/nemotron-nano-9b-v2","nvidia/nemotron-nano-12b-v2-vl":"free/nemotron-nano-12b-v2-vl","nvidia/nemotron-ultra-253b":"free/nemotron-3.5-lightning","nvidia/mistral-large-3-675b":"free/mistral-large-3-675b","nvidia/qwen3.5-122b-a10b":"free/qwen3.5-122b-a10b","nvidia/devstral-2-123b":"free/nemotron-3.5-lightning","free/nemotron-ultra-253b":"free/nemotron-3.5-lightning","free/devstral-2-123b":"free/nemotron-3.5-lightning","mistral-large":"free/mistral-large-3-675b","mistral-large-3-675b":"free/mistral-large-3-675b","qwen3.5-122b":"free/qwen3.5-122b-a10b","mistral-large-4":"mistral/mistral-large-4","qwen3-122b":"free/qwen3.5-122b-a10b","deepseek-free":"free/nemotron-3.5-lightning","deepseek-v4-pro":"free/nemotron-3.5-lightning","deepseek-v4-flash":"free/nemotron-3.5-lightning","v4-pro":"free/nemotron-3.5-lightning","v4-flash":"free/nemotron-3.5-lightning","mistral-free":"free/nemotron-3.5-lightning","glm-free":"free/nemotron-3.5-lightning","llama-free":"free/muse-glimmer-30b","qwen-coder":"free/nemotron-3.5-lightning","qwen-coder-free":"free/nemotron-3.5-lightning","qwen-thinking":"free/nemotron-3.5-lightning","qwen3-next":"free/qwen3-next-80b-a3b-instruct","qwen3-next-80b":"free/qwen3-next-80b-a3b-instruct","mistral-small":"free/nemotron-3.5-lightning","seed-oss":"free/seed-oss-36b","seed-oss-36b":"free/seed-oss-36b","coder-free":"free/laguna-xs-2.1","mistral-nemotron":"free/mistral-nemotron","step-flash":"free/step-3.7-flash","step-3.7-flash":"free/step-3.7-flash","nemotron-nano-9b":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-nano":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-nano-vl":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nano-vl":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-omni":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nano-omni":"free/nemotron-3-nano-omni-30b-a3b-reasoning","vision-free":"free/nemotron-3.5-bolt",nemotron:"free/nemotron-3.5-lightning","nemotron-ultra":"free/nemotron-3.5-lightning","nemotron-253b":"free/nemotron-3.5-lightning","nemotron-super":"free/nemotron-3-super-120b","nemotron-49b":"free/nemotron-3.5-lightning","nemotron-120b":"free/nemotron-3.5-lightning",devstral:"free/nemotron-3.5-lightning","devstral-2":"free/nemotron-3.5-lightning",maverick:"free/llama-4-maverick","nvidia/nemotron-3.5-lightning":"free/nemotron-3.5-lightning","nvidia/nemotron-3-nano-30b":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nvidia/nemotron-3-ultra-550b":"free/nemotron-3-ultra-550b","nvidia/minimax-m3.1-flash":"free/minimax-m3.1-flash","nvidia/llama-3.2-11b-vision":"free/llama-3.2-11b-vision","cohere/north-mini-code":"free/north-mini-code","poolside/laguna-xs-2.1":"free/laguna-xs-2.1",lightning:"free/nemotron-3.5-lightning","nemotron-lightning":"free/nemotron-3.5-lightning","nemotron-3.5-lightning":"free/nemotron-3.5-lightning","nano-30b":"free/nemotron-3-nano-omni-30b-a3b-reasoning","nemotron-nano-30b":"free/nemotron-3-nano-omni-30b-a3b-reasoning","ultra-550b":"free/nemotron-3-ultra-550b","nemotron-ultra-550b":"free/nemotron-3-ultra-550b","minimax-m3.1-flash":"free/minimax-m3.1-flash","llama-vision":"free/llama-3.2-11b-vision","llama-3.2-vision":"free/llama-3.2-11b-vision","north-mini":"free/laguna-xs-2.1","north-mini-code":"free/laguna-xs-2.1",laguna:"free/laguna-xs-2.1","laguna-xs":"free/laguna-xs-2.1","laguna-s":"poolside/laguna-s-2.1","laguna-s-2.1":"poolside/laguna-s-2.1","nvidia/muse-glimmer-30b":"free/muse-glimmer-30b","nvidia/nemotron-3.5-bolt":"free/nemotron-3.5-bolt","nemotron-3.5-bolt":"free/nemotron-3.5-bolt",bolt:"free/nemotron-3.5-bolt","nvidia/nemotron-3-super-120b":"free/nemotron-3-super-120b","nemotron-3-super-120b":"free/nemotron-3-super-120b","super-120b":"free/nemotron-3-super-120b",muse:"free/muse-glimmer-30b","muse-glimmer":"free/muse-glimmer-30b","muse-glimmer-30b":"free/muse-glimmer-30b",free:"free/nemotron-3.5-lightning",minimax:"minimax/minimax-m3","minimax-m3":"minimax/minimax-m3","minimax-m2.7":"minimax/minimax-m2.7","minimax-m2.5":"minimax/minimax-m2.5",glm:"zai/glm-5.3","glm-5.3":"zai/glm-5.3","glm-5-3":"zai/glm-5.3","glm-5.3-flash":"zai/glm-5.3-flash","glm-5-3-flash":"zai/glm-5.3-flash","glm-flash":"zai/glm-5.3-flash","glm-5.2":"zai/glm-5.2","glm-5":"zai/glm-5","glm-5.1":"zai/glm-5.1","glm-5-turbo":"zai/glm-5-turbo","auto-router":"auto",router:"auto",dalle:"openai/gpt-image-2","dall-e":"openai/gpt-image-2","gpt-image":"openai/gpt-image-1","gpt-image-2":"openai/gpt-image-2","nano-banana":"google/nano-banana",banana:"google/nano-banana","banana-pro":"google/nano-banana-pro","nano-banana-pro":"google/nano-banana-pro","nano-banana-2":"google/nano-banana-2","banana-2":"google/nano-banana-2",seedream:"bytedance/seedream-5-pro","grok-imagine":"xai/grok-imagine-image","grok-imagine-pro":"xai/grok-imagine-image-pro",cogview:"zai/cogview-4","grok-video":"xai/grok-imagine-video","grok-video-1.5":"xai/grok-imagine-video-1.5","grok-video-1-5":"xai/grok-imagine-video-1.5",seedance:"bytedance/seedance-1.5-pro","seedance-1.5":"bytedance/seedance-1.5-pro","seedance-2-fast":"bytedance/seedance-2.0-fast","seedance-2":"bytedance/seedance-2.0","seedance-2.5":"bytedance/seedance-2.5","seedance-2-5":"bytedance/seedance-2.5","seedance-2-mini":"bytedance/seedance-2.0-mini","seedance-2.0-mini":"bytedance/seedance-2.0-mini","seedance-mini":"bytedance/seedance-2.0-mini"};BLOCKRUN_MODELS=[{id:"auto",name:"Auto (Smart Router - Balanced)",inputPrice:0,outputPrice:0,contextWindow:105e4,maxOutput:128e3},{id:"free",name:"Free \u2192 Nemotron 3.5 Lightning",inputPrice:0,outputPrice:0,contextWindow:1e6,maxOutput:16384,reasoning:!0},{id:"eco",name:"Eco (Smart Router - Cost Optimized)",inputPrice:0,outputPrice:0,contextWindow:105e4,maxOutput:128e3},{id:"premium",name:"Premium (Smart Router - Best Quality)",inputPrice:0,outputPrice:0,contextWindow:2e6,maxOutput:2e5},{id:"openai/gpt-5.2",name:"GPT-5.2",version:"5.2",inputPrice:1.75,outputPrice:14,contextWindow:4e5,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5-mini",name:"GPT-5 Mini",version:"5.0",inputPrice:.25,outputPrice:2,contextWindow:2e5,maxOutput:128e3,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.6-luna"},{id:"openai/gpt-5-nano",name:"GPT-5 Nano",version:"5.0",inputPrice:.05,outputPrice:.4,contextWindow:128e3,maxOutput:128e3,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-nano"},{id:"openai/gpt-5.2-pro",name:"GPT-5.2 Pro",version:"5.2",inputPrice:21,outputPrice:168,contextWindow:4e5,maxOutput:128e3,reasoning:!0,vision:!0,toolCalling:!0},{id:"openai/gpt-6-astra",name:"GPT-6 Astra",version:"6",inputPrice:10,outputPrice:50,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-6-sol",name:"GPT-6 Sol",version:"6",inputPrice:2,outputPrice:10,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-6.1-sol",name:"GPT-6.1 Sol",version:"6.1",inputPrice:2,outputPrice:10,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-6.2-sol",name:"GPT-6.2 Sol",version:"6.2",inputPrice:2,outputPrice:10,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-6-luna",name:"GPT-6 Luna",version:"6",inputPrice:.1,outputPrice:.5,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-sol",name:"GPT-5.6 Sol",version:"5.6",inputPrice:4,outputPrice:20,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-terra",name:"GPT-5.6 Terra",version:"5.6",inputPrice:2,outputPrice:12,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-luna",name:"GPT-5.6 Luna",version:"5.6",inputPrice:.2,outputPrice:1.2,contextWindow:105e4,maxOutput:128e3,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-sol-pro",name:"GPT-5.6 Sol Pro",version:"5.6",inputPrice:4,outputPrice:20,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-terra-pro",name:"GPT-5.6 Terra Pro",version:"5.6",inputPrice:2,outputPrice:12,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.6-luna-pro",name:"GPT-5.6 Luna Pro",version:"5.6",inputPrice:.2,outputPrice:1.2,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.5",name:"GPT-5.5",version:"5.5",inputPrice:5,outputPrice:30,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.5-pro",name:"GPT-5.5 Pro",version:"5.5",inputPrice:30,outputPrice:180,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,toolCalling:!0},{id:"openai/chat-latest",name:"ChatGPT Instant (GPT-5.5)",version:"5.5",inputPrice:5,outputPrice:30,contextWindow:128e3,maxOutput:128e3,vision:!0,toolCalling:!0},{id:"openai/gpt-5.4",name:"GPT-5.4",version:"5.4",inputPrice:2.5,outputPrice:15,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.4-mini",name:"GPT-5.4 Mini",version:"5.4",inputPrice:.75,outputPrice:4.5,contextWindow:4e5,maxOutput:128e3,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.4-pro",name:"GPT-5.4 Pro",version:"5.4",inputPrice:30,outputPrice:180,contextWindow:105e4,maxOutput:128e3,reasoning:!0,vision:!0,toolCalling:!0},{id:"openai/gpt-5.4-nano",name:"GPT-5.4 Nano",version:"5.4",inputPrice:.2,outputPrice:1.25,contextWindow:105e4,maxOutput:128e3,toolCalling:!0},{id:"openai/gpt-5.1",name:"GPT-5.1",version:"5.1",inputPrice:1.25,outputPrice:10,contextWindow:4e5,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-5.3",name:"GPT-5.3",version:"5.3",inputPrice:1.75,outputPrice:14,contextWindow:128e3,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.2"},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",version:"5.3",inputPrice:1.75,outputPrice:14,contextWindow:4e5,maxOutput:128e3,agentic:!0,toolCalling:!0},{id:"openai/gpt-4.1",name:"GPT-4.1",version:"4.1",inputPrice:2,outputPrice:8,contextWindow:128e3,maxOutput:32768,vision:!0,toolCalling:!0},{id:"openai/gpt-4.1-mini",name:"GPT-4.1 Mini",version:"4.1",inputPrice:.4,outputPrice:1.6,contextWindow:128e3,maxOutput:32768,toolCalling:!0},{id:"openai/gpt-4.1-nano",name:"GPT-4.1 Nano",version:"4.1",inputPrice:.1,outputPrice:.4,contextWindow:128e3,maxOutput:32768,toolCalling:!0},{id:"openai/gpt-4o",name:"GPT-4o",version:"4o",inputPrice:2.5,outputPrice:10,contextWindow:128e3,maxOutput:16384,vision:!0,agentic:!0,toolCalling:!0},{id:"openai/gpt-4o-mini",name:"GPT-4o Mini",version:"4o-mini",inputPrice:.15,outputPrice:.6,contextWindow:128e3,maxOutput:16384,toolCalling:!0},{id:"openai/o1",name:"o1",version:"1",inputPrice:15,outputPrice:60,contextWindow:2e5,maxOutput:1e5,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-mini"},{id:"openai/o1-mini",name:"o1-mini",version:"1-mini",inputPrice:1.1,outputPrice:4.4,contextWindow:128e3,maxOutput:65536,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-mini"},{id:"openai/o3",name:"o3",version:"3",inputPrice:2,outputPrice:8,contextWindow:2e5,maxOutput:1e5,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-mini"},{id:"openai/o3-mini",name:"o3-mini",version:"3-mini",inputPrice:1.1,outputPrice:4.4,contextWindow:128e3,maxOutput:1e5,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-mini"},{id:"openai/o4-mini",name:"o4-mini",version:"4-mini",inputPrice:1.1,outputPrice:4.4,contextWindow:128e3,maxOutput:1e5,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"openai/gpt-5.4-mini"},{id:"anthropic/claude-haiku-4.5",name:"Claude Haiku 4.5",version:"4.5",inputPrice:1,outputPrice:5,contextWindow:2e5,maxOutput:64e3,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-sonnet-4.5",name:"Claude Sonnet 4.5",version:"4.5",inputPrice:3,outputPrice:15,contextWindow:2e5,maxOutput:64e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",version:"4.6",inputPrice:3,outputPrice:15,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-sonnet-5",name:"Claude Sonnet 5",version:"5",inputPrice:2,outputPrice:10,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-4.5",name:"Claude Opus 4.5",version:"4.5",inputPrice:5,outputPrice:25,contextWindow:2e5,maxOutput:64e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",version:"4.6",inputPrice:5,outputPrice:25,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-fable-5",name:"Claude Fable 5",version:"5",inputPrice:10,outputPrice:50,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-4.7",name:"Claude Opus 4.7",version:"4.7",inputPrice:5,outputPrice:25,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-4.8",name:"Claude Opus 4.8",version:"4.8",inputPrice:5,outputPrice:25,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-5",name:"Claude Opus 5",version:"5",inputPrice:5,outputPrice:25,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-fable-5.1",name:"Claude Fable 5.1",version:"5.1",inputPrice:10,outputPrice:50,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-fable-5.2",name:"Claude Fable 5.2",version:"5.2",inputPrice:8,outputPrice:40,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-opus-5.5",name:"Claude Opus 5.5",version:"5.5",inputPrice:4,outputPrice:20,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"anthropic/claude-sonnet-5.5",name:"Claude Sonnet 5.5",version:"5.5",inputPrice:2,outputPrice:10,contextWindow:1e6,maxOutput:128e3,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"google/gemini-3.1-pro",name:"Gemini 3.1 Pro",version:"3.1",inputPrice:2,outputPrice:12,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-3-pro-preview",name:"Gemini 3 Pro Preview",version:"3.0",inputPrice:2,outputPrice:12,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-4-argon",name:"Gemini 4 Argon",version:"4",inputPrice:2,outputPrice:10,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-4-carbon",name:"Gemini 4 Carbon",version:"4",inputPrice:2,outputPrice:10,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-3.8-flash",name:"Gemini 3.8 Flash",version:"3.8",inputPrice:.75,outputPrice:3.75,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-3.6-flash",name:"Gemini 3.6 Flash",version:"3.6",inputPrice:.75,outputPrice:3.75,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"google/gemini-3.5-flash",name:"Gemini 3.5 Flash",version:"3.5",inputPrice:1.5,outputPrice:9,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0,deprecated:!0,fallbackModel:"google/gemini-3.6-flash"},{id:"google/gemini-3.5-flash-lite",name:"Gemini 3.5 Flash Lite",version:"3.5",inputPrice:.3,outputPrice:2.5,contextWindow:1048576,maxOutput:65536,reasoning:!0,toolCalling:!0},{id:"google/gemini-3-flash-preview",name:"Gemini 3 Flash Preview",version:"3.0",inputPrice:.5,outputPrice:3,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0},{id:"google/gemini-2.5-pro",name:"Gemini 2.5 Pro",version:"2.5",inputPrice:1.25,outputPrice:10,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0,deprecated:!0,fallbackModel:"google/gemini-3.8-flash"},{id:"google/gemini-2.5-flash",name:"Gemini 2.5 Flash",version:"2.5",inputPrice:.3,outputPrice:2.5,contextWindow:1048576,maxOutput:65536,vision:!0,toolCalling:!0,deprecated:!0,fallbackModel:"google/gemini-3.5-flash-lite"},{id:"google/gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",version:"2.5",inputPrice:.1,outputPrice:.4,contextWindow:1048576,maxOutput:65536,vision:!0,toolCalling:!0},{id:"google/gemini-3.1-flash-lite",name:"Gemini 3.1 Flash Lite",version:"3.1",inputPrice:.25,outputPrice:1.5,contextWindow:1048576,maxOutput:65536,toolCalling:!0},{id:"deepseek/deepseek-chat",name:"DeepSeek Chat (V4.1 Flash)",version:"4.1-flash",inputPrice:.14,outputPrice:.28,contextWindow:1048576,maxOutput:65536,toolCalling:!0},{id:"deepseek/deepseek-reasoner",name:"DeepSeek Reasoner (V4.1 Flash)",version:"4.1-flash",inputPrice:.14,outputPrice:.28,contextWindow:1048576,maxOutput:65536,reasoning:!0,toolCalling:!0},{id:"deepseek/deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",version:"4.1-flash",inputPrice:.14,outputPrice:.28,contextWindow:1048576,maxOutput:65536,toolCalling:!0},{id:"deepseek/deepseek-v4-pro",name:"DeepSeek V4 Pro",version:"4-pro",inputPrice:1.32,outputPrice:3.96,contextWindow:1048576,maxOutput:65536,reasoning:!0,agentic:!0,toolCalling:!0},{id:"moonshot/kimi-k3.1-pro",name:"Kimi K3.1 Pro",version:"k3.1-pro",inputPrice:2,outputPrice:10,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"moonshot/kimi-k3",name:"Kimi K3",version:"k3",inputPrice:3,outputPrice:15,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"moonshot/kimi-k2.7",name:"Kimi K2.7",version:"k2.7",inputPrice:.95,outputPrice:4,contextWindow:262144,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"qwen/qwen3.7-max",name:"Qwen3.7 Max",version:"3.7-max",inputPrice:1.475,outputPrice:4.425,contextWindow:1e6,maxOutput:65536,reasoning:!0,agentic:!0,toolCalling:!0},{id:"qwen/qwen3.7-plus",name:"Qwen3.7 Plus",version:"3.7-plus",inputPrice:.32,outputPrice:1.28,contextWindow:1e6,maxOutput:131072,reasoning:!0,agentic:!0,toolCalling:!0},{id:"qwen/qwen3.7-flash",name:"Qwen3.7 Flash",version:"3.7-flash",inputPrice:.03,outputPrice:.13,contextWindow:1e6,maxOutput:65536,reasoning:!0,toolCalling:!0},{id:"moonshot/kimi-k2.6",name:"Kimi K2.6",version:"k2.6",inputPrice:.95,outputPrice:4,contextWindow:262144,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"moonshot/kimi-k2.5",name:"Kimi K2.5",version:"k2.5",inputPrice:.6,outputPrice:3,contextWindow:262144,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"nvidia/kimi-k2.5",name:"Kimi K2.5 (NVIDIA, retired)",version:"k2.5",inputPrice:.6,outputPrice:3,contextWindow:262144,maxOutput:16384,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0,deprecated:!0,fallbackModel:"moonshot/kimi-k2.5"},{id:"xai/grok-3",name:"Grok 3",version:"3",inputPrice:3,outputPrice:15,contextWindow:131072,maxOutput:16384,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"xai/grok-4-1-fast-non-reasoning"},{id:"xai/grok-3-mini",name:"Grok 3 Mini",version:"3-mini",inputPrice:.3,outputPrice:.5,contextWindow:131072,maxOutput:16384,toolCalling:!0,deprecated:!0,fallbackModel:"xai/grok-4-1-fast-non-reasoning"},{id:"xai/grok-4-fast-reasoning",name:"Grok 4 Fast Reasoning",version:"4",inputPrice:.2,outputPrice:.5,contextWindow:2e6,maxOutput:16384,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"xai/grok-4-1-fast-reasoning"},{id:"xai/grok-4-fast-non-reasoning",name:"Grok 4 Fast",version:"4",inputPrice:.2,outputPrice:.5,contextWindow:2e6,maxOutput:16384,toolCalling:!0,deprecated:!0,fallbackModel:"xai/grok-4-1-fast-non-reasoning"},{id:"xai/grok-4-1-fast-reasoning",name:"Grok 4.1 Fast Reasoning",version:"4.1",inputPrice:.2,outputPrice:.5,contextWindow:2e6,maxOutput:16384,reasoning:!0,toolCalling:!0},{id:"xai/grok-4-1-fast-non-reasoning",name:"Grok 4.1 Fast",version:"4.1",inputPrice:.2,outputPrice:.5,contextWindow:2e6,maxOutput:16384,toolCalling:!0},{id:"xai/grok-4-0709",name:"Grok 4 (0709)",version:"4-0709",inputPrice:3,outputPrice:15,contextWindow:256e3,maxOutput:16384,reasoning:!0,toolCalling:!0},{id:"xai/grok-2-vision",name:"Grok 2 Vision",version:"2",inputPrice:2,outputPrice:10,contextWindow:32768,maxOutput:16384,vision:!0,toolCalling:!0,deprecated:!0,fallbackModel:"xai/grok-4.3"},{id:"xai/grok-4.20-reasoning",name:"Grok 4.20 Reasoning",version:"4.20",inputPrice:2,outputPrice:6,contextWindow:2e6,maxOutput:16384,reasoning:!0,toolCalling:!0},{id:"xai/grok-4.20-non-reasoning",name:"Grok 4.20",version:"4.20",inputPrice:2,outputPrice:6,contextWindow:2e6,maxOutput:16384,toolCalling:!0},{id:"xai/grok-4.20-multi-agent",name:"Grok 4.20 Multi-Agent",version:"4.20",inputPrice:2,outputPrice:6,contextWindow:2e6,maxOutput:16384,reasoning:!0,toolCalling:!0},{id:"xai/grok-4.5",name:"Grok 4.5",version:"4.5",inputPrice:2,outputPrice:6,contextWindow:5e5,maxOutput:16384,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"xai/grok-4.7",name:"Grok 4.7",version:"4.7",inputPrice:2,outputPrice:6,contextWindow:5e5,maxOutput:16384,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"xai/grok-4.6",name:"Grok 4.6",version:"4.6",inputPrice:2,outputPrice:6,contextWindow:5e5,maxOutput:16384,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"xai/grok-4.3",name:"Grok 4.3",version:"4.3",inputPrice:1.25,outputPrice:2.5,contextWindow:1e6,maxOutput:16384,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"xai/grok-build-0.1",name:"Grok Build 0.1",version:"0.1",inputPrice:1,outputPrice:2,contextWindow:256e3,maxOutput:16384,agentic:!0,toolCalling:!0},{id:"tencent/hy3",name:"Tencent Hy3",version:"hy3",inputPrice:.132,outputPrice:.528,contextWindow:262144,maxOutput:128e3,reasoning:!0,toolCalling:!0,deprecated:!0,fallbackModel:"qwen/qwen3.7-flash"},{id:"xiaomi/mimo-v2.5-pro",name:"Xiaomi MiMo-V2.5 Pro",version:"v2.5-pro",inputPrice:.435,outputPrice:.87,contextWindow:1048576,maxOutput:131072,reasoning:!0,toolCalling:!0},{id:"minimax/minimax-m3",name:"MiniMax M3",version:"m3",inputPrice:.3,outputPrice:1.2,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,agentic:!0,toolCalling:!0},{id:"minimax/minimax-m2.7",name:"MiniMax M2.7",version:"m2.7",inputPrice:.3,outputPrice:1.2,contextWindow:204800,maxOutput:16384,reasoning:!0,agentic:!0,toolCalling:!0},{id:"minimax/minimax-m2.5",name:"MiniMax M2.5",version:"m2.5",inputPrice:.3,outputPrice:1.2,contextWindow:204800,maxOutput:16384,reasoning:!0,agentic:!0,toolCalling:!0,deprecated:!0,fallbackModel:"minimax/minimax-m2.7"},{id:"free/gpt-oss-120b",name:"[Free] GPT-OSS 120B",version:"120b",inputPrice:0,outputPrice:0,contextWindow:128e3,maxOutput:16384},{id:"free/gpt-oss-20b",name:"[Free] GPT-OSS 20B",version:"20b",inputPrice:0,outputPrice:0,contextWindow:128e3,maxOutput:16384},{id:"free/deepseek-v4-flash",name:"[Free] DeepSeek V4 Flash",version:"v4-flash",inputPrice:0,outputPrice:0,contextWindow:1e6,maxOutput:16384,reasoning:!0},{id:"free/qwen3-coder-480b",name:"[Free] Qwen3 Coder 480B",version:"480b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384},{id:"free/glm-4.7",name:"[Free] GLM-4.7",version:"4.7",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/llama-4-maverick",name:"[Free] Llama 4 Maverick",version:"4-maverick",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-3-nano-omni-30b-a3b-reasoning",name:"[Free] Nemotron 3 Nano Omni",version:"30b-a3b-omni-reasoning",inputPrice:0,outputPrice:0,contextWindow:256e3,maxOutput:16384,reasoning:!0},{id:"free/mistral-large-3-675b",name:"[Free] Mistral Large 3 675B",version:"3-675b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/qwen3.5-122b-a10b",name:"[Free] Qwen3.5 122B",version:"3.5-122b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/qwen3-next-80b-a3b-instruct",name:"[Free] Qwen3-Next 80B Instruct",version:"next-80b-a3b",inputPrice:0,outputPrice:0,contextWindow:262144,maxOutput:16384,reasoning:!0},{id:"free/seed-oss-36b",name:"[Free] Seed-OSS 36B",version:"oss-36b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384},{id:"free/mistral-nemotron",name:"[Free] Mistral Nemotron",version:"nemotron",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384},{id:"free/step-3.7-flash",name:"[Free] StepFun Step 3.7 Flash",version:"3.7-flash",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-nano-9b-v2",name:"[Free] Nemotron Nano 9B v2",version:"nano-9b-v2",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-nano-12b-v2-vl",name:"[Free] Nemotron Nano 12B v2 VL",version:"nano-12b-v2-vl",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-3.5-lightning",name:"[Free] Nemotron 3.5 Lightning",version:"3.5-lightning",inputPrice:0,outputPrice:0,contextWindow:1e6,maxOutput:16384,reasoning:!0},{id:"free/nemotron-3-nano-30b",name:"[Free] Nemotron 3 Nano 30B",version:"3-nano-30b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-3-ultra-550b",name:"[Free] Nemotron 3 Ultra 550B",version:"3-ultra-550b",inputPrice:0,outputPrice:0,contextWindow:1e6,maxOutput:16384,reasoning:!0},{id:"free/minimax-m3.1-flash",name:"[Free] MiniMax M3.1 Flash",version:"m3.1-flash",inputPrice:0,outputPrice:0,contextWindow:1048576,maxOutput:16384,reasoning:!0,toolCalling:!0},{id:"free/llama-3.2-11b-vision",name:"[Free] Llama 3.2 11B Vision",version:"3.2-11b-vision",inputPrice:0,outputPrice:0,contextWindow:128e3,maxOutput:16384},{id:"free/north-mini-code",name:"[Free] Cohere North Mini Code",version:"north-mini-code",inputPrice:0,outputPrice:0,contextWindow:256e3,maxOutput:16384,reasoning:!0,deprecated:!0,fallbackModel:"free/laguna-xs-2.1"},{id:"free/laguna-xs-2.1",name:"[Free] Poolside Laguna XS 2.1",version:"xs-2.1",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384},{id:"free/muse-glimmer-30b",name:"[Free] Muse Glimmer 30B",version:"30b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"free/nemotron-3.5-bolt",name:"[Free] Nemotron 3.5 Bolt",version:"3.5-bolt",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,vision:!0},{id:"free/nemotron-3-super-120b",name:"[Free] Nemotron 3 Super 120B",version:"3-super-120b",inputPrice:0,outputPrice:0,contextWindow:131072,maxOutput:16384,reasoning:!0},{id:"qwen/qwen3.8-flash",name:"Qwen3.8 Flash",version:"3.8-flash",inputPrice:.15,outputPrice:.47,contextWindow:1e6,maxOutput:131072,reasoning:!0,vision:!0,toolCalling:!0},{id:"deepseek/deepseek-v4-flash-vision-exp",name:"DeepSeek V4 Flash Vision",version:"v4-flash-vision-exp",inputPrice:.3,outputPrice:1.2,contextWindow:1048576,maxOutput:65536,reasoning:!0,vision:!0,toolCalling:!0},{id:"xiaomi/mimo-v2.5",name:"Xiaomi MiMo V2.5",version:"2.5",inputPrice:.14,outputPrice:.28,contextWindow:1048576,maxOutput:131072,reasoning:!0,vision:!0,toolCalling:!0},{id:"qwen/qwen3.8-max",name:"Qwen3.8 Max",version:"3.8-max",inputPrice:2,outputPrice:6,contextWindow:1e6,maxOutput:131072,reasoning:!0},{id:"tencent/hy4-preview",name:"Tencent Hy4 Preview",version:"hy4-preview",inputPrice:.834,outputPrice:2.501,contextWindow:1048576,maxOutput:64e3,reasoning:!0},{id:"mistral/mistral-large-4",name:"Mistral Large 4",version:"large-4",inputPrice:1.36,outputPrice:4.18,contextWindow:524288,maxOutput:262144,reasoning:!0,vision:!0,toolCalling:!0},{id:"poolside/laguna-s-2.1",name:"Poolside Laguna S 2.1",version:"s-2.1",inputPrice:.09,outputPrice:.18,contextWindow:1048576,maxOutput:131072},{id:"zai/glm-5.3",name:"GLM-5.3",version:"5.3",inputPrice:1.4,outputPrice:4.4,contextWindow:1e6,maxOutput:131072,reasoning:!0,toolCalling:!0},{id:"zai/glm-5.3-flash",name:"GLM-5.3 Flash",version:"5.3-flash",inputPrice:.15,outputPrice:.5,contextWindow:1e6,maxOutput:131072,reasoning:!0,vision:!0,toolCalling:!0},{id:"zai/glm-5.2",name:"GLM-5.2",version:"5.2",inputPrice:1.4,outputPrice:4.4,contextWindow:1e6,maxOutput:131072,reasoning:!0,toolCalling:!0},{id:"zai/glm-5.1",name:"GLM-5.1",version:"5.1",inputPrice:1.4,outputPrice:4.4,contextWindow:2e5,maxOutput:128e3,reasoning:!0,toolCalling:!0,promo:{flatPrice:.001,startDate:"2026-04-01",endDate:"2026-06-05"}},{id:"zai/glm-5",name:"GLM-5",version:"5",inputPrice:1,outputPrice:3.2,contextWindow:2e5,maxOutput:128e3,reasoning:!0,toolCalling:!0},{id:"zai/glm-5-turbo",name:"GLM-5 Turbo",version:"5-turbo",inputPrice:1.2,outputPrice:4,contextWindow:2e5,maxOutput:128e3,reasoning:!0,toolCalling:!0}];ALIAS_MODELS=Object.entries(MODEL_ALIASES).filter(([alias])=>!alias.includes("/")).map(([alias,targetId])=>{let target=BLOCKRUN_MODELS.find(m=>m.id===targetId);return target?toOpenClawModel({...target,id:alias,name:`${alias} \u2192 ${target.name}`}):null}).filter(m=>m!==null),OPENCLAW_MODELS=[...BLOCKRUN_MODELS.filter(m=>!(m.id in MODEL_ALIASES)).map(toOpenClawModel),...ALIAS_MODELS],OPENCLAW_MODEL_BY_ID=new Map(OPENCLAW_MODELS.map(m=>[m.id,m])),VISIBLE_OPENCLAW_MODELS=TOP_MODELS.flatMap(id2=>{let model=OPENCLAW_MODEL_BY_ID.get(id2);return model?[model]:[]})}});function validPercent(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:void 0}function platformFeePercentOf(row){if(row.billing_mode!=="paid")return 0;let pricing=row.pricing&&typeof row.pricing=="object"?row.pricing:void 0;return validPercent(pricing?.platform_fee_percent)??validPercent(row.platform_fee_percent)??0}function withPlatformFee(tokenCostUsd,platformFeePercent){let percent=validPercent(platformFeePercent)??0;return tokenCostUsd*(1+percent/100)}var init_platform_fee=__esm({"src/platform-fee.ts"(){"use strict"}});function fallbackCatalog(){return{models:BLOCKRUN_MODELS,openclaw:OPENCLAW_MODELS,visible:VISIBLE_OPENCLAW_MODELS,freeIds:new Set(BLOCKRUN_MODELS.filter(m=>m.id.startsWith("free/")).map(m=>m.id))}}function upstreamId(id2){return id2==="free/north-mini-code"?"cohere/north-mini-code":id2==="free/laguna-xs-2.1"?"poolside/laguna-xs-2.1":id2.startsWith("free/")?`nvidia/${id2.slice(5)}`:id2}function projectClawCatalog(state){let models=BLOCKRUN_MODELS.map(m=>({...m})),byUpstream=new Map(models.map(m=>[upstreamId(m.id),m])),additions=new Set,freeIds=new Set(fallbackCatalog().freeIds);for(let row of state.models){if(!row.id.includes("/")||row.id.startsWith("blockrun/")||!row.categories.includes("chat")||row.available===!1||!["paid","free","flat"].includes(row.billing_mode))continue;let old=byUpstream.get(row.id);if(old?.id.startsWith("free/")&&row.billing_mode!=="free")throw new Error("Gateway changed billing of a pinned free model");if(!old&&Object.hasOwn(MODEL_ALIASES,row.id))continue;let model=old??{id:row.id,name:row.name,inputPrice:0,outputPrice:0,contextWindow:row.context_window??32768,maxOutput:row.max_output??4096,toolCalling:!1,agentic:!1,reasoning:row.categories.includes("reasoning"),vision:row.categories.includes("vision")};if(row.billing_mode==="flat"&&(typeof row.pricing.flat!="number"||!Number.isFinite(row.pricing.flat)||row.pricing.flat<0))throw new Error("Invalid flat model price");model.name=row.name,model.inputPrice=row.billing_mode==="paid"?row.pricing.input:0,model.outputPrice=row.billing_mode==="paid"?row.pricing.output:0,delete model.promo,delete model.flatPrice,delete model.platformFeePercent,row.billing_mode==="flat"&&(model.flatPrice=row.pricing.flat);let feePercent=platformFeePercentOf(row);feePercent>0&&(model.platformFeePercent=feePercent),row.context_window&&(model.contextWindow=row.context_window),row.max_output&&(model.maxOutput=row.max_output),old||(models.push(model),additions.add(model.id))}let byId=new Map(models.map(m=>[m.id,m])),openclaw=models.filter(m=>!Object.hasOwn(MODEL_ALIASES,m.id)).map(toOpenClawModel);for(let[alias,target]of Object.entries(MODEL_ALIASES)){let model=byId.get(target);!alias.includes("/")&&model&&openclaw.push(toOpenClawModel({...model,id:alias,name:`${alias} \u2192 ${model.name}`}))}let definitions=new Map(openclaw.map(m=>[m.id,m])),visibleIds=new Set(VISIBLE_OPENCLAW_MODELS.map(m=>m.id));for(let group of state.groups)for(let row of group.models)additions.has(row.id)&&visibleIds.add(row.id);let visible=[...visibleIds].flatMap(id2=>definitions.has(id2)?[definitions.get(id2)]:[]);return{models,openclaw,visible,freeIds}}function createClawCatalog(options){let gatewayUrl=`${options.apiBase.replace(/\/$/,"")}/v1/models?format=json`,fetcher=options.fetch??globalThis.fetch,gatewayFetch=options.apiKey?createApiKeyFetch(options.apiKey,fetcher,options.apiBase):fetcher,client=createCatalogClient({network:options.network,gatewayUrl,catalogUrl:options.catalogUrl??process.env.BLOCKRUN_MODEL_CATALOG_URL,timeoutMs:options.timeoutMs??4e3,ttlMs:options.ttlMs??24e4,fetch:(url3,init2)=>String(url3)===gatewayUrl?gatewayFetch(url3,{...init2,redirect:"error"}):fetcher(url3,{...init2,redirect:"error"})}),view=fallbackCatalog(),inflight,lastReported,report=message=>{message!==lastReported&&(lastReported=message,console.warn(`[ClawRouter] Model catalog refresh failed, keeping the last good view: ${message}`))};return{current:()=>view,refresh(){return inflight||(inflight=(async()=>{try{let state=await client.refresh();if(state.lastError&&report(state.lastError),state.source==="live"){let next=projectClawCatalog(state);fingerprint(next)!==fingerprint(view)&&(view=next),state.lastError||(lastReported=void 0)}}catch(err){report(err instanceof Error?err.message:String(err))}return view})().finally(()=>{inflight=void 0}),inflight)}}}function fingerprint(view){return JSON.stringify([view.models.map(m=>[m.id,m.inputPrice,m.outputPrice,m.flatPrice??null,m.platformFeePercent??0,m.contextWindow,m.maxOutput]),view.visible.map(m=>m.id),[...view.freeIds].sort()])}var init_model_catalog=__esm({"src/model-catalog.ts"(){"use strict";init_runtime();init_api_key();init_models();init_platform_fee()}});var version,init_version=__esm({"node_modules/abitype/dist/esm/version.js"(){"use strict";version="1.2.3"}});var BaseError,init_errors=__esm({"node_modules/abitype/dist/esm/errors.js"(){"use strict";init_version();BaseError=class _BaseError extends Error{constructor(shortMessage,args={}){let details=args.cause instanceof _BaseError?args.cause.details:args.cause?.message?args.cause.message:args.details,docsPath9=args.cause instanceof _BaseError&&args.cause.docsPath||args.docsPath,message=[shortMessage||"An error occurred.","",...args.metaMessages?[...args.metaMessages,""]:[],...docsPath9?[`Docs: https://abitype.dev${docsPath9}`]:[],...details?[`Details: ${details}`]:[],`Version: abitype@${version}`].join(`
|
|
5
5
|
`);super(message),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),args.cause&&(this.cause=args.cause),this.details=details,this.docsPath=docsPath9,this.metaMessages=args.metaMessages,this.shortMessage=shortMessage}}}});function execTyped(regex,string4){return regex.exec(string4)?.groups}var bytesRegex,integerRegex,isTupleRegex,init_regex=__esm({"node_modules/abitype/dist/esm/regex.js"(){"use strict";bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,integerRegex=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,isTupleRegex=/^\(.+?\).*?$/}});function formatAbiParameter(abiParameter){let type2=abiParameter.type;if(tupleRegex.test(abiParameter.type)&&"components"in abiParameter){type2="(";let length=abiParameter.components.length;for(let i=0;i<length;i++){let component=abiParameter.components[i];type2+=formatAbiParameter(component),i<length-1&&(type2+=", ")}let result=execTyped(tupleRegex,abiParameter.type);return type2+=`)${result?.array||""}`,formatAbiParameter({...abiParameter,type:type2})}return"indexed"in abiParameter&&abiParameter.indexed&&(type2=`${type2} indexed`),abiParameter.name?`${type2} ${abiParameter.name}`:type2}var tupleRegex,init_formatAbiParameter=__esm({"node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js"(){"use strict";init_regex();tupleRegex=/^tuple(?<array>(\[(\d*)\])*)$/}});function formatAbiParameters(abiParameters){let params="",length=abiParameters.length;for(let i=0;i<length;i++){let abiParameter=abiParameters[i];params+=formatAbiParameter(abiParameter),i!==length-1&&(params+=", ")}return params}var init_formatAbiParameters=__esm({"node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js"(){"use strict";init_formatAbiParameter()}});function formatAbiItem(abiItem){return abiItem.type==="function"?`function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability&&abiItem.stateMutability!=="nonpayable"?` ${abiItem.stateMutability}`:""}${abiItem.outputs?.length?` returns (${formatAbiParameters(abiItem.outputs)})`:""}`:abiItem.type==="event"?`event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`:abiItem.type==="error"?`error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`:abiItem.type==="constructor"?`constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability==="payable"?" payable":""}`:abiItem.type==="fallback"?`fallback() external${abiItem.stateMutability==="payable"?" payable":""}`:"receive() external payable"}var init_formatAbiItem=__esm({"node_modules/abitype/dist/esm/human-readable/formatAbiItem.js"(){"use strict";init_formatAbiParameters()}});function isErrorSignature(signature3){return errorSignatureRegex.test(signature3)}function execErrorSignature(signature3){return execTyped(errorSignatureRegex,signature3)}function isEventSignature(signature3){return eventSignatureRegex.test(signature3)}function execEventSignature(signature3){return execTyped(eventSignatureRegex,signature3)}function isFunctionSignature(signature3){return functionSignatureRegex.test(signature3)}function execFunctionSignature(signature3){return execTyped(functionSignatureRegex,signature3)}function isStructSignature(signature3){return structSignatureRegex.test(signature3)}function execStructSignature(signature3){return execTyped(structSignatureRegex,signature3)}function isConstructorSignature(signature3){return constructorSignatureRegex.test(signature3)}function execConstructorSignature(signature3){return execTyped(constructorSignatureRegex,signature3)}function isFallbackSignature(signature3){return fallbackSignatureRegex.test(signature3)}function execFallbackSignature(signature3){return execTyped(fallbackSignatureRegex,signature3)}function isReceiveSignature(signature3){return receiveSignatureRegex.test(signature3)}var errorSignatureRegex,eventSignatureRegex,functionSignatureRegex,structSignatureRegex,constructorSignatureRegex,fallbackSignatureRegex,receiveSignatureRegex,modifiers,eventModifiers,functionModifiers,init_signatures=__esm({"node_modules/abitype/dist/esm/human-readable/runtime/signatures.js"(){"use strict";init_regex();errorSignatureRegex=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;eventSignatureRegex=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;functionSignatureRegex=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;structSignatureRegex=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;constructorSignatureRegex=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;fallbackSignatureRegex=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;receiveSignatureRegex=/^receive\(\) external payable$/;modifiers=new Set(["memory","indexed","storage","calldata"]),eventModifiers=new Set(["indexed"]),functionModifiers=new Set(["calldata","memory","storage"])}});var InvalidAbiItemError,UnknownTypeError,UnknownSolidityTypeError,init_abiItem=__esm({"node_modules/abitype/dist/esm/human-readable/errors/abiItem.js"(){"use strict";init_errors();InvalidAbiItemError=class extends BaseError{constructor({signature:signature3}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(signature3,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}},UnknownTypeError=class extends BaseError{constructor({type:type2}){super("Unknown type.",{metaMessages:[`Type "${type2}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},UnknownSolidityTypeError=class extends BaseError{constructor({type:type2}){super("Unknown type.",{metaMessages:[`Type "${type2}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}}});var InvalidAbiParameterError,InvalidAbiParametersError,InvalidParameterError,SolidityProtectedKeywordError,InvalidModifierError,InvalidFunctionModifierError,InvalidAbiTypeParameterError,init_abiParameter=__esm({"node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js"(){"use strict";init_errors();InvalidAbiParameterError=class extends BaseError{constructor({param}){super("Failed to parse ABI parameter.",{details:`parseAbiParameter(${JSON.stringify(param,null,2)})`,docsPath:"/api/human#parseabiparameter-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParameterError"})}},InvalidAbiParametersError=class extends BaseError{constructor({params}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(params,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}},InvalidParameterError=class extends BaseError{constructor({param}){super("Invalid ABI parameter.",{details:param}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},SolidityProtectedKeywordError=class extends BaseError{constructor({param,name}){super("Invalid ABI parameter.",{details:param,metaMessages:[`"${name}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},InvalidModifierError=class extends BaseError{constructor({param,type:type2,modifier}){super("Invalid ABI parameter.",{details:param,metaMessages:[`Modifier "${modifier}" not allowed${type2?` in "${type2}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},InvalidFunctionModifierError=class extends BaseError{constructor({param,type:type2,modifier}){super("Invalid ABI parameter.",{details:param,metaMessages:[`Modifier "${modifier}" not allowed${type2?` in "${type2}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${modifier}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},InvalidAbiTypeParameterError=class extends BaseError{constructor({abiParameter}){super("Invalid ABI parameter.",{details:JSON.stringify(abiParameter,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}}});var InvalidSignatureError,UnknownSignatureError,InvalidStructSignatureError,init_signature=__esm({"node_modules/abitype/dist/esm/human-readable/errors/signature.js"(){"use strict";init_errors();InvalidSignatureError=class extends BaseError{constructor({signature:signature3,type:type2}){super(`Invalid ${type2} signature.`,{details:signature3}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},UnknownSignatureError=class extends BaseError{constructor({signature:signature3}){super("Unknown signature.",{details:signature3}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},InvalidStructSignatureError=class extends BaseError{constructor({signature:signature3}){super("Invalid struct signature.",{details:signature3,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}}});var CircularReferenceError,init_struct=__esm({"node_modules/abitype/dist/esm/human-readable/errors/struct.js"(){"use strict";init_errors();CircularReferenceError=class extends BaseError{constructor({type:type2}){super("Circular reference detected.",{metaMessages:[`Struct "${type2}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}}});var InvalidParenthesisError,init_splitParameters=__esm({"node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js"(){"use strict";init_errors();InvalidParenthesisError=class extends BaseError{constructor({current,depth}){super("Unbalanced parentheses.",{metaMessages:[`"${current.trim()}" has too many ${depth>0?"opening":"closing"} parentheses.`],details:`Depth "${depth}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}}});function getParameterCacheKey(param,type2,structs){let structKey="";if(structs)for(let struct of Object.entries(structs)){if(!struct)continue;let propertyKey="";for(let property of struct[1])propertyKey+=`[${property.type}${property.name?`:${property.name}`:""}]`;structKey+=`(${struct[0]}{${propertyKey}})`}return type2?`${type2}:${param}${structKey}`:`${param}${structKey}`}var parameterCache,init_cache=__esm({"node_modules/abitype/dist/esm/human-readable/runtime/cache.js"(){"use strict";parameterCache=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])}});function parseSignature(signature3,structs={}){if(isFunctionSignature(signature3))return parseFunctionSignature(signature3,structs);if(isEventSignature(signature3))return parseEventSignature(signature3,structs);if(isErrorSignature(signature3))return parseErrorSignature(signature3,structs);if(isConstructorSignature(signature3))return parseConstructorSignature(signature3,structs);if(isFallbackSignature(signature3))return parseFallbackSignature(signature3);if(isReceiveSignature(signature3))return{type:"receive",stateMutability:"payable"};throw new UnknownSignatureError({signature:signature3})}function parseFunctionSignature(signature3,structs={}){let match=execFunctionSignature(signature3);if(!match)throw new InvalidSignatureError({signature:signature3,type:"function"});let inputParams=splitParameters(match.parameters),inputs=[],inputLength=inputParams.length;for(let i=0;i<inputLength;i++)inputs.push(parseAbiParameter(inputParams[i],{modifiers:functionModifiers,structs,type:"function"}));let outputs=[];if(match.returns){let outputParams=splitParameters(match.returns),outputLength=outputParams.length;for(let i=0;i<outputLength;i++)outputs.push(parseAbiParameter(outputParams[i],{modifiers:functionModifiers,structs,type:"function"}))}return{name:match.name,type:"function",stateMutability:match.stateMutability??"nonpayable",inputs,outputs}}function parseEventSignature(signature3,structs={}){let match=execEventSignature(signature3);if(!match)throw new InvalidSignatureError({signature:signature3,type:"event"});let params=splitParameters(match.parameters),abiParameters=[],length=params.length;for(let i=0;i<length;i++)abiParameters.push(parseAbiParameter(params[i],{modifiers:eventModifiers,structs,type:"event"}));return{name:match.name,type:"event",inputs:abiParameters}}function parseErrorSignature(signature3,structs={}){let match=execErrorSignature(signature3);if(!match)throw new InvalidSignatureError({signature:signature3,type:"error"});let params=splitParameters(match.parameters),abiParameters=[],length=params.length;for(let i=0;i<length;i++)abiParameters.push(parseAbiParameter(params[i],{structs,type:"error"}));return{name:match.name,type:"error",inputs:abiParameters}}function parseConstructorSignature(signature3,structs={}){let match=execConstructorSignature(signature3);if(!match)throw new InvalidSignatureError({signature:signature3,type:"constructor"});let params=splitParameters(match.parameters),abiParameters=[],length=params.length;for(let i=0;i<length;i++)abiParameters.push(parseAbiParameter(params[i],{structs,type:"constructor"}));return{type:"constructor",stateMutability:match.stateMutability??"nonpayable",inputs:abiParameters}}function parseFallbackSignature(signature3){let match=execFallbackSignature(signature3);if(!match)throw new InvalidSignatureError({signature:signature3,type:"fallback"});return{type:"fallback",stateMutability:match.stateMutability??"nonpayable"}}function parseAbiParameter(param,options){let parameterCacheKey=getParameterCacheKey(param,options?.type,options?.structs);if(parameterCache.has(parameterCacheKey))return parameterCache.get(parameterCacheKey);let isTuple=isTupleRegex.test(param),match=execTyped(isTuple?abiParameterWithTupleRegex:abiParameterWithoutTupleRegex,param);if(!match)throw new InvalidParameterError({param});if(match.name&&isSolidityKeyword(match.name))throw new SolidityProtectedKeywordError({param,name:match.name});let name=match.name?{name:match.name}:{},indexed=match.modifier==="indexed"?{indexed:!0}:{},structs=options?.structs??{},type2,components={};if(isTuple){type2="tuple";let params=splitParameters(match.type),components_=[],length=params.length;for(let i=0;i<length;i++)components_.push(parseAbiParameter(params[i],{structs}));components={components:components_}}else if(match.type in structs)type2="tuple",components={components:structs[match.type]};else if(dynamicIntegerRegex.test(match.type))type2=`${match.type}256`;else if(match.type==="address payable")type2="address";else if(type2=match.type,options?.type!=="struct"&&!isSolidityType(type2))throw new UnknownSolidityTypeError({type:type2});if(match.modifier){if(!options?.modifiers?.has?.(match.modifier))throw new InvalidModifierError({param,type:options?.type,modifier:match.modifier});if(functionModifiers.has(match.modifier)&&!isValidDataLocation(type2,!!match.array))throw new InvalidFunctionModifierError({param,type:options?.type,modifier:match.modifier})}let abiParameter={type:`${type2}${match.array??""}`,...name,...indexed,...components};return parameterCache.set(parameterCacheKey,abiParameter),abiParameter}function splitParameters(params,result=[],current="",depth=0){let length=params.trim().length;for(let i=0;i<length;i++){let char=params[i],tail=params.slice(i+1);switch(char){case",":return depth===0?splitParameters(tail,[...result,current.trim()]):splitParameters(tail,result,`${current}${char}`,depth);case"(":return splitParameters(tail,result,`${current}${char}`,depth+1);case")":return splitParameters(tail,result,`${current}${char}`,depth-1);default:return splitParameters(tail,result,`${current}${char}`,depth)}}if(current==="")return result;if(depth!==0)throw new InvalidParenthesisError({current,depth});return result.push(current.trim()),result}function isSolidityType(type2){return type2==="address"||type2==="bool"||type2==="function"||type2==="string"||bytesRegex.test(type2)||integerRegex.test(type2)}function isSolidityKeyword(name){return name==="address"||name==="bool"||name==="function"||name==="string"||name==="tuple"||bytesRegex.test(name)||integerRegex.test(name)||protectedKeywordsRegex.test(name)}function isValidDataLocation(type2,isArray2){return isArray2||type2==="bytes"||type2==="string"||type2==="tuple"}var abiParameterWithoutTupleRegex,abiParameterWithTupleRegex,dynamicIntegerRegex,protectedKeywordsRegex,init_utils=__esm({"node_modules/abitype/dist/esm/human-readable/runtime/utils.js"(){"use strict";init_regex();init_abiItem();init_abiParameter();init_signature();init_splitParameters();init_cache();init_signatures();abiParameterWithoutTupleRegex=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,abiParameterWithTupleRegex=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,dynamicIntegerRegex=/^u?int$/;protectedKeywordsRegex=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/}});function parseStructs(signatures){let shallowStructs={},signaturesLength=signatures.length;for(let i=0;i<signaturesLength;i++){let signature3=signatures[i];if(!isStructSignature(signature3))continue;let match=execStructSignature(signature3);if(!match)throw new InvalidSignatureError({signature:signature3,type:"struct"});let properties=match.properties.split(";"),components=[],propertiesLength=properties.length;for(let k=0;k<propertiesLength;k++){let trimmed=properties[k].trim();if(!trimmed)continue;let abiParameter=parseAbiParameter(trimmed,{type:"struct"});components.push(abiParameter)}if(!components.length)throw new InvalidStructSignatureError({signature:signature3});shallowStructs[match.name]=components}let resolvedStructs={},entries=Object.entries(shallowStructs),entriesLength=entries.length;for(let i=0;i<entriesLength;i++){let[name,parameters]=entries[i];resolvedStructs[name]=resolveStructs(parameters,shallowStructs)}return resolvedStructs}function resolveStructs(abiParameters=[],structs={},ancestors=new Set){let components=[],length=abiParameters.length;for(let i=0;i<length;i++){let abiParameter=abiParameters[i];if(isTupleRegex.test(abiParameter.type))components.push(abiParameter);else{let match=execTyped(typeWithoutTupleRegex,abiParameter.type);if(!match?.type)throw new InvalidAbiTypeParameterError({abiParameter});let{array:array2,type:type2}=match;if(type2 in structs){if(ancestors.has(type2))throw new CircularReferenceError({type:type2});components.push({...abiParameter,type:`tuple${array2??""}`,components:resolveStructs(structs[type2],structs,new Set([...ancestors,type2]))})}else if(isSolidityType(type2))components.push(abiParameter);else throw new UnknownTypeError({type:type2})}}return components}var typeWithoutTupleRegex,init_structs=__esm({"node_modules/abitype/dist/esm/human-readable/runtime/structs.js"(){"use strict";init_regex();init_abiItem();init_abiParameter();init_signature();init_struct();init_signatures();init_utils();typeWithoutTupleRegex=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/}});function parseAbi(signatures){let structs=parseStructs(signatures),abi2=[],length=signatures.length;for(let i=0;i<length;i++){let signature3=signatures[i];isStructSignature(signature3)||abi2.push(parseSignature(signature3,structs))}return abi2}var init_parseAbi=__esm({"node_modules/abitype/dist/esm/human-readable/parseAbi.js"(){"use strict";init_signatures();init_structs();init_utils()}});function parseAbiItem(signature3){let abiItem;if(typeof signature3=="string")abiItem=parseSignature(signature3);else{let structs=parseStructs(signature3),length=signature3.length;for(let i=0;i<length;i++){let signature_=signature3[i];if(!isStructSignature(signature_)){abiItem=parseSignature(signature_,structs);break}}}if(!abiItem)throw new InvalidAbiItemError({signature:signature3});return abiItem}var init_parseAbiItem=__esm({"node_modules/abitype/dist/esm/human-readable/parseAbiItem.js"(){"use strict";init_abiItem();init_signatures();init_structs();init_utils()}});function parseAbiParameter2(param){let abiParameter;if(typeof param=="string")abiParameter=parseAbiParameter(param,{modifiers});else{let structs=parseStructs(param),length=param.length;for(let i=0;i<length;i++){let signature3=param[i];if(!isStructSignature(signature3)){abiParameter=parseAbiParameter(signature3,{modifiers,structs});break}}}if(!abiParameter)throw new InvalidAbiParameterError({param});return abiParameter}var init_parseAbiParameter=__esm({"node_modules/abitype/dist/esm/human-readable/parseAbiParameter.js"(){"use strict";init_abiParameter();init_signatures();init_structs();init_utils()}});function parseAbiParameters(params){let abiParameters=[];if(typeof params=="string"){let parameters=splitParameters(params),length=parameters.length;for(let i=0;i<length;i++)abiParameters.push(parseAbiParameter(parameters[i],{modifiers}))}else{let structs=parseStructs(params),length=params.length;for(let i=0;i<length;i++){let signature3=params[i];if(isStructSignature(signature3))continue;let parameters=splitParameters(signature3),length2=parameters.length;for(let k=0;k<length2;k++)abiParameters.push(parseAbiParameter(parameters[k],{modifiers,structs}))}}if(abiParameters.length===0)throw new InvalidAbiParametersError({params});return abiParameters}var init_parseAbiParameters=__esm({"node_modules/abitype/dist/esm/human-readable/parseAbiParameters.js"(){"use strict";init_abiParameter();init_signatures();init_structs();init_utils();init_utils()}});var init_exports=__esm({"node_modules/abitype/dist/esm/exports/index.js"(){"use strict";init_formatAbiItem();init_formatAbiParameters();init_parseAbi();init_parseAbiItem();init_parseAbiParameter();init_parseAbiParameters();init_abiItem();init_abiParameter();init_signature();init_splitParameters();init_struct()}});function getAction(client,actionFn,name){let action_implicit=client[actionFn.name];if(typeof action_implicit=="function")return action_implicit;let action_explicit=client[name];return typeof action_explicit=="function"?action_explicit:params=>actionFn(client,params)}var init_getAction=__esm({"node_modules/viem/_esm/utils/getAction.js"(){"use strict"}});function formatAbiItem2(abiItem,{includeName=!1}={}){if(abiItem.type!=="function"&&abiItem.type!=="event"&&abiItem.type!=="error")throw new InvalidDefinitionTypeError(abiItem.type);return`${abiItem.name}(${formatAbiParams(abiItem.inputs,{includeName})})`}function formatAbiParams(params,{includeName=!1}={}){return params?params.map(param=>formatAbiParam(param,{includeName})).join(includeName?", ":","):""}function formatAbiParam(param,{includeName}){return param.type.startsWith("tuple")?`(${formatAbiParams(param.components,{includeName})})${param.type.slice(5)}`:param.type+(includeName&¶m.name?` ${param.name}`:"")}var init_formatAbiItem2=__esm({"node_modules/viem/_esm/utils/abi/formatAbiItem.js"(){"use strict";init_abi()}});function isHex(value,{even=!1,strict=!0}={}){return!value||typeof value!="string"||even&&value.length%2!==0?!1:strict?/^0x[0-9a-fA-F]*$/.test(value):value.startsWith("0x")}var init_isHex=__esm({"node_modules/viem/_esm/utils/data/isHex.js"(){"use strict"}});function size(value){return isHex(value,{strict:!1})?Math.ceil((value.length-2)/2):value.length}var init_size=__esm({"node_modules/viem/_esm/utils/data/size.js"(){"use strict";init_isHex()}});var version2,init_version2=__esm({"node_modules/viem/_esm/errors/version.js"(){"use strict";version2="2.57.16"}});function setErrorConfig(config2){errorConfig=config2}function walk(err,fn){return fn?.(err)?err:err&&typeof err=="object"&&"cause"in err&&err.cause!==void 0?walk(err.cause,fn):fn?null:err}var errorConfig,BaseError2,init_base=__esm({"node_modules/viem/_esm/errors/base.js"(){"use strict";init_version2();errorConfig={getDocsUrl:({docsBaseUrl,docsPath:docsPath9="",docsSlug})=>docsPath9?`${docsBaseUrl??"https://viem.sh"}${docsPath9}${docsSlug?`#${docsSlug}`:""}`:void 0,version:`viem@${version2}`};BaseError2=class _BaseError extends Error{constructor(shortMessage,args={}){let details=args.cause instanceof _BaseError?args.cause.details:args.cause?.message?args.cause.message:args.details,docsPath9=args.cause instanceof _BaseError&&args.cause.docsPath||args.docsPath,docsUrl=errorConfig.getDocsUrl?.({...args,docsPath:docsPath9}),message=[shortMessage||"An error occurred.","",...args.metaMessages?[...args.metaMessages,""]:[],...docsUrl?[`Docs: ${docsUrl}`]:[],...details?[`Details: ${details}`]:[],...errorConfig.version?[`Version: ${errorConfig.version}`]:[]].join(`
|
|
6
6
|
`);super(message,args.cause?{cause:args.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=details,this.docsPath=docsPath9,this.metaMessages=args.metaMessages,this.name=args.name??this.name,this.shortMessage=shortMessage,this.version=version2}walk(fn){return walk(this,fn)}}}});var AbiConstructorNotFoundError,AbiConstructorParamsNotFoundError,AbiDecodingDataSizeInvalidError,AbiDecodingDataSizeTooSmallError,AbiDecodingZeroDataError,AbiEncodingArrayLengthMismatchError,AbiEncodingBytesSizeMismatchError,AbiEncodingLengthMismatchError,AbiErrorInputsNotFoundError,AbiErrorNotFoundError,AbiErrorSignatureNotFoundError,AbiEventSignatureEmptyTopicsError,AbiEventSignatureNotFoundError,AbiEventNotFoundError,AbiFunctionNotFoundError,AbiFunctionOutputsNotFoundError,AbiFunctionSignatureNotFoundError,AbiItemAmbiguityError,BytesSizeMismatchError,DecodeLogDataMismatch,DecodeLogTopicsMismatch,InvalidAbiEncodingTypeError,InvalidAbiDecodingTypeError,InvalidArrayError,InvalidDefinitionTypeError,UnsupportedPackedAbiType,init_abi=__esm({"node_modules/viem/_esm/errors/abi.js"(){"use strict";init_formatAbiItem2();init_size();init_base();AbiConstructorNotFoundError=class extends BaseError2{constructor({docsPath:docsPath9}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
|
|
7
7
|
`),{docsPath:docsPath9,name:"AbiConstructorNotFoundError"})}},AbiConstructorParamsNotFoundError=class extends BaseError2{constructor({docsPath:docsPath9}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
|
|
@@ -2166,13 +2166,13 @@ ${code}
|
|
|
2166
2166
|
}`,fn;try{fn=new F(...constantNames,factoryCode)(...constantValues)}catch(err){throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`)}return options?.debug&&(fn.code=fullCode),fn.definite=ctx.definite,fn}function addConstant(ctx,value){for(let[name2,v]of ctx.constants)if(v===value)return name2;let name=`c${ctx.constantCounter++}`;return ctx.constants.set(name,value),name}function addUserConstant(ctx,fn){return ctx.definite=!1,addConstant(ctx,fn)}function newVar(ctx){return`v${ctx.varCounter++}`}function runtimeRun(schema,value){let result=schema._zod.run({value,issues:[]},{});if(result&&typeof result.then=="function")return INVALID;let r2=result;return r2.issues.length===0?r2.value:INVALID}function compileChild(doc,ctx,schema,accessor,needsValue=!0){let contentLen=doc.content.length,constantCount=ctx.constants.size,constantCounter=ctx.constantCounter,varCounter=ctx.varCounter;try{return generateCheck(doc,ctx,schema,accessor,needsValue)}catch(err){if(!(err instanceof ZodCompileUnsupportedError)||!err.islandable)throw err;if(doc.content.length=contentLen,ctx.constants.size>constantCount){let trailing=Array.from(ctx.constants.keys()).slice(constantCount);for(let k of trailing)ctx.constants.delete(k)}return ctx.constantCounter=constantCounter,ctx.varCounter=varCounter,emitRuntimeIsland(doc,ctx,schema,accessor)}}function emitRuntimeIsland(doc,ctx,schema,accessor){ctx.definite=!1;let schemaConst=addConstant(ctx,schema),runConst=addConstant(ctx,runtimeRun),outVar=newVar(ctx);return doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`),doc.write(`if (${outVar} === INVALID) return INVALID;`),outVar}function generateChecks(doc,ctx,schema,accessor){let schemaChecks=schema._zod.def.checks;if(!schemaChecks||schemaChecks.length===0)return accessor;let currentAccessor=accessor;for(let check2 of schemaChecks){let def=check2._zod.def;if(def.when&&!WHEN_DEFAULTED_CHECKS.has(def.check))throw new ZodCompileUnsupportedError('check with a custom "when" condition');switch(def.check){case"greater_than":generateGreaterThanCheck(doc,ctx,def,currentAccessor);break;case"less_than":generateLessThanCheck(doc,ctx,def,currentAccessor);break;case"multiple_of":generateMultipleOfCheck(doc,ctx,def,currentAccessor);break;case"number_format":generateNumberFormatCheck(doc,def,currentAccessor);break;case"min_length":{let min=numericOperand(def.minimum,"min_length"),len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum*2}`);doc.write(`if (${len} < ${min}) return INVALID;`);break}case"max_length":{let max=numericOperand(def.maximum,"max_length"),len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length > ${max}`);doc.write(`if (${len} > ${max}) return INVALID;`);break}case"length_equals":{let exact=numericOperand(def.length,"length_equals"),len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length*2}`);doc.write(`if (${len} !== ${exact}) return INVALID;`);break}case"min_size":doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum,"min_size")}) return INVALID;`);break;case"max_size":doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum,"max_size")}) return INVALID;`);break;case"size_equals":doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size,"size_equals")}) return INVALID;`);break;case"string_format":currentAccessor=generateStringFormatCheck(doc,ctx,def,currentAccessor);break;case"custom":currentAccessor=generateCustomRefineCheck(doc,ctx,check2,currentAccessor);break;case"bigint_format":generateBigIntFormatCheck(doc,def,currentAccessor);break;case"mime_type":generateMimeTypeCheck(doc,ctx,def,currentAccessor);break;case"property":generatePropertyCheck(doc,ctx,def,currentAccessor);break;case"properties":generatePropertiesChecks(doc,ctx,def,currentAccessor);break;case"overwrite":{let newAccessor=newVar(ctx);generateOverwriteCheck(doc,ctx,check2,currentAccessor,newAccessor),currentAccessor=newAccessor;break}default:throw new ZodCompileUnsupportedError(`check type ${def.check}`)}}return currentAccessor}function codePointLengthVar(doc,ctx,accessor,inDoubt){let cpLen=addConstant(ctx,codePointLength),v=newVar(ctx);return doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`),v}function numericOperand(value,label){if(typeof value!="number"||!Number.isFinite(value))throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`);return`${value}`}function comparisonOperand(ctx,value){if(typeof value=="bigint")return`${value}n`;if(typeof value=="number"){if(Number.isNaN(value))throw new ZodCompileUnsupportedError("comparison check with NaN bound");return`${value}`}if(value instanceof Date){if(Number.isNaN(value.getTime()))throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound");return addConstant(ctx,value)}throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`)}function generateGreaterThanCheck(doc,ctx,def,accessor){let op=def.inclusive?"<":"<=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateLessThanCheck(doc,ctx,def,accessor){let op=def.inclusive?">":">=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateMultipleOfCheck(doc,ctx,def,accessor){if(typeof def.value=="bigint"){if(def.value===BigInt(0))throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor");doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`)}else{let remainder=addConstant(ctx,floatSafeRemainder);doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value,"multiple_of")}) !== 0) return INVALID;`)}}function generateNumberFormatCheck(doc,def,accessor){let format3=def.format;switch(format3){case"safeint":doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`);break;case"int32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`);break;case"uint32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`);break;case"float32":doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`);break;case"float64":doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`);break;default:throw new ZodCompileUnsupportedError(`number format ${format3}`)}}function generateBigIntFormatCheck(doc,def,accessor){let format3=def.format;if(format3)switch(format3){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break;default:throw new ZodCompileUnsupportedError(`bigint format ${format3}`)}}function generateMimeTypeCheck(doc,ctx,def,accessor){let mimeTypes=def.mime;if(mimeTypes&&mimeTypes.length>0){let mimeSet=addConstant(ctx,new Set(mimeTypes));doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`)}}function generatePropertiesChecks(doc,ctx,def,accessor){if(def.when)throw new ZodCompileUnsupportedError('check with a custom "when" condition');doc.write(`if (${accessor} == null) return INVALID;`);let shape2=def.shape;for(let key3 of Reflect.ownKeys(shape2)){let keyExpr=typeof key3=="symbol"?addConstant(ctx,key3):esc(key3),inputVar=newVar(ctx);doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`),compileChild(doc,ctx,shape2[key3],inputVar,!1)}}function generatePropertyCheck(doc,ctx,def,accessor){let propAccessor=`${accessor}[${JSON.stringify(def.property)}]`;generateCheck(doc,ctx,def.schema,propAccessor)}function generateOverwriteCheck(doc,ctx,check2,currentAccessor,newAccessor){let tx=check2._zod.def.tx;if(!tx)throw new ZodCompileUnsupportedError("overwrite check without a transform function");if(isAsyncFunction(tx))throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported");let txConst=addConstant(ctx,tx);doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`)}function throwAsync(){throw new $ZodAsyncError}function pushIssue(issue2){this.issues.push(issue2)}function generateCustomRefineCheck(doc,ctx,check2,accessor){let def=check2._zod.def;if(def.fn){if(isAsyncFunction(def.fn))throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported");let fnConst=addUserConstant(ctx,def.fn),throwAsyncConst=addConstant(ctx,throwAsync),resVar=newVar(ctx);return doc.write(`const ${resVar} = ${fnConst}(${accessor});`),doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`),doc.write(`if (!${resVar}) return INVALID;`),accessor}if(check2._zod.check){if(isAsyncFunction(check2._zod.check))throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported");let checkFn=check2._zod.check,helperConst=addUserConstant(ctx,value=>{let fakePayload={value,issues:[],addIssue:pushIssue};return checkFn(fakePayload)instanceof Promise&&throwAsync(),fakePayload.issues.length===0?fakePayload.value:INVALID}),outVar=newVar(ctx);return doc.write(`const ${outVar} = ${helperConst}(${accessor});`),doc.write(`if (${outVar} === INVALID) return INVALID;`),outVar}throw new ZodCompileUnsupportedError("custom check without a predicate or check function")}function generateStringFormatCheck(doc,ctx,def,accessor,needsValue=!0){let fmt=def.format;if(fmt==="base64"){let validator=addConstant(ctx,isValidBase64);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="base64url"){let validator=addConstant(ctx,isValidBase64URL);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="jwt"){let validator=addConstant(ctx,isValidJWT),alg=addConstant(ctx,def.alg??null);return doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`),accessor}if(fmt==="ipv6"){let validator=addConstant(ctx,isValidIPv6);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="cidrv6"){let validator=addConstant(ctx,isValidCIDRv6);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="credit_card"){let validator=addConstant(ctx,isValidCreditCard);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="iban"){let validator=addConstant(ctx,isValidIBAN);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}let formatDef=def;if(fmt==="url"||fmt==="httpurl"||formatDef.normalize||formatDef.hostname!==void 0||formatDef.protocol!==void 0){let parseConst=addConstant(ctx,validateURL),defConst=addConstant(ctx,def),trimVar=newVar(ctx),urlVar=newVar(ctx);if(doc.write(`const ${trimVar} = ${accessor}.trim();`),doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`),doc.write(`if (typeof ${urlVar} === "number") return INVALID;`),formatDef.hostname!==void 0){let hostnameConst=addConstant(ctx,urlHostnameOk);doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`)}if(formatDef.protocol!==void 0){let protocolConst=addConstant(ctx,urlProtocolOk);doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`)}if(!needsValue)return null;let outputVar=newVar(ctx),outputExpr=formatDef.normalize?`${urlVar}.href`:`${addConstant(ctx,stripTabAndNewline)}(${trimVar})`;return doc.write(`const ${outputVar} = ${outputExpr};`),outputVar}let customFn=def.fn;if(customFn){if(isAsyncFunction(customFn))throw new ZodCompileUnsupportedError(`async string format ${fmt}`);let fnConst=addConstant(ctx,customFn);return doc.write(`if (!${fnConst}(${accessor})) return INVALID;`),accessor}if(PATTERN_IS_COMPLETE.has(fmt)&&def.pattern){let patternConst=addConstant(ctx,def.pattern);return doc.write(`${patternConst}.lastIndex = 0;`),doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`),accessor}let format3=def.format;switch(format3){case"regex":throw new ZodCompileUnsupportedError("regex format without a pattern");case"lowercase":doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`);break;case"uppercase":doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`);break;case"includes":doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`);break;case"starts_with":{let prefix=def.prefix;doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`);break}case"ends_with":{let suffix=def.suffix;doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`);break}default:throw new ZodCompileUnsupportedError(`string format ${format3}`)}return accessor}function generateCheck(doc,ctx,schema,accessor,needsValue=!0){let def=schema._zod.def,type2=def.type;if(def.coerce)throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type2}())`);let buildsValue=needsValue||!!def.checks?.length,typeAccessor;switch(type2){case"string":typeAccessor=generateStringCheck(doc,ctx,schema,accessor,buildsValue);break;case"number":typeAccessor=generateNumberCheck(doc,schema,accessor);break;case"boolean":typeAccessor=generateBooleanCheck(doc,accessor);break;case"bigint":typeAccessor=generateBigIntCheck(doc,schema,accessor);break;case"symbol":typeAccessor=generateSymbolCheck(doc,accessor);break;case"undefined":typeAccessor=generateUndefinedCheck(doc,accessor);break;case"null":typeAccessor=generateNullCheck(doc,accessor);break;case"any":case"unknown":typeAccessor=accessor;break;case"never":doc.write("return INVALID;"),typeAccessor=accessor;break;case"void":typeAccessor=generateVoidCheck(doc,accessor);break;case"nan":typeAccessor=generateNaNCheck(doc,accessor);break;case"date":typeAccessor=generateDateCheck(doc,accessor);break;case"object":typeAccessor=generateObjectCheck(doc,ctx,schema,accessor,buildsValue);break;case"optional":typeAccessor=generateOptionalCheck(doc,ctx,schema,accessor,buildsValue);break;case"nullable":typeAccessor=generateNullableCheck(doc,ctx,schema,accessor,buildsValue);break;case"array":typeAccessor=generateArrayCheck(doc,ctx,schema,accessor,buildsValue);break;case"literal":typeAccessor=generateLiteralCheck(doc,ctx,schema,accessor);break;case"enum":typeAccessor=generateEnumCheck(doc,ctx,schema,accessor);break;case"readonly":{let innerOut=generateWrapperCheck(doc,ctx,schema,accessor),frozenVar=newVar(ctx);doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`),typeAccessor=frozenVar;break}case"success":generateWrapperCheck(doc,ctx,schema,accessor),typeAccessor="true";break;case"default":case"prefault":typeAccessor=generateDefaultCheck(doc,ctx,schema,accessor);break;case"nonoptional":typeAccessor=generateNonOptionalCheck(doc,ctx,schema,accessor);break;case"tuple":typeAccessor=generateTupleCheck(doc,ctx,schema,accessor);break;case"union":typeAccessor=generateUnionCheck(doc,ctx,schema,accessor);break;case"intersection":typeAccessor=generateIntersectionCheck(doc,ctx,schema,accessor);break;case"record":typeAccessor=generateRecordCheck(doc,ctx,schema,accessor);break;case"map":typeAccessor=generateMapCheck(doc,ctx,schema,accessor);break;case"set":typeAccessor=generateSetCheck(doc,ctx,schema,accessor);break;case"file":typeAccessor=generateFileCheck(doc,accessor);break;case"template_literal":typeAccessor=generateTemplateLiteralCheck(doc,ctx,schema,accessor);break;case"lazy":typeAccessor=generateLazyCheck(doc,ctx,schema,accessor);break;case"pipe":typeAccessor=generatePipeCheck(doc,ctx,schema,accessor);break;case"custom":typeAccessor=generateCustomCheck(doc,ctx,schema,accessor);break;case"transform":typeAccessor=generateTransformCheck(doc,ctx,schema,accessor);break;case"catch":typeAccessor=generateCatchCheck(doc,ctx,schema,accessor);break;default:throw new ZodCompileUnsupportedError(`schema type ${type2}`)}return typeAccessor===null?null:generateChecks(doc,ctx,schema,typeAccessor)}function generateStringCheck(doc,ctx,schema,accessor,needsValue=!0){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);let def=schema._zod.def;return def.format===void 0?accessor:generateStringFormatCheck(doc,ctx,def,accessor,needsValue)}function generateNumberCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`);let def=schema._zod.def;return def.check==="number_format"&&def.format&&generateNumberFormatCheck(doc,{format:def.format},accessor),accessor}function generateBooleanCheck(doc,accessor){return doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`),accessor}function generateBigIntCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`);let def=schema._zod.def;if(def.format)switch(def.format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break}return accessor}function generateSymbolCheck(doc,accessor){return doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`),accessor}function generateUndefinedCheck(doc,accessor){return doc.write(`if (${accessor} !== undefined) return INVALID;`),accessor}function generateNullCheck(doc,accessor){return doc.write(`if (${accessor} !== null) return INVALID;`),accessor}function generateVoidCheck(doc,accessor){return doc.write(`if (${accessor} !== undefined) return INVALID;`),accessor}function generateNaNCheck(doc,accessor){return doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`),accessor}function generateDateCheck(doc,accessor){return doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`),accessor}function generateObjectCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def;doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`);let shape2=def.shape,keys=Object.keys(shape2),symbolKeys=Object.getOwnPropertySymbols(shape2),allKeys=symbolKeys.length?[...keys,...symbolKeys]:keys,keyExpr=k=>typeof k=="symbol"?addConstant(ctx,k):esc(k),propKey=k=>typeof k=="symbol"?`[${keyExpr(k)}]`:esc(k),propShape=shape2;if(keys.includes("__proto__"))throw new ZodCompileUnsupportedError('object shape key "__proto__"');let propOutputs=new Map;for(let key3 of allKeys){let propSchema=propShape[key3],kx=keyExpr(key3),inputVar=newVar(ctx);if(doc.write(`const ${inputVar} = ${accessor}[${kx}];`),propSchema._zod.optin!==void 0){let outputVar2=newVar(ctx);doc.write(`let ${outputVar2} = (() => {`),doc.indented(d=>{let outputAccessor=compileChild(d,ctx,propSchema,inputVar);d.write(`return ${outputAccessor};`)}),doc.write("})();"),propSchema._zod.optout==="optional"?(doc.write(`if (${outputVar2} === INVALID) {`),doc.indented(d=>{d.write(`if (${kx} in ${accessor}) return INVALID;`),d.write(`${outputVar2} = undefined;`)}),doc.write("}")):doc.write(`if (${outputVar2} === INVALID) return INVALID;`),propOutputs.set(key3,outputVar2)}else{requiresPresenceCheck(propSchema)&&doc.write(`if (!(${kx} in ${accessor})) return INVALID;`);let outputAccessor=compileChild(doc,ctx,propSchema,inputVar,buildsValue);outputAccessor!==null&&propOutputs.set(key3,outputAccessor)}}let catchall=def.catchall,unknownKeysMode="none";if(catchall){let catchallType=catchall._zod.def.type;if(catchallType==="never"){let condition=keys.map(k=>`k !== ${esc(k)}`).join(" && ")||"true";doc.write(`for (const k in ${accessor}) {`),doc.indented(d=>{d.write(`if (${condition}) return INVALID;`)}),doc.write("}")}else(catchallType==="unknown"||catchallType==="any")&&!catchall._zod.def.checks?.length?unknownKeysMode="passthrough":unknownKeysMode="schema"}let outputVar=newVar(ctx),hasConditionalKeys=allKeys.some(k=>mayOmitUndefined(propShape[k])||dropsWhenAbsent(propShape[k]));if(!buildsValue){if(unknownKeysMode==="schema"){let knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`),doc.indented(d=>{d.write('if (k === "__proto__") continue;'),knownSet&&d.write(`if (${knownSet}.has(k)) continue;`);let valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`),compileChild(d,ctx,catchall,valVar,!1)}),doc.write("}")}return null}if(hasConditionalKeys){doc.write(`const ${outputVar} = {};`);for(let k of allKeys){let kx=keyExpr(k),out=propOutputs.get(k);dropsWhenAbsent(propShape[k])?doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`):mayOmitUndefined(propShape[k])?doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`):doc.write(`${outputVar}[${kx}] = ${out};`)}}else{let propLiterals=allKeys.map(k=>`${propKey(k)}: ${propOutputs.get(k)}`).join(", ");doc.write(`const ${outputVar} = { ${propLiterals} };`)}if(unknownKeysMode!=="none"){let knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`),doc.indented(d=>{if(d.write('if (k === "__proto__") continue;'),knownSet&&d.write(`if (${knownSet}.has(k)) continue;`),unknownKeysMode==="passthrough")d.write(`${outputVar}[k] = ${accessor}[k];`);else{let valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`);let catchallOut=compileChild(d,ctx,catchall,valVar);d.write(`${outputVar}[k] = ${catchallOut};`)}}),doc.write("}")}return outputVar}function generateOptionalCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def;if(isExactOptional(schema))return generateCheck(doc,ctx,def.innerType,accessor,buildsValue);if(def.innerType._zod.optin==="defaulted"){let outputVar2=newVar(ctx),branchVar=newVar(ctx);return doc.write(`let ${outputVar2};`),doc.write(`if (${accessor} === undefined) {`),doc.indented(d=>{d.write(`const ${branchVar} = (() => {`),d.indented(d2=>{let innerOutput=generateCheck(d2,ctx,def.innerType,accessor);d2.write(`return ${innerOutput};`)}),d.write("})();"),d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`)}),doc.write("} else {"),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar2} = ${innerOutput};`)}),doc.write("}"),outputVar2}let outputVar=buildsValue?newVar(ctx):null;return outputVar&&doc.write(`let ${outputVar};`),doc.write(`if (${accessor} !== undefined) {`),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);outputVar&&innerOutput!==null&&d.write(`${outputVar} = ${innerOutput};`)}),doc.write("}"),outputVar}function isExactOptional(schema){return schema._zod.traits?.has("$ZodExactOptional")===!0}function requiresPresenceCheck(schema){return schema._zod.optin===void 0&&fastPathAcceptsAbsence(schema)}function fastPathAcceptsAbsence(schema){if(schema._zod.def.coerce)return!0;let def=schema._zod.def;switch(def.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return def.innerType?fastPathAcceptsAbsence(def.innerType):!1;case"literal":return!!def.values?.includes(void 0);case"enum":return!!schema._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return def.innerType?fastPathAcceptsAbsence(def.innerType):!0;case"catch":return!0;case"union":return def.options?def.options.some(fastPathAcceptsAbsence):!0;case"intersection":return!def.left||!def.right?!0:fastPathAcceptsAbsence(def.left)&&fastPathAcceptsAbsence(def.right);case"pipe":return def.in?fastPathAcceptsAbsence(def.in):!0;default:return!0}}function dropsWhenAbsent(schema){return schema._zod.optin==="optional"&&schema._zod.optout==="optional"}function mayOmitUndefined(schema){return(schema._zod.optin!=="defaulted"||schema._zod.optout==="optional")&&mayOutputUndefined(schema)}function mayOutputUndefined(schema){let def=schema._zod.def;switch(def.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!def.values?.includes(void 0);case"enum":return!!schema._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return def.innerType?mayOutputUndefined(def.innerType):!0;case"union":return def.options?def.options.some(mayOutputUndefined):!0;case"intersection":return!def.left||!def.right||mayOutputUndefined(def.left)||mayOutputUndefined(def.right);case"pipe":return def.out?mayOutputUndefined(def.out):!0;default:return!0}}function generateNullableCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def,outputVar=buildsValue?newVar(ctx):null;return outputVar&&doc.write(`let ${outputVar} = null;`),doc.write(`if (${accessor} !== null) {`),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);outputVar&&innerOutput!==null&&d.write(`${outputVar} = ${innerOutput};`)}),doc.write("}"),outputVar}function generateSizeGate(doc,schema,size4){for(let[max,check2]of sizeCaps(schema._zod.def.checks))doc.write(`if (${size4} > ${numericOperand(max,check2._zod.def.check)}) return INVALID;`)}function generateArrayCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`),generateSizeGate(doc,schema,`${accessor}.length`);let outputVar=buildsValue?newVar(ctx):null,iVar=newVar(ctx),elemVar=newVar(ctx);return outputVar&&doc.write(`const ${outputVar} = new Array(${accessor}.length);`),doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);let elemOutput=compileChild(d,ctx,def.element,elemVar,buildsValue);outputVar&&elemOutput!==null&&d.write(`${outputVar}[${iVar}] = ${elemOutput};`)}),doc.write("}"),outputVar}function generateLiteralCheck(doc,ctx,schema,accessor){let values=schema._zod.def.values;if(values.length!==1){let literalSet=addConstant(ctx,new Set(values));return doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`),accessor}let value=values[0];if(typeof value=="number"&&Number.isNaN(value)){let literalSet=addConstant(ctx,new Set(values));return doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`),accessor}if(typeof value=="string")doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`);else if(typeof value=="number"||typeof value=="boolean")doc.write(`if (${accessor} !== ${value}) return INVALID;`);else if(value===null)doc.write(`if (${accessor} !== null) return INVALID;`);else if(value===void 0)doc.write(`if (${accessor} !== undefined) return INVALID;`);else if(typeof value=="bigint")doc.write(`if (${accessor} !== ${value}n) return INVALID;`);else throw new ZodCompileUnsupportedError(`literal type ${typeof value}`);return accessor}function generateEnumCheck(doc,ctx,schema,accessor){let values=schema._zod.values;if(!values)throw new ZodCompileUnsupportedError("enum schema without enumerated values");let enumSet=addConstant(ctx,values);return doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`),accessor}function generateWrapperCheck(doc,ctx,schema,accessor){let def=schema._zod.def;return generateCheck(doc,ctx,def.innerType,accessor)}function generateDefaultCheck(doc,ctx,schema,accessor){let def=schema._zod.def,defaultGetter=Object.getOwnPropertyDescriptor(schema._zod.def,"defaultValue")?()=>schema._zod.def.defaultValue:void 0;if(schema._zod.def.type==="prefault"){if(!defaultGetter)return generateCheck(doc,ctx,def.innerType,accessor);let defaultFn=addConstant(ctx,defaultGetter),inputVar=newVar(ctx);return doc.write(`let ${inputVar} = ${accessor};`),doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`),generateCheck(doc,ctx,def.innerType,inputVar)}let outputVar=newVar(ctx);if(defaultGetter){let defaultFn=addConstant(ctx,defaultGetter),cloneFn=addConstant(ctx,shallowClone);doc.write(`let ${outputVar};`),doc.write(`if (${accessor} === undefined) {`),doc.indented(d=>{d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`)}),doc.write("} else {"),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`)}),doc.write("}")}else doc.write(`let ${outputVar};`),doc.write(`if (${accessor} !== undefined) {`),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)}),doc.write("}");return outputVar}function generateNonOptionalCheck(doc,ctx,schema,accessor){let def=schema._zod.def,innerOutput=generateCheck(doc,ctx,def.innerType,accessor),outputVar=newVar(ctx);return doc.write(`const ${outputVar} = ${innerOutput};`),doc.write(`if (${outputVar} === undefined) return INVALID;`),outputVar}function generateTupleCheck(doc,ctx,schema,accessor){let def=schema._zod.def,items=def.items,rest=def.rest;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);let optinStart=getTupleOptStart2(items,"optin"),optoutStart=getTupleOptStart2(items,"optout");rest?doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`):doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`);let outputVar=newVar(ctx);doc.write(`const ${outputVar} = [];`);for(let i=0;i<items.length;i++){let itemSchema=items[i];if(i>=optoutStart)doc.write(`if (${outputVar}.length === ${i}) {`),doc.indented(d=>{d.write(`if (${i} < ${accessor}.length) {`),d.indented(d2=>{let elemVar=newVar(ctx);d2.write(`const ${elemVar} = ${accessor}[${i}];`);let elemOutput=compileChild(d2,ctx,itemSchema,elemVar);d2.write(`${outputVar}[${i}] = ${elemOutput};`)}),d.write("} else {"),d.indented(d2=>{if(dropsWhenAbsent(itemSchema)){d2.write(`${outputVar}.length = ${i};`);return}let elemVar=newVar(ctx),branchVar=newVar(ctx);d2.write(`const ${elemVar} = undefined;`),d2.write(`const ${branchVar} = (() => {`),d2.indented(d3=>{let elemOutput=compileChild(d3,ctx,itemSchema,elemVar);d3.write(`return ${elemOutput};`)}),d2.write("})();"),d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`),d2.write(`else ${outputVar}[${i}] = ${branchVar};`)}),d.write("}")}),doc.write("}");else{let elemVar=newVar(ctx);doc.write(`const ${elemVar} = ${accessor}[${i}];`);let elemOutput=compileChild(doc,ctx,itemSchema,elemVar);doc.write(`${outputVar}[${i}] = ${elemOutput};`)}}if(rest){let iVar=newVar(ctx),elemVar=newVar(ctx);doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);let elemOutput=compileChild(d,ctx,rest,elemVar);d.write(`${outputVar}[${iVar}] = ${elemOutput};`)}),doc.write("}")}return outputVar}function getTupleOptStart2(items,key3){for(let i=items.length-1;i>=0;i--)if(!(key3==="optin"?items[i]._zod.optin!==void 0:items[i]._zod.optout==="optional"))return i+1;return 0}function generateUnionCheck(doc,ctx,schema,accessor){let def=schema._zod.def,options=def.options;if(def.discriminator)return generateDiscriminatedUnionCheck(doc,ctx,def,accessor);if(def.inclusive===!1)throw new ZodCompileUnsupportedError("exclusive unions (z.xor)");if(options.length===0)return doc.write("return INVALID;"),accessor;if(options.length===1)return generateCheck(doc,ctx,options[0],accessor);if(options.every(opt=>opt._zod.def.type==="literal"&&!opt._zod.def.checks?.length)){let values=new Set(options.flatMap(opt=>opt._zod.def.values)),valuesConst=addConstant(ctx,values);return doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`),accessor}let outputVar=newVar(ctx);doc.write(`let ${outputVar};`);for(let i=0;i<options.length;i++){let opt=options[i];i===0?doc.write(`${outputVar} = (() => {`):doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`),doc.indented(d=>{let branchOutput=generateCheck(d,ctx,opt,accessor);d.write(`return ${branchOutput};`)}),doc.write("})();")}return doc.write(`if (${outputVar} === INVALID) return INVALID;`),outputVar}function generateDiscriminatedUnionCheck(doc,ctx,def,accessor){if(def.unionFallback)throw new ZodCompileUnsupportedError("discriminated union with unionFallback");if(def.options.length===0)return doc.write("return INVALID;"),accessor;let discVar=newVar(ctx),outputVar=newVar(ctx);doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`),doc.write(`let ${outputVar};`);let firstBranch=!0,claimed=new Set;for(let option of def.options){let values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values");for(let value of values){if(claimed.has(value))throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`);claimed.add(value)}let conditions=Array.from(values,value=>literalEquality(ctx,discVar,value)),prefix=firstBranch?"if":"else if";doc.write(`${prefix} (${conditions.join(" || ")}) {`),doc.indented(d=>{let branchOutput=generateCheck(d,ctx,option,accessor);d.write(`${outputVar} = ${branchOutput};`)}),doc.write("}"),firstBranch=!1}return doc.write("else { return INVALID; }"),outputVar}function literalEquality(ctx,accessor,value){if(typeof value=="string")return`${accessor} === ${esc(value)}`;if(typeof value=="number")return Number.isNaN(value)?`Number.isNaN(${accessor})`:`${accessor} === ${value}`;if(typeof value=="boolean")return`${accessor} === ${value}`;if(value===null)return`${accessor} === null`;if(value===void 0)return`${accessor} === undefined`;if(typeof value=="bigint")return`${accessor} === ${value}n`;if(typeof value=="symbol"){let symbolConst=addConstant(ctx,value);return`${accessor} === ${symbolConst}`}throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`)}function generateIntersectionCheck(doc,ctx,schema,accessor){let def=schema._zod.def;ctx.definite=!1;let leftOutput=compileChild(doc,ctx,def.left,accessor),rightOutput=compileChild(doc,ctx,def.right,accessor),mergeConst=addConstant(ctx,mergeValues),mergedVar=newVar(ctx);return doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`),doc.write(`if (!${mergedVar}.valid) return INVALID;`),`${mergedVar}.data`}function generateRecordCheck(doc,ctx,schema,accessor){let def=schema._zod.def,isPlainObjectConst=addConstant(ctx,isPlainObject2);doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);let outputVar=newVar(ctx),kVar=newVar(ctx),valVar=newVar(ctx);doc.write(`const ${outputVar} = {};`);let recordDef=def,keyValues=recordDef.partial?void 0:def.keyType._zod.values;if(keyValues){let inputKeys=[];for(let key3 of keyValues){if(!(typeof key3=="string"||typeof key3=="number"||typeof key3=="symbol"))throw new ZodCompileUnsupportedError(`record key value ${String(key3)}`);let inputKey=typeof key3=="number"?key3.toString():key3;if(inputKey==="__proto__")throw new ZodCompileUnsupportedError('record key "__proto__"');inputKeys.push(inputKey);let keyConst=addConstant(ctx,key3),outKey=generateCheck(doc,ctx,def.keyType,keyConst),valueVar=newVar(ctx);doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx,inputKey)}];`);let valOutput=compileChild(doc,ctx,def.valueType,valueVar);doc.write(`${outputVar}[${outKey}] = ${valOutput};`)}let knownKeysConst=addConstant(ctx,new Set(inputKeys));return doc.write(`for (const ${kVar} in ${accessor}) {`),doc.indented(d=>{d.write(`if (${knownKeysConst}.has(${kVar})) continue;`),recordDef.mode==="loose"?d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`):d.write("return INVALID;")}),doc.write("}"),outputVar}let keyDef=def.keyType._zod.def;if(!(keyDef.type==="string"&&keyDef.format===void 0&&!keyDef.coerce&&(keyDef.checks?.length??0)===0)){let isLoose=def.mode==="loose",keyFn=compileFn(def.keyType);keyFn.definite===!1&&(ctx.definite=!1);let keyFast=addConstant(ctx,keyFn),numericConst=addConstant(ctx,number),outKeyVar=newVar(ctx);return emitOwnKeys(doc,ctx,accessor,kVar,d=>{d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`),d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`),isLoose?d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`):d.write(`if (${outKeyVar} === INVALID) return INVALID;`),d.write(`if (${outKeyVar} === "__proto__") continue;`);let valueVar=newVar(ctx);d.write(`const ${valueVar} = ${accessor}[${kVar}];`);let valOutput=compileChild(d,ctx,def.valueType,valueVar);d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`)}),outputVar}return emitOwnKeys(doc,ctx,accessor,kVar,d=>{d.write(`const ${valVar} = ${accessor}[${kVar}];`);let valOutput=compileChild(d,ctx,def.valueType,valVar);d.write(`${outputVar}[${kVar}] = ${valOutput};`)},"return INVALID;"),outputVar}function emitOwnKeys(doc,ctx,accessor,kVar,body,onSymbol){let propIsEnumerableConst=addConstant(ctx,Object.prototype.propertyIsEnumerable),symsVar=newVar(ctx),keysVar=newVar(ctx),iVar=newVar(ctx);doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`),doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`),doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${kVar} = ${keysVar}[${iVar}];`),d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`),body(d)}),doc.write("}"),doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${kVar} = ${symsVar}[${iVar}];`),d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`),onSymbol?d.write(onSymbol):body(d)}),doc.write("}")}function literalPropertyKey(ctx,key3){return typeof key3=="string"?esc(key3):addConstant(ctx,key3)}function generateMapCheck(doc,ctx,schema,accessor){let def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`),generateSizeGate(doc,schema,`${accessor}.size`);let outputVar=newVar(ctx),kVar=newVar(ctx),valVar=newVar(ctx);return doc.write(`const ${outputVar} = new Map();`),doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`),doc.indented(d=>{let keyOutput=generateCheck(d,ctx,def.keyType,kVar),valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`)}),doc.write("}"),outputVar}function generateSetCheck(doc,ctx,schema,accessor){let def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`),generateSizeGate(doc,schema,`${accessor}.size`);let outputVar=newVar(ctx),valVar=newVar(ctx);return doc.write(`const ${outputVar} = new Set();`),doc.write(`for (const ${valVar} of ${accessor}) {`),doc.indented(d=>{let valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.add(${valOutput});`)}),doc.write("}"),outputVar}function generateFileCheck(doc,accessor){return doc.write(`if (!(${accessor} instanceof File)) return INVALID;`),accessor}function generateTemplateLiteralCheck(doc,ctx,schema,accessor){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);let pattern=schema._zod.pattern;if(pattern){let patternConst=addConstant(ctx,pattern);doc.write(`${patternConst}.lastIndex = 0;`),doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`)}return accessor}function generateLazyCheck(doc,ctx,schema,accessor){let def=schema._zod.def,getterConst=addUserConstant(ctx,def.getter),cacheConst=addConstant(ctx,{parser:null});doc.write(`if (!${cacheConst}.parser) {`),doc.indented(d=>{d.write(`const inner = ${getterConst}();`),d.write(`${cacheConst}.parser = function(input) {`),d.indented(d2=>{d2.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),d2.write("return result.issues.length === 0 ? result.value : INVALID;")}),d.write("};")}),doc.write("}");let outputVar=newVar(ctx);return doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`),doc.write(`if (${outputVar} === INVALID) return INVALID;`),outputVar}function generatePipeCheck(doc,ctx,schema,accessor){let def=schema._zod.def,inputOutput=generateCheck(doc,ctx,def.in,accessor);if(def.transform){if(isAsyncFunction(def.transform))throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported");let transformFn=def.transform,helperConst=addUserConstant(ctx,value=>{let fakePayload={value,issues:[],addIssue:pushIssue},result=transformFn(value,fakePayload);return result instanceof Promise?INVALID:fakePayload.issues.length===0?result:INVALID}),transformedVar=newVar(ctx);return doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`),doc.write(`if (${transformedVar} === INVALID) return INVALID;`),generateCheck(doc,ctx,def.out,transformedVar)}else return generateCheck(doc,ctx,def.out,inputOutput)}function isAsyncFunction(fn){return typeof fn=="function"&&(fn.constructor.name==="AsyncFunction"||fn[Symbol.toStringTag]==="AsyncFunction")}function generateCustomCheck(doc,ctx,schema,accessor){let def=schema._zod.def;if(def.fn){if(isAsyncFunction(def.fn))throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported");let fnConst=addUserConstant(ctx,def.fn),throwAsyncConst=addConstant(ctx,throwAsync),resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`),doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`),doc.write(`if (!${resVar}) return INVALID;`)}else throw new ZodCompileUnsupportedError("custom schema without a predicate function");return accessor}function runtimeCatch(innerSchema,catchValue,value){let result=innerSchema._zod.run({value,issues:[]},{});if(result&&typeof result.then=="function")return INVALID;let r2=result;return r2.issues.length===0?r2.value:catchValue()}function generateCatchCheck(doc,ctx,schema,accessor){let def=schema._zod.def;if(!def.catchValue[CONSTANT_CATCH])throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)",!1);let outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`),doc.indented(d=>{let innerOut=compileChild(d,ctx,def.innerType,accessor);d.write(`return ${innerOut};`)}),doc.write("})();");let innerConst=addConstant(ctx,def.innerType),catchConst=addUserConstant(ctx,def.catchValue),catchHelperConst=addConstant(ctx,runtimeCatch);return doc.write(`if (${outputVar} === INVALID) {`),doc.indented(d=>{d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`),d.write(`if (${outputVar} === INVALID) return INVALID;`)}),doc.write("}"),outputVar}function generateTransformCheck(doc,ctx,schema,accessor){let def=schema._zod.def;if(def.transform){if(isAsyncFunction(def.transform))throw new ZodCompileAsyncError("z.compile: async transforms are not supported");let transformFn=def.transform,helperConst=addUserConstant(ctx,value=>{let fakePayload={value,issues:[],addIssue:pushIssue},result=transformFn(value,fakePayload);return result instanceof Promise?INVALID:fakePayload.issues.length===0?result:INVALID}),outputVar=newVar(ctx);return doc.write(`const ${outputVar} = ${helperConst}(${accessor});`),doc.write(`if (${outputVar} === INVALID) return INVALID;`),outputVar}return accessor}var INVALID,FALLBACK_FLAG,ZodCompileAsyncError,ZodCompileUnsupportedError,WHEN_DEFAULTED_CHECKS,PATTERN_IS_COMPLETE,init_compile=__esm({"node_modules/zod/v4/core/compile.js"(){"use strict";init_core();init_doc();init_memoizer();init_regexes();init_schemas();init_util();INVALID=Symbol.for("zod.compile.invalid"),FALLBACK_FLAG=Symbol.for("zod.compile.fallback"),ZodCompileAsyncError=class extends Error{constructor(message="z.compile does not support async refinements, transforms, or checks"){super(message),this.name="ZodCompileAsyncError"}},ZodCompileUnsupportedError=class extends Error{constructor(feature,islandable=!0){super(`z.compile does not support ${feature}; this schema must use the runtime parser`),this.name="ZodCompileUnsupportedError",this.islandable=islandable}};WHEN_DEFAULTED_CHECKS=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);PATTERN_IS_COMPLETE=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"])}});function snapshotChecks(def){return def.checks&&(def.checks=[...def.checks]),def}function _string(Class2,params){return new Class2(snapshotChecks({type:"string",...normalizeParams(params)}))}function _coercedString(Class2,params){return new Class2(snapshotChecks({type:"string",coerce:!0,...normalizeParams(params)}))}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _mac(Class2,params){return new Class2({type:"string",format:"mac",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _creditCard(Class2,params){return new Class2({type:"string",format:"credit_card",check:"string_format",abort:!1,...normalizeParams(params)})}function _iban(Class2,params){return new Class2({type:"string",format:"iban",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2(snapshotChecks({type:"number",checks:[],...normalizeParams(params)}))}function _coercedNumber(Class2,params){return new Class2(snapshotChecks({type:"number",coerce:!0,checks:[],...normalizeParams(params)}))}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _float32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float32",...normalizeParams(params)})}function _float64(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float64",...normalizeParams(params)})}function _int32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"int32",...normalizeParams(params)})}function _uint32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"uint32",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class2,params){return new Class2({type:"boolean",coerce:!0,...normalizeParams(params)})}function _bigint(Class2,params){return new Class2({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class2,params){return new Class2({type:"bigint",coerce:!0,...normalizeParams(params)})}function _int64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...normalizeParams(params)})}function _uint64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...normalizeParams(params)})}function _symbol(Class2,params){return new Class2({type:"symbol",...normalizeParams(params)})}function _undefined2(Class2,params){return new Class2({type:"undefined",...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _any(Class2){return new Class2({type:"any"})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _void(Class2,params){return new Class2({type:"void",...normalizeParams(params)})}function _date(Class2,params){return new Class2({type:"date",...normalizeParams(params)})}function _coercedDate(Class2,params){return new Class2({type:"date",coerce:!0,...normalizeParams(params)})}function _nan(Class2,params){return new Class2({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!1})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!0})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!1})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!0})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size4,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size:size4})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _properties(shape2,params){return new $ZodCheckProperties({check:"properties",shape:shape2,...normalizeParams(params)})}function _mime(types2,params){return new $ZodCheckMimeType({check:"mime_type",mime:types2,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form2){return _overwrite(input2=>input2.normalize(form2))}function _trim(){return _overwrite(input2=>input2.trim())}function _toLowerCase(){return _overwrite(input2=>input2.toLowerCase())}function _toUpperCase(){return _overwrite(input2=>input2.toUpperCase())}function _slugify(){return _overwrite(input2=>slugify(input2))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _union(Class2,options,params){return new Class2({type:"union",options,...normalizeParams(params)})}function _xor(Class2,options,params){return new Class2({type:"union",options,inclusive:!1,...normalizeParams(params)})}function _discriminatedUnion(Class2,discriminator,options,params){return new Class2({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class2,left,right){return new Class2({type:"intersection",left,right})}function _tuple(Class2,items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest,rest=hasRest?_paramsOrRest:null;return new Class2({type:"tuple",items,rest,...normalizeParams(params)})}function _record(Class2,keyType,valueType,params){return new Class2({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class2,keyType,valueType,params){return new Class2({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class2,valueType,params){return new Class2({type:"set",valueType,...normalizeParams(params)})}function _enum(Class2,values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new Class2({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class2,entries,params){return new Class2({type:"enum",entries,...normalizeParams(params)})}function _literal(Class2,value,params){return new Class2({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class2,params){return new Class2({type:"file",...normalizeParams(params)})}function _transform(Class2,fn){return new Class2({type:"transform",transform:fn})}function _optional(Class2,innerType){return new Class2({type:"optional",innerType})}function _nullable(Class2,innerType){return new Class2({type:"nullable",innerType})}function _default(Class2,innerType,defaultValue){return new Class2({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class2,innerType,params){return new Class2({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class2,innerType){return new Class2({type:"success",innerType})}function _catch(Class2,innerType,catchValue){return new Class2({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:constantCatch(catchValue)})}function _pipe(Class2,in_,out){return new Class2({type:"pipe",in:in_,out})}function _readonly(Class2,innerType){return new Class2({type:"readonly",innerType})}function _templateLiteral(Class2,parts,params){return new Class2({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class2,getter){return new Class2({type:"lazy",getter})}function _promise(Class2,innerType){return new Class2({type:"promise",innerType})}function _custom(Class2,fn,_params){let norm=normalizeParams(_params);return norm.abort??(norm.abort=!0),new Class2({type:"custom",check:"custom",fn,...norm})}function _refine(Class2,fn,_params){return new Class2({type:"custom",check:"custom",fn,...normalizeParams(_params)})}function _superRefine(fn,params){let ch=_check(payload=>(payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(issue(issue2,payload.value,ch._zod.def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=ch),_issue.continue??(_issue.continue=!ch._zod.def.abort),payload.issues.push(issue(_issue))}},fn(payload.value,payload)),params);return ch}function _check(fn,params){let ch=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch._zod.check=fn,ch}function describe(description){let ch=new $ZodCheck({check:"describe"});return ch._zod.onattach=[inst=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}],ch._zod.check=()=>{},ch}function meta(metadata){let ch=new $ZodCheck({check:"meta"});return ch._zod.onattach=[inst=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}],ch._zod.check=()=>{},ch}function _stringbool(Classes,_params){let params=normalizeParams(_params),truthyArray=params.truthy??["true","1","yes","on","y","enabled"],falsyArray=params.falsy??["false","0","no","off","n","disabled"];params.case!=="sensitive"&&(truthyArray=truthyArray.map(v=>typeof v=="string"?v.toLowerCase():v),falsyArray=falsyArray.map(v=>typeof v=="string"?v.toLowerCase():v));let truthySet=new Set(truthyArray),falsySet=new Set(falsyArray),_Codec=Classes.Codec??$ZodCodec,_Boolean=Classes.Boolean??$ZodBoolean,_String=Classes.String??$ZodString,stringSchema=new _String({type:"string",error:params.error}),booleanSchema=new _Boolean({type:"boolean",error:params.error}),codec2=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:((input2,payload)=>{let data=input2;return params.case!=="sensitive"&&(data=data.toLowerCase()),truthySet.has(data)?!0:falsySet.has(data)?!1:(payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec2,continue:!1}),{})}),reverseTransform:((input2,_payload)=>input2===!0?truthyArray[0]||"true":falsyArray[0]||"false"),error:params.error});return codec2._zod.bag.truthy=truthyArray,codec2._zod.bag.falsy=falsyArray,codec2._zod.bag.case=params.case??"insensitive",codec2}function _stringFormat(Class2,format3,fnOrRegex,_params={}){let params=normalizeParams(_params),def={check:"string_format",type:"string",format:format3,fn:typeof fnOrRegex=="function"?fnOrRegex:val=>fnOrRegex.test(val),...params};return fnOrRegex instanceof RegExp&&(def.pattern=fnOrRegex),new Class2(def)}var TimePrecision,init_api=__esm({"node_modules/zod/v4/core/api.js"(){"use strict";init_checks();init_registries();init_schemas();init_util();TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}}});function assignProps(target,...sources){for(let source of sources)for(let key3 of Reflect.ownKeys(source))Object.prototype.propertyIsEnumerable.call(source,key3)&&assignProp(target,key3,source[key3]);return target}function initializeContext(params){let target=params?.target??"draft-2020-12";return target==="draft-4"&&(target="draft-04"),target==="draft-7"&&(target="draft-07"),{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??void 0}}function handleUnrepresentable(schema,ctx,json2,params,message){let result=typeof ctx.unrepresentable=="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return!1;if(result===void 0||result==="throw")throw new Error(message);return Object.assign(json2,result),!0}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a3;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen)return seen.count++,_params.schemaPath.includes(schema)&&(seen.cycle=_params.path),seen.schema;let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result),ctx.sharedDefsExtractedFor=void 0,ctx.sharedEmitDoneFor=void 0;let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;parent&&(result.ref||(result.ref=parent),processSchema(parent,ctx,params),ctx.seen.get(parent).isParent=!0)}let meta3=ctx.metadataRegistry.get(schema);return meta3&&assignProps(result.schema,meta3),ctx.io==="input"&&isTransforming(schema)&&(delete result.schema.examples,delete result.schema.default),ctx.io==="input"&&"_prefault"in result.schema&&((_a3=result.schema).default??(_a3.default=result.schema._prefault)),delete result.schema._prefault,ctx.seen.get(schema).schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){let root2=ctx.seen.get(schema);if(!root2)throw new Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id2=ctx.metadataRegistry.get(entry[0])?.id;if(id2){let existing=idToSchema.get(id2);if(existing&&existing!==entry[0])throw new Error(`Duplicate schema id "${id2}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id2,entry[0])}}let makeURI=entry=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??(id3=>id3);if(externalId)return{ref:uriGenerator(externalId)};let id2=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id2,{defId:id2,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id2)}`}}let uriPrefix="#",defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root2&&!entry[1].schema.id)return{ref:uriPrefix};let defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}},extractToDef=entry=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);seen.def={...seen.schema},defId&&(seen.defId=defId);let schema2=seen.schema;for(let key3 in schema2)delete schema2[key3];schema2.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
|
|
2167
2167
|
|
|
2168
2168
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}seen.count>1&&ctx.reused==="ref"&&extractToDef(entry)}ctx.external&&(ctx.sharedDefsExtractedFor=ctx.external)}function compactTypeUnion(schema){let options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==void 0)return;let types2=[];for(let option of options){if(!option||typeof option!="object")return;compactTypeUnion(option);let keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;let type2=option.type;for(let member of Array.isArray(type2)?type2:[type2]){if(typeof member!="string")return;types2.includes(member)||types2.push(member)}}delete schema.anyOf,schema.type=types2.length===1?types2[0]:types2}function undeclaredConstraint(member){let extra=member.additionalProperties;return extra===void 0||extra===!1||typeof extra!="object"||extra===null?null:Object.keys(extra).length?extra:null}function foldObjects(members2){let objects=[];for(let member of members2){if(typeof member!="object"||member.type!=="object")return null;for(let key3 in member)if(!FOLDABLE_KEYS.has(key3))return null;objects.push(member)}let properties={},required2=new Set;for(let object2 of objects){for(let key3 in object2.properties){if(Object.prototype.hasOwnProperty.call(properties,key3))continue;let parts=[];for(let other of objects){let part=other.properties?.[key3]??undeclaredConstraint(other);part!=null&&(parts.some(seen=>JSON.stringify(seen)===JSON.stringify(part))||parts.push(part))}let merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key3,merged)}for(let key3 of object2.required??[])required2.add(key3)}let folded={type:"object",properties};if(required2.size&&(folded.required=[...required2]),objects.every(object2=>object2.additionalProperties===!1))folded.additionalProperties=!1;else{let constraints=[];for(let object2 of objects){let constraint=undeclaredConstraint(object2);constraint&&!constraints.some(seen=>JSON.stringify(seen)===JSON.stringify(constraint))&&constraints.push(constraint)}constraints.length===1?folded.additionalProperties=constraints[0]:constraints.length>1&&(folded.additionalProperties={allOf:constraints})}return folded}function foldIntersection(json2){let allOf=json2.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(let key3 of FOLDABLE_KEYS)if(key3 in json2)return;let unions=allOf.filter(m=>UNION_KEYS.some(k=>Array.isArray(m[k]))),folded=null;if(!unions.length)folded=foldObjects(allOf);else{let union2=unions[0],keyword=UNION_KEYS.find(k=>Array.isArray(union2[k]));if(Object.keys(union2).length!==1)return;let rest=allOf.filter(m=>m!==union2),branches=union2[keyword].map(branch=>foldObjects([...rest,branch]));if(branches.some(b=>!b))return;folded={[keyword]:branches}}folded&&(delete json2.allOf,assignProps(json2,folded))}function finalize(ctx,schema){let root2=ctx.seen.get(schema);if(!root2)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema)):assignProps(schema2,refSchema),assignProps(schema2,_cached),zodSchema._zod.parent===ref)for(let key3 in schema2)key3==="$ref"||key3==="allOf"||key3 in _cached||delete schema2[key3];if(refSchema.$ref&&refSeen.def)for(let key3 in schema2)key3==="$ref"||key3==="allOf"||key3 in refSeen.def&&JSON.stringify(schema2[key3])===JSON.stringify(refSeen.def[key3])&&delete schema2[key3]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema2.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key3 in schema2)key3==="$ref"||key3==="allOf"||key3 in parentSeen.def&&JSON.stringify(schema2[key3])===JSON.stringify(parentSeen.def[key3])&&delete schema2[key3]}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);if(ctx.target!=="openapi-3.0")for(let entry of ctx.seen.entries())compactTypeUnion(entry[1].def??entry[1].schema);for(let rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){let carriers=new Map;for(let seen of ctx.seen.values())for(let json2 of[seen.schema,seen.def]){let allOf=json2?.allOf;if(!Array.isArray(allOf))continue;let existing=carriers.get(allOf);existing?existing.push(json2):carriers.set(allOf,[json2])}for(let allOf of ctx.intersections)for(let json2 of carriers.get(allOf)??[])foldIntersection(json2)}}let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id2=ctx.external.registry.get(schema)?.id;if(!id2)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id2)}assignProps(result,root2.defId?root2.schema:root2.def??root2.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external)for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,assignProp(defs,seen.defId,seen.def))}ctx.external&&(ctx.sharedEmitDoneFor=ctx.external),ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key3 in def.shape)if(isTransforming(def.shape[key3],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var FOLDABLE_KEYS,UNION_KEYS,createToJSONSchemaMethod,createStandardJSONSchemaMethod,init_to_json_schema=__esm({"node_modules/zod/v4/core/to-json-schema.js"(){"use strict";init_registries();init_util();FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]),UNION_KEYS=["oneOf","anyOf"];createToJSONSchemaMethod=(schema,processors={})=>params=>{let ctx=initializeContext({...params,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)}}});function aggregateChecks(schema){let agg={},def=schema._zod.def,list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(let ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);let bag=schema._zod.bag;bag.minimum!==void 0&&narrowMin(agg,"minimum",bag.minimum),bag.exclusiveMinimum!==void 0&&narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum),bag.maximum!==void 0&&narrowMax(agg,"maximum",bag.maximum),bag.exclusiveMaximum!==void 0&&narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum),bag.multipleOf!==void 0&&addDivisor(agg,bag.multipleOf),bag.format!==void 0&&(agg.format??(agg.format=bag.format),bag.format.includes("int")&&(agg.isInt=!0)),bag.mime&&intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}function inputOptin(schema){let def=schema._zod.def;return def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")?inputOptin(def.out):def.type==="catch"?inputOptin(def.innerType):schema._zod.optin}function stringifyKeyNames(bySchema,json2,visited){if(json2.$ref){if(visited.has(json2))return json2;visited.add(json2);let def=bySchema.get(json2)?.def;if(!def)return json2;let inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json2:inlined}for(let keyword of["anyOf","oneOf"]){let branches=json2[keyword];if(!Array.isArray(branches))continue;let mapped=branches.map(branch=>stringifyKeyNames(bySchema,branch,visited));mapped.some((branch,i)=>branch!==branches[i])&&(json2={...json2,[keyword]:mapped})}let types2=Array.isArray(json2.type)?json2.type:[json2.type],numericType=!types2.includes("string")&&types2.some(t=>t==="number"||t==="integer"),values=json2.enum??(json2.const!==void 0?[json2.const]:void 0);if(!numericType&&!values?.some(v=>typeof v=="number"))return json2;let{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format:format3,id:id2,...rest}=json2;return rest.enum?rest.enum=rest.enum.map(v=>typeof v=="number"?String(v):v):typeof rest.const=="number"&&(rest.const=String(rest.const)),numericType&&(rest.type="string",values||(rest.pattern=(types2.includes("number")?number:integer).source)),rest}function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())entry.def&&!bySchema.has(entry.schema)&&bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record2 of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record2),names2=(seen?.def??seen?.schema)?.propertyNames;if(!names2||names2===!0||rewrites.has(names2))continue;let rewritten=stringifyKeyNames(bySchema,names2,new Set);rewritten!==names2&&rewrites.set(names2,rewritten)}if(rewrites.size)for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);rewritten&&(carrier.propertyNames=rewritten)}}function serializeDefaultValue(value,schema,ctx,json2,params){let unrepresentable=!1,serialized=JSON.stringify(value,(_,val)=>typeof val!="bigint"?val:(unrepresentable=!0,null));return unrepresentable?(handleUnrepresentable(schema,ctx,json2,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT):JSON.parse(serialized)}function toJSONSchema(input2,params){if("_idmap"in input2){let registry4=input2,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry4._idmap.entries()){let[_,schema]=entry;processSchema(schema,ctx2)}let schemas={},external={registry:registry4,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry4._idmap.entries()){let[key3,schema]=entry;extractDefs(ctx2,schema),assignProp(schemas,key3,finalize(ctx2,schema))}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return processSchema(input2,ctx),extractDefs(ctx,input2),finalize(ctx,input2)}var narrowMin,narrowMax,narrowBoth,addDivisor,addPattern,intersectMime,setFormat,minContributor,maxContributor,formatContributor,contributors,formatMap,exactPatterns,exactPattern,stringProcessor,numberProcessor,booleanProcessor,bigintProcessor,symbolProcessor,nullProcessor,undefinedProcessor,voidProcessor,neverProcessor,anyProcessor,unknownProcessor,dateProcessor,enumProcessor,literalProcessor,nanProcessor,templateLiteralProcessor,fileProcessor,successProcessor,customProcessor,functionProcessor,transformProcessor,mapProcessor,setProcessor,arrayProcessor,objectProcessor,unionProcessor,intersectionProcessor,tupleProcessor,pendingRecords,recordProcessor,nullableProcessor,nonoptionalProcessor,UNREPRESENTABLE_DEFAULT,defaultProcessor,prefaultProcessor,catchProcessor,pipeProcessor,readonlyProcessor,promiseProcessor,optionalProcessor,lazyProcessor,allProcessors,init_json_schema_processors=__esm({"node_modules/zod/v4/core/json-schema-processors.js"(){"use strict";init_regexes();init_schemas();init_to_json_schema();init_util();narrowMin=(agg,key3,value)=>{(agg[key3]===void 0||value>agg[key3])&&(agg[key3]=value)},narrowMax=(agg,key3,value)=>{(agg[key3]===void 0||value<agg[key3])&&(agg[key3]=value)},narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value),narrowMax(agg,"maximum",value)},addDivisor=(agg,value)=>{agg.multipleOf??(agg.multipleOf=[]),agg.multipleOf.includes(value)||agg.multipleOf.push(value)},addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set),agg.patterns.add(pattern)},intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter(m=>mime.includes(m)):[...mime]},setFormat=(agg,format3)=>{agg.format=format3,format3.includes("int")&&(agg.isInt=!0)},minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum),maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum),formatContributor=ranges=>(agg,def)=>{setFormat(agg,def.format);let[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum),narrowMax(agg,"maximum",maximum)},contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format),def.pattern&&addPattern(agg,def.pattern),(def.format==="base64"||def.format==="base64url")&&(agg.contentEncoding=def.format),(def.local||def.precision===-1)&&(agg.laxFormat=!0)},mime_type:(agg,def)=>intersectMime(agg,def.mime)};formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]),exactPattern=p=>exactPatterns.get(p)??p,stringProcessor=(schema,ctx,_json,_params)=>{let json2=_json;json2.type="string";let{minimum,maximum,format:format3,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum=="number"&&(json2.minLength=minimum),typeof maximum=="number"&&(json2.maxLength=maximum),format3&&(json2.format=formatMap[format3]??format3,json2.format===""&&delete json2.format,(format3==="time"||laxFormat)&&delete json2.format),contentEncoding&&(json2.contentEncoding=contentEncoding),patterns&&patterns.size>0){let patternList=[...patterns].map(exactPattern);patternList.length===1?json2.pattern=patternList[0].source:patternList.length>1&&(json2.allOf=[...patternList.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema,ctx,_json,params)=>{let json2=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json2.type=isInt?"integer":"number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin?legacy?(json2.minimum=exclusiveMinimum,json2.exclusiveMinimum=!0):json2.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json2.minimum=minimum),exMax?legacy?(json2.maximum=exclusiveMaximum,json2.exclusiveMaximum=!0):json2.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json2.maximum=maximum),multipleOf){let divisors=new Set;for(let divisor of multipleOf)Number.isFinite(divisor)&&divisor!==0?divisors.add(Math.abs(divisor)):handleUnrepresentable(schema,ctx,json2,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);let[first,...rest]=divisors;first!==void 0&&(json2.multipleOf=first),rest.length&&(json2.allOf=[...json2.allOf??[],...rest.map(m=>({multipleOf:m}))])}},booleanProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},bigintProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"BigInt cannot be represented in JSON Schema")},symbolProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json2,_params)=>{ctx.target==="openapi-3.0"?(json2.type="string",json2.nullable=!0,json2.enum=[null]):json2.type="null"},undefinedProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Undefined cannot be represented in JSON Schema")},voidProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json2,_params)=>{json2.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json2,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);if(values.length===0){json2.not={};return}values.every(v=>typeof v=="number")&&(json2.type="number"),values.every(v=>typeof v=="string")&&(json2.type="string"),json2.enum=values},literalProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;if(def.values.length===0){json2.not={};return}let vals=[];for(let val of def.values)if(val===void 0){if(handleUnrepresentable(schema,ctx,json2,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val=="bigint"){if(handleUnrepresentable(schema,ctx,json2,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json2.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json2.enum=[val]:json2.const=val}else vals.every(v=>typeof v=="number")&&(json2.type="number"),vals.every(v=>typeof v=="string")&&(json2.type="string"),vals.every(v=>typeof v=="boolean")&&(json2.type="boolean"),vals.every(v=>v===null)&&(json2.type="null"),json2.enum=vals},nanProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json2,_params)=>{let _json=json2,pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json2,_params)=>{let _json=json2;_json.type="string",_json.format="binary",_json.contentEncoding="binary";let{minimum,maximum,mime}=aggregateChecks(schema);minimum!==void 0&&(_json.minLength=minimum),maximum!==void 0&&(_json.maxLength=maximum),mime&&(mime.length===0?_json.not={}:mime.length===1?_json.contentMediaType=mime[0]:_json.anyOf=mime.map(m=>({contentMediaType:m})))},successProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},customProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Custom types cannot be represented in JSON Schema")},functionProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Function types cannot be represented in JSON Schema")},transformProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Transforms cannot be represented in JSON Schema")},mapProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Map cannot be represented in JSON Schema")},setProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum),json2.type="array",json2.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};objectProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,shape2=def.shape;if(Object.getOwnPropertySymbols(shape2).length&&handleUnrepresentable(schema,ctx,json2,params,"Symbol keys cannot be represented in JSON Schema"))return;json2.type="object",json2.properties={};for(let key3 in shape2)assignProp(json2.properties,key3,processSchema(shape2[key3],ctx,{...params,path:[...params.path,"properties",key3]}));let requiredKeys=[];for(let key3 of Object.keys(shape2)){let field=def.shape[key3];(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)&&requiredKeys.push(key3)}requiredKeys.length>0&&(json2.required=requiredKeys),def.catchall?._zod.def.type==="never"?json2.additionalProperties=!1:def.catchall?def.catchall&&(json2.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json2.additionalProperties=!1)},unionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));isExclusive?json2.oneOf=options:json2.anyOf=options},intersectionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json2.allOf=allOf,ctx.intersections.push(allOf)},tupleProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"||ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null,minItems=def.items.length;for(;minItems>0;){let item=def.items[minItems-1];if(!(ctx.io==="input"?inputOptin(item)!==void 0:item._zod.optout==="optional"))break;minItems--}let maxItems=def.items.length,isClosed=!def.rest;ctx.target==="draft-2020-12"?(json2.prefixItems=prefixItems,isClosed?json2.items=!1:rest&&(json2.items=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):ctx.target==="openapi-3.0"?(json2.items={anyOf:prefixItems},rest&&json2.items.anyOf.push(rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):(json2.items=prefixItems,isClosed?json2.additionalItems=!1:rest&&(json2.additionalItems=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems));let{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum)};pendingRecords=new WeakMap;recordProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="object";let keyType=def.keyType,patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json2.patternProperties={};for(let pattern of patterns)assignProp(json2.patternProperties,exactPattern(pattern).source,valueSchema)}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json2.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending=pendingRecords.get(ctx);pending||(pending=[],pendingRecords.set(ctx,pending),ctx.deferred.push(()=>rewriteKeyNames(ctx))),pending.push(schema)}json2.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values,omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==void 0;if(keyValues&&!def.partial&&!omittableOnInput){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json2.required=validKeyValues.map(String))}},nullableProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json2.nullable=!0):json2.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();defaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value!==UNREPRESENTABLE_DEFAULT&&(json2.default=value)},prefaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io!=="input")return;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value!==UNREPRESENTABLE_DEFAULT&&(json2._prefault=value)},catchProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema,ctx,json2,params,"Dynamic catch values are not supported in JSON Schema");return}json2.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json2.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}}});var JSONSchemaGenerator,init_json_schema_generator=__esm({"node_modules/zod/v4/core/json-schema-generator.js"(){"use strict";init_json_schema_processors();init_to_json_schema();JSONSchemaGenerator=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";normalizedTarget==="draft-4"&&(normalizedTarget="draft-04"),normalizedTarget==="draft-7"&&(normalizedTarget="draft-07"),this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){_params&&(_params.cycles&&(this.ctx.cycles=_params.cycles),_params.reused&&(this.ctx.reused=_params.reused),_params.external&&(this.ctx.external=_params.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}}}});var json_schema_exports={};var init_json_schema=__esm({"node_modules/zod/v4/core/json-schema.js"(){"use strict"}});var core_exports2={};__export(core_exports2,{$ZodAny:()=>$ZodAny,$ZodArray:()=>$ZodArray,$ZodAsyncError:()=>$ZodAsyncError,$ZodBase64:()=>$ZodBase64,$ZodBase64URL:()=>$ZodBase64URL,$ZodBigInt:()=>$ZodBigInt,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBoolean:()=>$ZodBoolean,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCUID:()=>$ZodCUID,$ZodCUID2:()=>$ZodCUID2,$ZodCatch:()=>$ZodCatch,$ZodCheck:()=>$ZodCheck,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckProperties:()=>$ZodCheckProperties,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCodec:()=>$ZodCodec,$ZodCreditCard:()=>$ZodCreditCard,$ZodCustom:()=>$ZodCustom,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodCyclicError:()=>$ZodCyclicError,$ZodDate:()=>$ZodDate,$ZodDefault:()=>$ZodDefault,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodE164:()=>$ZodE164,$ZodEmail:()=>$ZodEmail,$ZodEmoji:()=>$ZodEmoji,$ZodEncodeError:()=>$ZodEncodeError,$ZodEnum:()=>$ZodEnum,$ZodError:()=>$ZodError,$ZodExactOptional:()=>$ZodExactOptional,$ZodFile:()=>$ZodFile,$ZodFunction:()=>$ZodFunction,$ZodGUID:()=>$ZodGUID,$ZodIBAN:()=>$ZodIBAN,$ZodIPv4:()=>$ZodIPv4,$ZodIPv6:()=>$ZodIPv6,$ZodISODate:()=>$ZodISODate,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODuration:()=>$ZodISODuration,$ZodISOTime:()=>$ZodISOTime,$ZodIntersection:()=>$ZodIntersection,$ZodJWT:()=>$ZodJWT,$ZodKSUID:()=>$ZodKSUID,$ZodLazy:()=>$ZodLazy,$ZodLiteral:()=>$ZodLiteral,$ZodMAC:()=>$ZodMAC,$ZodMap:()=>$ZodMap,$ZodNaN:()=>$ZodNaN,$ZodNanoID:()=>$ZodNanoID,$ZodNever:()=>$ZodNever,$ZodNonOptional:()=>$ZodNonOptional,$ZodNull:()=>$ZodNull,$ZodNullable:()=>$ZodNullable,$ZodNumber:()=>$ZodNumber,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodObject:()=>$ZodObject,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodOptional:()=>$ZodOptional,$ZodPipe:()=>$ZodPipe,$ZodPrefault:()=>$ZodPrefault,$ZodPreprocess:()=>$ZodPreprocess,$ZodPromise:()=>$ZodPromise,$ZodReadonly:()=>$ZodReadonly,$ZodRealError:()=>$ZodRealError,$ZodRecord:()=>$ZodRecord,$ZodRegistry:()=>$ZodRegistry,$ZodSet:()=>$ZodSet,$ZodString:()=>$ZodString,$ZodStringFormat:()=>$ZodStringFormat,$ZodSuccess:()=>$ZodSuccess,$ZodSymbol:()=>$ZodSymbol,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodTransform:()=>$ZodTransform,$ZodTuple:()=>$ZodTuple,$ZodType:()=>$ZodType,$ZodULID:()=>$ZodULID,$ZodURL:()=>$ZodURL,$ZodUUID:()=>$ZodUUID,$ZodUndefined:()=>$ZodUndefined,$ZodUnion:()=>$ZodUnion,$ZodUnknown:()=>$ZodUnknown,$ZodVoid:()=>$ZodVoid,$ZodXID:()=>$ZodXID,$ZodXor:()=>$ZodXor,$brand:()=>$brand,$constructor:()=>$constructor,$input:()=>$input,$output:()=>$output,Doc:()=>Doc,INVALID:()=>INVALID,JSONSchema:()=>json_schema_exports,JSONSchemaGenerator:()=>JSONSchemaGenerator,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,URL_BAD_FORMAT:()=>URL_BAD_FORMAT,URL_UNPARSEABLE:()=>URL_UNPARSEABLE,ZodCompileAsyncError:()=>ZodCompileAsyncError,ZodCompileUnsupportedError:()=>ZodCompileUnsupportedError,_any:()=>_any,_array:()=>_array,_base64:()=>_base64,_base64url:()=>_base64url,_bigint:()=>_bigint,_boolean:()=>_boolean,_catch:()=>_catch,_check:()=>_check,_cidrv4:()=>_cidrv4,_cidrv6:()=>_cidrv6,_coercedBigint:()=>_coercedBigint,_coercedBoolean:()=>_coercedBoolean,_coercedDate:()=>_coercedDate,_coercedNumber:()=>_coercedNumber,_coercedString:()=>_coercedString,_creditCard:()=>_creditCard,_cuid:()=>_cuid,_cuid2:()=>_cuid2,_custom:()=>_custom,_date:()=>_date,_decode:()=>_decode,_decodeAsync:()=>_decodeAsync,_default:()=>_default,_discriminatedUnion:()=>_discriminatedUnion,_e164:()=>_e164,_email:()=>_email,_emoji:()=>_emoji2,_encode:()=>_encode,_encodeAsync:()=>_encodeAsync,_endsWith:()=>_endsWith,_enum:()=>_enum,_file:()=>_file,_float32:()=>_float32,_float64:()=>_float64,_gt:()=>_gt,_gte:()=>_gte,_guid:()=>_guid,_iban:()=>_iban,_includes:()=>_includes,_int:()=>_int,_int32:()=>_int32,_int64:()=>_int64,_intersection:()=>_intersection,_ipv4:()=>_ipv4,_ipv6:()=>_ipv6,_isoDate:()=>_isoDate,_isoDateTime:()=>_isoDateTime,_isoDuration:()=>_isoDuration,_isoTime:()=>_isoTime,_jwt:()=>_jwt,_ksuid:()=>_ksuid,_lazy:()=>_lazy,_length:()=>_length,_literal:()=>_literal,_lowercase:()=>_lowercase,_lt:()=>_lt,_lte:()=>_lte,_mac:()=>_mac,_map:()=>_map,_max:()=>_lte,_maxLength:()=>_maxLength,_maxSize:()=>_maxSize,_mime:()=>_mime,_min:()=>_gte,_minLength:()=>_minLength,_minSize:()=>_minSize,_multipleOf:()=>_multipleOf,_nan:()=>_nan,_nanoid:()=>_nanoid,_nativeEnum:()=>_nativeEnum,_negative:()=>_negative,_never:()=>_never,_nonnegative:()=>_nonnegative,_nonoptional:()=>_nonoptional,_nonpositive:()=>_nonpositive,_normalize:()=>_normalize,_null:()=>_null2,_nullable:()=>_nullable,_number:()=>_number,_optional:()=>_optional,_overwrite:()=>_overwrite,_parse:()=>_parse,_parseAsync:()=>_parseAsync,_pipe:()=>_pipe,_positive:()=>_positive,_promise:()=>_promise,_properties:()=>_properties,_property:()=>_property,_readonly:()=>_readonly,_record:()=>_record,_refine:()=>_refine,_regex:()=>_regex,_safeDecode:()=>_safeDecode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeEncode:()=>_safeEncode,_safeEncodeAsync:()=>_safeEncodeAsync,_safeParse:()=>_safeParse,_safeParseAsync:()=>_safeParseAsync,_set:()=>_set,_size:()=>_size,_slugify:()=>_slugify,_startsWith:()=>_startsWith,_string:()=>_string,_stringFormat:()=>_stringFormat,_stringbool:()=>_stringbool,_success:()=>_success,_superRefine:()=>_superRefine,_symbol:()=>_symbol,_templateLiteral:()=>_templateLiteral,_toLowerCase:()=>_toLowerCase,_toUpperCase:()=>_toUpperCase,_transform:()=>_transform,_trim:()=>_trim,_tuple:()=>_tuple,_uint32:()=>_uint32,_uint64:()=>_uint64,_ulid:()=>_ulid,_undefined:()=>_undefined2,_union:()=>_union,_unknown:()=>_unknown,_uppercase:()=>_uppercase,_url:()=>_url,_uuid:()=>_uuid,_uuidv4:()=>_uuidv4,_uuidv6:()=>_uuidv6,_uuidv7:()=>_uuidv7,_void:()=>_void,_xid:()=>_xid,_xor:()=>_xor,base64Charset:()=>base64Charset,base64urlCharset:()=>base64urlCharset,canParseURL:()=>canParseURL,clone:()=>clone,compile:()=>compile,compileFn:()=>compileFn,config:()=>config,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,decode:()=>decode3,decodeAsync:()=>decodeAsync,describe:()=>describe,encode:()=>encode5,encodeAsync:()=>encodeAsync,extractDefs:()=>extractDefs,finalize:()=>finalize,flattenError:()=>flattenError,formatError:()=>formatError,getDiscriminatedOption:()=>getDiscriminatedOption,globalConfig:()=>globalConfig,globalRegistry:()=>globalRegistry,handleUnrepresentable:()=>handleUnrepresentable,initializeContext:()=>initializeContext,isBackEdge:()=>isBackEdge,isRecursiveSchema:()=>isRecursiveSchema,isValidBase64:()=>isValidBase64,isValidBase64URL:()=>isValidBase64URL,isValidCIDRv6:()=>isValidCIDRv6,isValidCreditCard:()=>isValidCreditCard,isValidIBAN:()=>isValidIBAN,isValidIPv6:()=>isValidIPv6,isValidJWT:()=>isValidJWT,locales:()=>locales_exports,memoizer:()=>memoizer,mergeValues:()=>mergeValues,meta:()=>meta,parse:()=>parse3,parseAsync:()=>parseAsync,parseURLObject:()=>parseURLObject,prettifyError:()=>prettifyError,process:()=>processSchema,processSchema:()=>processSchema,regexes:()=>regexes_exports,registry:()=>registry,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,standardProps:()=>standardProps,stripTabAndNewline:()=>stripTabAndNewline,toDotPath:()=>toDotPath,toJSONSchema:()=>toJSONSchema,toZod:()=>toZod,treeifyError:()=>treeifyError,urlHostnameOk:()=>urlHostnameOk,urlProtocolOk:()=>urlProtocolOk,util:()=>util_exports,validate:()=>validate10,validateAsync:()=>validateAsync,validateURL:()=>validateURL,version:()=>version4,withParser:()=>withParser});var init_core2=__esm({"node_modules/zod/v4/core/index.js"(){"use strict";init_core();init_parse();init_errors6();init_schemas();init_memoizer();init_checks();init_versions();init_util();init_util();init_regexes();init_locales();init_registries();init_doc();init_compile();init_api();init_to_json_schema();init_json_schema_processors();init_json_schema_generator();init_json_schema()}});var checks_exports2={};__export(checks_exports2,{endsWith:()=>_endsWith,gt:()=>_gt,gte:()=>_gte,includes:()=>_includes,length:()=>_length,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,maxLength:()=>_maxLength,maxSize:()=>_maxSize,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,negative:()=>_negative,nonnegative:()=>_nonnegative,nonpositive:()=>_nonpositive,normalize:()=>_normalize,overwrite:()=>_overwrite,positive:()=>_positive,properties:()=>_properties,property:()=>_property,regex:()=>_regex,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,trim:()=>_trim,uppercase:()=>_uppercase});var init_checks2=__esm({"node_modules/zod/v4/classic/checks.js"(){"use strict";init_core2()}});function _lazyMethod(proto,key3,make){Object.defineProperty(proto,key3,{configurable:!0,enumerable:!1,get(){let value=make(this);return Object.defineProperty(this,key3,{value,configurable:!0,writable:!0}),value},set(value){Object.defineProperty(this,key3,{value,configurable:!0,writable:!0})}})}var _installedErrorProtos,initializer2,ZodError,ZodRealError,init_errors7=__esm({"node_modules/zod/v4/classic/errors.js"(){"use strict";init_core2();init_core2();init_util();_installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let proto=Object.getPrototypeOf(inst);_installedErrorProtos.has(proto)||(_installedErrorProtos.add(proto),_lazyMethod(proto,"format",self2=>mapper=>formatError(self2,mapper)),_lazyMethod(proto,"flatten",self2=>mapper=>flattenError(self2,mapper)),_lazyMethod(proto,"addIssue",self2=>issue2=>{self2.issues.push(issue2),self2.message=JSON.stringify(self2.issues,jsonStringifyReplacer,2)}),_lazyMethod(proto,"addIssues",self2=>issues2=>{self2.issues.push(...issues2),self2.message=JSON.stringify(self2.issues,jsonStringifyReplacer,2)}),Object.defineProperty(proto,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error})}});var parse4,parseAsync2,safeParse2,safeParseAsync2,encode6,decode4,encodeAsync2,decodeAsync2,safeEncode2,safeDecode2,safeEncodeAsync2,safeDecodeAsync2,init_parse2=__esm({"node_modules/zod/v4/classic/parse.js"(){"use strict";init_core2();init_errors7();init_core2();parse4=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode6=_encode(ZodRealError),decode4=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError)}});var schemas_exports2={};__export(schemas_exports2,{ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,codec:()=>codec,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom2,date:()=>date2,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,float32:()=>float32,float64:()=>float64,function:()=>_function,guid:()=>guid2,hash:()=>hash5,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,literal:()=>literal,looseObject:()=>looseObject,looseRecord:()=>looseRecord,mac:()=>mac2,map:()=>map,meta:()=>meta2,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,never:()=>never,nonoptional:()=>nonoptional,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,partialRecord:()=>partialRecord,pipe:()=>pipe,prefault:()=>prefault,preprocess:()=>preprocess,promise:()=>promise,readonly:()=>readonly,record:()=>record,refine:()=>refine,set:()=>set,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,transform:()=>transform,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,url:()=>url,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});function _ensureDefaultLocale(){globalConfig.localeError||config(en_default())}function _ensureDefaultMemoizer(){globalConfig.memoizer||config({memoizer:memoizer()})}function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function guid2(params){return _guid(ZodGUID,params)}function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...util_exports.normalizeParams(params)})}function emoji2(params){return _emoji2(ZodEmoji,params)}function nanoid2(params){return _nanoid(ZodNanoID,params)}function cuid3(params){return _cuid(ZodCUID,params)}function cuid22(params){return _cuid2(ZodCUID2,params)}function ulid2(params){return _ulid(ZodULID,params)}function xid2(params){return _xid(ZodXID,params)}function ksuid2(params){return _ksuid(ZodKSUID,params)}function ipv42(params){return _ipv4(ZodIPv4,params)}function mac2(params){return _mac(ZodMAC,params)}function ipv62(params){return _ipv6(ZodIPv6,params)}function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}function base642(params){return _base64(ZodBase64,params)}function base64url2(params){return _base64url(ZodBase64URL,params)}function e1642(params){return _e164(ZodE164,params)}function creditCard2(params){return _creditCard(ZodCreditCard,params)}function iban2(params){return _iban(ZodIBAN,params)}function jwt(params){return _jwt(ZodJWT,params)}function stringFormat(format3,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format3,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash5(alg,params){let enc=params?.enc??"hex",format3=`${alg}_${enc}`,regex=regexes_exports[format3];if(!regex)throw new Error(`Unrecognized hash format: ${format3}`);return _stringFormat(ZodCustomStringFormat,format3,regex,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function bigint2(params){return _bigint(ZodBigInt,params)}function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}function symbol(params){return _symbol(ZodSymbol,params)}function _undefined3(params){return _undefined2(ZodUndefined,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function _void2(params){return _void(ZodVoid,params)}function date2(params){return _date(ZodDate,params)}function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape2=schema._zod.def.shape;return _enum2(Object.keys(shape2))}function object(shape2,params){let def={type:"object",shape:shape2??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape2,params){return new ZodObject({type:"object",shape:shape2,catchall:never(),...util_exports.normalizeParams(params)})}function looseObject(shape2,params){return new ZodObject({type:"object",shape:shape2,catchall:unknown(),...util_exports.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...util_exports.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest,rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...util_exports.normalizeParams(params)})}function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params),partial:!0})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...util_exports.normalizeParams(params)})}function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...util_exports.normalizeParams(params)})}function set(valueType,params){return new ZodSet({type:"set",valueType,...util_exports.normalizeParams(params)})}function _enum2(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...util_exports.normalizeParams(params)})}function file(params){return _file(ZodFile,params)}function transform(fn){return new ZodTransform({type:"transform",transform:fn})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}function success(innerType){return new ZodSuccess({type:"success",innerType})}function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:util_exports.constantCatch(catchValue)})}function nan(params){return _nan(ZodNaN,params)}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){let def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...util_exports.normalizeParams(params)})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function promise(innerType){return new ZodPromise({type:"promise",innerType})}function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}function check(fn){let ch=new $ZodCheck({check:"custom"});return ch._zod.check=fn,ch}function custom2(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function _instanceof(cls,params={}){let inst=new ZodInstanceOf({type:"custom",check:"custom",fn:data=>data instanceof cls,abort:!0,...util_exports.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=payload=>{payload.value instanceof cls||payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}function json(params){let jsonSchema=lazy(()=>union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)]));return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodType,_ZodString,ZodString,ZodStringFormat,ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodMAC,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodCreditCard,ZodIBAN,ZodJWT,ZodCustomStringFormat,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodBigIntFormat,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodDate,ZodArray,ZodObject,ZodUnion,ZodXor,ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodEnum,ZodLiteral,ZodFile,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodSuccess,ZodCatch,ZodNaN,ZodPipe,ZodCodec,ZodPreprocess,ZodReadonly,ZodTemplateLiteral,ZodLazy,ZodPromise,ZodFunction,ZodCustom,describe2,meta2,ZodInstanceOf,stringbool,init_schemas2=__esm({"node_modules/zod/v4/classic/schemas.js"(){"use strict";init_core2();init_core2();init_json_schema_processors();init_regexes();init_to_json_schema();init_en();init_checks2();init_parse2();ZodType=$constructor("ZodType",(inst,def)=>(_ensureDefaultLocale(),$ZodType.init(inst,def),inst.def=def,inst.type=def.type,inst),{check(...chks){let def=this.def;return this.clone(util_exports.mergeDefs(def,{checks:[...def.checks??[],...chks.map(ch=>typeof ch=="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta3){return reg.add(this,meta3),this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get"~standard"(){return util_exports.hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set"~standard"(value){util_exports.own(this,"~standard",value)},parse:function _parse2(data,params){return parse4(this,data,params,{callee:_parse2})},parseAsync:async function _parseAsync2(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync2})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){util_exports.own(this,"spa",value)},validate(data,params){return validate10(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode2(data,params){return encode6(this,data,params,{callee:_encode2})},decode:function _decode2(data,params){return decode4(this,data,params,{callee:_decode2})},encodeAsync:async function _encodeAsync2(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync2})},decodeAsync:async function _decodeAsync2(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync2})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},util_exports.derived({format:inst=>aggregateChecks(inst).format??null,minLength:inst=>aggregateChecks(inst).minimum??null,maxLength:inst=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def),ZodStringFormat.init(inst,def)});ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def),ZodStringFormat.init(inst,def)});ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params),inst.isFinite=!0},util_exports.derived({minValue:inst=>{let{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:inst=>{let{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:inst=>{let{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:inst=>aggregateChecks(inst).format??null},{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}}));ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},util_exports.derived({minValue:inst=>aggregateChecks(inst).minimum??null,maxValue:inst=>aggregateChecks(inst).maximum??null,format:inst=>aggregateChecks(inst).format??null},{gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},gt(value,params){return this.check(_gt(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value,params){return this.check(_multipleOf(value,params))}}));ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params))},util_exports.derived({minDate:inst=>{let{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:inst=>{let{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer(),$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params),inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params),util_exports.installLazyProp(inst,"shape",self2=>self2._zod.def.shape,!1)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},exactPartial(...args){return util_exports.partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){let def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map(item=>new ZodOptional({type:"optional",innerType:item}))})}});ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer(),$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer(),$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer(),$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params),inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params),inst.enum=def.entries,inst.options=[...inst._zod.values];let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params),inst.min=(size4,params)=>inst.check(_minSize(size4,params)),inst.max=(size4,params)=>inst.check(_maxSize(size4,params)),inst.mime=(types2,params)=>inst.check(_mime(Array.isArray(types2)?types2:[types2],params))});ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output2=def.transform(payload.value,payload);return output2 instanceof Promise?output2.then(output3=>(payload.value=output3,payload)):(payload.value=output2,payload)}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params),inst.in=def.in,inst.out=def.out});ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.getter()});ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});describe2=describe,meta2=meta,ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape2,params){return this.check(_properties(shape2,params))}});stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args)}});function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodIssueCode,ZodFirstPartyTypeKind,init_compat2=__esm({"node_modules/zod/v4/classic/compat.js"(){"use strict";init_core2();ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={})}});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date3,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var init_iso=__esm({"node_modules/zod/v4/classic/iso.js"(){"use strict";init_core2();init_schemas2();init_schemas2()}});function detectVersion(schema,defaultTarget){let $schema=schema.$schema;return $schema==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":$schema==="http://json-schema.org/draft-07/schema#"?"draft-7":$schema==="http://json-schema.org/draft-04/schema#"?"draft-4":defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index2)=>index2<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let path8=ref.slice(1).split("/").filter(Boolean);if(path8.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path8[0]===defsKey){let key3=path8[1]===void 0?void 0:decodeJSONPointerSegment(path8[1]);if(!key3||!ctx.defs[key3])throw new Error(`Reference not found: ${ref}`);return ctx.defs[key3]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){return z.transform(value=>value).check(payload=>{let value=payload.value;if(typeof value!="object"||value===null||Array.isArray(value))return;let keys=Object.getOwnPropertyNames(value);if(guards.minProperties!==void 0&&keys.length<guards.minProperties&&payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:!0,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value,inst:objectSchema,continue:!0}),guards.maxProperties!==void 0&&keys.length>guards.maxProperties&&payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value,inst:objectSchema,continue:!0}),guards.keySchema)for(let key3 of keys){let result=guards.keySchema.safeParse(key3);result.success||payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key3,path:[key3],continue:!0})}}).pipe(objectSchema)}function canonicalKey(value,seen){if(value===null)return"z";let type2=typeof value;if(type2!=="object"){if(type2==="number"&&Number.isNaN(value))return null;let raw=String(value);return`${type2[0]}${raw.length}:${raw}`}if(seen.has(value))return null;seen.add(value);try{if(Array.isArray(value)){let parts2=[];for(let item of value){let key3=canonicalKey(item,seen);if(key3===null)return null;parts2.push(key3)}return`a${parts2.length}:[${parts2.join(",")}]`}let keys=Object.keys(value).sort(),parts=[];for(let k of keys){let key3=canonicalKey(value[k],seen);if(key3===null)return null;parts.push(`${k.length}:${k}=${key3}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value)}}function containsRef(value){return typeof value!="object"||value===null?!1:Array.isArray(value)?value.some(containsRef):typeof value.$ref=="string"?!0:Object.entries(value).some(([key3,sub])=>SCHEMA_KEYWORDS.has(key3)?containsRef(sub):!SCHEMA_MAP_KEYWORDS.has(key3)||typeof sub!="object"||sub===null?!1:Object.values(sub).some(containsRef))}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){return z.transform(value=>value).check(payload=>{let items=payload.value;if(Array.isArray(items)){if(guards.uniqueItems===!0){let firstSeen=new Map;for(let i=0;i<items.length;i++){let key3=canonicalKey(items[i],new Set);if(key3===null)continue;let first=firstSeen.get(key3);if(first===void 0){firstSeen.set(key3,i);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${first}`,input:items,path:[i],continue:!0})}}if(guards.containsSchema){let minContains=guards.minContains??1,ceiling=guards.maxContains!==void 0?guards.maxContains+1:Number.POSITIVE_INFINITY,matches=0;for(let item of items)if(guards.containsSchema.safeParse(item).success&&++matches>=ceiling)break;matches<minContains&&payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,input:items,continue:!0}),guards.maxContains!==void 0&&matches>guards.maxContains&&payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:!0})}}}).pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema!==!1)return restSchema===void 0||restSchema===!0?z.any():convertSchema(restSchema,ctx)}function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not=="object"&&Object.keys(schema.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw new Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every(v=>typeof v=="string"))return z.enum(enumValues);let literalSchemas=enumValues.map(v=>z.literal(v));return literalSchemas.length<2?literalSchemas[0]:z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type2=schema.type;if(Array.isArray(type2)){let typeSchemas=type2.map(t=>{let typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});return typeSchemas.length===0?z.never():typeSchemas.length===1?typeSchemas[0]:z.union(typeSchemas)}if(!type2)return z.any();let zodSchema;switch(type2){case"string":{let stringSchema=z.string();if(schema.format){let format3=schema.format;format3==="email"?stringSchema=stringSchema.check(z.email()):format3==="uri"||format3==="uri-reference"?stringSchema=stringSchema.check(z.url()):format3==="uuid"||format3==="guid"?stringSchema=stringSchema.check(z.uuid()):format3==="date-time"?stringSchema=stringSchema.check(z.iso.datetime({offset:!0})):format3==="date"?stringSchema=stringSchema.check(z.iso.date()):format3==="time"?stringSchema=stringSchema.check(z.regex(fullTime)):format3==="duration"?stringSchema=stringSchema.check(z.iso.duration()):format3==="hostname"?stringSchema=stringSchema.check(z.hostname()):format3==="ipv4"?stringSchema=stringSchema.check(z.ipv4()):format3==="ipv6"?stringSchema=stringSchema.check(z.ipv6()):format3==="mac"?stringSchema=stringSchema.check(z.mac()):format3==="cidr"?stringSchema=stringSchema.check(z.cidrv4()):format3==="cidr-v6"?stringSchema=stringSchema.check(z.cidrv6()):format3==="base64"?stringSchema=stringSchema.check(z.base64()):format3==="base64url"?stringSchema=stringSchema.check(z.base64url()):format3==="e164"?stringSchema=stringSchema.check(z.e164()):format3==="credit_card"?stringSchema=stringSchema.check(z.creditCard()):format3==="iban"?stringSchema=stringSchema.check(z.iban()):format3==="jwt"?stringSchema=stringSchema.check(z.jwt()):format3==="emoji"?stringSchema=stringSchema.check(z.emoji()):format3==="nanoid"?stringSchema=stringSchema.check(z.nanoid()):format3==="cuid"?stringSchema=stringSchema.check(z.cuid()):format3==="cuid2"?stringSchema=stringSchema.check(z.cuid2()):format3==="ulid"?stringSchema=stringSchema.check(z.ulid()):format3==="xid"?stringSchema=stringSchema.check(z.xid()):format3==="ksuid"&&(stringSchema=stringSchema.check(z.ksuid()))}typeof schema.minLength=="number"&&(stringSchema=stringSchema.min(schema.minLength)),typeof schema.maxLength=="number"&&(stringSchema=stringSchema.max(schema.maxLength)),schema.pattern&&(stringSchema=stringSchema.regex(new RegExp(schema.pattern))),zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type2==="integer"?z.number().int():z.number();typeof schema.minimum=="number"&&schema.exclusiveMinimum!==!0&&(numberSchema=numberSchema.min(schema.minimum)),typeof schema.maximum=="number"&&schema.exclusiveMaximum!==!0&&(numberSchema=numberSchema.max(schema.maximum)),typeof schema.exclusiveMinimum=="number"?numberSchema=numberSchema.gt(schema.exclusiveMinimum):schema.exclusiveMinimum===!0&&typeof schema.minimum=="number"&&(numberSchema=numberSchema.gt(schema.minimum)),typeof schema.exclusiveMaximum=="number"?numberSchema=numberSchema.lt(schema.exclusiveMaximum):schema.exclusiveMaximum===!0&&typeof schema.maximum=="number"&&(numberSchema=numberSchema.lt(schema.maximum)),typeof schema.multipleOf=="number"&&(numberSchema=numberSchema.multipleOf(schema.multipleOf)),zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape2={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]),additionalSchema=typeof schema.additionalProperties=="object"?convertSchema(schema.additionalProperties,ctx):void 0;for(let[key3,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);assignProp(shape2,key3,requiredSet.has(key3)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape2).length>0&&schemasToIntersect.push(z.object(shape2).passthrough()),schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++)result=z.intersection(result,schemasToIntersect[i]);zodSchema=result}if(schema.additionalProperties===!1){let propertyKeys=Object.keys(shape2),patterns=patternKeys.map(p=>new RegExp(p)),basePatternSchema=zodSchema;zodSchema=zodSchema.check(payload=>{if(!isPlainObject2(payload.value))return;let unrecognized=[];for(let key3 of Object.keys(payload.value))propertyKeys.includes(key3)||patterns.some(regex=>regex.test(key3))||unrecognized.push(key3);unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})})}}else{let objectSchema=z.object(shape2);schema.additionalProperties===!1?zodSchema=objectSchema.strict():additionalSchema?zodSchema=objectSchema.catchall(additionalSchema):zodSchema=objectSchema.passthrough()}let hasKeyGuard=schema.propertyNames!==void 0&&schema.propertyNames!==!0,minProperties=typeof schema.minProperties=="number"?schema.minProperties:void 0,maxProperties=typeof schema.maxProperties=="number"?schema.maxProperties:void 0;if(hasKeyGuard||minProperties!==void 0||maxProperties!==void 0){let keySchema;if(hasKeyGuard){let keyJSONSchema=typeof schema.propertyNames=="object"&&schema.propertyNames.type===void 0?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{let prefixItems=schema.prefixItems,items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=prefixItems.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=Array.isArray(items)?void 0:getTupleRest(items,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(Array.isArray(items)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=items.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=getTupleRest(schema.additionalItems,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);typeof schema.minItems=="number"&&(arraySchema=arraySchema.min(schema.minItems)),typeof schema.maxItems=="number"&&(arraySchema=arraySchema.max(schema.maxItems)),zodSchema=arraySchema}else zodSchema=z.array(z.any());(schema.uniqueItems===!0||schema.contains!==void 0)&&(zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===!0,containsSchema:schema.contains!==void 0?convertSchema(schema.contains,ctx):void 0,minContains:typeof schema.minContains=="number"?schema.minContains:void 0,maxContains:typeof schema.maxContains=="number"?schema.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${type2}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema=="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map(s3=>convertSchema(s3,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map(s3=>convertSchema(s3,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++)result=z.intersection(result,convertSchema(schema.allOf[i],ctx));baseSchema=result}schema.nullable===!0&&ctx.version==="openapi-3.0"&&(baseSchema=z.nullable(baseSchema)),schema.readOnly===!0&&(baseSchema=z.readonly(baseSchema)),schema.default!==void 0&&(baseSchema=baseSchema.default(schema.default));let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key3 of coreMetadataKeys)key3 in schema&&(extraMeta[key3]=schema[key3]);let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key3 of contentMetadataKeys)key3 in schema&&(extraMeta[key3]=schema[key3]);if(schema.type==="object"&&schema.$ref===void 0){schema.propertyNames!==void 0&&!containsRef(schema.propertyNames)&&(extraMeta.propertyNames=schema.propertyNames);for(let key3 of["minProperties","maxProperties"])schema[key3]!==void 0&&(extraMeta[key3]=schema[key3])}if(schema.type==="array"&&schema.$ref===void 0){schema.contains!==void 0&&!containsRef(schema.contains)&&(extraMeta.contains=schema.contains);for(let key3 of["uniqueItems","minContains","maxContains"])schema[key3]!==void 0&&(extraMeta[key3]=schema[key3])}for(let key3 of Object.keys(schema))RECOGNIZED_KEYS.has(key3)||assignProp(extraMeta,key3,schema[key3]);return Object.keys(extraMeta).length>0&&ctx.registry.add(baseSchema,extraMeta),schema.description&&(baseSchema=baseSchema.describe(schema.description)),baseSchema}function fromJSONSchema(schema,params){if(typeof schema=="boolean")return schema?z.any():z.never();let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let version31=detectVersion(normalized,params?.defaultTarget),defs=normalized.$defs||normalized.definitions||{},ctx={version:version31,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var z,RECOGNIZED_KEYS,SCHEMA_KEYWORDS,SCHEMA_MAP_KEYWORDS,fullTime,init_from_json_schema=__esm({"node_modules/zod/v4/classic/from-json-schema.js"(){"use strict";init_registries();init_util();init_checks2();init_iso();init_schemas2();z={...schemas_exports2,...checks_exports2,iso:iso_exports},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/}});function visit(schema,fnOrHandlers){let fn=typeof fnOrHandlers=="function"?fnOrHandlers:(node2,rewritten)=>{let h=fnOrHandlers[node2._zod.def.type];return h?h(node2,rewritten):node2},cache2=new Map;function run(s3){let cached2=cache2.get(s3);if(cached2===RESOLVING)return new $ZodLazy({type:"lazy",getter:()=>cache2.get(s3)});if(cached2!==void 0)return cached2;cache2.set(s3,RESOLVING);let inner=mapInner(s3),mapped=fn(inner,inner!==s3);return cache2.set(s3,mapped),mapped}function mapInner(s3){let def=s3._zod.def,kind=def.type;switch(kind){case"object":{let oldShape=def.shape,keys=Object.keys(oldShape),changed=!1,newShape={};for(let k of keys){let mapped=run(oldShape[k]);mapped!==oldShape[k]&&(changed=!0),newShape[k]=mapped}let newCatchall=def.catchall;return def.catchall&&(newCatchall=run(def.catchall),newCatchall!==def.catchall&&(changed=!0)),changed?clone(s3,{...def,shape:newShape,catchall:newCatchall}):s3}case"array":{let mapped=run(def.element);return mapped===def.element?s3:clone(s3,{...def,element:mapped})}case"tuple":{let oldItems=def.items,changed=!1,newItems=[];for(let item of oldItems){let mapped=run(item);mapped!==item&&(changed=!0),newItems.push(mapped)}let newRest=def.rest;return def.rest&&(newRest=run(def.rest),newRest!==def.rest&&(changed=!0)),changed?clone(s3,{...def,items:newItems,rest:newRest}):s3}case"record":case"map":{let newKey=run(def.keyType),newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s3:clone(s3,{...def,keyType:newKey,valueType:newVal})}case"set":{let newVal=run(def.valueType);return newVal===def.valueType?s3:clone(s3,{...def,valueType:newVal})}case"union":{let oldOptions=def.options,changed=!1,newOptions=[];for(let opt of oldOptions){let mapped=run(opt);mapped!==opt&&(changed=!0),newOptions.push(mapped)}return changed?clone(s3,{...def,options:newOptions}):s3}case"intersection":{let newLeft=run(def.left),newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s3:clone(s3,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let newInner=run(def.innerType);return newInner===def.innerType?s3:clone(s3,{...def,innerType:newInner})}case"pipe":{let newIn=run(def.in),newOut=run(def.out);return newIn===def.in&&newOut===def.out?s3:clone(s3,{...def,in:newIn,out:newOut})}case"function":{let newInput=run(def.input),newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s3:clone(s3,{...def,input:newInput,output:newOutput})}case"lazy":{let original=def.getter,{_cachedInner,...rest}=def;return clone(s3,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s3;default:return s3}}return run(schema)}var RESOLVING,init_visit=__esm({"node_modules/zod/v4/core/visit.js"(){"use strict";init_schemas();init_util();RESOLVING=Symbol("z.visit/resolving")}});function deepPartial(schema){return visit(schema,{object:s3=>s3.partial(),union:s3=>{let def=s3._zod.def;return def.discriminator===void 0?s3:union(def.options)}})}var init_deep_partial=__esm({"node_modules/zod/v4/classic/deep-partial.js"(){"use strict";init_visit();init_schemas2()}});function withChecks(side,checks){if(!checks?.length)return side;let def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:!0})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:s3=>inSide(s3._zod.def),default:(s3,rewritten)=>rewritten?optional(s3._zod.def.innerType):s3,catch:(s3,rewritten)=>rewritten?s3._zod.def.innerType:s3})}function output(schema){return visit(schema,{pipe:s3=>outSide(s3._zod.def),prefault:(s3,rewritten)=>rewritten?s3._zod.def.innerType:s3})}var init_in_out=__esm({"node_modules/zod/v4/classic/in-out.js"(){"use strict";init_util();init_visit();init_schemas2()}});var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm({"node_modules/zod/v4/classic/coerce.js"(){"use strict";init_core2();init_schemas2()}});var external_exports={};__export(external_exports,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,INVALID:()=>INVALID,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCompileAsyncError:()=>ZodCompileAsyncError,ZodCompileUnsupportedError:()=>ZodCompileUnsupportedError,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodError:()=>ZodError,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodIssueCode:()=>ZodIssueCode,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRealError:()=>ZodRealError,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>coerce_exports,compile:()=>compile,config:()=>config,core:()=>core_exports2,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom2,date:()=>date2,decode:()=>decode4,decodeAsync:()=>decodeAsync2,deepPartial:()=>deepPartial,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode6,encodeAsync:()=>encodeAsync2,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,fromJSONSchema:()=>fromJSONSchema,function:()=>_function,getDiscriminatedOption:()=>getDiscriminatedOption,getErrorMap:()=>getErrorMap,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash5,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,includes:()=>_includes,input:()=>input,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>iso_exports,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,length:()=>_length,literal:()=>literal,locales:()=>locales_exports,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,memoizer:()=>memoizer,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,output:()=>output,overwrite:()=>_overwrite,parse:()=>parse4,parseAsync:()=>parseAsync2,partialRecord:()=>partialRecord,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,preprocess:()=>preprocess,prettifyError:()=>prettifyError,promise:()=>promise,properties:()=>_properties,property:()=>_property,readonly:()=>readonly,record:()=>record,refine:()=>refine,regex:()=>_regex,regexes:()=>regexes_exports,registry:()=>registry,safeDecode:()=>safeDecode2,safeDecodeAsync:()=>safeDecodeAsync2,safeEncode:()=>safeEncode2,safeEncodeAsync:()=>safeEncodeAsync2,safeParse:()=>safeParse2,safeParseAsync:()=>safeParseAsync2,set:()=>set,setErrorMap:()=>setErrorMap,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,toZod:()=>toZod,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,uppercase:()=>_uppercase,url:()=>url,util:()=>util_exports,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,validate:()=>validate10,validateAsync:()=>validateAsync,void:()=>_void2,withParser:()=>withParser,xid:()=>xid2,xor:()=>xor});var init_external=__esm({"node_modules/zod/v4/classic/external.js"(){"use strict";init_core2();init_schemas2();init_checks2();init_errors7();init_parse2();init_compat2();init_core2();init_json_schema_processors();init_from_json_schema();init_deep_partial();init_in_out();init_locales();init_iso();init_iso();init_coerce()}});var init_zod=__esm({"node_modules/zod/index.js"(){"use strict";init_external();init_external()}});var NonEmptyString,Any,OptionalAny,NetworkSchemaV1,NetworkSchemaV2,NetworkSchema,PRINTABLE_ASCII_REGEX,ResourceInfoSchema,PaymentRequirementsV1Schema,maxPaymentAccepts,PaymentRequiredV1Schema,PaymentPayloadV1Schema,PaymentRequirementsV2Schema,PaymentRequiredV2Schema,PaymentPayloadV2Schema,PaymentRequirementsSchema,PaymentRequiredSchema,PaymentPayloadSchema,init_chunk_Z7WXFCST=__esm({"node_modules/@x402/core/dist/esm/chunk-Z7WXFCST.mjs"(){"use strict";init_zod();init_zod();NonEmptyString=external_exports.string().min(1),Any=external_exports.record(external_exports.string(),external_exports.unknown()),OptionalAny=external_exports.record(external_exports.string(),external_exports.unknown()).optional().nullable(),NetworkSchemaV1=NonEmptyString,NetworkSchemaV2=external_exports.string().regex(/^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$/,{message:"Network must be in CAIP-2 format (e.g., 'eip155:84532')"}),NetworkSchema=external_exports.union([NetworkSchemaV1,NetworkSchemaV2]),PRINTABLE_ASCII_REGEX=/^[\x20-\x7e]+$/,ResourceInfoSchema=external_exports.object({url:NonEmptyString,description:external_exports.string().nullish().transform(v=>v??void 0),mimeType:external_exports.string().nullish().transform(v=>v??void 0),serviceName:external_exports.string().min(1).max(32).regex(PRINTABLE_ASCII_REGEX).nullish().transform(v=>v??void 0),tags:external_exports.array(external_exports.string().min(1).max(32).regex(PRINTABLE_ASCII_REGEX)).max(5).nullish().transform(v=>v??void 0),iconUrl:external_exports.string().max(2048).nullish().transform(v=>v??void 0)}),PaymentRequirementsV1Schema=external_exports.object({scheme:NonEmptyString,network:NetworkSchemaV1,maxAmountRequired:NonEmptyString,resource:NonEmptyString,description:external_exports.string(),mimeType:external_exports.string().optional(),outputSchema:Any.optional().nullable(),payTo:NonEmptyString,maxTimeoutSeconds:external_exports.number().positive(),asset:NonEmptyString,extra:OptionalAny}),maxPaymentAccepts=1024,PaymentRequiredV1Schema=external_exports.object({x402Version:external_exports.literal(1),error:external_exports.string().optional(),accepts:external_exports.array(PaymentRequirementsV1Schema).min(1).max(maxPaymentAccepts)}),PaymentPayloadV1Schema=external_exports.object({x402Version:external_exports.literal(1),scheme:NonEmptyString,network:NetworkSchemaV1,payload:Any}),PaymentRequirementsV2Schema=external_exports.object({scheme:NonEmptyString,network:NetworkSchemaV2,amount:NonEmptyString,asset:NonEmptyString,payTo:NonEmptyString,maxTimeoutSeconds:external_exports.number().positive(),extra:OptionalAny}),PaymentRequiredV2Schema=external_exports.object({x402Version:external_exports.literal(2),error:external_exports.string().nullish().transform(v=>v??void 0),resource:ResourceInfoSchema,accepts:external_exports.array(PaymentRequirementsV2Schema).min(1).max(maxPaymentAccepts),extensions:OptionalAny}),PaymentPayloadV2Schema=external_exports.object({x402Version:external_exports.literal(2),resource:ResourceInfoSchema.nullish().transform(v=>v??void 0),accepted:PaymentRequirementsV2Schema,payload:Any,extensions:OptionalAny}),PaymentRequirementsSchema=external_exports.union([PaymentRequirementsV1Schema,PaymentRequirementsV2Schema]),PaymentRequiredSchema=external_exports.discriminatedUnion("x402Version",[PaymentRequiredV1Schema,PaymentRequiredV2Schema]),PaymentPayloadSchema=external_exports.discriminatedUnion("x402Version",[PaymentPayloadV1Schema,PaymentPayloadV2Schema])}});var x402Version,init_chunk_VE37GDG2=__esm({"node_modules/@x402/core/dist/esm/chunk-VE37GDG2.mjs"(){"use strict";x402Version=2}});var init_chunk_MA7F3CLI=__esm({"node_modules/@x402/core/dist/esm/chunk-MA7F3CLI.mjs"(){"use strict"}});function numberToDecimalString(n){let str=n.toString();if(!/[eE]/.test(str))return str;let[significand,exponentStr]=str.split(/[eE]/),exp=parseInt(exponentStr,10),negative=significand.startsWith("-"),abs=negative?significand.slice(1):significand,[intDigits,fracDigits=""]=abs.split("."),allDigits=intDigits+fracDigits,decimalPos=intDigits.length+exp,result;return decimalPos<=0?result="0."+"0".repeat(-decimalPos)+allDigits:decimalPos>=allDigits.length?result=allDigits+"0".repeat(decimalPos-allDigits.length):result=allDigits.slice(0,decimalPos)+"."+allDigits.slice(decimalPos),(negative?"-":"")+result}function parseMoneyString(money){let cleaned=money.replace(/^\$/,"").trim();if(!/^\d+(?:\.\d+)?$/.test(cleaned)||/[eE]/.test(cleaned))throw new Error(`Invalid money format: ${money}`);return cleaned}function parseMoney(money){if(typeof money=="number"){if(!Number.isFinite(money)||money<0)throw new Error(`Invalid money format: ${money}`);return{amount:numberToDecimalString(money)}}let match=money.trim().match(/^\$?\s*(-?\d+(?:\.\d+)?)(?:\s+([A-Za-z][A-Za-z0-9.]*))?$/);if(!match)throw new Error(`Invalid money format: ${money}`);let amount=parseMoneyString(match[1]),rawSymbol=match[2];return!rawSymbol||rawSymbol.toUpperCase()==="USD"?{amount}:{amount,symbol:rawSymbol.toUpperCase()}}function convertToTokenAmount(decimalAmount,decimals){if(/[eE]/.test(decimalAmount))throw new Error(`Invalid amount: ${decimalAmount} \u2014 use decimal notation, not scientific notation`);if(!/^-?\d+\.?\d*$/.test(decimalAmount))throw new Error(`Invalid amount: ${decimalAmount}`);let[intPart,decPart=""]=decimalAmount.split("."),paddedDec=decPart.padEnd(decimals,"0").slice(0,decimals);return(intPart+paddedDec).replace(/^0+/,"")||"0"}function safeBase64Encode(data){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let bytes=new TextEncoder().encode(data),binaryString=Array.from(bytes,byte=>String.fromCharCode(byte)).join("");return globalThis.btoa(binaryString)}return Buffer.from(data,"utf8").toString("base64")}function safeBase64Decode(data){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let binaryString=globalThis.atob(data),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return new TextDecoder("utf-8").decode(bytes)}return Buffer.from(data,"base64").toString("utf-8")}function deepEqual(obj1,obj2){let normalize4=obj=>{if(obj==null||typeof obj!="object")return JSON.stringify(obj);if(Array.isArray(obj))return JSON.stringify(obj.map(item=>typeof item=="object"&&item!==null?JSON.parse(normalize4(item)):item));let sorted={};return Object.keys(obj).sort().forEach(key3=>{let value=obj[key3];sorted[key3]=typeof value=="object"&&value!==null?JSON.parse(normalize4(value)):value}),JSON.stringify(sorted)};try{return normalize4(obj1)===normalize4(obj2)}catch{return JSON.stringify(obj1)===JSON.stringify(obj2)}}function toComparableArray(value){if(Array.isArray(value))return value;if(!(value==null||typeof value=="object"))return[value]}var escapeRegExp,networkPatternToRegExp,networkMatchesPattern,findSchemesByNetwork,findByNetworkAndScheme,Base64EncodedRegex,ADDITIVE_ARRAY_INFO_FIELDS,init_chunk_XW2CWVLZ=__esm({"node_modules/@x402/core/dist/esm/chunk-XW2CWVLZ.mjs"(){"use strict";escapeRegExp=value=>value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),networkPatternToRegExp=pattern=>{let source=escapeRegExp(pattern).replace(/\\\*/g,".*");return new RegExp(`^${source}$`)},networkMatchesPattern=(pattern,network)=>networkPatternToRegExp(pattern).test(network),findSchemesByNetwork=(map2,network)=>{let implementationsByScheme=map2.get(network);if(!implementationsByScheme){for(let[registeredNetworkPattern,implementations]of map2.entries())if(networkMatchesPattern(registeredNetworkPattern,network)){implementationsByScheme=implementations;break}}return implementationsByScheme},findByNetworkAndScheme=(map2,scheme,network)=>findSchemesByNetwork(map2,network)?.get(scheme),Base64EncodedRegex=/^[A-Za-z0-9+/]*={0,2}$/;ADDITIVE_ARRAY_INFO_FIELDS={"builder-code":new Set(["s"])}}});async function readLimitedText(response,limit){if(!response.body)return response.text();let reader=response.body.getReader(),chunks=[],total=0;for(;;){let{done,value}=await reader.read();if(done)break;if(total+=value.byteLength,total>limit)throw await reader.cancel(),new ResponseBodyTooLargeError2(limit);chunks.push(value)}let buffer2=new Uint8Array(total),offset=0;for(let chunk of chunks)buffer2.set(chunk,offset),offset+=chunk.byteLength;return new TextDecoder().decode(buffer2)}function encodePaymentSignatureHeader(paymentPayload){return safeBase64Encode(JSON.stringify(paymentPayload))}function decodePaymentRequiredHeader(paymentRequiredHeader){if(!Base64EncodedRegex.test(paymentRequiredHeader))throw new Error("Invalid payment required header");return requireDecodedJsonObject(JSON.parse(safeBase64Decode(paymentRequiredHeader)),"Payment required header")}function decodePaymentResponseHeader(paymentResponseHeader){if(!Base64EncodedRegex.test(paymentResponseHeader))throw new Error("Invalid payment response header");return requireDecodedJsonObject(JSON.parse(safeBase64Decode(paymentResponseHeader)),"Payment response header")}var MAX_CONTROL_PLANE_RESPONSE_BYTES,ResponseBodyTooLargeError2,verifyResponseSchema,settleResponseSchema,supportedKindSchema,supportedResponseSchema,x402HTTPClient,requireDecodedJsonObject,init_chunk_PVRH2E6N=__esm({"node_modules/@x402/core/dist/esm/chunk-PVRH2E6N.mjs"(){"use strict";init_chunk_Z7WXFCST();init_chunk_VE37GDG2();init_chunk_MA7F3CLI();init_chunk_XW2CWVLZ();MAX_CONTROL_PLANE_RESPONSE_BYTES=1<<20,ResponseBodyTooLargeError2=class extends Error{constructor(limit){super(`http response body too large: limit ${limit} bytes`),this.name="ResponseBodyTooLargeError"}};verifyResponseSchema=external_exports.object({isValid:external_exports.boolean(),invalidReason:external_exports.string().nullish().transform(v=>v??void 0),invalidMessage:external_exports.string().nullish().transform(v=>v??void 0),payer:external_exports.string().nullish().transform(v=>v??void 0),extensions:external_exports.record(external_exports.string(),external_exports.unknown()).nullish().transform(v=>v??void 0),extra:external_exports.record(external_exports.string(),external_exports.unknown()).nullish().transform(v=>v??void 0)}),settleResponseSchema=external_exports.object({success:external_exports.boolean(),errorReason:external_exports.string().nullish().transform(v=>v??void 0),errorMessage:external_exports.string().nullish().transform(v=>v??void 0),payer:external_exports.string().nullish().transform(v=>v??void 0),transaction:external_exports.string(),network:external_exports.custom(value=>typeof value=="string"),amount:external_exports.string().nullish().transform(v=>v??void 0),extensions:external_exports.record(external_exports.string(),external_exports.unknown()).nullish().transform(v=>v??void 0),extra:external_exports.record(external_exports.string(),external_exports.unknown()).nullish().transform(v=>v??void 0)}),supportedKindSchema=external_exports.object({x402Version:external_exports.number(),scheme:external_exports.string(),network:external_exports.custom(value=>typeof value=="string"),extra:external_exports.record(external_exports.string(),external_exports.unknown()).nullish().transform(v=>v??void 0)}),supportedResponseSchema=external_exports.object({kinds:external_exports.array(supportedKindSchema),extensions:external_exports.array(external_exports.string()).default([]),signers:external_exports.record(external_exports.string(),external_exports.array(external_exports.string())).default({})}),x402HTTPClient=class{constructor(client){this.client=client,this.paymentRequiredHooks=[]}onPaymentRequired(hook){return this.paymentRequiredHooks.push(hook),this}async handlePaymentRequired(paymentRequired,requestUrl2){for(let hook of this.getPaymentRequiredHooks(paymentRequired)){let result=await hook({paymentRequired,requestUrl:requestUrl2});if(result?.headers)return result.headers}return null}encodePaymentSignatureHeader(paymentPayload){switch(paymentPayload.x402Version){case 2:return{"PAYMENT-SIGNATURE":encodePaymentSignatureHeader(paymentPayload)};case 1:return{"X-PAYMENT":encodePaymentSignatureHeader(paymentPayload)};default:throw new Error(`Unsupported x402 version: ${paymentPayload.x402Version}`)}}getPaymentRequiredResponse(getHeader,body){let paymentRequired=getHeader("PAYMENT-REQUIRED");if(paymentRequired)return decodePaymentRequiredHeader(paymentRequired);if(body&&body instanceof Object&&"x402Version"in body&&body.x402Version===1)return body;throw new Error("Invalid payment required response")}getPaymentSettleResponse(getHeader){let paymentResponse=getHeader("PAYMENT-RESPONSE");if(paymentResponse)return decodePaymentResponseHeader(paymentResponse);let xPaymentResponse=getHeader("X-PAYMENT-RESPONSE");if(xPaymentResponse)return decodePaymentResponseHeader(xPaymentResponse);throw new Error("Payment response header not found")}async createPaymentPayload(paymentRequired){return this.client.createPaymentPayload(paymentRequired)}async processPaymentResult(paymentPayload,getHeader,status2){let settleResponse;try{settleResponse=this.getPaymentSettleResponse(getHeader)}catch{}if(paymentPayload.x402Version===1)return{recovered:!1,settleResponse};let paymentRequired;if(!settleResponse&&status2===402)try{paymentRequired=this.getPaymentRequiredResponse(getHeader)}catch{}let requirements=paymentPayload.accepted;if(!requirements)throw new Error("Invalid x402 v2 payment payload: missing `accepted`");let ctx={paymentPayload,requirements,...settleResponse?{settleResponse}:{},...paymentRequired?{paymentRequired}:{}};return{recovered:(await this.client.handlePaymentResponse(ctx))?.recovered===!0,settleResponse}}parsePaymentResult(args){let{status:status2,getHeader,body}=args,header;try{header=this.getPaymentSettleResponse(getHeader)}catch{if(status2===402)try{header=this.getPaymentRequiredResponse(getHeader,body)}catch{}}let paymentStatus="none";return header&&!("success"in header)&&(paymentStatus="payment_required"),header&&"success"in header&&(paymentStatus=header.success?"settled":"settle_failed"),{status:status2,paymentStatus,body,header}}async processResponse(response){let getHeader=name=>response.headers.get(name),body=(response.headers.get("content-type")??"").includes("application/json")?await response.json():await response.text();return this.parsePaymentResult({status:response.status,getHeader,body})}getPaymentRequiredHooks(paymentRequired){let hooks=[...this.paymentRequiredHooks],declaredExtensions=paymentRequired.extensions;if(!declaredExtensions)return hooks;for(let extension3 of this.client.getExtensions()){let hook=extension3.transportHooks?.http?.onPaymentRequired;!hook||!(extension3.key in declaredExtensions)||hooks.push(context=>hook(declaredExtensions[extension3.key],context))}return hooks}};requireDecodedJsonObject=(value,headerLabel)=>{if(typeof value!="object"||value===null||Array.isArray(value))throw new Error(`${headerLabel} must decode to a JSON object`);return value}}});var client_exports={};__export(client_exports,{DEFAULT_MAX_AMOUNT_PER_PAYMENT:()=>DEFAULT_MAX_AMOUNT_PER_PAYMENT,x402Client:()=>x402Client,x402HTTPClient:()=>x402HTTPClient});function isAtomicAmount(amount){return/^\d+$/.test(amount)}function findSpendControlAssetEntry(controls,requirement,defaultAsset){if(controls.allowedAssets!==!0)return controls.allowedAssets?.find(entry=>networkMatchesPattern(entry.network,requirement.network)?entry.asset.toLowerCase()===requirement.asset.toLowerCase()?!0:defaultAsset!=null&&defaultAsset.symbol.toLowerCase()===entry.asset.toLowerCase():!1)}function resolveAtomicSpendCap(controls,requirement,defaultAsset){if(controls===!1)return;let assetEntry=findSpendControlAssetEntry(controls,requirement,defaultAsset);if(assetEntry?.maxAmountPerPayment!=null){if(!isAtomicAmount(assetEntry.maxAmountPerPayment))throw new Error(`spendControls.allowedAssets[].maxAmountPerPayment must be an integer atomic amount, not a dollar value; got ${JSON.stringify(assetEntry.maxAmountPerPayment)}`);return assetEntry.maxAmountPerPayment}if(!defaultAsset||controls.maxAmountPerPayment===!1)return;let usdLimit=controls.maxAmountPerPayment??DEFAULT_MAX_AMOUNT_PER_PAYMENT;return convertToTokenAmount(parseMoney(usdLimit).amount,defaultAsset.decimals)}function mergeArraysUnique(client,server){let merged=[];for(let item of[...client,...server])merged.some(existing=>deepEqual(existing,item))||merged.push(item);return merged}var DEFAULT_MAX_AMOUNT_PER_PAYMENT,x402Client,init_client=__esm({"node_modules/@x402/core/dist/esm/client/index.mjs"(){"use strict";init_chunk_PVRH2E6N();init_chunk_Z7WXFCST();init_chunk_VE37GDG2();init_chunk_MA7F3CLI();init_chunk_XW2CWVLZ();DEFAULT_MAX_AMOUNT_PER_PAYMENT="$1";x402Client=class _x402Client{constructor(paymentRequirementsSelector){this.registeredClientSchemes=new Map,this.schemeClientHookAdapters=new Map,this.policies=[],this.registeredExtensions=new Map,this.spendControls={},this.beforePaymentCreationHooks=[],this.afterPaymentCreationHooks=[],this.onPaymentCreationFailureHooks=[],this.paymentResponseHooks=[],this.paymentRequirementsSelector=paymentRequirementsSelector||((x402Version2,accepts)=>accepts[0])}static fromConfig(config2){let client=new _x402Client(config2.paymentRequirementsSelector);return config2.schemes.forEach(scheme=>{scheme.x402Version===1?client.registerV1(scheme.network,scheme.client):client.register(scheme.network,scheme.client)}),config2.policies?.forEach(policy=>{client.registerPolicy(policy)}),config2.spendControls!==void 0&&client.setSpendControls(config2.spendControls),client}register(network,client){return this._registerScheme(x402Version,network,client)}registerV1(network,client){return this._registerScheme(1,network,client)}registerPolicy(policy){return this.policies.push(policy),this}setSpendControls(controls){return this.spendControls=controls,this}registerExtension(extension3){return this.registeredExtensions.set(extension3.key,extension3),this}getExtensions(){return Array.from(this.registeredExtensions.values())}onBeforePaymentCreation(hook){return this.beforePaymentCreationHooks.push(hook),this}onAfterPaymentCreation(hook){return this.afterPaymentCreationHooks.push(hook),this}onPaymentCreationFailure(hook){return this.onPaymentCreationFailureHooks.push(hook),this}onPaymentResponse(hook){return this.paymentResponseHooks.push(hook),this}async handlePaymentResponse(ctx){for(let hook of this.getLabeledHooks("onPaymentResponse",ctx.paymentPayload.x402Version,ctx.requirements,ctx.paymentRequired?.extensions??ctx.paymentPayload.extensions)){let result=await hook(ctx);if(result&&"recovered"in result&&result.recovered)return{recovered:!0}}}async createPaymentPayload(paymentRequired){let clientSchemesByNetwork=this.registeredClientSchemes.get(paymentRequired.x402Version);if(!clientSchemesByNetwork)throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);let requirements=this.selectPaymentRequirements(paymentRequired.x402Version,paymentRequired.accepts),context={paymentRequired,selectedRequirements:requirements};for(let hook of this.getLabeledHooks("beforePaymentCreation",paymentRequired.x402Version,requirements,paymentRequired.extensions)){let result=await hook(context);if(result&&"abort"in result&&result.abort)throw new Error(`Payment creation aborted: ${result.reason}`)}try{let schemeNetworkClient=findByNetworkAndScheme(clientSchemesByNetwork,requirements.scheme,requirements.network);if(!schemeNetworkClient)throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);let partialPayload=await schemeNetworkClient.createPaymentPayload(paymentRequired.x402Version,requirements,{extensions:paymentRequired.extensions,maxAmountPerPayment:resolveAtomicSpendCap(this.spendControls,requirements,schemeNetworkClient.findDefaultAsset?.(requirements.asset,requirements.network))}),paymentPayload;if(partialPayload.x402Version==1)paymentPayload=partialPayload;else{let mergedExtensions=this.mergeExtensions(paymentRequired.extensions,partialPayload.extensions);paymentPayload={x402Version:partialPayload.x402Version,payload:partialPayload.payload,extensions:mergedExtensions,resource:paymentRequired.resource,accepted:requirements}}paymentPayload=await this.enrichPaymentPayloadWithExtensions(paymentPayload,paymentRequired);let createdContext={...context,paymentPayload};for(let hook of this.getLabeledHooks("afterPaymentCreation",paymentRequired.x402Version,requirements,paymentRequired.extensions))await hook(createdContext);return paymentPayload}catch(error62){let failureContext={...context,error:error62};for(let hook of this.getLabeledHooks("onPaymentCreationFailure",paymentRequired.x402Version,requirements,paymentRequired.extensions)){let result=await hook(failureContext);if(result&&"recovered"in result&&result.recovered)return result.payload}throw error62}}mergeExtensions(serverExtensions,clientExtensions){if(!clientExtensions)return serverExtensions;if(!serverExtensions)return clientExtensions;let merged={...serverExtensions};for(let[key3,clientValue]of Object.entries(clientExtensions)){let serverValue=merged[key3];if(serverValue===null||typeof serverValue!="object"||Array.isArray(serverValue)||clientValue===null||typeof clientValue!="object"||Array.isArray(clientValue)){merged[key3]=clientValue;continue}let serverRecord=serverValue,clientRecord=clientValue,additiveFields=ADDITIVE_ARRAY_INFO_FIELDS[key3],extensionValue={...serverRecord},pending=[{target:extensionValue,source:clientRecord}];for(let item of pending)for(let[fieldKey,clientFieldValue]of Object.entries(item.source)){let serverFieldValue=item.target[fieldKey];if(serverFieldValue!==null&&typeof serverFieldValue=="object"&&!Array.isArray(serverFieldValue)&&clientFieldValue!==null&&typeof clientFieldValue=="object"&&!Array.isArray(clientFieldValue)){let nestedValue={...serverFieldValue};item.target[fieldKey]=nestedValue,pending.push({target:nestedValue,source:clientFieldValue});continue}if(additiveFields?.has(fieldKey)&&(Array.isArray(serverFieldValue)||Array.isArray(clientFieldValue))){let serverArray=toComparableArray(serverFieldValue),clientArray=toComparableArray(clientFieldValue);if(serverArray&&clientArray){item.target[fieldKey]=mergeArraysUnique(clientArray,serverArray);continue}}Object.prototype.hasOwnProperty.call(item.target,fieldKey)||(item.target[fieldKey]=clientFieldValue)}merged[key3]=extensionValue}return merged}async enrichPaymentPayloadWithExtensions(paymentPayload,paymentRequired){if(this.registeredExtensions.size===0)return paymentPayload;let enriched=paymentPayload;for(let[,extension3]of this.registeredExtensions)extension3.enrichPaymentPayload&&(enriched=await extension3.enrichPaymentPayload(enriched,paymentRequired));return{...enriched,extensions:this.mergeExtensions(paymentRequired.extensions,enriched.extensions)}}selectPaymentRequirements(x402Version2,paymentRequirements){let clientSchemesByNetwork=this.registeredClientSchemes.get(x402Version2);if(!clientSchemesByNetwork)throw new Error(`No client registered for x402 version: ${x402Version2}`);let supportedPaymentRequirements=paymentRequirements.filter(requirement=>{let clientSchemes=findSchemesByNetwork(clientSchemesByNetwork,requirement.network);return clientSchemes?clientSchemes.has(requirement.scheme):!1});if(supportedPaymentRequirements.length===0)throw new Error(`No network/scheme registered for x402 version: ${x402Version2} which comply with the payment requirements. ${JSON.stringify({x402Version:x402Version2,paymentRequirements,x402Versions:Array.from(this.registeredClientSchemes.keys()),networks:Array.from(clientSchemesByNetwork.keys()),schemes:Array.from(clientSchemesByNetwork.values()).map(schemes2=>Array.from(schemes2.keys())).flat()})}`);let recognizedFlowRequirements=supportedPaymentRequirements.filter(requirement=>{let flow=requirement.extra?.paymentFlow;return flow==null||flow==="authorization"||flow==="upfront"||flow==="escrow"});if(recognizedFlowRequirements.length===0)throw new Error(`No payment requirements with a recognized paymentFlow for x402 version: ${x402Version2}`);let filteredRequirements=this.applySpendControls(x402Version2,recognizedFlowRequirements,clientSchemesByNetwork);for(let policy of this.policies)if(filteredRequirements=policy(x402Version2,filteredRequirements),filteredRequirements.length===0)throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version2}`);let authorizationAccepts=filteredRequirements.filter(requirement=>requirement.extra?.paymentFlow==null||requirement.extra?.paymentFlow==="authorization");return authorizationAccepts.length>0&&(filteredRequirements=authorizationAccepts),this.paymentRequirementsSelector(x402Version2,filteredRequirements)}applySpendControls(x402Version2,requirements,clientSchemesByNetwork){let controls=this.spendControls;if(controls===!1)return requirements;let rawAmountOf=requirement=>x402Version2===1?requirement.maxAmountRequired:requirement.amount,schemeFor=requirement=>findByNetworkAndScheme(clientSchemesByNetwork,requirement.scheme,requirement.network),defaultAssetFor=requirement=>schemeFor(requirement)?.findDefaultAsset?.(requirement.asset,requirement.network),findAssetEntry=requirement=>findSpendControlAssetEntry(controls,requirement,defaultAssetFor(requirement)),filtered=controls.allowedAssets===!0?requirements:requirements.filter(requirement=>defaultAssetFor(requirement)!=null?!0:findAssetEntry(requirement)!=null);if(filtered.length===0)throw new Error("All payment requirements were rejected by spendControls: only default assets or entries in spendControls.allowedAssets are allowed. Add an allowedAssets entry for non-default tokens, set allowedAssets: true, or set spendControls: false.");let usdLimit=controls.maxAmountPerPayment===!1?!1:controls.maxAmountPerPayment??DEFAULT_MAX_AMOUNT_PER_PAYMENT,beforeAmountCaps=filtered,rejectedByAssetCap=!1,rejectedUsdSymbol;if(filtered=filtered.filter(requirement=>{let defaultAsset=defaultAssetFor(requirement),assetEntry=findSpendControlAssetEntry(controls,requirement,defaultAsset),cap=resolveAtomicSpendCap(controls,requirement,defaultAsset);if(cap===void 0)return!0;let rawAmount=rawAmountOf(requirement);if(!isAtomicAmount(rawAmount)){if(assetEntry?.maxAmountPerPayment!=null)return rejectedByAssetCap=!0,!1;if(usdLimit===!1)return!0;let valueScaled=BigInt(convertToTokenAmount(rawAmount,18)),capScaled=BigInt(convertToTokenAmount(parseMoney(usdLimit).amount,18)),ok2=valueScaled<=capScaled;return ok2||(rejectedUsdSymbol=defaultAsset?.symbol),ok2}let ok=BigInt(rawAmount)<=BigInt(cap);return ok||(assetEntry?.maxAmountPerPayment!=null?rejectedByAssetCap=!0:rejectedUsdSymbol=defaultAsset?.symbol),ok}),filtered.length===0)throw rejectedByAssetCap&&beforeAmountCaps.every(requirement=>findAssetEntry(requirement)?.maxAmountPerPayment!=null)?new Error("All payment requirements were rejected by spendControls.allowedAssets maxAmountPerPayment. Raise the per-asset cap, or omit maxAmountPerPayment to allow uncapped (default assets then fall back to the top-level USD cap)."):new Error(`All payment requirements were rejected by spendControls.maxAmountPerPayment (${String(usdLimit)}${rejectedUsdSymbol?`, including ${rejectedUsdSymbol}`:""}). Raise maxAmountPerPayment, set it to false to disable, set allowedAssets[].maxAmountPerPayment for a per-asset atomic cap, or set spendControls: false to disable all spend controls.`);return filtered}_registerScheme(x402Version2,network,client){this.registeredClientSchemes.has(x402Version2)||this.registeredClientSchemes.set(x402Version2,new Map);let clientSchemesByNetwork=this.registeredClientSchemes.get(x402Version2);clientSchemesByNetwork.has(network)||clientSchemesByNetwork.set(network,new Map),clientSchemesByNetwork.get(network).set(client.scheme,client),this.schemeClientHookAdapters.has(x402Version2)||this.schemeClientHookAdapters.set(x402Version2,new Map);let adaptersByNetwork=this.schemeClientHookAdapters.get(x402Version2);adaptersByNetwork.has(network)||adaptersByNetwork.set(network,new Map);let adaptersByScheme=adaptersByNetwork.get(network),hooks=client.schemeHooks;if(!hooks)return adaptersByScheme.delete(client.scheme),this;let handles2={};return hooks.onBeforePaymentCreation&&(handles2.beforePaymentCreation=hooks.onBeforePaymentCreation),hooks.onAfterPaymentCreation&&(handles2.afterPaymentCreation=hooks.onAfterPaymentCreation),hooks.onPaymentCreationFailure&&(handles2.onPaymentCreationFailure=hooks.onPaymentCreationFailure),hooks.onPaymentResponse&&(handles2.onPaymentResponse=hooks.onPaymentResponse),Object.keys(handles2).length>0?adaptersByScheme.set(client.scheme,handles2):adaptersByScheme.delete(client.scheme),this}getLabeledHooks(phase,x402Version2,requirements,declaredExtensions){let manual;switch(phase){case"beforePaymentCreation":manual=this.beforePaymentCreationHooks;break;case"afterPaymentCreation":manual=this.afterPaymentCreationHooks;break;case"onPaymentCreationFailure":manual=this.onPaymentCreationFailureHooks;break;case"onPaymentResponse":manual=this.paymentResponseHooks;break}let out=[...manual],adaptersByNetwork=this.schemeClientHookAdapters.get(x402Version2),hook=(adaptersByNetwork?findByNetworkAndScheme(adaptersByNetwork,requirements.scheme,requirements.network):void 0)?.[phase];if(hook!==void 0&&out.push(hook),!declaredExtensions)return out;let extensionHookKey=this.getClientExtensionHookKey(phase);for(let[extensionKey,extension3]of this.registeredExtensions){if(!(extensionKey in declaredExtensions))continue;let extensionHook=extension3.hooks?.[extensionHookKey];extensionHook&&out.push((async ctx=>extensionHook(declaredExtensions[extensionKey],ctx)))}return out}getClientExtensionHookKey(phase){switch(phase){case"beforePaymentCreation":return"onBeforePaymentCreation";case"afterPaymentCreation":return"onAfterPaymentCreation";case"onPaymentCreationFailure":return"onPaymentCreationFailure";case"onPaymentResponse":return"onPaymentResponse"}}}}});var init_http4=__esm({"node_modules/@x402/core/dist/esm/http/index.mjs"(){"use strict";init_chunk_PVRH2E6N();init_chunk_Z7WXFCST();init_chunk_VE37GDG2();init_chunk_MA7F3CLI();init_chunk_XW2CWVLZ()}});async function capReturnedPaymentRequired(response){if(response.status!==402)return response;let body=await readLimitedText(response,MAX_CONTROL_PLANE_RESPONSE_BYTES);return new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers})}function wrapFetchWithPayment(fetch2,client){let httpClient=client instanceof x402HTTPClient?client:new x402HTTPClient(client);return async(input2,init2)=>{let request2=new Request(input2,init2),clonedRequest=request2.clone(),response=await fetch2(request2);if(response.status!==402)return response;let responseText=await readLimitedText(response,MAX_CONTROL_PLANE_RESPONSE_BYTES),paymentRequired;try{let getHeader=name=>response.headers.get(name),body;try{responseText&&(body=JSON.parse(responseText))}catch{}paymentRequired=httpClient.getPaymentRequiredResponse(getHeader,body)}catch(error62){throw new Error(`Failed to parse payment requirements: ${error62 instanceof Error?error62.message:"Unknown error"}`)}let requestUrl2=response.url||request2.url,hookHeaders=await httpClient.handlePaymentRequired(paymentRequired,requestUrl2);if(hookHeaders){let hookRequest=clonedRequest.clone();for(let[key3,value]of Object.entries(hookHeaders))hookRequest.headers.set(key3,value);let hookResponse=await fetch2(hookRequest);if(hookResponse.status!==402)return hookResponse;await readLimitedText(hookResponse,MAX_CONTROL_PLANE_RESPONSE_BYTES)}let paymentPayload;try{paymentPayload=await client.createPaymentPayload(paymentRequired)}catch(error62){throw new Error(`Failed to create payment payload: ${error62 instanceof Error?error62.message:"Unknown error"}`)}let paymentHeaders=httpClient.encodePaymentSignatureHeader(paymentPayload);if(clonedRequest.headers.has("PAYMENT-SIGNATURE")||clonedRequest.headers.has("X-PAYMENT"))throw new Error("Payment already attempted");for(let[key3,value]of Object.entries(paymentHeaders))clonedRequest.headers.set(key3,value);clonedRequest.headers.set("Access-Control-Expose-Headers","PAYMENT-RESPONSE,X-PAYMENT-RESPONSE");let secondResponse=await fetch2(clonedRequest.clone());if((await httpClient.processPaymentResult(paymentPayload,name=>secondResponse.headers.get(name),secondResponse.status)).recovered){secondResponse.status===402&&await readLimitedText(secondResponse,MAX_CONTROL_PLANE_RESPONSE_BYTES);let freshPayload=await client.createPaymentPayload(paymentRequired),retryHeaders=httpClient.encodePaymentSignatureHeader(freshPayload),retryRequest=clonedRequest;for(let[k,v]of Object.entries(retryHeaders))retryRequest.headers.set(k,v);retryRequest.headers.set("Access-Control-Expose-Headers","PAYMENT-RESPONSE,X-PAYMENT-RESPONSE");let retryResponse=await fetch2(retryRequest);return await httpClient.processPaymentResult(freshPayload,name=>retryResponse.headers.get(name),retryResponse.status),capReturnedPaymentRequired(retryResponse)}return capReturnedPaymentRequired(secondResponse)}}var init_esm5=__esm({"node_modules/@x402/fetch/dist/esm/index.mjs"(){"use strict";init_client();init_http4();init_client();init_http4()}});function resolveMaxTokens(parsed,fallback2=4096){let usable=v=>typeof v=="number"&&Number.isFinite(v)&&v>0?v:void 0,candidates=[usable(parsed.max_tokens),usable(parsed.max_completion_tokens)].filter(n=>n!==void 0);return candidates.length>0?Math.max(...candidates):fallback2}var init_max_tokens=__esm({"src/max-tokens.ts"(){"use strict"}});function isPaymentChain(value){return typeof value=="string"&&PAYMENT_CHAINS.includes(value)}var PAYMENT_CHAINS,PAYMENT_CHAIN_LABELS,PAYMENT_CHAIN_GATEWAYS,CAIP2_ARC,init_payment_chain=__esm({"src/payment-chain.ts"(){"use strict";PAYMENT_CHAINS=["base","solana","arc"];PAYMENT_CHAIN_LABELS={base:"Base",solana:"Solana",arc:"Arc"},PAYMENT_CHAIN_GATEWAYS={base:"https://blockrun.ai/api",solana:"https://sol.blockrun.ai/api",arc:"https://arc.blockrun.ai/api"},CAIP2_ARC="eip155:5042"}});import*as fs from"fs";import*as path from"path";import{homedir as homedir2}from"os";import{randomUUID}from"crypto";function normalizePayee(value){return EVM_ADDRESS.test(value)?value.toLowerCase():value}function isAddressList(list){return ADDRESS_LISTS.includes(list)}function normalizePolicyValues(list,values){return isAddressList(list)?values.map(normalizePayee):[...values]}function isValidPolicyValues(values){return Array.isArray(values)&&values.every(v=>typeof v=="string"&&v.length>0)}function isPolicyList(value){return POLICY_LISTS.includes(value)}function cloneLimits(limits){let clone2={...limits};for(let key3 of POLICY_LISTS){let val=limits[key3];val!==void 0&&(clone2[key3]=[...val])}return clone2}function mergeSpendHistory(a,b){let merged=[],ids=new Set,legacyKept=new Map;for(let ledger2 of[a,b]){let legacySeen=new Map;for(let r2 of ledger2){if(r2.id!==void 0){ids.has(r2.id)||(ids.add(r2.id),merged.push(r2));continue}let key3=`${r2.timestamp}|${r2.amount}|${r2.model??""}|${r2.action??""}`,nth=(legacySeen.get(key3)??0)+1;legacySeen.set(key3,nth),nth>(legacyKept.get(key3)??0)&&(legacyKept.set(key3,nth),merged.push(r2))}}return merged.sort((x,y)=>x.timestamp-y.timestamp)}function canonicalLimits(limits){return JSON.stringify(Object.fromEntries(Object.entries(limits).sort(([a],[b])=>a<b?-1:1)))}function getSharedSpendControl(){let host=sharedControlHost();return host.__clawrouterSharedSpendControl??=new SpendControl,host.__clawrouterSharedSpendControl}function parseQuotedAmountMicros(selected){let raw=selected.amount??selected.maxAmountRequired;if(!(typeof raw!="string"||!CANONICAL_AMOUNT.test(raw)))return BigInt(raw)}function parseQuotedAmountUsd(selected){let raw=selected.amount??selected.maxAmountRequired;if(typeof raw!="string"||!CANONICAL_AMOUNT.test(raw))return;let micros=Number(raw);if(Number.isSafeInteger(micros))return micros/1e6}function assertSpendPolicyAllows(control,selected){let quoted=parseQuotedAmountUsd(selected);if(quoted===void 0&&control.hasAmountLimits())throw new SpendPolicyError(`Payment quote carries no usable amount (${JSON.stringify(selected.amount??selected.maxAmountRequired)}); refusing to sign against a configured spend limit`);let estimatedCost3=quoted??0,result=control.check(estimatedCost3,{payTo:selected.payTo,network:selected.network,asset:selected.asset});if(!result.allowed)throw new SpendPolicyError(result.reason??"blocked by spend policy",{blockedBy:result.blockedBy,blockedByPolicy:result.blockedByPolicy});if(control.hasAggregateLimits())return control.reserve(estimatedCost3)}function registerSpendPolicyHook(x402,control){let reservations=new WeakMap;x402.onBeforePaymentCreation(async ctx=>{let selected=ctx.selectedRequirements,reservationId=assertSpendPolicyAllows(control,selected);reservationId!==void 0&&reservations.set(ctx.selectedRequirements,reservationId)}),x402.onAfterPaymentCreation(async ctx=>{let key3=ctx.selectedRequirements,id2=reservations.get(key3);id2!==void 0&&(reservations.delete(key3),control.settleReservation(id2,{action:"x402 payment"}))}),x402.onPaymentCreationFailure(async ctx=>{let key3=ctx.selectedRequirements,id2=reservations.get(key3);id2!==void 0&&(reservations.delete(key3),control.releaseReservation(id2))})}function settledChargeUsd(response){let raw=response.headers.get("x-blockrun-cost-usd");if(raw===null)return;let trimmed=raw.trim();if(trimmed==="")return;let value=Number(trimmed);return Number.isFinite(value)&&value>=0?value:void 0}function withSpendPolicy(inner,control,consumeEstimateUsd){return async(input2,init2)=>{let published=consumeEstimateUsd();if(published===void 0||!control.hasAmountLimits())return inner(input2,init2);let estimate=Number.isFinite(published)&&published>0?published:0,result=control.checkAmount(estimate);if(!result.allowed)throw new SpendPolicyError(result.reason??"blocked by spend policy",{blockedBy:result.blockedBy});let reservationId=control.hasAggregateLimits()?control.reserve(estimate):void 0,response;try{response=await inner(input2,init2)}catch(err){throw reservationId!==void 0&&control.releaseReservation(reservationId),err}let settled=settledChargeUsd(response),charged=response.ok?settled??estimate:settled??0;return reservationId!==void 0&&control.releaseReservation(reservationId),charged>0&&control.record(charged,{action:"BlockRun account charge"}),response}}function formatDuration(seconds){if(seconds<60)return`${seconds}s`;if(seconds<3600)return`${Math.ceil(seconds/60)} min`;{let hours=Math.floor(seconds/3600),mins=Math.ceil(seconds%3600/60);return mins>0?`${hours}h ${mins}m`:`${hours}h`}}var WALLET_DIR,HOUR_MS,DAY_MS,CAIP2_BASE,CAIP2_SOLANA_MAINNET,PAYABLE_NETWORKS,POLICY_LISTS,ADDRESS_LISTS,EVM_ADDRESS,UnreadableSpendPolicyError,MalformedSpendPolicyError,SpendPolicyConflictError,FileSpendControlStorage,InMemorySpendControlStorage,RESERVATION_TTL_MS,SpendControl,sharedControlHost,SpendPolicyError,CANONICAL_AMOUNT,init_spend_control=__esm({"src/spend-control.ts"(){"use strict";init_fs_read();init_payment_chain();WALLET_DIR=path.join(homedir2(),".openclaw","blockrun"),HOUR_MS=3600*1e3,DAY_MS=24*HOUR_MS,CAIP2_BASE="eip155:8453",CAIP2_SOLANA_MAINNET="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d",PAYABLE_NETWORKS=[CAIP2_BASE,CAIP2_SOLANA_MAINNET,CAIP2_ARC],POLICY_LISTS=["allowedPayees","blockedPayees","allowedNetworks","allowedAssets"],ADDRESS_LISTS=["allowedPayees","blockedPayees","allowedAssets"],EVM_ADDRESS=/^0x[0-9a-fA-F]{40}$/;UnreadableSpendPolicyError=class extends Error{constructor(cause){super(`[ClawRouter] Failed to load spending data: ${cause}`),this.name="UnreadableSpendPolicyError"}},MalformedSpendPolicyError=class extends Error{constructor(key3){super(`[ClawRouter] refusing to load spending.json: ${key3} is malformed; a corrupted policy file must not widen what the agent may pay`),this.name="MalformedSpendPolicyError"}};SpendPolicyConflictError=class extends Error{constructor(){super("spending.json limits changed underneath this write; nothing was written"),this.name="SpendPolicyConflictError"}},FileSpendControlStorage=class{spendingFile;constructor(spendingFile){this.spendingFile=spendingFile??path.join(WALLET_DIR,"spending.json")}load(){let raw;try{raw=readTextFileSync(this.spendingFile)}catch(err){let code=err?.code;if(code==="ENOENT"||code==="ENOTDIR")return null;throw new UnreadableSpendPolicyError(err)}try{let data=JSON.parse(raw),rawLimits=data.limits??{},rawHistory=data.history??[],limits={};for(let key3 of["perRequest","hourly","daily","session"]){let val=rawLimits[key3];typeof val=="number"&&val>0&&Number.isFinite(val)&&(limits[key3]=val)}for(let key3 of POLICY_LISTS){if(!Object.prototype.hasOwnProperty.call(rawLimits,key3))continue;let val=rawLimits[key3];if(!isValidPolicyValues(val))throw new MalformedSpendPolicyError(key3);val.length!==0&&(limits[key3]=normalizePolicyValues(key3,val))}let history=[];if(Array.isArray(rawHistory))for(let r2 of rawHistory)typeof r2?.timestamp=="number"&&typeof r2?.amount=="number"&&Number.isFinite(r2.timestamp)&&Number.isFinite(r2.amount)&&r2.amount>=0&&history.push({timestamp:r2.timestamp,amount:r2.amount,model:typeof r2.model=="string"?r2.model:void 0,action:typeof r2.action=="string"?r2.action:void 0,...typeof r2.id=="string"&&r2.id!==""?{id:r2.id}:{}});return{limits,history}}catch(err){throw err instanceof MalformedSpendPolicyError?err:new UnreadableSpendPolicyError(err)}}save(data){try{fs.existsSync(WALLET_DIR)||fs.mkdirSync(WALLET_DIR,{recursive:!0,mode:448});let tmp=`${this.spendingFile}.${process.pid}.tmp`;fs.writeFileSync(tmp,JSON.stringify(data,null,2),{mode:384}),fs.renameSync(tmp,this.spendingFile)}catch(err){console.error(`[ClawRouter] Failed to save spending data: ${err}`)}}saveHistory(history){let storedLimits={};try{let current=this.load();current&&(storedLimits=current.limits)}catch{return}this.save({limits:storedLimits,history})}saveLimits(limits,expect){let current;try{current=this.load()}catch{return}if(expect!==void 0&&canonicalLimits(current?.limits??{})!==canonicalLimits(expect))throw new SpendPolicyConflictError;this.save({limits,history:current?.history??[]})}},InMemorySpendControlStorage=class{data=null;load(){return this.data?{limits:cloneLimits(this.data.limits),history:this.data.history.map(r2=>({...r2}))}:null}save(data){this.data={limits:cloneLimits(data.limits),history:data.history.map(r2=>({...r2}))}}saveLimits(limits,expect){if(expect!==void 0&&canonicalLimits(this.data?.limits??{})!==canonicalLimits(expect))throw new SpendPolicyConflictError;this.data={limits:cloneLimits(limits),history:this.data?.history.map(r2=>({...r2}))??[]}}},RESERVATION_TTL_MS=120*1e3,SpendControl=class{limits={};history=[];sessionSpent=0;sessionCalls=0;pending=new Map;reservationSeq=0;limitsDirty=!1;diskLimits={};policyFileBroken;initialHistoryLoaded=!1;storage;now;constructor(options){this.storage=options?.storage??new FileSpendControlStorage,this.now=options?.now??(()=>Date.now()),this.load()}setLimit(window2,amount){if(!Number.isFinite(amount)||amount<=0)throw new Error("Limit must be a finite positive number");this.limits[window2]=amount,this.limitsDirty=!0,this.save()}clearLimit(window2){delete this.limits[window2],this.limitsDirty=!0,this.save()}setPolicy(list,values){if(!isPolicyList(list))throw new Error(`Unknown policy list: ${String(list)}`);if(!isValidPolicyValues(values)||values.length===0)throw new Error("Policy list must be a non-empty array of non-empty strings");this.limits[list]=normalizePolicyValues(list,values),this.limitsDirty=!0,this.save()}clearPolicy(list){if(!isPolicyList(list))throw new Error(`Unknown policy list: ${String(list)}`);delete this.limits[list],this.limitsDirty=!0,this.save()}getLimits(){return cloneLimits(this.limits)}getPolicyFileError(){return this.policyFileBroken}reloadLimits(){let data;try{data=this.storage.load()}catch(err){if(err instanceof UnreadableSpendPolicyError){console.error(`${err.message}: keeping the limits already in effect`);return}if(!(err instanceof MalformedSpendPolicyError))throw err;this.policyFileBroken=err.message,console.error(`[ClawRouter] ${err.message}`);return}this.initialHistoryLoaded||(data&&(this.history=data.history,this.cleanup()),this.initialHistoryLoaded=!0),this.policyFileBroken=void 0,this.limits=data?cloneLimits(data.limits):{},this.diskLimits=cloneLimits(this.limits),this.limitsDirty=!1}check(estimatedCost3,counterparty){if(this.policyFileBroken!==void 0)return{allowed:!1,reason:`Spend policy is unreadable, refusing all payments: ${this.policyFileBroken}`};if(this.limits.blockedPayees&&this.limits.blockedPayees.length>0||this.limits.allowedPayees&&this.limits.allowedPayees.length>0){if(counterparty?.payTo===void 0)return{allowed:!1,blockedByPolicy:this.limits.blockedPayees?.length?"blockedPayees":"allowedPayees",reason:"Payee policy is configured but no payTo was provided to check()"};let payTo=normalizePayee(counterparty.payTo);if(this.limits.blockedPayees?.includes(payTo))return{allowed:!1,blockedByPolicy:"blockedPayees",reason:`Payee is blocked by policy: ${counterparty.payTo}`};if(this.limits.allowedPayees&&this.limits.allowedPayees.length>0&&!this.limits.allowedPayees.includes(payTo))return{allowed:!1,blockedByPolicy:"allowedPayees",reason:`Payee is not in the configured allowlist: ${counterparty.payTo}`}}if(this.limits.allowedNetworks&&this.limits.allowedNetworks.length>0){if(counterparty?.network===void 0)return{allowed:!1,blockedByPolicy:"allowedNetworks",reason:"Network policy is configured but no network was provided to check()"};if(!this.limits.allowedNetworks.includes(counterparty.network))return{allowed:!1,blockedByPolicy:"allowedNetworks",reason:`Network is not in the configured allowlist: ${counterparty.network}`}}if(this.limits.allowedAssets&&this.limits.allowedAssets.length>0){if(counterparty?.asset===void 0)return{allowed:!1,blockedByPolicy:"allowedAssets",reason:"Asset policy is configured but no asset was provided to check()"};if(!this.limits.allowedAssets.includes(normalizePayee(counterparty.asset)))return{allowed:!1,blockedByPolicy:"allowedAssets",reason:`Asset is not in the configured allowlist: ${counterparty.asset}`}}return this.checkAmount(estimatedCost3)}checkAmount(estimatedCost3){if(this.policyFileBroken!==void 0)return{allowed:!1,reason:`Spend policy is unreadable, refusing all payments: ${this.policyFileBroken}`};let now2=this.now();if((this.limits.hourly!==void 0||this.limits.daily!==void 0)&&this.syncHistory(),this.limits.perRequest!==void 0&&estimatedCost3>this.limits.perRequest)return{allowed:!1,blockedBy:"perRequest",remaining:this.limits.perRequest,reason:`Per-request limit exceeded: $${estimatedCost3.toFixed(4)} > $${this.limits.perRequest.toFixed(2)} max`};if(this.limits.hourly!==void 0){let hourlySpent=this.getSpendingInWindow(now2-HOUR_MS,now2,now2),remaining=this.limits.hourly-hourlySpent;if(estimatedCost3>remaining){let oldestInWindow=this.history.find(r2=>r2.timestamp>=now2-HOUR_MS),resetIn=oldestInWindow?Math.ceil((oldestInWindow.timestamp+HOUR_MS-now2)/1e3):0;return{allowed:!1,blockedBy:"hourly",remaining,reason:`Hourly limit exceeded: $${(hourlySpent+estimatedCost3).toFixed(2)} > $${this.limits.hourly.toFixed(2)} max`,resetIn}}}if(this.limits.daily!==void 0){let dailySpent=this.getSpendingInWindow(now2-DAY_MS,now2,now2),remaining=this.limits.daily-dailySpent;if(estimatedCost3>remaining){let oldestInWindow=this.history.find(r2=>r2.timestamp>=now2-DAY_MS),resetIn=oldestInWindow?Math.ceil((oldestInWindow.timestamp+DAY_MS-now2)/1e3):0;return{allowed:!1,blockedBy:"daily",remaining,reason:`Daily limit exceeded: $${(dailySpent+estimatedCost3).toFixed(2)} > $${this.limits.daily.toFixed(2)} max`,resetIn}}}if(this.limits.session!==void 0){let sessionSpent=this.sessionSpent+this.pendingTotal(),remaining=this.limits.session-sessionSpent;if(estimatedCost3>remaining)return{allowed:!1,blockedBy:"session",remaining,reason:`Session limit exceeded: $${(sessionSpent+estimatedCost3).toFixed(2)} > $${this.limits.session.toFixed(2)} max`}}return{allowed:!0}}record(amount,metadata){if(!Number.isFinite(amount)||amount<0)throw new Error("Record amount must be a non-negative finite number");let record2={timestamp:this.now(),amount,model:metadata?.model,action:metadata?.action,id:randomUUID()};this.history.push(record2),this.sessionSpent+=amount,this.sessionCalls+=1,this.cleanup(),this.save()}hasAmountLimits(){return this.limits.perRequest!==void 0||this.limits.hourly!==void 0||this.limits.daily!==void 0||this.limits.session!==void 0}hasAggregateLimits(){return this.limits.hourly!==void 0||this.limits.daily!==void 0||this.limits.session!==void 0}reserve(amount){if(!Number.isFinite(amount)||amount<0)throw new Error("Reservation amount must be a non-negative finite number");let id2=`${this.now()}-${this.reservationSeq+=1}`;return this.pending.set(id2,{amount,expiresAt:this.now()+RESERVATION_TTL_MS}),id2}settleReservation(id2,metadata){let held=this.pending.get(id2);held&&(this.pending.delete(id2),this.record(held.amount,metadata))}releaseReservation(id2){this.pending.delete(id2)}pendingTotal(){this.expireReservations();let total=0;for(let held of this.pending.values())total+=held.amount;return total}expireReservations(){let now2=this.now();for(let[id2,held]of this.pending)held.expiresAt<=now2&&this.pending.delete(id2)}getSpendingInWindow(from28,to2,now2){return this.history.filter(r2=>r2.timestamp>=from28&&r2.timestamp<=to2).reduce((sum,r2)=>sum+r2.amount,0)+(to2>=now2?this.pendingTotal():0)}getSpending(window2){let now2=this.now();switch(window2){case"hourly":return this.getSpendingInWindow(now2-HOUR_MS,now2,now2);case"daily":return this.getSpendingInWindow(now2-DAY_MS,now2,now2);case"session":return this.sessionSpent+this.pendingTotal()}}getRemaining(window2){let limit=this.limits[window2];return limit===void 0?null:Math.max(0,limit-this.getSpending(window2))}getStatus(){let now2=this.now(),hourlySpent=this.getSpendingInWindow(now2-HOUR_MS,now2,now2),dailySpent=this.getSpendingInWindow(now2-DAY_MS,now2,now2);return{limits:cloneLimits(this.limits),spending:{hourly:hourlySpent,daily:dailySpent,session:this.sessionSpent},remaining:{hourly:this.limits.hourly!==void 0?this.limits.hourly-hourlySpent:null,daily:this.limits.daily!==void 0?this.limits.daily-dailySpent:null,session:this.limits.session!==void 0?this.limits.session-(this.sessionSpent+this.pendingTotal()):null},calls:this.sessionCalls}}getHistory(limit){let records=[...this.history].reverse();return limit?records.slice(0,limit):records}resetSession(){this.sessionSpent=0,this.sessionCalls=0}syncHistory(){let data;try{data=this.storage.load()}catch{return}!data||data.history.length===0||(this.history=mergeSpendHistory(this.history,data.history),this.cleanup())}cleanup(){let cutoff=this.now()-DAY_MS;this.history=this.history.filter(r2=>r2.timestamp>=cutoff)}save(){if(this.policyFileBroken===void 0){if(!this.limitsDirty&&this.storage.saveHistory){this.syncHistory(),this.storage.saveHistory([...this.history]);return}if(this.limitsDirty&&this.storage.saveLimits){try{this.storage.saveLimits(cloneLimits(this.limits),cloneLimits(this.diskLimits))}catch(err){if(err instanceof SpendPolicyConflictError)try{let current=this.storage.load();this.limits=cloneLimits(current?.limits??{}),this.diskLimits=cloneLimits(this.limits),this.limitsDirty=!1}catch{}throw err}this.diskLimits=cloneLimits(this.limits),this.limitsDirty=!1;return}this.storage.save({limits:cloneLimits(this.limits),history:[...this.history]})}}load(){let data;try{data=this.storage.load()}catch(err){if(err instanceof UnreadableSpendPolicyError||err instanceof MalformedSpendPolicyError){this.policyFileBroken=err.message,console.error(`[ClawRouter] ${err.message}`),console.error("[ClawRouter] All paid requests will be refused until spending.json is repaired. Free models are unaffected.");return}throw err}data&&(this.limits=cloneLimits(data.limits),this.diskLimits=cloneLimits(data.limits),this.history=data.history,this.cleanup()),this.initialHistoryLoaded=!0}},sharedControlHost=()=>process;SpendPolicyError=class extends Error{blockedBy;blockedByPolicy;constructor(reason,blocked){super(`Payment creation aborted: ${reason}`),this.name="SpendPolicyError",this.blockedBy=blocked?.blockedBy,this.blockedByPolicy=blocked?.blockedByPolicy}},CANONICAL_AMOUNT=/^\d+$/}});function batchEligible(method,urlPath,bodyStr){if(method!=="POST"||!urlPath.endsWith("/v1/chat/completions")||!bodyStr)return!1;try{return JSON.parse(bodyStr).stream!==!0}catch{return!1}}function createPayFetchWithPreAuth(baseFetch,client,ttlMs=DEFAULT_TTL_MS,options){let httpClient=new x402HTTPClient(client),cache2=new Map;return async(input2,init2)=>{let request2=new Request(input2,init2),callerSignal=init2?.signal!==void 0?init2.signal:input2 instanceof Request?input2.signal:void 0,send=(req,extra)=>baseFetch(req,callerSignal?{...extra,signal:callerSignal}:extra),urlPath=new URL(request2.url).pathname,requestModel="",bodyLength=0,maxTokens=0,requestBody="";if(init2?.body)try{let bodyStr=init2.body instanceof Uint8Array?new TextDecoder().decode(init2.body):typeof init2.body=="string"?init2.body:"";if(bodyStr){requestBody=bodyStr,bodyLength=bodyStr.length;let parsed=JSON.parse(bodyStr);requestModel=parsed.model??"",maxTokens=resolveMaxTokens(parsed,0)}}catch{}let cacheKey3=`${urlPath}:${requestModel}`,notifyAcceptedPayment=(response2,payload2)=>{if(!(!(response2.headers.has("payment-response")||response2.headers.has("x-payment-response"))||!options?.onPayment))try{options.onPayment({model:requestModel,amount:payload2.accepted.amount,network:payload2.accepted.network})}catch(error62){console.error(`[ClawRouter] onPayment callback failed: ${error62 instanceof Error?error62.message:String(error62)}`)}},needMicros=(()=>{if(!options?.estimateAmount||!requestModel)return;let est=options.estimateAmount(requestModel,bodyLength,maxTokens);return est===void 0?void 0:Number(est)})(),notifyDeclinedPayment=()=>{if(options?.onPaymentDeclined)try{options.onPaymentDeclined()}catch(error62){console.error(`[ClawRouter] onPaymentDeclined callback failed: ${error62 instanceof Error?error62.message:String(error62)}`)}},cached2=options?.skipPreAuth?void 0:cache2.get(cacheKey3);if(cached2!==void 0&&Date.now()-cached2.cachedAt<ttlMs&&cached2.coverMicros!==void 0&&needMicros!==void 0&&needMicros<=cached2.coverMicros&&cached2.coverMicros<=needMicros*(1+PREAUTH_OVERPAY_TOLERANCE)){let paymentInFlight=!1;try{let payload2=await client.createPaymentPayload(cached2.paymentRequired),headers=httpClient.encodePaymentSignatureHeader(payload2),preAuthRequest=request2.clone();for(let[key3,value]of Object.entries(headers))preAuthRequest.headers.set(key3,value);paymentInFlight=!0;let response2=await send(preAuthRequest);if(response2.status!==402)return notifyAcceptedPayment(response2,payload2),response2;paymentInFlight=!1,notifyDeclinedPayment(),cache2.delete(cacheKey3)}catch(err){if(cache2.delete(cacheKey3),err instanceof SpendPolicyError||paymentInFlight)throw err}}let batch=options?.solanaBatch&&batchEligible(request2.method,urlPath,requestBody)?options.solanaBatch:void 0,closesAtStart=batch?await batch.payer.closeFence():void 0,batchTemplate=batch?request2.clone():void 0,clonedRequest=request2.clone(),response=await send(request2);if(response.status!==402)return response;let paymentRequired;try{let getHeader=name=>response.headers.get(name),body;try{let responseText=await Promise.race([response.text(),new Promise((_,reject)=>setTimeout(()=>reject(new Error("Body read timeout")),3e4))]);responseText&&(body=JSON.parse(responseText))}catch{}paymentRequired=httpClient.getPaymentRequiredResponse(getHeader,body),cache2.set(cacheKey3,{paymentRequired,cachedAt:Date.now(),coverMicros:needMicros})}catch(error62){throw new Error(`Failed to parse payment requirements: ${error62 instanceof Error?error62.message:"Unknown error"}`,{cause:error62})}if(batch&&batchTemplate){let outcome=await payInBatch(batch,batchTemplate,paymentRequired,closesAtStart,send,httpClient);if(outcome.kind==="done"){if(outcome.charged&&options?.onPayment)try{options.onPayment({model:requestModel,...outcome.charged})}catch(error62){console.error(`[ClawRouter] onPayment callback failed: ${error62 instanceof Error?error62.message:String(error62)}`)}return outcome.response}paymentRequired=outcome.paymentRequired}let payload=await client.createPaymentPayload(paymentRequired),paymentHeaders=httpClient.encodePaymentSignatureHeader(payload);for(let[key3,value]of Object.entries(paymentHeaders))clonedRequest.headers.set(key3,value);let paidResponse=await send(clonedRequest);return paidResponse.status===402&¬ifyDeclinedPayment(),notifyAcceptedPayment(paidResponse,payload),paidResponse}}async function payInBatch(batch,template,paymentRequired,closesAtStart,fetchPaid,httpClient){let unpaidAnswer,mark=batch.begin(),sent=!1,attempt;try{attempt=await batch.payer.pay(paymentRequired,headers=>{let paid=template.clone();for(let[key3,value]of Object.entries(headers))paid.headers.set(key3,value);return sent=!0,fetchPaid(paid)},async()=>{let fresh=await fetchPaid(template.clone());if(fresh.status===402){let text=await fresh.text().catch(()=>""),body;try{body=text?JSON.parse(text):void 0}catch{}return{kind:"challenge",paymentRequired:httpClient.getPaymentRequiredResponse(name=>fresh.headers.get(name),body)}}if(fresh.ok)return{kind:"served",response:fresh};throw unpaidAnswer=fresh,new Error(`fresh challenge answered HTTP ${fresh.status}`)},closesAtStart)}catch(error62){throw sent?(batch.settle(mark,{kind:"in_doubt"}),error62 instanceof Error&&error62.name==="BatchPaymentUnresolvedError"?error62:new PaymentInDoubtError(error62)):(batch.settle(mark,{kind:"not_charged"}),error62)}if(attempt.kind==="paid"){let chargedMicros=receiptChargedMicros(attempt.response);batch.settle(mark,{kind:"paid",chargedMicros});let accept=paymentRequired.accepts.find(a=>a.scheme==="batch-settlement"),charged=chargedMicros!==void 0?{amount:chargedMicros.toString(),network:accept?.network??"solana"}:void 0;return{kind:"done",response:attempt.response,charged}}if(batch.settle(mark,{kind:"not_charged"}),attempt.kind==="served")return{kind:"done",response:attempt.response};if(attempt.kind==="failed"){if(unpaidAnswer)return{kind:"done",response:unpaidAnswer};throw attempt.error}return{kind:"exact",paymentRequired:attempt.paymentRequired??paymentRequired}}function receiptChargedMicros(response){let header=response.headers.get("payment-response")??response.headers.get("x-payment-response");if(!header)return;let receipt;try{let parsed=JSON.parse(Buffer.from(header,"base64").toString("utf8"));receipt=parsed&&typeof parsed=="object"?parsed:void 0}catch{return}for(let value of[receipt?.extra?.chargedAmount,receipt?.amount])if(typeof value=="string"&&/^\d+$/.test(value))return BigInt(value)}var DEFAULT_TTL_MS,PREAUTH_OVERPAY_TOLERANCE,PaymentInDoubtError,init_payment_preauth=__esm({"src/payment-preauth.ts"(){"use strict";init_esm5();init_max_tokens();init_spend_control();DEFAULT_TTL_MS=36e5,PREAUTH_OVERPAY_TOLERANCE=.03,PaymentInDoubtError=class extends Error{constructor(cause){super(`batch-settlement payment sent, outcome unknown: ${cause instanceof Error?cause.message:String(cause)}`,{cause}),this.name="PaymentInDoubtError"}}}});function withBuilderCodeServiceCode(extensions){let merged={...extensions??{}},existing=merged["builder-code"]??{},existingServiceCodes=Array.isArray(existing.info?.s)?existing.info.s.filter(code=>typeof code=="string"):[];return merged["builder-code"]={...existing,info:{...existing.info??{},s:existingServiceCodes.includes(BLOCKRUN_SERVICE_CODE)?[...existingServiceCodes]:[...existingServiceCodes,BLOCKRUN_SERVICE_CODE]}},merged}var BLOCKRUN_SERVICE_CODE,init_builder_code=__esm({"src/builder-code.ts"(){"use strict";BLOCKRUN_SERVICE_CODE="bc_5hucoh0l"}});var UINT256_MAX,init_chunk_EL2GVDVK=__esm({"node_modules/@x402/evm/dist/esm/chunk-EL2GVDVK.mjs"(){"use strict";UINT256_MAX=(1n<<256n)-1n}});var init_chunk_5JE2UIZP=__esm({"node_modules/@x402/evm/dist/esm/chunk-5JE2UIZP.mjs"(){"use strict"}});var init_chunk_VS3RYAYE=__esm({"node_modules/@x402/evm/dist/esm/chunk-VS3RYAYE.mjs"(){"use strict"}});var init_chunk_23QU4APL=__esm({"node_modules/@x402/evm/dist/esm/chunk-23QU4APL.mjs"(){"use strict"}});function getEvmChainId(network){if(!network.startsWith("eip155:"))throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);let match=EIP155_NETWORK_REGEX.exec(network);if(!match)throw new Error(`Invalid CAIP-2 chain ID: ${network}`);let chainId=Number(match[1]);if(!Number.isSafeInteger(chainId))throw new Error(`Invalid CAIP-2 chain ID: ${network}`);return chainId}function getCrypto(){let cryptoObj=globalThis.crypto;if(!cryptoObj)throw new Error("Crypto API not available");return cryptoObj}function createNonce(){return toHex(getCrypto().getRandomValues(new Uint8Array(32)))}function createPermit2Nonce(){let randomBytes9=getCrypto().getRandomValues(new Uint8Array(32));return BigInt(toHex(randomBytes9)).toString()}var EIP155_NETWORK_REGEX,init_chunk_EKCH75YB=__esm({"node_modules/@x402/evm/dist/esm/chunk-EKCH75YB.mjs"(){"use strict";init_esm4();EIP155_NETWORK_REGEX=/^eip155:(\d+)$/}});function getEvmChainIdV1(network){let chainId=EVM_NETWORK_CHAIN_ID_MAP[network];if(!chainId)throw new Error(`Unsupported v1 network: ${network}`);return chainId}var EVM_NETWORK_CHAIN_ID_MAP,NETWORKS,authorizationTypes,permit2WitnessTypes,eip2612PermitTypes,eip2612NoncesAbi,erc20ApproveAbi,erc20AllowanceAbi,ERC20_APPROVE_GAS_LIMIT,DEFAULT_MAX_FEE_PER_GAS,DEFAULT_MAX_PRIORITY_FEE_PER_GAS,PERMIT2_ADDRESS,x402ExactPermit2ProxyAddress,init_chunk_5AIYL4HT=__esm({"node_modules/@x402/evm/dist/esm/chunk-5AIYL4HT.mjs"(){"use strict";EVM_NETWORK_CHAIN_ID_MAP={ethereum:1,sepolia:11155111,abstract:2741,"abstract-testnet":11124,"base-sepolia":84532,base:8453,"avalanche-fuji":43113,avalanche:43114,iotex:4689,sei:1329,"sei-testnet":1328,polygon:137,"polygon-amoy":80002,peaq:3338,story:1514,educhain:41923,"skale-base-sepolia":324705682,megaeth:4326,monad:143,"monad-testnet":10143,stable:988,"stable-testnet":2201,celo:42220,flare:14,hemi:43111,"hemi-testnet":743111},NETWORKS=Object.keys(EVM_NETWORK_CHAIN_ID_MAP);authorizationTypes={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},permit2WitnessTypes={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},eip2612PermitTypes={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},eip2612NoncesAbi=[{type:"function",name:"nonces",inputs:[{name:"owner",type:"address"}],outputs:[{type:"uint256"}],stateMutability:"view"}],erc20ApproveAbi=[{type:"function",name:"approve",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}],stateMutability:"nonpayable"}],erc20AllowanceAbi=[{type:"function",name:"allowance",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}],stateMutability:"view"}],ERC20_APPROVE_GAS_LIMIT=70000n,DEFAULT_MAX_FEE_PER_GAS=1000000000n,DEFAULT_MAX_PRIORITY_FEE_PER_GAS=100000000n,PERMIT2_ADDRESS="0x000000000022D473030F116dDEE9F6B43aC78BA3",x402ExactPermit2ProxyAddress="0x402085c248EeA27D92E8b30b2C58ed07f9E20001"}});async function signEip2612Permit(signer,tokenAddress,tokenName,tokenVersion,chainId,deadline,permittedAmount){let owner=signer.address,spender=getAddress(PERMIT2_ADDRESS),nonce2=await signer.readContract({address:tokenAddress,abi:eip2612NoncesAbi,functionName:"nonces",args:[owner]}),domain2={name:tokenName,version:tokenVersion,chainId,verifyingContract:tokenAddress},approvalAmount=BigInt(permittedAmount),message={owner,spender,value:approvalAmount,nonce:nonce2,deadline:BigInt(deadline)},signature3=await signer.signTypedData({domain:domain2,types:eip2612PermitTypes,primaryType:"Permit",message});return{from:owner,asset:tokenAddress,spender,amount:approvalAmount.toString(),nonce:nonce2.toString(),deadline,signature:signature3,version:"1"}}async function signErc20ApprovalTransaction(signer,tokenAddress,chainId){let from28=signer.address,spender=getAddress(PERMIT2_ADDRESS),data=encodeFunctionData({abi:erc20ApproveAbi,functionName:"approve",args:[spender,maxUint256]}),nonce2=await signer.getTransactionCount({address:from28}),maxFeePerGas,maxPriorityFeePerGas;try{let fees2=await signer.estimateFeesPerGas?.();if(!fees2)throw new Error("no fee estimates available");maxFeePerGas=fees2.maxFeePerGas,maxPriorityFeePerGas=fees2.maxPriorityFeePerGas}catch{maxFeePerGas=DEFAULT_MAX_FEE_PER_GAS,maxPriorityFeePerGas=DEFAULT_MAX_PRIORITY_FEE_PER_GAS}let signedTransaction=await signer.signTransaction({to:tokenAddress,data,nonce:nonce2,gas:ERC20_APPROVE_GAS_LIMIT,maxFeePerGas,maxPriorityFeePerGas,chainId});return{from:from28,asset:tokenAddress,spender,amount:maxUint256.toString(),signedTransaction,version:ERC20_APPROVAL_GAS_SPONSORING_VERSION}}function isConfigByChainId(options){let keys=Object.keys(options);return keys.length>0&&keys.every(key3=>/^\d+$/.test(key3))}function getRpcClient(rpcUrl){let existing=rpcClientCache.get(rpcUrl);if(existing)return existing;let client=createPublicClient({transport:http(rpcUrl)});return rpcClientCache.set(rpcUrl,client),client}function resolveRpcUrl(network,options){if(options){if(isConfigByChainId(options)){let chainId=getEvmChainId(network);return options[chainId]?.rpcUrl}return options.rpcUrl}}function resolveExtensionRpcCapabilities(network,signer,options){let capabilities={signTransaction:signer.signTransaction,readContract:signer.readContract,getTransactionCount:signer.getTransactionCount,estimateFeesPerGas:signer.estimateFeesPerGas};if(!(!capabilities.readContract||!capabilities.getTransactionCount||!capabilities.estimateFeesPerGas))return capabilities;let rpcUrl=resolveRpcUrl(network,options);if(!rpcUrl)return capabilities;let rpcClient=getRpcClient(rpcUrl);return capabilities.readContract||(capabilities.readContract=args=>rpcClient.readContract(args)),capabilities.getTransactionCount||(capabilities.getTransactionCount=async args=>rpcClient.getTransactionCount({address:args.address})),capabilities.estimateFeesPerGas||(capabilities.estimateFeesPerGas=async()=>rpcClient.estimateFeesPerGas()),capabilities}function warnCannotReadForSponsoring(network){warnedNetworks.has(network)||(warnedNetworks.add(network),console.warn(`[x402] gas sponsoring is advertised for ${network} but the client cannot read the chain, so the sponsored permit/approval will not be signed and a fresh wallet will get 412 permit2_allowance_required. Pass { rpcUrl } to ExactEvmScheme, or use a signer with readContract (e.g. toClientEvmSigner(account, publicClient)).`))}async function trySignEip2612PermitExtension(signer,options,requirements,result,context,approvalAmount){if(!context?.extensions?.[EIP2612_GAS_SPONSORING_KEY])return;let capabilities=resolveExtensionRpcCapabilities(requirements.network,signer,options);if(!capabilities.readContract){warnCannotReadForSponsoring(requirements.network);return}let tokenName=requirements.extra?.name,tokenVersion=requirements.extra?.version;if(!tokenName||!tokenVersion)return;let chainId=getEvmChainId(requirements.network),tokenAddress=getAddress(requirements.asset),requiredAllowance=approvalAmount??requirements.amount;try{if(await capabilities.readContract({address:tokenAddress,abi:erc20AllowanceAbi,functionName:"allowance",args:[signer.address,PERMIT2_ADDRESS]})>=BigInt(requiredAllowance))return}catch{}let deadline=result.payload?.permit2Authorization?.deadline??Math.floor(Date.now()/1e3+requirements.maxTimeoutSeconds).toString(),info=await signEip2612Permit({address:signer.address,signTypedData:msg=>signer.signTypedData(msg),readContract:capabilities.readContract},tokenAddress,tokenName,tokenVersion,chainId,deadline,requiredAllowance);return{[EIP2612_GAS_SPONSORING_KEY]:{info}}}async function trySignErc20ApprovalExtension(signer,options,requirements,context,approvalAmount){if(!context?.extensions?.[ERC20_APPROVAL_GAS_SPONSORING_KEY])return;let capabilities=resolveExtensionRpcCapabilities(requirements.network,signer,options);if(!capabilities.readContract){warnCannotReadForSponsoring(requirements.network);return}if(!capabilities.signTransaction||!capabilities.getTransactionCount)return;let chainId=getEvmChainId(requirements.network),tokenAddress=getAddress(requirements.asset),requiredAllowance=approvalAmount??requirements.amount;try{if(await capabilities.readContract({address:tokenAddress,abi:erc20AllowanceAbi,functionName:"allowance",args:[signer.address,PERMIT2_ADDRESS]})>=BigInt(requiredAllowance))return}catch{}let info=await signErc20ApprovalTransaction({address:signer.address,signTransaction:capabilities.signTransaction,getTransactionCount:capabilities.getTransactionCount,estimateFeesPerGas:capabilities.estimateFeesPerGas},tokenAddress,chainId);return{[ERC20_APPROVAL_GAS_SPONSORING_KEY]:{info}}}var EIP2612_GAS_SPONSORING_KEY,ERC20_APPROVAL_GAS_SPONSORING_KEY,ERC20_APPROVAL_GAS_SPONSORING_VERSION,rpcClientCache,warnedNetworks,init_chunk_AB46Q4WU=__esm({"node_modules/@x402/evm/dist/esm/chunk-AB46Q4WU.mjs"(){"use strict";init_chunk_EKCH75YB();init_chunk_5AIYL4HT();init_esm4();init_esm4();init_esm4();init_esm4();EIP2612_GAS_SPONSORING_KEY="eip2612GasSponsoring",ERC20_APPROVAL_GAS_SPONSORING_KEY="erc20ApprovalGasSponsoring",ERC20_APPROVAL_GAS_SPONSORING_VERSION="1";rpcClientCache=new Map;warnedNetworks=new Set}});function resolveNetworkKey(network){if(network in DEFAULT_ASSETS)return network;let chainId=EVM_NETWORK_CHAIN_ID_MAP[network];return chainId!==void 0?`eip155:${chainId}`:network}var DEFAULT_ASSETS,findDefaultAsset,init_chunk_6XWQF37J=__esm({"node_modules/@x402/evm/dist/esm/chunk-6XWQF37J.mjs"(){"use strict";init_chunk_5AIYL4HT();DEFAULT_ASSETS={"eip155:8453":[{asset:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",name:"USD Coin",version:"2",decimals:6,symbol:"USDC"}],"eip155:84532":[{asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",name:"USDC",version:"2",decimals:6,symbol:"USDC"}],"eip155:1":[{asset:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",name:"USD Coin",version:"2",decimals:6,symbol:"USDC"}],"eip155:43114":[{asset:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",name:"USD Coin",version:"2",decimals:6,symbol:"USDC"}],"eip155:4326":[{asset:"0xFAfDdbb3FC7688494971a79cc65DCa3EF82079E7",name:"MegaUSD",version:"1",decimals:18,symbol:"MegaUSD",assetTransferMethod:"permit2",supportsEip2612:!0}],"eip155:143":[{asset:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",name:"USDC",version:"2",decimals:6,symbol:"USDC"}],"eip155:10143":[{asset:"0x534b2f3A21130d7a60830c2Df862319e593943A3",name:"USDC",version:"2",decimals:6,symbol:"USDC"}],"eip155:988":[{asset:"0x779Ded0c9e1022225f8E0630b35a9b54bE713736",name:"USDT0",version:"1",decimals:6,symbol:"USDT0"}],"eip155:2201":[{asset:"0x78Cf24370174180738C5B8E352B6D14c83a6c9A9",name:"USDT0",version:"1",decimals:6,symbol:"USDT0"}],"eip155:137":[{asset:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",name:"USD Coin",version:"2",decimals:6,symbol:"USDC"}],"eip155:42161":[{asset:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",name:"USD Coin",version:"2",decimals:6,symbol:"USDC"}],"eip155:421614":[{asset:"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",name:"USD Coin",version:"2",decimals:6,symbol:"USDC"}],"eip155:31612":[{asset:"0xdD468A1DDc392dcdbEf6db6e34E89AA338F9F186",name:"Mezo USD",version:"1",decimals:18,symbol:"mUSD",assetTransferMethod:"permit2",supportsEip2612:!0}],"eip155:31611":[{asset:"0x118917a40FAF1CD7a13dB0Ef56C86De7973Ac503",name:"Mezo USD",version:"1",decimals:18,symbol:"mUSD",assetTransferMethod:"permit2",supportsEip2612:!0}],"eip155:723487":[{asset:"0x33ad9e4BD16B69B5BFdED37D8B5D9fF9aba014Fb",name:"Stable Coin",version:"1",decimals:6,symbol:"SBC",assetTransferMethod:"permit2",supportsEip2612:!0}],"eip155:72344":[{asset:"0x33ad9e4BD16B69B5BFdED37D8B5D9fF9aba014Fb",name:"Stable Coin",version:"1",decimals:6,symbol:"SBC",assetTransferMethod:"permit2",supportsEip2612:!0}],"eip155:36900":[{asset:"0x9cb8142aEBBcdc60AF7c97Af897A67A8f3CA71C2",name:"USDC.e",version:"2",decimals:6,symbol:"USDC.e"}],"eip155:190415":[{asset:"0x401eCb1D350407f13ba348573E5630B83638E30D",name:"Bridged USDC",version:"2",decimals:6,symbol:"USDC.e"}],"eip155:181228":[{asset:"0x401eCb1D350407f13ba348573E5630B83638E30D",name:"Bridged USDC",version:"2",decimals:6,symbol:"USDC.e"}],"eip155:50":[{asset:"0xfA2958CB79b0491CC627c1557F441eF849Ca8eb1",name:"USDC",version:"2",decimals:6,symbol:"USDC"}],"eip155:51":[{asset:"0xb5AB69F7bBada22B28e79C8FFAECe55eF1c771D4",name:"USDC",version:"2",decimals:6,symbol:"USDC"}],"eip155:38833":[{asset:"0xA5b8BF902b2844dA17d4506cc827F7F1681735E7",name:"USDC",version:"1",decimals:6,symbol:"USDC",assetTransferMethod:"permit2"}],"eip155:14":[{asset:"0xe7cd86e13AC4309349F30B3435a9d337750fC82D",name:"USD\u20AE0",version:"1",decimals:6,symbol:"USDT0"}],"eip155:42220":[{asset:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",name:"USDC",version:"2",decimals:6,symbol:"USDC"},{asset:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",name:"Tether USD",version:"1",decimals:6,symbol:"USDT"},{asset:"0xD2ab3C9A02DBBAB236BfEC45D1d755DF4267F771",name:"Tether America USD",version:"1",decimals:6,symbol:"USAT"}],"eip155:11142220":[{asset:"0x01C5C0122039549AD1493B8220cABEdD739BC44E",name:"USDC",version:"2",decimals:6,symbol:"USDC"}],"eip155:1329":[{asset:"0xe15fC38F6D8c56aF07bbCBe3BAf5708A2Bf42392",name:"USDC",version:"2",decimals:6,symbol:"USDC"}],"eip155:1328":[{asset:"0x4fCF1784B31630811181f670Aea7A7bEF803eaED",name:"USDC",version:"2",decimals:6,symbol:"USDC"}],"eip155:5042":[{asset:"0x3600000000000000000000000000000000000000",name:"USDC",version:"2",decimals:6,symbol:"USDC"}],"eip155:5042002":[{asset:"0x3600000000000000000000000000000000000000",name:"USDC",version:"2",decimals:6,symbol:"USDC"}],"eip155:4663":[{asset:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",name:"Global Dollar",version:"1",decimals:6,symbol:"USDG"}],"eip155:43111":[{asset:"0xad11a8BEb98bbf61dbb1aa0F6d6F2ECD87b35afA",name:"Bridged USDC (Stargate)",version:"2",decimals:6,symbol:"USDC.e"}],"eip155:743111":[{asset:"0xD47971C7F5B1067d25cd45d30b2c9eb60de96443",name:"USDC.e",version:"1",decimals:6,symbol:"USDC.e",assetTransferMethod:"permit2"}]};findDefaultAsset=(asset,network)=>{let key3=resolveNetworkKey(network),assets=DEFAULT_ASSETS[key3];if(!assets)return;let normalized=asset.toLowerCase();return assets.find(entry=>entry.asset.toLowerCase()===normalized)}}});var ExactEvmSchemeV1,init_chunk_X42JDBHW=__esm({"node_modules/@x402/evm/dist/esm/chunk-X42JDBHW.mjs"(){"use strict";init_chunk_EL2GVDVK();init_chunk_5JE2UIZP();init_chunk_VS3RYAYE();init_chunk_23QU4APL();init_chunk_AB46Q4WU();init_chunk_EKCH75YB();init_chunk_6XWQF37J();init_chunk_5AIYL4HT();init_esm4();ExactEvmSchemeV1=class{constructor(signer){this.signer=signer,this.scheme="exact",this.findDefaultAsset=findDefaultAsset}async createPaymentPayload(x402Version2,paymentRequirements){let selectedV1=paymentRequirements,nonce2=createNonce(),now2=Math.floor(Date.now()/1e3),authorization={from:this.signer.address,to:getAddress(selectedV1.payTo),value:selectedV1.maxAmountRequired,validAfter:(now2-600).toString(),validBefore:(now2+selectedV1.maxTimeoutSeconds).toString(),nonce:nonce2},signature3=await this.signAuthorization(authorization,selectedV1),payload={authorization,signature:signature3};return{x402Version:x402Version2,scheme:selectedV1.scheme,network:selectedV1.network,payload}}async signAuthorization(authorization,requirements){let chainId=getEvmChainIdV1(requirements.network);if(!requirements.extra?.name||!requirements.extra?.version)throw new Error(`EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`);let{name,version:version31}=requirements.extra,domain2={name,version:version31,chainId,verifyingContract:getAddress(requirements.asset)},message={from:getAddress(authorization.from),to:getAddress(authorization.to),value:BigInt(authorization.value),validAfter:BigInt(authorization.validAfter),validBefore:BigInt(authorization.validBefore),nonce:authorization.nonce};return await this.signer.signTypedData({domain:domain2,types:authorizationTypes,primaryType:"TransferWithAuthorization",message})}}}});async function createPermit2PayloadForProxy(proxyAddress,signer,x402Version2,paymentRequirements){let now2=Math.floor(Date.now()/1e3),nonce2=createPermit2Nonce(),validAfter="0",deadline=(now2+paymentRequirements.maxTimeoutSeconds).toString(),permit2Authorization={from:signer.address,permitted:{token:getAddress(paymentRequirements.asset),amount:paymentRequirements.amount},spender:proxyAddress,nonce:nonce2,deadline,witness:{to:getAddress(paymentRequirements.payTo),validAfter}},signature3=await signPermit2Authorization(signer,permit2Authorization,paymentRequirements);return{x402Version:x402Version2,payload:{signature:signature3,permit2Authorization}}}async function signPermit2Authorization(signer,permit2Authorization,requirements){let chainId=getEvmChainId(requirements.network);return await signer.signTypedData({domain:{name:"Permit2",chainId,verifyingContract:PERMIT2_ADDRESS},types:permit2WitnessTypes,primaryType:"PermitWitnessTransferFrom",message:{permitted:{token:getAddress(permit2Authorization.permitted.token),amount:BigInt(permit2Authorization.permitted.amount)},spender:getAddress(permit2Authorization.spender),nonce:BigInt(permit2Authorization.nonce),deadline:BigInt(permit2Authorization.deadline),witness:{to:getAddress(permit2Authorization.witness.to),validAfter:BigInt(permit2Authorization.witness.validAfter)}}})}var init_chunk_QKR4OFMY=__esm({"node_modules/@x402/evm/dist/esm/chunk-QKR4OFMY.mjs"(){"use strict";init_chunk_VS3RYAYE();init_chunk_23QU4APL();init_chunk_AB46Q4WU();init_chunk_EKCH75YB();init_chunk_5AIYL4HT();init_esm4()}});async function createPermit2Payload(signer,x402Version2,paymentRequirements){return createPermit2PayloadForProxy(x402ExactPermit2ProxyAddress,signer,x402Version2,paymentRequirements)}var MAX_UINT256,init_chunk_H3CLVT6Z=__esm({"node_modules/@x402/evm/dist/esm/chunk-H3CLVT6Z.mjs"(){"use strict";init_chunk_QKR4OFMY();init_chunk_5AIYL4HT();MAX_UINT256=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")}});var init_utils14=__esm({"node_modules/@x402/core/dist/esm/utils/index.mjs"(){"use strict";init_chunk_XW2CWVLZ()}});async function createEIP3009Payload(signer,x402Version2,paymentRequirements){let nonce2=createNonce(),now2=Math.floor(Date.now()/1e3),authorization={from:signer.address,to:getAddress(paymentRequirements.payTo),value:paymentRequirements.amount,validAfter:"0",validBefore:(now2+paymentRequirements.maxTimeoutSeconds).toString(),nonce:nonce2},signature3=await signEIP3009Authorization(signer,authorization,paymentRequirements);return{x402Version:x402Version2,payload:{authorization,signature:signature3}}}async function signEIP3009Authorization(signer,authorization,requirements){let chainId=getEvmChainId(requirements.network);if(!requirements.extra?.name||!requirements.extra?.version)throw new Error(`EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`);let{name,version:version31}=requirements.extra,domain2={name,version:version31,chainId,verifyingContract:getAddress(requirements.asset)},message={from:getAddress(authorization.from),to:getAddress(authorization.to),value:BigInt(authorization.value),validAfter:BigInt(authorization.validAfter),validBefore:BigInt(authorization.validBefore),nonce:authorization.nonce};return await signer.signTypedData({domain:domain2,types:authorizationTypes,primaryType:"TransferWithAuthorization",message})}function registerExactEvmScheme(client,config2){let evmScheme=new ExactEvmScheme(config2.signer,config2.schemeOptions);return config2.networks&&config2.networks.length>0?config2.networks.forEach(network=>{client.register(network,evmScheme)}):client.register("eip155:*",evmScheme),(config2.networks&&config2.networks.length>0?NETWORKS.filter(name=>config2.networks.some(pattern=>networkMatchesPattern(pattern,`eip155:${getEvmChainIdV1(name)}`))):NETWORKS).forEach(network=>{client.registerV1(network,new ExactEvmSchemeV1(config2.signer))}),config2.policies&&config2.policies.forEach(policy=>{client.registerPolicy(policy)}),client}var ExactEvmScheme,init_chunk_374U7QOG=__esm({"node_modules/@x402/evm/dist/esm/chunk-374U7QOG.mjs"(){"use strict";init_chunk_X42JDBHW();init_chunk_H3CLVT6Z();init_chunk_AB46Q4WU();init_chunk_EKCH75YB();init_chunk_6XWQF37J();init_chunk_5AIYL4HT();init_esm4();init_utils14();ExactEvmScheme=class{constructor(signer,options){this.signer=signer,this.options=options,this.scheme="exact",this.findDefaultAsset=findDefaultAsset}async createPaymentPayload(x402Version2,paymentRequirements,context){if((paymentRequirements.extra?.assetTransferMethod??"eip3009")==="permit2"){let result=await createPermit2Payload(this.signer,x402Version2,paymentRequirements),eip2612Extensions=await trySignEip2612PermitExtension(this.signer,this.options,paymentRequirements,result,context);if(eip2612Extensions)return{...result,extensions:eip2612Extensions};let erc20Extensions=await trySignErc20ApprovalExtension(this.signer,this.options,paymentRequirements,context);return erc20Extensions?{...result,extensions:erc20Extensions}:result}return createEIP3009Payload(this.signer,x402Version2,paymentRequirements)}}}});var init_chunk_DBYTBFOQ=__esm({"node_modules/@x402/evm/dist/esm/chunk-DBYTBFOQ.mjs"(){"use strict"}});var init_client2=__esm({"node_modules/@x402/evm/dist/esm/exact/client/index.mjs"(){"use strict";init_chunk_374U7QOG();init_chunk_X42JDBHW();init_chunk_EL2GVDVK();init_chunk_5JE2UIZP();init_chunk_DBYTBFOQ();init_chunk_H3CLVT6Z();init_chunk_QKR4OFMY();init_chunk_VS3RYAYE();init_chunk_23QU4APL();init_chunk_AB46Q4WU();init_chunk_EKCH75YB();init_chunk_6XWQF37J();init_chunk_5AIYL4HT()}});var SALT_BINDING_TYPEHASH,PAYMENT_INFO_TYPEHASH,init_chunk_BBPWOJXX=__esm({"node_modules/@x402/evm/dist/esm/chunk-BBPWOJXX.mjs"(){"use strict";init_chunk_5JE2UIZP();init_chunk_5AIYL4HT();init_esm4();init_esm4();SALT_BINDING_TYPEHASH=keccak256(toBytes("x402AuthCaptureSaltBinding(address receiverAuthorizer,address policy,uint256 saltNonce)")),PAYMENT_INFO_TYPEHASH=keccak256(new TextEncoder().encode("PaymentInfo(address operator,address payer,address receiver,address token,uint120 maxAmount,uint48 preApprovalExpiry,uint48 authorizationExpiry,uint48 refundExpiry,uint16 minFeeBps,uint16 maxFeeBps,address feeReceiver,uint256 salt)"))}});var init_chunk_QCE52OSD=__esm({"node_modules/@x402/evm/dist/esm/chunk-QCE52OSD.mjs"(){"use strict";init_chunk_BBPWOJXX();init_chunk_EKCH75YB();init_chunk_6XWQF37J()}});var init_chunk_XE4FB4AB=__esm({"node_modules/@x402/evm/dist/esm/chunk-XE4FB4AB.mjs"(){"use strict"}});var init_chunk_W6ON4LG2=__esm({"node_modules/@x402/evm/dist/esm/chunk-W6ON4LG2.mjs"(){"use strict"}});var init_chunk_BOZHBVFZ=__esm({"node_modules/@x402/evm/dist/esm/chunk-BOZHBVFZ.mjs"(){"use strict"}});var CHANNEL_CONFIG_TYPEHASH,UINT96_MASK,init_chunk_7DJ4WEQ5=__esm({"node_modules/@x402/evm/dist/esm/chunk-7DJ4WEQ5.mjs"(){"use strict";init_chunk_EKCH75YB();init_esm4();CHANNEL_CONFIG_TYPEHASH=keccak256(toBytes("ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)")),UINT96_MASK=(1n<<96n)-1n}});var init_chunk_AEYKXGQA=__esm({"node_modules/@x402/evm/dist/esm/chunk-AEYKXGQA.mjs"(){"use strict";init_chunk_W6ON4LG2();init_chunk_BOZHBVFZ();init_chunk_7DJ4WEQ5();init_chunk_DBYTBFOQ();init_chunk_AB46Q4WU();init_chunk_EKCH75YB();init_chunk_6XWQF37J();init_chunk_5AIYL4HT();init_http4();init_http4();init_client()}});var init_chunk_SPPQBP6P=__esm({"node_modules/@x402/evm/dist/esm/chunk-SPPQBP6P.mjs"(){"use strict";init_chunk_BOZHBVFZ();init_chunk_7DJ4WEQ5()}});var DEFAULT_ASSET_CONTRACT_CACHE_TTL_MS,init_chunk_VGMBXJLA=__esm({"node_modules/@x402/evm/dist/esm/chunk-VGMBXJLA.mjs"(){"use strict";init_chunk_23QU4APL();DEFAULT_ASSET_CONTRACT_CACHE_TTL_MS=900*1e3}});var init_chunk_3EVS7UJG=__esm({"node_modules/@x402/evm/dist/esm/chunk-3EVS7UJG.mjs"(){"use strict";init_chunk_AB46Q4WU();init_chunk_EKCH75YB();init_chunk_6XWQF37J();init_chunk_5AIYL4HT()}});function toClientEvmSigner(signer,publicClient){let readContract2=signer.readContract??publicClient?.readContract.bind(publicClient),result={address:signer.address,signTypedData:msg=>signer.signTypedData(msg)};readContract2&&(result.readContract=readContract2);let signTransaction4=signer.signTransaction;signTransaction4&&(result.signTransaction=args=>signTransaction4(args));let getTransactionCount2=signer.getTransactionCount??publicClient?.getTransactionCount?.bind(publicClient);getTransactionCount2&&(result.getTransactionCount=args=>getTransactionCount2(args));let estimateFeesPerGas3=signer.estimateFeesPerGas??publicClient?.estimateFeesPerGas?.bind(publicClient);return estimateFeesPerGas3&&(result.estimateFeesPerGas=()=>estimateFeesPerGas3()),result}var init_esm6=__esm({"node_modules/@x402/evm/dist/esm/index.mjs"(){"use strict";init_chunk_QCE52OSD();init_chunk_XE4FB4AB();init_chunk_BBPWOJXX();init_chunk_AEYKXGQA();init_chunk_W6ON4LG2();init_chunk_SPPQBP6P();init_chunk_BOZHBVFZ();init_chunk_7DJ4WEQ5();init_chunk_374U7QOG();init_chunk_VGMBXJLA();init_chunk_X42JDBHW();init_chunk_EL2GVDVK();init_chunk_5JE2UIZP();init_chunk_DBYTBFOQ();init_chunk_3EVS7UJG();init_chunk_H3CLVT6Z();init_chunk_QKR4OFMY();init_chunk_VS3RYAYE();init_chunk_23QU4APL();init_chunk_AB46Q4WU();init_chunk_EKCH75YB();init_chunk_6XWQF37J();init_chunk_5AIYL4HT()}});function escapeRegExp2(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function keywordMatcher(keyword){let cached2=matcherCache.get(keyword);if(cached2)return cached2;let kw=keyword.toLowerCase(),matcher;if(UNSEGMENTED_SCRIPT.test(kw)||kw.length===0)matcher={needle:kw,pattern:null};else{let lead=WORD_CHAR.test(kw[0])?BOUNDARY_BEFORE:"",escaped=escapeRegExp2(kw),body=escaped,trail="",needle=kw,lastWord=kw.slice(kw.lastIndexOf(" ")+1);if(WORD_CHAR.test(kw[kw.length-1])&&ASCII_PHRASE.test(kw)&&lastWord.length<=BOUNDED_LAST_WORD_LENGTH){let forms=[];/\d$/.test(kw)?forms.push(escaped):lastWord.length<=3?(forms.push(`${escaped}${SHORT_SUFFIXES}`),/(?:x|s|z|ch|sh)$/.test(kw)&&forms.push(`${escaped}${SIBILANT_PLURAL}`)):(forms.push(`${escaped}${MID_SUFFIXES}`),kw.endsWith("e")?(forms.push(`${escaped.slice(0,-1)}${DROPPED_E_SUFFIXES}`),needle=kw.slice(0,-1)):kw.endsWith("y")?(forms.push(`${escaped.slice(0,-1)}(?:ies|ied)`),needle=kw.slice(0,-1)):/[aeiou][bdgmnprt]$/.test(kw)&&forms.push(`${escaped}${kw[kw.length-1]}${DOUBLED_CONSONANT_SUFFIXES}`)),body=`(?:${forms.join("|")})`,trail=BOUNDARY_AFTER}matcher={needle,pattern:new RegExp(`${lead}${body}${trail}`,"u")}}return matcherCache.set(keyword,matcher),matcher}function matchesKeyword(text,keyword){let{needle,pattern}=keywordMatcher(keyword);return text.includes(needle)?pattern===null?!0:pattern.test(text):!1}function scoreTokenCount(estimatedTokens,thresholds){return estimatedTokens<thresholds.simple?{name:"tokenCount",score:-1,signal:`short (${estimatedTokens} tokens)`}:estimatedTokens>thresholds.complex?{name:"tokenCount",score:1,signal:`long (${estimatedTokens} tokens)`}:{name:"tokenCount",score:0,signal:null}}function scoreKeywordMatch(text,keywords,name,signalLabel,thresholds,scores){let matches=keywords.filter(kw=>matchesKeyword(text,kw));return matches.length>=thresholds.high?{name,score:scores.high,signal:`${signalLabel} (${matches.slice(0,3).join(", ")})`}:matches.length>=thresholds.low?{name,score:scores.low,signal:`${signalLabel} (${matches.slice(0,3).join(", ")})`}:{name,score:scores.none,signal:null}}function scoreMultiStep(text){return[/first.*then/i,/step \d/i,/(?:^|\n)\s*\d+[.)]\s/].filter(p=>p.test(text)).length>0?{name:"multiStepPatterns",score:.5,signal:"multi-step"}:{name:"multiStepPatterns",score:0,signal:null}}function scoreQuestionComplexity(prompt){let count=(prompt.match(/[??]/g)||[]).length;return count>3?{name:"questionComplexity",score:.5,signal:`${count} questions`}:{name:"questionComplexity",score:0,signal:null}}function scoreAgenticTask(text,keywords){let matchCount=0,signals=[];for(let keyword of keywords)matchesKeyword(text,keyword)&&(matchCount++,signals.length<3&&signals.push(keyword));return matchCount>=4?{dimensionScore:{name:"agenticTask",score:1,signal:`agentic (${signals.join(", ")})`},agenticScore:1}:matchCount>=3?{dimensionScore:{name:"agenticTask",score:.6,signal:`agentic (${signals.join(", ")})`},agenticScore:.6}:matchCount>=1?{dimensionScore:{name:"agenticTask",score:.2,signal:`agentic-light (${signals.join(", ")})`},agenticScore:.2}:{dimensionScore:{name:"agenticTask",score:0,signal:null},agenticScore:0}}function classifyByRules(prompt,systemPrompt,estimatedTokens,config2){let userText=prompt.toLowerCase(),reasoningDimension=scoreKeywordMatch(userText,config2.reasoningKeywords,"reasoningMarkers","reasoning",{low:1,high:2},{none:0,low:.7,high:1}),dimensions=[scoreTokenCount(estimatedTokens,config2.tokenCountThresholds),scoreKeywordMatch(userText,config2.codeKeywords,"codePresence","code",{low:1,high:2},{none:0,low:.5,high:1}),reasoningDimension,scoreKeywordMatch(userText,config2.technicalKeywords,"technicalTerms","technical",{low:2,high:4},{none:0,low:.5,high:1}),scoreKeywordMatch(userText,config2.creativeKeywords,"creativeMarkers","creative",{low:1,high:2},{none:0,low:.5,high:.7}),scoreKeywordMatch(userText,config2.simpleKeywords,"simpleIndicators","simple",{low:1,high:2},{none:0,low:-1,high:-1}),scoreMultiStep(userText),scoreQuestionComplexity(prompt),scoreKeywordMatch(userText,config2.imperativeVerbs,"imperativeVerbs","imperative",{low:1,high:2},{none:0,low:.3,high:.5}),scoreKeywordMatch(userText,config2.constraintIndicators,"constraintCount","constraints",{low:1,high:3},{none:0,low:.3,high:.7}),scoreKeywordMatch(userText,config2.outputFormatKeywords,"outputFormat","format",{low:1,high:2},{none:0,low:.4,high:.7}),scoreKeywordMatch(userText,config2.referenceKeywords,"referenceComplexity","references",{low:1,high:2},{none:0,low:.3,high:.5}),scoreKeywordMatch(userText,config2.negationKeywords,"negationComplexity","negation",{low:2,high:3},{none:0,low:.3,high:.5}),scoreKeywordMatch(userText,config2.domainSpecificKeywords,"domainSpecificity","domain-specific",{low:1,high:2},{none:0,low:.5,high:.8})],agenticResult=scoreAgenticTask(userText,config2.agenticTaskKeywords);dimensions.push(agenticResult.dimensionScore);let agenticScore=agenticResult.agenticScore,signals=dimensions.filter(d=>d.signal!==null).map(d=>d.signal),weights=config2.dimensionWeights,weightedScore=0;for(let d of dimensions){let w=weights[d.name]??0;weightedScore+=d.score*w}if(reasoningDimension.score===1){let confidence2=calibrateConfidence(Math.max(weightedScore,.3),config2.confidenceSteepness);return{score:weightedScore,tier:"REASONING",confidence:Math.max(confidence2,.85),signals,agenticScore,dimensions}}let{simpleMedium,mediumComplex,complexReasoning}=config2.tierBoundaries,tier,distanceFromBoundary;weightedScore<simpleMedium?(tier="SIMPLE",distanceFromBoundary=simpleMedium-weightedScore):weightedScore<mediumComplex?(tier="MEDIUM",distanceFromBoundary=Math.min(weightedScore-simpleMedium,mediumComplex-weightedScore)):weightedScore<complexReasoning?(tier="COMPLEX",distanceFromBoundary=Math.min(weightedScore-mediumComplex,complexReasoning-weightedScore)):(tier="REASONING",distanceFromBoundary=weightedScore-complexReasoning);let confidence=calibrateConfidence(distanceFromBoundary,config2.confidenceSteepness);return confidence<config2.confidenceThreshold?{score:weightedScore,tier:null,confidence,signals,agenticScore,dimensions}:{score:weightedScore,tier,confidence,signals,agenticScore,dimensions}}function calibrateConfidence(distance,steepness){return 1/(1+Math.exp(-steepness*distance))}function usablePricing(pricing){if(!pricing)return;let ok=value=>value===void 0||Number.isFinite(value)&&value>=0;return pricing.flatPrice!==void 0?ok(pricing.flatPrice)?pricing:void 0:ok(pricing.inputPrice)&&ok(pricing.outputPrice)?pricing:void 0}function rawCost(pricing,estimatedInputTokens,maxOutputTokens){if(pricing?.flatPrice!==void 0)return pricing.flatPrice;let inputPrice=pricing?.inputPrice??0,outputPrice=pricing?.outputPrice??0;return estimatedInputTokens/1e6*inputPrice+maxOutputTokens/1e6*outputPrice}function baselineCostFor(modelPricing,estimatedInputTokens,maxOutputTokens){let opusPricing=usablePricing(modelPricing.get(BASELINE_MODEL_ID)),inputPrice=opusPricing?.inputPrice??BASELINE_INPUT_PRICE,outputPrice=opusPricing?.outputPrice??BASELINE_OUTPUT_PRICE;return estimatedInputTokens/1e6*inputPrice+maxOutputTokens/1e6*outputPrice}function savingsFor(costEstimate,baselineCost,pricing,routingProfile){return routingProfile==="premium"||pricing===void 0||!(baselineCost>0)?0:Math.max(0,(baselineCost-costEstimate)/baselineCost)}function selectModel(tier,confidence,method,reasoning,tierConfigs,modelPricing,estimatedInputTokens,maxOutputTokens,routingProfile,agenticScore){let model=tierConfigs[tier].primary,pricing=usablePricing(modelPricing.get(model)),costEstimate=rawCost(pricing,estimatedInputTokens,maxOutputTokens),baselineCost=baselineCostFor(modelPricing,estimatedInputTokens,maxOutputTokens),savings=savingsFor(costEstimate,baselineCost,pricing,routingProfile);return{model,tier,confidence,method,reasoning,costEstimate,baselineCost,savings,...agenticScore!==void 0&&{agenticScore}}}function getFallbackChain(tier,tierConfigs){let config2=tierConfigs[tier];return[config2.primary,...config2.fallback]}function calculateModelCost(model,modelPricing,estimatedInputTokens,maxOutputTokens,routingProfile){let pricing=usablePricing(modelPricing.get(model)),costEstimate=Math.max(rawCost(pricing,estimatedInputTokens,maxOutputTokens)*(1+SERVER_MARGIN_PERCENT/100),MIN_PAYMENT_USD),baselineCost=baselineCostFor(modelPricing,estimatedInputTokens,maxOutputTokens),savings=savingsFor(costEstimate,baselineCost,pricing,routingProfile);return{costEstimate,baselineCost,savings}}function keepOrFailOpen(models,keep){let filtered=models.filter(keep);return filtered.length>0?filtered:models}function filterByToolCalling(models,hasTools,supportsToolCalling){return hasTools?keepOrFailOpen(models,supportsToolCalling):models}function filterByVision(models,hasVision,supportsVision){return hasVision?keepOrFailOpen(models,supportsVision):models}function filterByExcludeList(models,excludeList){return excludeList.size===0?models:keepOrFailOpen(models,m=>!excludeList.has(m))}function getFallbackChainFiltered(tier,tierConfigs,estimatedTotalTokens,getContextWindow){let fullChain=getFallbackChain(tier,tierConfigs),filtered=fullChain.filter(modelId=>{let contextWindow=getContextWindow(modelId);return contextWindow===void 0?!0:contextWindow>=estimatedTotalTokens*1.1});return filtered.length===0?fullChain:filtered}function filterCandidatesByCapacity(models,estimatedInputTokens,requestedOutputTokens,getCapabilities2){return models.filter(modelId=>{let capabilities=getCapabilities2(modelId);return capabilities?capabilities.contextWindow>=(estimatedInputTokens+requestedOutputTokens)*1.1&&capabilities.maxOutput>=requestedOutputTokens:!0})}function estimateTokens(text){if(text.length===0)return 0;let cjk=text.match(CJK_CHARS)?.length??0;return cjk+Math.ceil((text.length-cjk)/4)}function scanLimit(promptTruncationChars){return Number.isFinite(promptTruncationChars)?Math.max(1,Math.min(MAX_SCAN_CHARS,Math.floor(promptTruncationChars))):MAX_SCAN_CHARS}function sampleForScan(value,limit){if(value.length<=limit)return value;let prefixLength=Math.ceil(limit/2),suffixLength=limit-prefixLength;return suffixLength<=0?value.slice(0,prefixLength):`${value.slice(0,prefixLength)}
|
|
2169
|
-
${value.slice(-suffixLength)}`}function applyPromotions(tierConfigs,promotions,profile,now2=new Date){if(!promotions||promotions.length===0)return tierConfigs;let result=tierConfigs;for(let promo of promotions){let start=Date.parse(promo.startDate),end=Date.parse(promo.endDate);if(!(!Number.isFinite(start)||!Number.isFinite(end))&&!(now2.getTime()<start||now2.getTime()>=end)&&!(promo.profiles&&!promo.profiles.includes(profile))){if(result===tierConfigs){result={...tierConfigs};for(let t of Object.keys(result))result[t]={...result[t]}}for(let[tier,override]of Object.entries(promo.tierOverrides))result[tier]&&(override.primary&&(result[tier].primary=override.primary),override.fallback&&(result[tier].fallback=override.fallback))}}return result}function applyUnavailableModels(tierConfigs,unavailableModels){if(!unavailableModels||unavailableModels.length===0)return tierConfigs;let dead=new Set(unavailableModels),result=tierConfigs;for(let tier of Object.keys(tierConfigs)){let config2=tierConfigs[tier],alive=[config2.primary,...config2.fallback].filter(model=>!dead.has(model));alive.length===0||alive[0]===config2.primary&&alive.length===config2.fallback.length+1||(result===tierConfigs&&(result={...tierConfigs}),result[tier]={primary:alive[0],fallback:alive.slice(1)})}return result}function getStrategy(name){let strategy=registry2.get(name);if(!strategy)throw new Error(`Unknown routing strategy: ${name}`);return strategy}function registerStrategy(strategy){registry2.set(strategy.name,strategy)}function inferToolRequirement(prompt,_systemPrompt,toolChoice){if(toolChoice==="none")return!1;if(toolChoice==="required"||typeof toolChoice=="object"&&toolChoice!==null&&toolChoice.type==="function")return!0;let text=prompt,explicitTool=/\b(?:use|call|invoke)\s+(?:the\s+)?[\w.-]+\s+(?:tool|function|api)\b|\btool[_ -]?call\b|使用.{0,20}(?:工具|函数|接口)|调用.{0,20}(?:工具|函数|接口)/i,codeEnvironment=/\b(?:run|execute)\s+(?:the\s+)?(?:tests?|command|script|build|linter)|\b(?:edit|modify|patch|create|write|save|delete|rename|move|inspect|read)\b.{0,60}\b(?:file|repository|repo|codebase|directory|folder)\b|\b(?:terminal|shell|bash|zsh|pytest|npm test|pnpm test|git\s+(?:status|diff|commit)|docker)\b|(?:运行|执行).{0,20}(?:测试|命令|脚本|构建)|(?:修改|编辑|修复|创建|读取|检查|保存).{0,30}(?:文件|仓库|代码库|目录)/i,webAction=/\b(?:browse|search|look up|fetch|open)\b.{0,80}\b(?:web|website|url|online|documentation|docs|news|weather|price)\b|(?:浏览|搜索|查询|打开).{0,30}(?:网页|网站|链接|文档|新闻|天气|价格)/i,statefulAction=/\b(?:refund|cancel|book|reserve|purchase|buy|return|exchange|transfer|update|change)\b.{0,80}\b(?:order|booking|reservation|account|address|payment|subscription|ticket|flight|item)\b|(?:退款|取消|预订|购买|退货|换货|转账|更新|修改).{0,30}(?:订单|预订|账户|地址|付款|订阅|票|航班|商品)/i;return explicitTool.test(text)||codeEnvironment.test(text)||webAction.test(text)||statefulAction.test(text)}function likelyNeedsParallelToolCalls(prompt,needsTools,toolCount,toolNames){if(!needsTools||toolCount===void 0||toolCount<1)return!1;let text=prompt.trim();if(/\b(?:in parallel|simultaneously|concurrently|for each|each of|every one|both|(?:two|three|multiple|several)\s+(?:cities|locations|items|tasks|orders|users|files))\b|并行|同时|分别|每个|各自|(?:两个|三个|多个)(?:城市|地点|项目|任务|订单|用户|文件)|cada uno|para cada|simult[aá]neamente/i.test(text))return!0;let sentenceClauses=text.split(/[.!?。!?]+/).map(part=>part.trim()).filter(part=>part.length>=8);if(/\b(?:also|additionally|furthermore)\b|另外|此外|그리고/i.test(text)&&sentenceClauses.length>=2||/\band\s+(?:also|for the)\b/i.test(text)||/\b\d+(?:\.\d+)?\s+(?:and|or)\s+\d+(?:\.\d+)?\s*(?:gb|mb|tb|kg|g|ml|oz|cups?|cores?|cpus?)\b/i.test(text))return!0;let operationTokens=new Set(["add","delete","remove","cancel","return","exchange","modify","book","transfer","send","upload","download","create","close"]),lowered=text.toLowerCase();if(new Set((toolNames??[]).flatMap(name=>name.toLowerCase().split(/[^a-z0-9\u3400-\u9fff]+/)).filter(token=>operationTokens.has(token)&&new RegExp(`\\b${token}(?:s|es|d|ed|ing)?\\b`).test(lowered))).size>=2)return!0;let nonEmptyLines=text.split(/\r?\n/).map(line=>line.trim()).filter(Boolean),quantityMentions=text.match(/\b(?:\d+(?:\.\d+)?|one|two|three|four|five|six|seven|eight|nine|ten)\s*(?:oz|ounce|ounces|g|gram|grams|kg|ml|cups?|pieces?|tablespoons?)\b/gi)??[];if(nonEmptyLines.length>=2&&quantityMentions.length>=2)return!0;let repeatedLookup=/\b(?:weather|climate|clima|tiempo|temperature|snow|news|report)\b|天气|气象|温度|降雪|新闻|报告/i.test(text),multiLocationConnector=/\b(?:and also|both)\b|\s(?:y|e)\s|还有|以及|和|、/i.test(text),commaSeparatedLocations=(text.match(/[,,]/g)??[]).length>=2;if(repeatedLookup&&(multiLocationConnector||commaSeparatedLocations))return!0;let distinctOrderParts=/\b(?:food|meal)\b[\s\S]*\bdrink\b|\bdrink\b[\s\S]*\b(?:food|meal)\b/i.test(text),koreanParallelClauses=(text.match(/,/g)??[]).length>=3&&/하고|그리고/.test(text);return distinctOrderParts||koreanParallelClauses}function classifyTask(prompt,systemPrompt,options){let fullText=`${systemPrompt??""} ${prompt}`,estimatedInputTokens=estimateTokens(fullText),limit=scanLimit(options.config.classifier.promptTruncationChars),scannedPrompt=sampleForScan(prompt,limit),scannedSystemPrompt=sampleForScan(systemPrompt??"",limit),scannedFullText=`${scannedSystemPrompt} ${scannedPrompt}`,text=scannedPrompt.toLowerCase(),explicitCodeSignal=/```|\b(?:typescript|javascript|python|rust|java|sql|stack trace|traceback|exception)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(scannedPrompt),codeConstructSignal=/\b(?:implement|refactor|debug|write|edit|modify|create|define|review|fix)\b[\s\S]{0,48}\b(?:api|function|class|method)\b|\b(?:api|function|class|method)\b[\s\S]{0,48}\b(?:code|implementation|typescript|javascript|python|rust|java)\b/i.test(scannedPrompt),nativeCodeSignal=/\b(?:programmed|written|implemented?|code)\s+(?:in|using)\s+(?:c\+\+|c|rust|go)\b/i.test(scannedPrompt),errorClassSignal=/\b[A-Z][A-Za-z]*(?:Error|Exception)\b/.test(scannedPrompt),hasCode=explicitCodeSignal||codeConstructSignal||nativeCodeSignal||errorClassSignal,codingAction=/\b(?:write|implement|refactor|debug|fix|patch|compile|build|run|test|script|program|code|function|class|module|repo(?:sitory)?)\b|编写|实现|重构|调试|修复|编译|脚本|代码/i.test(scannedPrompt),codeArtifact=/```|\b(?:stack trace|traceback)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(scannedPrompt)||codeConstructSignal||nativeCodeSignal||errorClassSignal,toolsAvailable=options.hasTools??!1,needsTools=options.requiresTools??(toolsAvailable&&inferToolRequirement(scannedPrompt,scannedSystemPrompt)),likelyParallelToolCalls=likelyNeedsParallelToolCalls(scannedPrompt,needsTools,options.toolCount,options.toolNames),normalizedToolNames=(options.toolNames??[]).map(name=>name.toLowerCase()),airlineToolSignal=normalizedToolNames.some(name=>/(?:flight|reservation|airport|baggage|passenger)/.test(name)),retailToolSignal=normalizedToolNames.some(name=>/(?:order|product|item|return|exchange|address)/.test(name)),webResearchToolSignal=normalizedToolNames.some(name=>/^(?:web_?search|web_?fetch)$/.test(name)),agentDomain=airlineToolSignal&&!retailToolSignal?"airline":retailToolSignal&&!airlineToolSignal?"retail":webResearchToolSignal?"web_research":"other",clueConnectors=scannedFullText.match(/\b(?:after|before|while|where|whose|which|in \d{4}|as of|over \d+|another|also|furthermore)\b|(?:之后|之前|其中|截至|超过|另一个|此外)/gi)??[],entityResolutionSignal=/\b(?:identify|who (?:is|was)|what (?:is|was) the name|which (?:person|player|company|country|city)|find the (?:person|player|name|entity))\b|(?:找出|识别|是谁|哪位|名称是什么)/i.test(scannedFullText),exactAnswerSignal=/\b(?:exact answer|single best-supported answer|following clues|multiple public sources)\b|(?:精确答案|根据.*线索|多个公开来源)/i.test(scannedFullText),deepWebResearch=agentDomain==="web_research"&&(exactAnswerSignal||entityResolutionSignal&&(clueConnectors.length>=3||prompt.length>=320)),globalOptimizationSignal=/\b(?:cheapest|lowest[- ]price|least expensive|most expensive|highest(?:[- ]priced)?|largest|smallest|maximum|minimum|best available|closest|not (?:cost|exceed))\b|最便宜|最低价|最贵|最高价|最大|最小/i.test(scannedPrompt),globalScopeSignal=/\b(?:everything|all (?:(?:my|your|their|the) )?(?:future |upcoming )?(?:items|orders|passengers|flights|reservations|bookings)|every (?:item|order|passenger|flight|reservation|booking))\b|全部|所有|每个/i.test(scannedPrompt),globalChoiceSignal=globalOptimizationSignal||globalScopeSignal,crossRecordSignal=/\b(?:another|other|different|previous)\s+(?:order|reservation|booking|account|address)\b|另一(?:个)?(?:订单|预订|账户|地址)|其他(?:订单|预订|账户|地址)/i.test(scannedPrompt),reservationIds=scannedPrompt.match(/\b(?=[A-Z0-9]*\d)(?=[A-Z0-9]*[A-Z])[A-Z0-9]{6}\b/g)??[],crossReservationBatchSignal=agentDomain==="airline"&&(/\b(?:two|three|multiple|several)(?:\s+of\s+(?:my|our|the))?\s+(?:upcoming\s+)?(?:reservations?|bookings?)\b|\b(?:a\s+)?(?:second|third)\s+(?:reservation|booking)\b/i.test(scannedPrompt)||new Set(reservationIds).size>=2),conditionalGlobalWorkflowSignal=agentDomain==="airline"&&globalScopeSignal&&/\b(?:if|that (?:contain|have)|longer than|shorter than|under|over|at (?:most|least)|wherever possible)\b|如果|超过|少于|不超过|尽可能/i.test(scannedPrompt)&&/\b(?:cancel|change|upgrade|move|book)\b[\s\S]*\b(?:cancel|change|upgrade|move|book)\b|取消[\s\S]*(?:升级|更改)|升级[\s\S]*(?:取消|更改)/i.test(scannedPrompt),policyExceptionSignal=agentDomain==="retail"&&/\b(?:return|refund|send back|get (?:my |the )?money back)\b|退货|退款|退回/i.test(scannedPrompt)&&/\b(?:amex|american express|visa|mastercard|credit card|debit card|different card|another card|other card)\b|信用卡|借记卡|其他卡|另一张卡/i.test(scannedPrompt),singleSelectedPolicyException=policyExceptionSignal&&/\b(?:return|refund|send back)\b[^.!?。!?]{0,96}\b(?:the )?(?:pricier|cheaper|more expensive|less expensive|costlier|one)\b/i.test(scannedPrompt),negotiatedWorkflowSignal=agentDomain==="retail"&&/\b(?:return|exchange)\b|退货|退回|换货|交换/i.test(scannedPrompt),numberedSteps=(scannedPrompt.match(/(?:^|\s)\d+(?:\.\d+)*[.)]\s+/g)??[]).length,complexMultiToolPlan=likelyParallelToolCalls&&((options.toolCount??0)>=6||numberedSteps>=3||prompt.length>1200),agentRisk=needsTools&&singleSelectedPolicyException?"policy_exception_simple":needsTools&&policyExceptionSignal?"policy_exception":needsTools&&agentDomain==="airline"&&(globalOptimizationSignal||conditionalGlobalWorkflowSignal)?"complex_high":needsTools&&(likelyParallelToolCalls||globalChoiceSignal||crossRecordSignal||crossReservationBatchSignal||negotiatedWorkflowSignal)?"high":"standard",needsVision=options.hasVision??!1,needsStructuredOutput=options.requiresStructuredOutput??!1,latencySensitive=/\b(?:urgent|asap|fast|quick|low latency|real[- ]time)\b|尽快|马上|快速|低延迟/i.test(scannedPrompt),highStakes=/\b(?:production|security|payment|legal|medical|financial|audit)\b|生产|安全|支付|法律|医疗|财务|审计/i.test(scannedPrompt),terminalToolSignal=normalizedToolNames.some(name=>/^(?:terminalexec|terminalinspect|terminalsendkeys)$/.test(name)),simpleTerminalArtifact=/\b(?:create|write|convert|generate|build|implement|run|fix|repair|debug|make)\b[\s\S]{0,120}\b(?:file|script|csv|parquet|json|txt|server|endpoint)\b/i.test(scannedPrompt),terminalComplexRepair=terminalToolSignal&&/\b(?:multiple|several)\s+(?:scripts?|files?|components?)\b|\b(?:pipeline|dependencies)\b[\s\S]{0,100}\b(?:fail|issue|fix|repair|run|execute)\b|\b(?:identify|find|fix|repair)\s+(?:and\s+)?(?:fix\s+)?all\s+(?:the\s+)?issues\b/i.test(scannedPrompt),mentionedTerminalRuntimes=new Set((scannedPrompt.match(/\b(?:gcc|clang|rustc|javac|go\s+build|node|python)\b/gi)??[]).map(name=>name.toLowerCase().replace(/\s+/g," "))),terminalCrossRuntimeArtifact=terminalToolSignal&&(/\bpolyglot\b/i.test(scannedPrompt)||/\b(?:both|each)\b[\s\S]{0,120}\b(?:compilers?|runtimes?|toolchains?)\b/i.test(scannedPrompt)||mentionedTerminalRuntimes.size>=2&&/\b(?:compile|build|run|execute)\b/i.test(scannedPrompt)),terminalFrameworkToNativeArtifact=terminalToolSignal&&/\b(?:pytorch|tensorflow|jax|onnx|state[_ -]?dict|checkpoint|safetensors?)\b|\.(?:pth|pt|onnx)\b/i.test(scannedPrompt)&&/\b(?:pure|native|programmed|written|implemented?)\s+(?:in|using)\s+(?:c\+\+|c|rust|go)\b|\b(?:c\+\+|c|rust|go)\s+(?:program|binary|executable|cli|tool|implementation)\b/i.test(scannedPrompt)&&/\b(?:inference|model|weights?|tensor|export|convert|load)\b/i.test(scannedPrompt);needsTools&&(terminalComplexRepair||terminalCrossRuntimeArtifact||terminalFrameworkToNativeArtifact)&&(agentRisk==="standard"||agentRisk==="high")&&(agentRisk="complex_high");let complexTerminalOperation=/\b(?:git|ssh|nginx|https|certificate|authentication|credential|deploy|production|encrypt|gpg|shred|securely delete|decommission|benchmark|evaluate|embedding|chess|image|search the web|schema|statistical|statistics|aggregate|join|multiple inputs?)\b/i.test(scannedPrompt),terminalCredentialSignal=/\b(?:ssh|nginx|certificate|authentication|credentials?|passwords?|api keys?|deploy|production|encrypt|gpg|shred|securely delete|decommission)\b/i.test(scannedPrompt)||/\b(?:access|auth|authentication|bearer|secret|api)\s+tokens?\b|\btokens?\s+(?:secret|credential|authentication)\b/i.test(scannedPrompt),terminalSafetySensitive=terminalToolSignal&&(highStakes||terminalCredentialSignal),implicitTerminalCode=needsTools&&terminalToolSignal&&agentRisk==="standard"&&!highStakes&&!complexTerminalOperation&&numberedSteps<3&&prompt.length<=1e3&&simpleTerminalArtifact,language=/[\u3400-\u9fff]/.test(scannedPrompt)&&!/[\u3040-\u30ff]/.test(scannedPrompt)?"zh":"other",multipleChoiceSignals=(scannedPrompt.match(/(?:^|\n)\s*[A-D][.)]\s+/gim)??[]).length,numericSignals=(scannedPrompt.match(/-?\d+(?:[.,]\d+)?/g)??[]).length,compactMathProblem=!hasCode&&prompt.length<2500&&numericSignals>=2&&(/[+×÷=%$€£¥]|\b(?:total|each|per|times|half|twice|percent|how many|how much|calculate)\b/i.test(scannedPrompt)||/[??]\s*$/.test(scannedPrompt.trim())||numericSignals>=3),taskType="chat";return needsVision?taskType="vision":estimatedInputTokens>8e4?taskType="long_context":needsTools&&(codeArtifact||hasCode&&codingAction||implicitTerminalCode)?taskType="code_agent":needsTools&&likelyParallelToolCalls&&!complexMultiToolPlan?taskType="tool_agent_parallel":needsTools?taskType="tool_agent":multipleChoiceSignals>=3?taskType="reasoning_mcq":compactMathProblem?taskType="reasoning_math":errorClassSignal||/\b(?:bug|debug|error|failure|failing|regression|crash)\b|修复|报错|错误|调试/i.test(text)?taskType="debug":hasCode||/\b(?:refactor|implement|patch|edit|rewrite)\b|重构|实现|修改/i.test(text)?taskType="code_edit":needsStructuredOutput||/\b(?:extract|json|schema|csv)\b|字段|提取/i.test(text)?taskType="extraction":/\b(?:prove|derive|theorem|formal|mathematical|reasoning)\b|证明|推导|定理|数学/i.test(text)&&(taskType="reasoning"),{taskType,estimatedInputTokens,hasCode,needsTools,toolsAvailable,needsVision,needsStructuredOutput,latencySensitive,highStakes,language,likelyParallelToolCalls,complexMultiToolPlan,agentDomain,deepWebResearch,agentRisk,terminalToolSignal,terminalSafetySensitive,implicitTerminalCode,codeArtifact}}function affinityBand(features){let{taskType,agentDomain,agentRisk,deepWebResearch,terminalToolSignal}=features,terminalSafety=features.terminalSafetySensitive;switch(taskType){case"code_agent":return terminalToolSignal&&agentRisk==="complex_high"?TERMINAL_COMPLEX_HIGH:AFFINITY.codeAgent;case"tool_agent":return terminalToolSignal&&agentRisk==="complex_high"?TERMINAL_COMPLEX_HIGH:terminalToolSignal?terminalSafety?AFFINITY.terminalToolSafety:AFFINITY.terminalTool:agentDomain==="web_research"?deepWebResearch?WEB_RESEARCH_DEEP:WEB_RESEARCH:agentDomain==="retail"?agentRisk==="standard"?AFFINITY.retailStandard:agentRisk==="policy_exception"?RETAIL_POLICY_EXCEPTION:agentRisk==="policy_exception_simple"?RETAIL_POLICY_EXCEPTION_SIMPLE:AFFINITY.retailHigh:agentDomain==="airline"?agentRisk==="complex_high"?AFFINITY.airlineComplex:AFFINITY.airlineStandard:AFFINITY.toolAgent;case"tool_agent_parallel":return terminalToolSignal?terminalSafety?AFFINITY.parallelTerminalSafety:AFFINITY.parallelTerminal:agentDomain==="web_research"?deepWebResearch?WEB_RESEARCH_DEEP:WEB_RESEARCH:agentDomain==="retail"?agentRisk==="policy_exception"?RETAIL_POLICY_EXCEPTION:agentRisk==="policy_exception_simple"?RETAIL_POLICY_EXCEPTION_SIMPLE:AFFINITY.parallelRetail:agentDomain==="airline"?agentRisk==="complex_high"?AFFINITY.parallelAirlineComplex:AFFINITY.parallelAirline:AFFINITY.parallel;case"code_edit":case"debug":return AFFINITY.codeEdit;case"reasoning":return AFFINITY.reasoning;case"reasoning_mcq":return AFFINITY.reasoningMcq;case"reasoning_math":return AFFINITY.reasoningMath;case"vision":return AFFINITY.vision;case"long_context":return AFFINITY.longContext;case"extraction":return features.language==="zh"?AFFINITY.extractionZh:AFFINITY.extraction;case"chat":return AFFINITY.chat}}function affinityIn(band,modelId){let name=modelId.toLowerCase().slice(modelId.indexOf("/")+1);return Math.max(NEUTRAL_AFFINITY,band[name]??0)}function evidenceCandidates(task){return task==="code_agent"?["openai/gpt-5.3-codex","anthropic/claude-sonnet-5","openai/gpt-5.6-luna","google/gemini-3.6-flash","moonshot/kimi-k3.1-pro","deepseek/deepseek-v4-pro"]:task==="tool_agent"?["anthropic/claude-sonnet-5","anthropic/claude-opus-5","openai/gpt-5.6-luna","openai/gpt-4.1","openai/gpt-4o-mini","google/gemini-3.6-flash","openai/gpt-5.3-codex","moonshot/kimi-k3.1-pro","deepseek/deepseek-v4-pro"]:task==="tool_agent_parallel"?["anthropic/claude-opus-5","anthropic/claude-opus-4.8","anthropic/claude-sonnet-5","openai/gpt-5.6-luna","openai/gpt-4.1","openai/gpt-4o-mini","xai/grok-4.5","google/gemini-3.6-flash","deepseek/deepseek-v4-pro"]:task==="long_context"?["google/gemini-3.1-pro","deepseek/deepseek-v4-pro","qwen/qwen3.7-max","zai/glm-5.2","google/gemini-3.6-flash"]:task==="reasoning_mcq"?["google/gemini-3-flash-preview","google/gemini-3.6-flash","xai/grok-4.5","anthropic/claude-sonnet-5","deepseek/deepseek-v4-pro"]:task==="extraction"?["moonshot/kimi-k3.1-pro","google/gemini-3.6-flash","anthropic/claude-sonnet-5"]:task==="reasoning_math"?["google/gemini-3.6-flash","xai/grok-4.5","anthropic/claude-sonnet-5","deepseek/deepseek-v4-pro","moonshot/kimi-k3.1-pro"]:[]}function isEligible(modelId,features,maxOutputTokens,options){let model=options.modelCapabilities?.[modelId]??DEFAULT_MODEL_CAPABILITIES[modelId];return model?features.needsTools&&!model.supportsTools||features.needsVision&&!model.supportsVision||features.needsStructuredOutput&&!model.supportsTools||model.maxOutputTokens<maxOutputTokens?!1:model.contextWindow>=(features.estimatedInputTokens+maxOutputTokens)*1.1:!0}function estimatedCost(modelId,options,inputTokens,outputTokens){let price2=usablePricing(options.modelPricing.get(modelId));return price2?price2.flatPrice!==void 0?price2.flatPrice:(inputTokens*price2.inputPrice+outputTokens*price2.outputPrice)/1e6:Number.POSITIVE_INFINITY}function profileScore(modelId,options,now2){let profile=options.modelPerformance?.[modelId]??LIVE_MODEL_PROFILES[modelId]??HISTORICAL_MODEL_PROFILES[modelId];if(!profile)return;let measuredAt=Date.parse(profile.measuredAt);if(!Number.isFinite(measuredAt))return;let finite=(value,optional2)=>value===void 0?optional2:Number.isFinite(value)&&value>=0;if(!finite(profile.latencyMs,!1)||!finite(profile.outputTokensPerSecond,!1)||!finite(profile.p95LatencyMs,!0)||!finite(profile.intelligenceIndex,!0)||!finite(profile.errorRate,!0)||!finite(profile.samples,!0))return;let ageDays=Math.max(0,(now2.getTime()-measuredAt)/864e5),sampleConfidence=profile.samples===void 0?1:Math.min(1,Math.max(0,profile.samples)/10),freshness=Math.pow(.5,ageDays/30)*sampleConfidence,quality=profile.intelligenceIndex===void 0?void 0:Math.min(1,profile.intelligenceIndex/50),speed=Math.min(1,(2e3/Math.max(500,profile.latencyMs)+profile.outputTokensPerSecond/250)/2),tailSpeed=Math.min(1,3e3/Math.max(750,profile.p95LatencyMs??profile.latencyMs)),reliability=Math.max(0,1-(profile.errorRate??0));return{quality,speed,tailSpeed,reliability,freshness}}function route(prompt,systemPrompt,maxOutputTokens,options){return getStrategy(options.config.strategy??"portfolio").route(prompt,systemPrompt,maxOutputTokens,options)}var UNSEGMENTED_SCRIPT,WORD_CHAR,ASCII_PHRASE,SEGMENTED_WORD_CHAR,BOUNDARY_BEFORE,BOUNDARY_AFTER,BOUNDED_LAST_WORD_LENGTH,SHORT_SUFFIXES,SIBILANT_PLURAL,MID_SUFFIXES,DROPPED_E_SUFFIXES,DOUBLED_CONSONANT_SUFFIXES,matcherCache,BASELINE_MODEL_ID,BASELINE_INPUT_PRICE,BASELINE_OUTPUT_PRICE,SERVER_MARGIN_PERCENT,MIN_PAYMENT_USD,CJK_CHARS,MAX_SCAN_CHARS,RulesStrategy,registry2,DEFAULT_ROUTING_CONFIG,DEFAULT_MODEL_CAPABILITIES,model_profiles_generated_default,LIVE_MODEL_PROFILES,HISTORICAL_MODEL_PROFILES,DEFAULT_PORTFOLIO_WEIGHTS,NEUTRAL_AFFINITY,TERMINAL_COMPLEX_HIGH,WEB_RESEARCH_DEEP,WEB_RESEARCH,RETAIL_POLICY_EXCEPTION,RETAIL_POLICY_EXCEPTION_SIMPLE,AFFINITY,VERIFIED_TOOL_FALLBACKS,PortfolioStrategy,init_dist=__esm({"node_modules/@blockrun/router-core/dist/index.js"(){"use strict";UNSEGMENTED_SCRIPT=/[-ۿ -ヿ㐀-䶿一-鿿가-豈--]/,WORD_CHAR=/[\p{L}\p{N}]/u,ASCII_PHRASE=/^[a-z0-9' -]+$/,SEGMENTED_WORD_CHAR="\\p{Script=Latin}\\p{Script=Cyrillic}\\p{Script=Greek}\\p{N}",BOUNDARY_BEFORE=`(?<![${SEGMENTED_WORD_CHAR}])`,BOUNDARY_AFTER=`(?![${SEGMENTED_WORD_CHAR}])`,BOUNDED_LAST_WORD_LENGTH=6,SHORT_SUFFIXES="(?:s|ed|ing)?",SIBILANT_PLURAL="es",MID_SUFFIXES="(?:s|es|ed|d|ing|er|ers|ly|ment|ments|ation|ations|e|en|n|a|as|o|os|em|et|ung|ungen)?",DROPPED_E_SUFFIXES="(?:ing|ed|es|er|ers|ation|ations)",DOUBLED_CONSONANT_SUFFIXES="(?:ing|ed|er|ers)",matcherCache=new Map;BASELINE_MODEL_ID="anthropic/claude-opus-4.7",BASELINE_INPUT_PRICE=5,BASELINE_OUTPUT_PRICE=25;SERVER_MARGIN_PERCENT=5,MIN_PAYMENT_USD=.001;CJK_CHARS=/[ -ヿ㐀-䶿一-鿿가-豈--]/g;MAX_SCAN_CHARS=8e3;RulesStrategy=class{name="rules";route(prompt,systemPrompt,maxOutputTokens,options){let{config:config2,modelPricing}=options,fullText=`${systemPrompt??""} ${prompt}`,estimatedTokens=estimateTokens(fullText),limit=scanLimit(config2.classifier.promptTruncationChars),scannedPrompt=sampleForScan(prompt,limit),scannedSystemPrompt=systemPrompt?sampleForScan(systemPrompt,limit):void 0,ruleResult=classifyByRules(scannedPrompt,scannedSystemPrompt,estimatedTokens,config2.scoring),{routingProfile}=options,tierConfigs,profileSuffix,profile;if(routingProfile==="eco")tierConfigs=config2.ecoTiers??config2.tiers,profileSuffix=config2.ecoTiers?" | eco":" | eco (default tiers)",profile="eco";else if(routingProfile==="premium")tierConfigs=config2.premiumTiers??config2.tiers,profileSuffix=config2.premiumTiers?" | premium":" | premium (default tiers)",profile="premium";else{let isAutoAgentic=(ruleResult.agenticScore??0)>=.5,agenticModeSetting=config2.overrides.agenticMode,hasToolsInRequest=options.requiresTools??options.hasTools??!1,useAgenticTiers;agenticModeSetting===!1?useAgenticTiers=!1:agenticModeSetting===!0?useAgenticTiers=config2.agenticTiers!=null:useAgenticTiers=(hasToolsInRequest||isAutoAgentic)&&config2.agenticTiers!=null,tierConfigs=useAgenticTiers?config2.agenticTiers:config2.tiers,profileSuffix=useAgenticTiers?` | agentic${hasToolsInRequest?" (tools)":""}`:"",profile=useAgenticTiers?"agentic":"auto"}tierConfigs=applyPromotions(tierConfigs,config2.promotions,profile,options.now),tierConfigs=applyUnavailableModels(tierConfigs,options.unavailableModels);let agenticScoreValue=ruleResult.agenticScore;if(estimatedTokens>config2.overrides.maxTokensForceComplex)return{...selectModel("COMPLEX",.95,"rules",`Input exceeds ${config2.overrides.maxTokensForceComplex} tokens${profileSuffix}`,tierConfigs,modelPricing,estimatedTokens,maxOutputTokens,routingProfile,agenticScoreValue),tierConfigs,profile};let hasStructuredOutput=options.requiresStructuredOutput===!0,tier,confidence,method="rules",reasoning=`score=${ruleResult.score.toFixed(2)} | ${ruleResult.signals.join(", ")}`;if(ruleResult.tier!==null?(tier=ruleResult.tier,confidence=ruleResult.confidence):(tier=config2.overrides.ambiguousDefaultTier,confidence=.5,reasoning+=` | ambiguous -> default: ${tier}`),hasStructuredOutput){let tierRank={SIMPLE:0,MEDIUM:1,COMPLEX:2,REASONING:3},minTier=config2.overrides.structuredOutputMinTier;tierRank[tier]<tierRank[minTier]&&(reasoning+=` | upgraded to ${minTier} (structured output)`,tier=minTier)}return reasoning+=profileSuffix,{...selectModel(tier,confidence,method,reasoning,tierConfigs,modelPricing,estimatedTokens,maxOutputTokens,routingProfile,agenticScoreValue),tierConfigs,profile}}},registry2=new Map;registry2.set("rules",new RulesStrategy);DEFAULT_ROUTING_CONFIG={version:"3.5",strategy:"portfolio",portfolio:{auto:{quality:.47,capability:.2,cost:.18,speed:.07,reliability:.03,legacy:.05},eco:{quality:.36,capability:.2,cost:.28,speed:.1,reliability:.04,legacy:.02},premium:{quality:.58,capability:.2,cost:.08,speed:.06,reliability:.06,legacy:.02},highStakesBoost:{quality:.08,reliability:.05},latencySensitiveSpeedBoost:.08,affinityFloorGap:{auto:.1,eco:.22,premium:.05}},classifier:{llmModel:"google/gemini-3.5-flash-lite",llmMaxTokens:10,llmTemperature:0,promptTruncationChars:500,cacheTtlMs:36e5},scoring:{tokenCountThresholds:{simple:50,complex:500},codeKeywords:["function","class","import","def","SELECT","async","await","const","let","var","return","```","\u51FD\u6570","\u7C7B","\u5BFC\u5165","\u5B9A\u4E49","\u67E5\u8BE2","\u5F02\u6B65","\u7B49\u5F85","\u5E38\u91CF","\u53D8\u91CF","\u8FD4\u56DE","\u95A2\u6570","\u30AF\u30E9\u30B9","\u30A4\u30F3\u30DD\u30FC\u30C8","\u975E\u540C\u671F","\u5B9A\u6570","\u5909\u6570","\u0444\u0443\u043D\u043A\u0446\u0438\u044F","\u043A\u043B\u0430\u0441\u0441","\u0438\u043C\u043F\u043E\u0440\u0442","\u043E\u043F\u0440\u0435\u0434\u0435\u043B","\u0437\u0430\u043F\u0440\u043E\u0441","\u0430\u0441\u0438\u043D\u0445\u0440\u043E\u043D\u043D\u044B\u0439","\u043E\u0436\u0438\u0434\u0430\u0442\u044C","\u043A\u043E\u043D\u0441\u0442\u0430\u043D\u0442\u0430","\u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F","\u0432\u0435\u0440\u043D\u0443\u0442\u044C","funktion","klasse","importieren","definieren","abfrage","asynchron","erwarten","konstante","variable","zur\xFCckgeben","funci\xF3n","clase","importar","definir","consulta","as\xEDncrono","esperar","constante","variable","retornar","fun\xE7\xE3o","classe","importar","definir","consulta","ass\xEDncrono","aguardar","constante","vari\xE1vel","retornar","\uD568\uC218","\uD074\uB798\uC2A4","\uAC00\uC838\uC624\uAE30","\uC815\uC758","\uCFFC\uB9AC","\uBE44\uB3D9\uAE30","\uB300\uAE30","\uC0C1\uC218","\uBCC0\uC218","\uBC18\uD658","\u062F\u0627\u0644\u0629","\u0641\u0626\u0629","\u0627\u0633\u062A\u064A\u0631\u0627\u062F","\u062A\u0639\u0631\u064A\u0641","\u0627\u0633\u062A\u0639\u0644\u0627\u0645","\u063A\u064A\u0631 \u0645\u062A\u0632\u0627\u0645\u0646","\u0627\u0646\u062A\u0638\u0627\u0631","\u062B\u0627\u0628\u062A","\u0645\u062A\u063A\u064A\u0631","\u0625\u0631\u062C\u0627\u0639"],reasoningKeywords:["prove","theorem","derive","step by step","chain of thought","formally","mathematical","proof","logically","\u8BC1\u660E","\u5B9A\u7406","\u63A8\u5BFC","\u9010\u6B65","\u601D\u7EF4\u94FE","\u5F62\u5F0F\u5316","\u6570\u5B66","\u903B\u8F91","\u8A3C\u660E","\u5B9A\u7406","\u5C0E\u51FA","\u30B9\u30C6\u30C3\u30D7\u30D0\u30A4\u30B9\u30C6\u30C3\u30D7","\u8AD6\u7406\u7684","\u0434\u043E\u043A\u0430\u0437\u0430\u0442\u044C","\u0434\u043E\u043A\u0430\u0436\u0438","\u0434\u043E\u043A\u0430\u0437\u0430\u0442\u0435\u043B\u044C\u0441\u0442\u0432","\u0442\u0435\u043E\u0440\u0435\u043C\u0430","\u0432\u044B\u0432\u0435\u0441\u0442\u0438","\u0448\u0430\u0433 \u0437\u0430 \u0448\u0430\u0433\u043E\u043C","\u043F\u043E\u0448\u0430\u0433\u043E\u0432\u043E","\u043F\u043E\u044D\u0442\u0430\u043F\u043D\u043E","\u0446\u0435\u043F\u043E\u0447\u043A\u0430 \u0440\u0430\u0441\u0441\u0443\u0436\u0434\u0435\u043D\u0438\u0439","\u0440\u0430\u0441\u0441\u0443\u0436\u0434\u0435\u043D\u0438","\u0444\u043E\u0440\u043C\u0430\u043B\u044C\u043D\u043E","\u043C\u0430\u0442\u0435\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438","\u043B\u043E\u0433\u0438\u0447\u0435\u0441\u043A\u0438","beweisen","beweis","theorem","ableiten","schritt f\xFCr schritt","gedankenkette","formal","mathematisch","logisch","demostrar","teorema","derivar","paso a paso","cadena de pensamiento","formalmente","matem\xE1tico","prueba","l\xF3gicamente","provar","teorema","derivar","passo a passo","cadeia de pensamento","formalmente","matem\xE1tico","prova","logicamente","\uC99D\uBA85","\uC815\uB9AC","\uB3C4\uCD9C","\uB2E8\uACC4\uBCC4","\uC0AC\uACE0\uC758 \uC5F0\uC1C4","\uD615\uC2DD\uC801","\uC218\uD559\uC801","\uB17C\uB9AC\uC801","\u0625\u062B\u0628\u0627\u062A","\u0646\u0638\u0631\u064A\u0629","\u0627\u0634\u062A\u0642\u0627\u0642","\u062E\u0637\u0648\u0629 \u0628\u062E\u0637\u0648\u0629","\u0633\u0644\u0633\u0644\u0629 \u0627\u0644\u062A\u0641\u0643\u064A\u0631","\u0631\u0633\u0645\u064A\u0627\u064B","\u0631\u064A\u0627\u0636\u064A","\u0628\u0631\u0647\u0627\u0646","\u0645\u0646\u0637\u0642\u064A\u0627\u064B"],simpleKeywords:["what is","define","translate","hello","yes or no","capital of","how old","who is","when was","\u4EC0\u4E48\u662F","\u5B9A\u4E49","\u7FFB\u8BD1","\u4F60\u597D","\u662F\u5426","\u9996\u90FD","\u591A\u5927","\u8C01\u662F","\u4F55\u65F6","\u3068\u306F","\u5B9A\u7FA9","\u7FFB\u8A33","\u3053\u3093\u306B\u3061\u306F","\u306F\u3044\u304B\u3044\u3044\u3048","\u9996\u90FD","\u8AB0","\u0447\u0442\u043E \u0442\u0430\u043A\u043E\u0435","\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435","\u043F\u0435\u0440\u0435\u0432\u0435\u0441\u0442\u0438","\u043F\u0435\u0440\u0435\u0432\u0435\u0434\u0438","\u043F\u0440\u0438\u0432\u0435\u0442","\u0434\u0430 \u0438\u043B\u0438 \u043D\u0435\u0442","\u0441\u0442\u043E\u043B\u0438\u0446\u0430","\u0441\u043A\u043E\u043B\u044C\u043A\u043E \u043B\u0435\u0442","\u043A\u0442\u043E \u0442\u0430\u043A\u043E\u0439","\u043A\u043E\u0433\u0434\u0430","\u043E\u0431\u044A\u044F\u0441\u043D\u0438","was ist","definiere","\xFCbersetze","hallo","ja oder nein","hauptstadt","wie alt","wer ist","wann","erkl\xE4re","qu\xE9 es","definir","traducir","hola","s\xED o no","capital de","cu\xE1ntos a\xF1os","qui\xE9n es","cu\xE1ndo","o que \xE9","definir","traduzir","ol\xE1","sim ou n\xE3o","capital de","quantos anos","quem \xE9","quando","\uBB34\uC5C7","\uC815\uC758","\uBC88\uC5ED","\uC548\uB155\uD558\uC138\uC694","\uC608 \uB610\uB294 \uC544\uB2C8\uC624","\uC218\uB3C4","\uB204\uAD6C","\uC5B8\uC81C","\u0645\u0627 \u0647\u0648","\u062A\u0639\u0631\u064A\u0641","\u062A\u0631\u062C\u0645","\u0645\u0631\u062D\u0628\u0627","\u0646\u0639\u0645 \u0623\u0648 \u0644\u0627","\u0639\u0627\u0635\u0645\u0629","\u0645\u0646 \u0647\u0648","\u0645\u062A\u0649"],technicalKeywords:["algorithm","optimize","architecture","distributed","kubernetes","microservice","database","infrastructure","\u7B97\u6CD5","\u4F18\u5316","\u67B6\u6784","\u5206\u5E03\u5F0F","\u5FAE\u670D\u52A1","\u6570\u636E\u5E93","\u57FA\u7840\u8BBE\u65BD","\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0","\u6700\u9069\u5316","\u30A2\u30FC\u30AD\u30C6\u30AF\u30C1\u30E3","\u5206\u6563","\u30DE\u30A4\u30AF\u30ED\u30B5\u30FC\u30D3\u30B9","\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9","\u0430\u043B\u0433\u043E\u0440\u0438\u0442\u043C","\u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u0442\u044C","\u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0430\u0446\u0438","\u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0438\u0440\u0443\u0439","\u0430\u0440\u0445\u0438\u0442\u0435\u043A\u0442\u0443\u0440\u0430","\u0440\u0430\u0441\u043F\u0440\u0435\u0434\u0435\u043B\u0451\u043D\u043D\u044B\u0439","\u043C\u0438\u043A\u0440\u043E\u0441\u0435\u0440\u0432\u0438\u0441","\u0431\u0430\u0437\u0430 \u0434\u0430\u043D\u043D\u044B\u0445","\u0438\u043D\u0444\u0440\u0430\u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0430","algorithmus","optimieren","architektur","verteilt","kubernetes","mikroservice","datenbank","infrastruktur","algoritmo","optimizar","arquitectura","distribuido","microservicio","base de datos","infraestructura","algoritmo","otimizar","arquitetura","distribu\xEDdo","microsservi\xE7o","banco de dados","infraestrutura","\uC54C\uACE0\uB9AC\uC998","\uCD5C\uC801\uD654","\uC544\uD0A4\uD14D\uCC98","\uBD84\uC0B0","\uB9C8\uC774\uD06C\uB85C\uC11C\uBE44\uC2A4","\uB370\uC774\uD130\uBCA0\uC774\uC2A4","\uC778\uD504\uB77C","\u062E\u0648\u0627\u0631\u0632\u0645\u064A\u0629","\u062A\u062D\u0633\u064A\u0646","\u0628\u0646\u064A\u0629","\u0645\u0648\u0632\u0639","\u062E\u062F\u0645\u0629 \u0645\u0635\u063A\u0631\u0629","\u0642\u0627\u0639\u062F\u0629 \u0628\u064A\u0627\u0646\u0627\u062A","\u0628\u0646\u064A\u0629 \u062A\u062D\u062A\u064A\u0629"],creativeKeywords:["story","poem","compose","brainstorm","creative","imagine","write a","\u6545\u4E8B","\u8BD7","\u521B\u4F5C","\u5934\u8111\u98CE\u66B4","\u521B\u610F","\u60F3\u8C61","\u5199\u4E00\u4E2A","\u7269\u8A9E","\u8A69","\u4F5C\u66F2","\u30D6\u30EC\u30A4\u30F3\u30B9\u30C8\u30FC\u30E0","\u5275\u9020\u7684","\u60F3\u50CF","\u0438\u0441\u0442\u043E\u0440\u0438\u044F","\u0440\u0430\u0441\u0441\u043A\u0430\u0437","\u0441\u0442\u0438\u0445\u043E\u0442\u0432\u043E\u0440\u0435\u043D\u0438\u0435","\u0441\u043E\u0447\u0438\u043D\u0438\u0442\u044C","\u0441\u043E\u0447\u0438\u043D\u0438","\u043C\u043E\u0437\u0433\u043E\u0432\u043E\u0439 \u0448\u0442\u0443\u0440\u043C","\u0442\u0432\u043E\u0440\u0447\u0435\u0441\u043A\u0438\u0439","\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u0442\u044C","\u043F\u0440\u0438\u0434\u0443\u043C\u0430\u0439","\u043D\u0430\u043F\u0438\u0448\u0438","geschichte","gedicht","komponieren","brainstorming","kreativ","vorstellen","schreibe","erz\xE4hlung","historia","poema","componer","lluvia de ideas","creativo","imaginar","escribe","hist\xF3ria","poema","compor","criativo","imaginar","escreva","\uC774\uC57C\uAE30","\uC2DC","\uC791\uACE1","\uBE0C\uB808\uC778\uC2A4\uD1A0\uBC0D","\uCC3D\uC758\uC801","\uC0C1\uC0C1","\uC791\uC131","\u0642\u0635\u0629","\u0642\u0635\u064A\u062F\u0629","\u062A\u0623\u0644\u064A\u0641","\u0639\u0635\u0641 \u0630\u0647\u0646\u064A","\u0625\u0628\u062F\u0627\u0639\u064A","\u062A\u062E\u064A\u0644","\u0627\u0643\u062A\u0628"],imperativeVerbs:["build","create","implement","design","develop","construct","generate","deploy","configure","set up","\u6784\u5EFA","\u521B\u5EFA","\u5B9E\u73B0","\u8BBE\u8BA1","\u5F00\u53D1","\u751F\u6210","\u90E8\u7F72","\u914D\u7F6E","\u8BBE\u7F6E","\u69CB\u7BC9","\u4F5C\u6210","\u5B9F\u88C5","\u8A2D\u8A08","\u958B\u767A","\u751F\u6210","\u30C7\u30D7\u30ED\u30A4","\u8A2D\u5B9A","\u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u044C","\u043F\u043E\u0441\u0442\u0440\u043E\u0439","\u0441\u043E\u0437\u0434\u0430\u0442\u044C","\u0441\u043E\u0437\u0434\u0430\u0439","\u0440\u0435\u0430\u043B\u0438\u0437\u043E\u0432\u0430\u0442\u044C","\u0440\u0435\u0430\u043B\u0438\u0437\u0443\u0439","\u0441\u043F\u0440\u043E\u0435\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C","\u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0430\u0442\u044C","\u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0430\u0439","\u0441\u043A\u043E\u043D\u0441\u0442\u0440\u0443\u0438\u0440\u043E\u0432\u0430\u0442\u044C","\u0441\u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C","\u0441\u0433\u0435\u043D\u0435\u0440\u0438\u0440\u0443\u0439","\u0440\u0430\u0437\u0432\u0435\u0440\u043D\u0443\u0442\u044C","\u0440\u0430\u0437\u0432\u0435\u0440\u043D\u0438","\u043D\u0430\u0441\u0442\u0440\u043E\u0438\u0442\u044C","\u043D\u0430\u0441\u0442\u0440\u043E\u0439","erstellen","bauen","implementieren","entwerfen","entwickeln","konstruieren","generieren","bereitstellen","konfigurieren","einrichten","construir","crear","implementar","dise\xF1ar","desarrollar","generar","desplegar","configurar","construir","criar","implementar","projetar","desenvolver","gerar","implantar","configurar","\uAD6C\uCD95","\uC0DD\uC131","\uAD6C\uD604","\uC124\uACC4","\uAC1C\uBC1C","\uBC30\uD3EC","\uC124\uC815","\u0628\u0646\u0627\u0621","\u0625\u0646\u0634\u0627\u0621","\u062A\u0646\u0641\u064A\u0630","\u062A\u0635\u0645\u064A\u0645","\u062A\u0637\u0648\u064A\u0631","\u062A\u0648\u0644\u064A\u062F","\u0646\u0634\u0631","\u0625\u0639\u062F\u0627\u062F"],constraintIndicators:["under","at most","at least","within","no more than","o(","maximum","minimum","limit","budget","\u4E0D\u8D85\u8FC7","\u81F3\u5C11","\u6700\u591A","\u5728\u5185","\u6700\u5927","\u6700\u5C0F","\u9650\u5236","\u9884\u7B97","\u4EE5\u4E0B","\u6700\u5927","\u6700\u5C0F","\u5236\u9650","\u4E88\u7B97","\u043D\u0435 \u0431\u043E\u043B\u0435\u0435","\u043D\u0435 \u043C\u0435\u043D\u0435\u0435","\u043A\u0430\u043A \u043C\u0438\u043D\u0438\u043C\u0443\u043C","\u0432 \u043F\u0440\u0435\u0434\u0435\u043B\u0430\u0445","\u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C","\u043C\u0438\u043D\u0438\u043C\u0443\u043C","\u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u0435","\u0431\u044E\u0434\u0436\u0435\u0442","h\xF6chstens","mindestens","innerhalb","nicht mehr als","maximal","minimal","grenze","budget","como m\xE1ximo","al menos","dentro de","no m\xE1s de","m\xE1ximo","m\xEDnimo","l\xEDmite","presupuesto","no m\xE1ximo","pelo menos","dentro de","n\xE3o mais que","m\xE1ximo","m\xEDnimo","limite","or\xE7amento","\uC774\uD558","\uC774\uC0C1","\uCD5C\uB300","\uCD5C\uC18C","\uC81C\uD55C","\uC608\uC0B0","\u0639\u0644\u0649 \u0627\u0644\u0623\u0643\u062B\u0631","\u0639\u0644\u0649 \u0627\u0644\u0623\u0642\u0644","\u0636\u0645\u0646","\u0644\u0627 \u064A\u0632\u064A\u062F \u0639\u0646","\u0623\u0642\u0635\u0649","\u0623\u062F\u0646\u0649","\u062D\u062F","\u0645\u064A\u0632\u0627\u0646\u064A\u0629"],outputFormatKeywords:["json","yaml","xml","table","csv","markdown","schema","format as","structured","\u8868\u683C","\u683C\u5F0F\u5316\u4E3A","\u7ED3\u6784\u5316","\u30C6\u30FC\u30D6\u30EB","\u30D5\u30A9\u30FC\u30DE\u30C3\u30C8","\u69CB\u9020\u5316","\u0442\u0430\u0431\u043B\u0438\u0446\u0430","\u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043A\u0430\u043A","\u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439","tabelle","formatieren als","strukturiert","tabla","formatear como","estructurado","tabela","formatar como","estruturado","\uD14C\uC774\uBE14","\uD615\uC2DD","\uAD6C\uC870\uD654","\u062C\u062F\u0648\u0644","\u062A\u0646\u0633\u064A\u0642","\u0645\u0646\u0638\u0645"],referenceKeywords:["above","below","previous","following","the docs","the api","the code","earlier","attached","\u4E0A\u9762","\u4E0B\u9762","\u4E4B\u524D","\u63A5\u4E0B\u6765","\u6587\u6863","\u4EE3\u7801","\u9644\u4EF6","\u4E0A\u8A18","\u4E0B\u8A18","\u524D\u306E","\u6B21\u306E","\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8","\u30B3\u30FC\u30C9","\u0432\u044B\u0448\u0435","\u043D\u0438\u0436\u0435","\u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0438\u0439","\u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0439","\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430\u0446\u0438\u044F","\u043A\u043E\u0434","\u0440\u0430\u043D\u0435\u0435","\u0432\u043B\u043E\u0436\u0435\u043D\u0438\u0435","oben","unten","vorherige","folgende","dokumentation","der code","fr\xFCher","anhang","arriba","abajo","anterior","siguiente","documentaci\xF3n","el c\xF3digo","adjunto","acima","abaixo","anterior","seguinte","documenta\xE7\xE3o","o c\xF3digo","anexo","\uC704","\uC544\uB798","\uC774\uC804","\uB2E4\uC74C","\uBB38\uC11C","\uCF54\uB4DC","\uCCA8\uBD80","\u0623\u0639\u0644\u0627\u0647","\u0623\u062F\u0646\u0627\u0647","\u0627\u0644\u0633\u0627\u0628\u0642","\u0627\u0644\u062A\u0627\u0644\u064A","\u0627\u0644\u0648\u062B\u0627\u0626\u0642","\u0627\u0644\u0643\u0648\u062F","\u0645\u0631\u0641\u0642"],negationKeywords:["don't","do not","avoid","never","without","except","exclude","no longer","\u4E0D\u8981","\u907F\u514D","\u4ECE\u4E0D","\u6CA1\u6709","\u9664\u4E86","\u6392\u9664","\u3057\u306A\u3044\u3067","\u907F\u3051\u308B","\u6C7A\u3057\u3066","\u306A\u3057\u3067","\u9664\u304F","\u043D\u0435 \u0434\u0435\u043B\u0430\u0439","\u043D\u0435 \u043D\u0430\u0434\u043E","\u043D\u0435\u043B\u044C\u0437\u044F","\u0438\u0437\u0431\u0435\u0433\u0430\u0442\u044C","\u043D\u0438\u043A\u043E\u0433\u0434\u0430","\u0431\u0435\u0437","\u043A\u0440\u043E\u043C\u0435","\u0438\u0441\u043A\u043B\u044E\u0447\u0438\u0442\u044C","\u0431\u043E\u043B\u044C\u0448\u0435 \u043D\u0435","nicht","vermeide","niemals","ohne","au\xDFer","ausschlie\xDFen","nicht mehr","no hagas","evitar","nunca","sin","excepto","excluir","n\xE3o fa\xE7a","evitar","nunca","sem","exceto","excluir","\uD558\uC9C0 \uB9C8","\uD53C\uD558\uB2E4","\uC808\uB300","\uC5C6\uC774","\uC81C\uC678","\u0644\u0627 \u062A\u0641\u0639\u0644","\u062A\u062C\u0646\u0628","\u0623\u0628\u062F\u0627\u064B","\u0628\u062F\u0648\u0646","\u0628\u0627\u0633\u062A\u062B\u0646\u0627\u0621","\u0627\u0633\u062A\u0628\u0639\u0627\u062F"],domainSpecificKeywords:["quantum","fpga","vlsi","risc-v","asic","photonics","genomics","proteomics","topological","homomorphic","zero-knowledge","lattice-based","\u91CF\u5B50","\u5149\u5B50\u5B66","\u57FA\u56E0\u7EC4\u5B66","\u86CB\u767D\u8D28\u7EC4\u5B66","\u62D3\u6251","\u540C\u6001","\u96F6\u77E5\u8BC6","\u683C\u5BC6\u7801","\u91CF\u5B50","\u30D5\u30A9\u30C8\u30CB\u30AF\u30B9","\u30B2\u30CE\u30DF\u30AF\u30B9","\u30C8\u30DD\u30ED\u30B8\u30AB\u30EB","\u043A\u0432\u0430\u043D\u0442\u043E\u0432\u044B\u0439","\u0444\u043E\u0442\u043E\u043D\u0438\u043A\u0430","\u0433\u0435\u043D\u043E\u043C\u0438\u043A\u0430","\u043F\u0440\u043E\u0442\u0435\u043E\u043C\u0438\u043A\u0430","\u0442\u043E\u043F\u043E\u043B\u043E\u0433\u0438\u0447\u0435\u0441\u043A\u0438\u0439","\u0433\u043E\u043C\u043E\u043C\u043E\u0440\u0444\u043D\u044B\u0439","\u0441 \u043D\u0443\u043B\u0435\u0432\u044B\u043C \u0440\u0430\u0437\u0433\u043B\u0430\u0448\u0435\u043D\u0438\u0435\u043C","\u043D\u0430 \u043E\u0441\u043D\u043E\u0432\u0435 \u0440\u0435\u0448\u0451\u0442\u043E\u043A","quanten","photonik","genomik","proteomik","topologisch","homomorph","zero-knowledge","gitterbasiert","cu\xE1ntico","fot\xF3nica","gen\xF3mica","prote\xF3mica","topol\xF3gico","homom\xF3rfico","qu\xE2ntico","fot\xF4nica","gen\xF4mica","prote\xF4mica","topol\xF3gico","homom\xF3rfico","\uC591\uC790","\uD3EC\uD1A0\uB2C9\uC2A4","\uC720\uC804\uCCB4\uD559","\uC704\uC0C1","\uB3D9\uD615","\u0643\u0645\u064A","\u0636\u0648\u0626\u064A\u0627\u062A","\u062C\u064A\u0646\u0648\u0645\u064A\u0627\u062A","\u0637\u0648\u0628\u0648\u0644\u0648\u062C\u064A","\u062A\u0645\u0627\u062B\u0644\u064A"],agenticTaskKeywords:["read file","read the file","look at","check the","open the","edit","modify","update the","change the","write to","create file","execute","deploy","install","npm","pip","compile","after that","and also","once done","step 1","step 2","fix","debug","until it works","keep trying","iterate","make sure","verify","confirm","\u8BFB\u53D6\u6587\u4EF6","\u67E5\u770B","\u6253\u5F00","\u7F16\u8F91","\u4FEE\u6539","\u66F4\u65B0","\u521B\u5EFA","\u6267\u884C","\u90E8\u7F72","\u5B89\u88C5","\u7B2C\u4E00\u6B65","\u7B2C\u4E8C\u6B65","\u4FEE\u590D","\u8C03\u8BD5","\u76F4\u5230","\u786E\u8BA4","\u9A8C\u8BC1","leer archivo","editar","modificar","actualizar","ejecutar","desplegar","instalar","paso 1","paso 2","arreglar","depurar","verificar","ler arquivo","editar","modificar","atualizar","executar","implantar","instalar","passo 1","passo 2","corrigir","depurar","verificar","\uD30C\uC77C \uC77D\uAE30","\uD3B8\uC9D1","\uC218\uC815","\uC5C5\uB370\uC774\uD2B8","\uC2E4\uD589","\uBC30\uD3EC","\uC124\uCE58","\uB2E8\uACC4 1","\uB2E8\uACC4 2","\uB514\uBC84\uADF8","\uD655\uC778","\u0642\u0631\u0627\u0621\u0629 \u0645\u0644\u0641","\u062A\u062D\u0631\u064A\u0631","\u062A\u0639\u062F\u064A\u0644","\u062A\u062D\u062F\u064A\u062B","\u062A\u0646\u0641\u064A\u0630","\u0646\u0634\u0631","\u062A\u062B\u0628\u064A\u062A","\u0627\u0644\u062E\u0637\u0648\u0629 1","\u0627\u0644\u062E\u0637\u0648\u0629 2","\u0625\u0635\u0644\u0627\u062D","\u062A\u0635\u062D\u064A\u062D","\u062A\u062D\u0642\u0642"],dimensionWeights:{tokenCount:.08,codePresence:.15,reasoningMarkers:.18,technicalTerms:.1,creativeMarkers:.05,simpleIndicators:.02,multiStepPatterns:.12,questionComplexity:.05,imperativeVerbs:.03,constraintCount:.04,outputFormat:.03,referenceComplexity:.02,negationComplexity:.01,domainSpecificity:.02,agenticTask:.04},tierBoundaries:{simpleMedium:0,mediumComplex:.3,complexReasoning:.5},confidenceSteepness:12,confidenceThreshold:.7},tiers:{SIMPLE:{primary:"google/gemini-3.5-flash-lite",fallback:["google/gemini-3-flash-preview","deepseek/deepseek-chat","google/gemini-3.1-flash-lite","openai/gpt-5.6-luna","openai/gpt-5.4-nano","google/gemini-2.5-flash-lite","nvidia/nemotron-3.5-lightning"]},MEDIUM:{primary:"google/gemini-3.6-flash",fallback:["zai/glm-5.3-flash","openai/gpt-5.6-terra","google/gemini-3-flash-preview","deepseek/deepseek-chat","google/gemini-3.5-flash-lite","minimax/minimax-m3","google/gemini-3.1-flash-lite","openai/gpt-5.6-luna","google/gemini-2.5-flash-lite"]},COMPLEX:{primary:"google/gemini-3.1-pro",fallback:["google/gemini-3.6-flash","anthropic/claude-sonnet-5","xai/grok-4.5","google/gemini-3.8-flash","anthropic/claude-sonnet-4.6","openai/gpt-5.6-terra","openai/gpt-5.5","openai/gpt-5.4","zai/glm-5.3","moonshot/kimi-k3.1-pro","deepseek/deepseek-v4-pro","deepseek/deepseek-chat","google/gemini-3.5-flash-lite"]},REASONING:{primary:"deepseek/deepseek-reasoner",fallback:["deepseek/deepseek-v4-pro","xai/grok-4.3","qwen/qwen3.7-plus","google/gemini-3.6-flash","openai/gpt-5.4-mini"]}},ecoTiers:{SIMPLE:{primary:"nvidia/nemotron-3.5-lightning",fallback:["nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","google/gemini-2.5-flash-lite","zai/glm-5.3-flash","openai/gpt-5.6-luna","openai/gpt-5.4-nano","google/gemini-3.1-flash-lite"]},MEDIUM:{primary:"zai/glm-5.3-flash",fallback:["deepseek/deepseek-chat","google/gemini-3.1-flash-lite","openai/gpt-5.6-luna","openai/gpt-5.4-nano","google/gemini-2.5-flash-lite","google/gemini-3.5-flash-lite"]},COMPLEX:{primary:"zai/glm-5.3-flash",fallback:["deepseek/deepseek-chat","minimax/minimax-m3","deepseek/deepseek-v4-pro","google/gemini-3.1-flash-lite","google/gemini-3.5-flash-lite"]},REASONING:{primary:"deepseek/deepseek-reasoner",fallback:["deepseek/deepseek-v4-pro","qwen/qwen3.7-plus","minimax/minimax-m3","zai/glm-5.3-flash"]}},premiumTiers:{SIMPLE:{primary:"google/gemini-3.6-flash",fallback:["anthropic/claude-haiku-4.5","zai/glm-5.3","google/gemini-3.5-flash-lite","deepseek/deepseek-chat"]},MEDIUM:{primary:"openai/gpt-5.3-codex",fallback:["anthropic/claude-sonnet-5","moonshot/kimi-k3.1-pro","zai/glm-5.3","google/gemini-3.6-flash","google/gemini-3.8-flash","xai/grok-4.5","anthropic/claude-sonnet-4.6","openai/gpt-5.6-terra"]},COMPLEX:{primary:"anthropic/claude-fable-5",fallback:["anthropic/claude-opus-5","anthropic/claude-opus-4.8","anthropic/claude-opus-4.7","anthropic/claude-sonnet-5","anthropic/claude-sonnet-4.6","xai/grok-4.5","moonshot/kimi-k3.1-pro","openai/gpt-5.6-terra","openai/gpt-5.5","openai/gpt-5.4","openai/gpt-5.3-codex","zai/glm-5.3","deepseek/deepseek-v4-pro","deepseek/deepseek-chat","nvidia/nemotron-3.5-lightning"]},REASONING:{primary:"anthropic/claude-sonnet-5",fallback:["anthropic/claude-sonnet-4.6","anthropic/claude-opus-5","anthropic/claude-opus-4.8","anthropic/claude-opus-4.7","xai/grok-4.5","deepseek/deepseek-v4-pro","xai/grok-4.3","openai/gpt-5.4-mini"]}},agenticTiers:{SIMPLE:{primary:"openai/gpt-4o-mini",fallback:["openai/gpt-5.6-luna","zai/glm-5.3-flash","anthropic/claude-haiku-4.5","google/gemini-3.5-flash-lite"]},MEDIUM:{primary:"openai/gpt-5.6-luna",fallback:["google/gemini-3.6-flash","zai/glm-5.3-flash","openai/gpt-5.6-terra","openai/gpt-4o-mini","anthropic/claude-haiku-4.5","deepseek/deepseek-chat","moonshot/kimi-k3.1-pro"]},COMPLEX:{primary:"anthropic/claude-sonnet-5",fallback:["anthropic/claude-sonnet-4.6","anthropic/claude-opus-5","anthropic/claude-opus-4.8","anthropic/claude-opus-4.7","xai/grok-4.5","moonshot/kimi-k3.1-pro","openai/gpt-5.6-terra","openai/gpt-5.5","openai/gpt-5.4","openai/gpt-5.3-codex","zai/glm-5.3","deepseek/deepseek-v4-pro","deepseek/deepseek-chat","nvidia/nemotron-3.5-lightning"]},REASONING:{primary:"anthropic/claude-sonnet-5",fallback:["anthropic/claude-sonnet-4.6","anthropic/claude-opus-5","anthropic/claude-opus-4.8","anthropic/claude-opus-4.7","xai/grok-4.5","deepseek/deepseek-v4-pro","deepseek/deepseek-reasoner"]}},promotions:[],overrides:{maxTokensForceComplex:1e5,structuredOutputMinTier:"MEDIUM",ambiguousDefaultTier:"MEDIUM"}},DEFAULT_MODEL_CAPABILITIES=Object.freeze({"anthropic/claude-fable-5":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-fable-5.1":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-fable-5.2":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!1,supportsVision:!0},"anthropic/claude-haiku-4.5":{contextWindow:2e5,maxOutputTokens:64e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-opus-4.5":{contextWindow:2e5,maxOutputTokens:64e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-opus-4.7":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-opus-4.8":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-opus-5":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-opus-5.5":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-sonnet-4.5":{contextWindow:2e5,maxOutputTokens:64e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-sonnet-4.6":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-sonnet-5":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-sonnet-5.5":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"cohere/north-mini-code":{contextWindow:256e3,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"deepseek/deepseek-chat":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"deepseek/deepseek-reasoner":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"deepseek/deepseek-v4-flash-vision-exp":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!1,supportsVision:!0},"deepseek/deepseek-v4-pro":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"deepseek/deepseek-v4.1-flash":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"google/gemini-2.5-flash":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-2.5-flash-lite":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"google/gemini-2.5-pro":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-3-flash-preview":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-3.1-flash-lite":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"google/gemini-3.1-pro":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-3.5-flash":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-3.5-flash-lite":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"google/gemini-3.6-flash":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-3.8-flash":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-4-argon":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!1,supportsVision:!0},"google/gemini-4-carbon":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-4-hydrogen":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!1,supportsVision:!0},"google/gemini-4-neon":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!1,supportsVision:!0},"minimax/minimax-m2.7":{contextWindow:204800,maxOutputTokens:16384,supportsTools:!0,supportsVision:!1},"minimax/minimax-m3":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"mistral/mistral-large-4":{contextWindow:524288,maxOutputTokens:262144,supportsTools:!1,supportsVision:!0},"moonshot/kimi-k3.1-pro":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"nvidia/minimax-m3.1-flash":{contextWindow:1048576,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"nvidia/muse-glimmer-30b":{contextWindow:131072,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning":{contextWindow:256e3,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"nvidia/nemotron-3-super-120b":{contextWindow:131072,maxOutputTokens:16384,supportsTools:!1,supportsVision:!0},"nvidia/nemotron-3-ultra-550b":{contextWindow:1e6,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"nvidia/nemotron-3.5-bolt":{contextWindow:131072,maxOutputTokens:16384,supportsTools:!1,supportsVision:!0},"nvidia/nemotron-3.5-lightning":{contextWindow:1e6,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"openai/chat-latest":{contextWindow:128e3,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-4.1":{contextWindow:128e3,maxOutputTokens:32768,supportsTools:!0,supportsVision:!0},"openai/gpt-4.1-mini":{contextWindow:128e3,maxOutputTokens:32768,supportsTools:!0,supportsVision:!1},"openai/gpt-4o":{contextWindow:128e3,maxOutputTokens:16384,supportsTools:!0,supportsVision:!0},"openai/gpt-4o-mini":{contextWindow:128e3,maxOutputTokens:16384,supportsTools:!0,supportsVision:!1},"openai/gpt-5-mini":{contextWindow:2e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"openai/gpt-5.1":{contextWindow:4e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.2":{contextWindow:4e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.2-pro":{contextWindow:4e5,maxOutputTokens:128e3,supportsTools:!1,supportsVision:!0},"openai/gpt-5.3-codex":{contextWindow:4e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"openai/gpt-5.4":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.4-mini":{contextWindow:4e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.4-nano":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"openai/gpt-5.4-pro":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!1,supportsVision:!0},"openai/gpt-5.5":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.5-pro":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!1,supportsVision:!0},"openai/gpt-5.6-luna":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.6-luna-pro":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!1,supportsVision:!0},"openai/gpt-5.6-sol":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.6-sol-pro":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.6-terra":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.6-terra-pro":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-6-astra":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-6-luna":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-6-sol":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-6.1-sol":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-6.2-astra":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!1,supportsVision:!0},"openai/gpt-6.2-sol":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!1,supportsVision:!0},"openai/o1":{contextWindow:2e5,maxOutputTokens:1e5,supportsTools:!0,supportsVision:!1},"openai/o3":{contextWindow:2e5,maxOutputTokens:1e5,supportsTools:!0,supportsVision:!1},"openai/o3-mini":{contextWindow:128e3,maxOutputTokens:1e5,supportsTools:!0,supportsVision:!1},"openai/o4-mini":{contextWindow:128e3,maxOutputTokens:1e5,supportsTools:!0,supportsVision:!1},"poolside/laguna-s-2.1":{contextWindow:1048576,maxOutputTokens:131072,supportsTools:!1,supportsVision:!1},"poolside/laguna-xs-2.1":{contextWindow:131072,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"qwen/qwen3.7-flash":{contextWindow:1e6,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"qwen/qwen3.7-max":{contextWindow:1e6,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"qwen/qwen3.7-plus":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!0,supportsVision:!1},"qwen/qwen3.8-flash":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!1,supportsVision:!0},"qwen/qwen3.8-max":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!1,supportsVision:!1},"tencent/hy4-preview":{contextWindow:1048576,maxOutputTokens:64e3,supportsTools:!1,supportsVision:!1},"xai/grok-4.3":{contextWindow:1e6,maxOutputTokens:16384,supportsTools:!0,supportsVision:!0},"xai/grok-4.5":{contextWindow:5e5,maxOutputTokens:16384,supportsTools:!0,supportsVision:!0},"xai/grok-4.6":{contextWindow:5e5,maxOutputTokens:16384,supportsTools:!0,supportsVision:!0},"xai/grok-4.7":{contextWindow:5e5,maxOutputTokens:16384,supportsTools:!0,supportsVision:!0},"xai/grok-build-0.1":{contextWindow:256e3,maxOutputTokens:16384,supportsTools:!0,supportsVision:!1},"xiaomi/mimo-v2.5":{contextWindow:1048576,maxOutputTokens:131072,supportsTools:!0,supportsVision:!0},"xiaomi/mimo-v2.5-pro":{contextWindow:1048576,maxOutputTokens:131072,supportsTools:!0,supportsVision:!1},"zai/glm-5":{contextWindow:2e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"zai/glm-5-turbo":{contextWindow:2e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"zai/glm-5.1":{contextWindow:2e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"zai/glm-5.2":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!0,supportsVision:!1},"zai/glm-5.3":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!0,supportsVision:!1},"zai/glm-5.3-flash":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!0,supportsVision:!0}}),model_profiles_generated_default={"anthropic/claude-fable-5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:9298.5,p95LatencyMs:9873.4,outputTokensPerSecond:55.17,errorRate:0,samples:3},"anthropic/claude-haiku-4.5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3157.4,p95LatencyMs:3170.7,outputTokensPerSecond:162.16,errorRate:0,samples:3},"anthropic/claude-opus-4.5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6497.7,p95LatencyMs:6953.7,outputTokensPerSecond:78.99,errorRate:0,samples:3},"anthropic/claude-opus-4.7":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5316.5,p95LatencyMs:6121.5,outputTokensPerSecond:97.34,errorRate:0,samples:3},"anthropic/claude-opus-4.8":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6216.1,p95LatencyMs:6847.7,outputTokensPerSecond:82.81,errorRate:0,samples:3},"anthropic/claude-opus-5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:7309,p95LatencyMs:7745.2,outputTokensPerSecond:70.17,errorRate:0,samples:3},"anthropic/claude-sonnet-4.5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6330.4,p95LatencyMs:6631.6,outputTokensPerSecond:81.03,errorRate:0,samples:3},"anthropic/claude-sonnet-4.6":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6508,p95LatencyMs:6698.3,outputTokensPerSecond:78.6,errorRate:0,samples:3},"anthropic/claude-sonnet-5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6165.4,p95LatencyMs:6582.9,outputTokensPerSecond:83.62,errorRate:0,samples:3},"deepseek/deepseek-chat":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4351.4,p95LatencyMs:4543.7,outputTokensPerSecond:117.78,errorRate:0,samples:3},"deepseek/deepseek-reasoner":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5201.2,p95LatencyMs:6079.6,outputTokensPerSecond:99.77,errorRate:0,samples:3},"deepseek/deepseek-v4-pro":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:8781.2,p95LatencyMs:9881.1,outputTokensPerSecond:58.98,errorRate:0,samples:3},"deepseek/deepseek-v4.1-flash":{measuredAt:"2026-10-20T18:12:51Z",latencyMs:2383.5,p95LatencyMs:2547.8,outputTokensPerSecond:216.53,errorRate:0,samples:3},"google/gemini-2.5-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5416.4,p95LatencyMs:6442.8,outputTokensPerSecond:213.07,errorRate:0,samples:3},"google/gemini-2.5-flash-lite":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5002.6,p95LatencyMs:5780.3,outputTokensPerSecond:408.43,errorRate:0,samples:3},"google/gemini-2.5-pro":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:28169.5,p95LatencyMs:29491.4,outputTokensPerSecond:147.3,errorRate:0,samples:3},"google/gemini-3-flash-preview":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4717.1,p95LatencyMs:5037.1,outputTokensPerSecond:198.71,errorRate:0,samples:3},"google/gemini-3.1-flash-lite":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:2855.8,p95LatencyMs:3172.7,outputTokensPerSecond:286.91,errorRate:0,samples:3},"google/gemini-3.1-pro":{measuredAt:"2026-08-29T16:59:54Z",latencyMs:24194.1,p95LatencyMs:27269.6,outputTokensPerSecond:109.47,errorRate:0,samples:3},"google/gemini-3.5-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5320.6,p95LatencyMs:5429.8,outputTokensPerSecond:226.21,errorRate:0,samples:3},"google/gemini-3.5-flash-lite":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3515.8,p95LatencyMs:4363.4,outputTokensPerSecond:248.9,errorRate:0,samples:3},"google/gemini-3.6-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:13020,p95LatencyMs:15383.1,outputTokensPerSecond:187.87,errorRate:0,samples:3},"minimax/minimax-m2.7":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:8761.1,p95LatencyMs:10199.3,outputTokensPerSecond:59.18,errorRate:0,samples:3},"minimax/minimax-m3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:11101.9,p95LatencyMs:26087.1,outputTokensPerSecond:101.12,errorRate:0,samples:3},"moonshot/kimi-k3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:24498.9,p95LatencyMs:40365.3,outputTokensPerSecond:25.11,errorRate:0,samples:3},"moonshot/kimi-k3.1-pro":{measuredAt:"2026-11-23T20:18:18Z",latencyMs:9243.1,p95LatencyMs:10504.1,outputTokensPerSecond:55.89,errorRate:0,samples:3},"nvidia/mistral-nemotron":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:7349.6,p95LatencyMs:9932.3,outputTokensPerSecond:79.48,errorRate:.3333,samples:3},"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning":{measuredAt:"2026-08-29T16:59:54Z",latencyMs:9324.6,p95LatencyMs:12992,outputTokensPerSecond:64.96,errorRate:.3333,samples:3},"nvidia/nemotron-nano-12b-v2-vl":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5846.9,p95LatencyMs:5846.9,outputTokensPerSecond:87.57,errorRate:.6667,samples:3},"nvidia/nemotron-nano-9b-v2":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5282.5,p95LatencyMs:5282.5,outputTokensPerSecond:96.92,errorRate:.6667,samples:3},"nvidia/step-3.7-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4617.4,p95LatencyMs:5237.4,outputTokensPerSecond:112.92,errorRate:.3333,samples:3},"openai/chat-latest":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3690.9,p95LatencyMs:4344,outputTokensPerSecond:111.85,errorRate:0,samples:3},"openai/gpt-4.1":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3527.9,p95LatencyMs:3831.7,outputTokensPerSecond:141.27,errorRate:0,samples:3},"openai/gpt-4.1-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4268.2,p95LatencyMs:5101.5,outputTokensPerSecond:103.42,errorRate:0,samples:3},"openai/gpt-4.1-nano":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3088.3,p95LatencyMs:3369.2,outputTokensPerSecond:150.31,errorRate:0,samples:3},"openai/gpt-4o":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:2995.2,p95LatencyMs:3174.2,outputTokensPerSecond:171.32,errorRate:0,samples:3},"openai/gpt-4o-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4751.5,p95LatencyMs:4930.4,outputTokensPerSecond:107.84,errorRate:0,samples:3},"openai/gpt-5-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4558.1,p95LatencyMs:5081.9,outputTokensPerSecond:113.25,errorRate:0,samples:3},"openai/gpt-5.2":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5436.6,p95LatencyMs:5928.8,outputTokensPerSecond:95.47,errorRate:0,samples:3},"openai/gpt-5.3-codex":{measuredAt:"2026-08-29T16:59:54Z",latencyMs:15290.4,p95LatencyMs:15290.4,outputTokensPerSecond:33.49,errorRate:.6667,samples:3},"openai/gpt-5.4":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5596,p95LatencyMs:5919.4,outputTokensPerSecond:91.67,errorRate:0,samples:3},"openai/gpt-5.4-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3377.8,p95LatencyMs:3646.8,outputTokensPerSecond:138.08,errorRate:0,samples:3},"openai/gpt-5.4-nano":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4040.4,p95LatencyMs:4205.9,outputTokensPerSecond:118.52,errorRate:0,samples:3},"openai/gpt-5.5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6367.8,p95LatencyMs:7330.7,outputTokensPerSecond:81.29,errorRate:0,samples:3},"openai/gpt-5.6-luna":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6064.5,p95LatencyMs:7347.3,outputTokensPerSecond:87.93,errorRate:0,samples:3},"openai/gpt-5.6-luna-pro":{measuredAt:"2026-08-29T16:59:54Z",latencyMs:13914.9,p95LatencyMs:13914.9,outputTokensPerSecond:36.79,errorRate:.6667,samples:3},"openai/gpt-5.6-sol":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:7720.2,p95LatencyMs:9108.2,outputTokensPerSecond:67.47,errorRate:0,samples:3},"openai/gpt-5.6-sol-pro":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:11442.7,p95LatencyMs:13363.1,outputTokensPerSecond:148.75,errorRate:0,samples:3},"openai/gpt-5.6-terra":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4941,p95LatencyMs:5095.3,outputTokensPerSecond:103.69,errorRate:0,samples:3},"openai/gpt-5.6-terra-pro":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3574.1,p95LatencyMs:4126.3,outputTokensPerSecond:133.59,errorRate:0,samples:3},"openai/gpt-6.1-sol":{measuredAt:"2026-10-20T18:12:51Z",latencyMs:11324,p95LatencyMs:12747.6,outputTokensPerSecond:45.11,errorRate:0,samples:3},"openai/o1":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4324.9,p95LatencyMs:5838.1,outputTokensPerSecond:125.86,errorRate:0,samples:3},"openai/o3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5463.4,p95LatencyMs:5613.1,outputTokensPerSecond:93.8,errorRate:0,samples:3},"openai/o3-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:2912.7,p95LatencyMs:3092.1,outputTokensPerSecond:176.49,errorRate:0,samples:3},"openai/o4-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4958.7,p95LatencyMs:5313,outputTokensPerSecond:103.81,errorRate:0,samples:3},"qwen/qwen3.7-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3385.5,p95LatencyMs:4042.7,outputTokensPerSecond:153.94,errorRate:0,samples:3},"qwen/qwen3.7-max":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:9387.1,p95LatencyMs:10490.2,outputTokensPerSecond:54.92,errorRate:0,samples:3},"qwen/qwen3.7-plus":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:9766.6,p95LatencyMs:9798.2,outputTokensPerSecond:52.42,errorRate:0,samples:3},"tencent/hy3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6062.3,p95LatencyMs:7070.2,outputTokensPerSecond:87.3,errorRate:0,samples:3},"xai/grok-4.3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:9467.7,p95LatencyMs:10087.9,outputTokensPerSecond:48.36,errorRate:0,samples:3},"xai/grok-4.5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:13564.8,p95LatencyMs:17351.9,outputTokensPerSecond:60.71,errorRate:0,samples:3},"xai/grok-build-0.1":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:16394.8,p95LatencyMs:18035.4,outputTokensPerSecond:96.86,errorRate:0,samples:3},"xiaomi/mimo-v2.5-pro":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:12070.7,p95LatencyMs:12386.8,outputTokensPerSecond:42.44,errorRate:0,samples:3},"zai/glm-5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6839.7,p95LatencyMs:7261.4,outputTokensPerSecond:75.16,errorRate:0,samples:3},"zai/glm-5-turbo":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:55348.5,p95LatencyMs:114086.6,outputTokensPerSecond:14.64,errorRate:0,samples:3},"zai/glm-5.1":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:15658.4,p95LatencyMs:17307.1,outputTokensPerSecond:32.9,errorRate:0,samples:3},"zai/glm-5.2":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:10308.5,p95LatencyMs:15127.6,outputTokensPerSecond:54.87,errorRate:0,samples:3},"zai/glm-5.3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:7272.4,p95LatencyMs:7998.1,outputTokensPerSecond:71.09,errorRate:0,samples:3},"zai/glm-5.3-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:10545.3,p95LatencyMs:11672.4,outputTokensPerSecond:49.01,errorRate:0,samples:3}},LIVE_MODEL_PROFILES=Object.freeze(model_profiles_generated_default),HISTORICAL_MODEL_PROFILES=Object.freeze({"anthropic/claude-haiku-4.5":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:2305,outputTokensPerSecond:140.6},"anthropic/claude-sonnet-4.6":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:2110,outputTokensPerSecond:121.3},"deepseek/deepseek-chat":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:1431,outputTokensPerSecond:179.2,intelligenceIndex:32},"google/gemini-2.5-flash":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:1238,outputTokensPerSecond:207.6,intelligenceIndex:20},"google/gemini-2.5-flash-lite":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:1353,outputTokensPerSecond:192.5,intelligenceIndex:20},"google/gemini-2.5-pro":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:1294,outputTokensPerSecond:197.8},"google/gemini-3.1-pro":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:1609,outputTokensPerSecond:167.2},"openai/gpt-4o-mini":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:2764,outputTokensPerSecond:92.8},"openai/gpt-5.3-codex":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:7935,outputTokensPerSecond:32.3}});DEFAULT_PORTFOLIO_WEIGHTS=DEFAULT_ROUTING_CONFIG.portfolio;NEUTRAL_AFFINITY=.68,TERMINAL_COMPLEX_HIGH={"claude-sonnet-5":1,"gpt-5.3-codex":.87,"gpt-5.6-luna":.78,"gemini-3.6-flash":.76},WEB_RESEARCH_DEEP={"claude-sonnet-5":1,"gpt-5.6-luna":.88,"gemini-3.6-flash":.84,"claude-opus-5":.8,"claude-opus-4.8":.78},WEB_RESEARCH={"claude-sonnet-5":1,"gpt-5.6-luna":.88,"gemini-3.6-flash":.86,"claude-opus-5":.84,"claude-opus-4.8":.82},RETAIL_POLICY_EXCEPTION={"gpt-4.1":1,"claude-sonnet-5":.9,"deepseek-v4-pro":.82,"gpt-5.6-luna":.8,"gpt-4o-mini":.76},RETAIL_POLICY_EXCEPTION_SIMPLE={"gpt-5.6-luna":1,"gpt-4.1":.86,"deepseek-v4-pro":.82,"gpt-4o-mini":.8},AFFINITY={codeAgent:{"gpt-5.3-codex":1,"claude-sonnet-5":.98,"gpt-5.6-luna":.96,"gemini-3.6-flash":.92,"kimi-k3.1-pro":.9,"deepseek-v4-pro":.88,"glm-5.2":.88},terminalTool:{"gpt-5.6-luna":1,"gpt-5.3-codex":.98,"claude-sonnet-5":.9,"gemini-3.6-flash":.89},terminalToolSafety:{"claude-sonnet-5":1,"claude-opus-4.8":.9,"gpt-5.3-codex":.84},retailStandard:{"gpt-5.6-luna":1,"claude-sonnet-5":.88,"gemini-3.6-flash":.82,"gpt-5.3-codex":.81,"kimi-k3.1-pro":.78,"deepseek-v4-pro":.76},retailHigh:{"deepseek-v4-pro":1,"claude-sonnet-5":.88,"gemini-3.6-flash":.82,"gpt-5.3-codex":.81,"kimi-k3.1-pro":.78,"gpt-5.6-luna":.76},airlineComplex:{"claude-sonnet-5":1,"gpt-5.6-luna":.78,"gemini-3.6-flash":.76,"deepseek-v4-pro":.74},airlineStandard:{"gpt-5.6-luna":1,"claude-sonnet-5":.9,"gemini-3.6-flash":.8,"deepseek-v4-pro":.76},toolAgent:{"claude-sonnet-5":1,"gemini-3.6-flash":.88,"gpt-5.3-codex":.87,"kimi-k3.1-pro":.85,"gpt-5.6-luna":.84,"deepseek-v4-pro":.82},parallelTerminalSafety:{"claude-sonnet-5":1,"claude-opus-4.8":.9,"gpt-5.3-codex":.86},parallelTerminal:{"gpt-5.6-luna":1,"gpt-5.3-codex":.98,"claude-sonnet-5":.92,"gemini-3.6-flash":.88},parallelRetail:{"deepseek-v4-pro":1,"claude-sonnet-5":.88,"claude-opus-4.8":.84,"gpt-5.6-luna":.78,"gemini-3.6-flash":.76},parallelAirlineComplex:{"claude-sonnet-5":1,"gpt-5.6-luna":.78,"claude-opus-4.8":.76,"gemini-3.6-flash":.74},parallelAirline:{"gpt-5.6-luna":1,"claude-sonnet-5":.9,"gemini-3.6-flash":.8},parallel:{"claude-opus-4.8":1,"claude-sonnet-5":.84,"grok-4.5":.82,"gemini-3.6-flash":.8,"deepseek-v4-pro":.78},codeEdit:{"gpt-5.3-codex":1,"claude-sonnet-4.6":.94,"glm-5.2":.9,"deepseek-v4-pro":.86},reasoning:{"claude-sonnet-5":.98,"claude-sonnet-4.6":.98,"deepseek-v4-pro":.95,"grok-4.5":.94,"gemini-3.1-pro":.92,"gemini-3.6-flash":.92},reasoningMcq:{"gemini-3-flash-preview":1,"gemini-3.6-flash":.91,"grok-4.5":.9,"claude-sonnet-5":.88,"deepseek-v4-pro":.84},reasoningMath:{"gemini-3.6-flash":1,"grok-4.5":.93,"claude-sonnet-5":.9,"deepseek-v4-pro":.9,"kimi-k3.1-pro":.88},vision:{"gemini-3.1-pro":.96,"qwen3.7-max":.9,"claude-sonnet-4.6":.9,"kimi-k3.1-pro":.9,"grok-4.3":.9},longContext:{"gemini-3.1-pro":1,"qwen3.7-max":.89,"glm-5.2":.89,"gemini-3.6-flash":.88,"deepseek-v4-pro":.85},extractionZh:{"kimi-k3.1-pro":1,"gemini-3.6-flash":.88,"gemini-3.5-flash-lite":.88,"gpt-4o-mini":.88,"claude-sonnet-5":.88,"claude-sonnet-4.6":.88},extraction:{"kimi-k3.1-pro":.9,"gemini-3.6-flash":.9,"gemini-3.5-flash-lite":.9,"gpt-4o-mini":.9,"claude-sonnet-5":.9,"claude-sonnet-4.6":.9},chat:{"gemini-3.6-flash":.86,"gemini-3.5-flash-lite":.86,"kimi-k3.1-pro":.86}};VERIFIED_TOOL_FALLBACKS=["anthropic/claude-fable-5.1","anthropic/claude-opus-5.5","anthropic/claude-sonnet-5.5","deepseek/deepseek-v4.1-flash","google/gemini-3.8-flash","google/gemini-4-carbon","openai/gpt-5.1","openai/gpt-6-astra","openai/gpt-6-luna","openai/gpt-6-sol","openai/gpt-6.1-sol","xai/grok-4.6","xai/grok-4.7","xiaomi/mimo-v2.5"];PortfolioStrategy=class{name="portfolio";rules=new RulesStrategy;route(prompt,systemPrompt,maxOutputTokens,options){let features=classifyTask(prompt,systemPrompt,options),base4=this.rules.route(prompt,systemPrompt,maxOutputTokens,{...options,requiresTools:features.needsTools}),tierConfigs=base4.tierConfigs;if(!tierConfigs)return base4;let targetTier=(features.taskType==="reasoning_mcq"||features.taskType==="reasoning_math")&&(base4.tier==="SIMPLE"||base4.tier==="MEDIUM")?"REASONING":(features.taskType==="debug"||features.taskType==="code_edit")&&features.codeArtifact&&base4.tier==="SIMPLE"?"MEDIUM":base4.tier,configuredCandidates=tierConfigs[targetTier]?getFallbackChain(targetTier,tierConfigs):[],unavailable=new Set(options.unavailableModels??[]),verifiedToolFallbacks=features.needsTools?VERIFIED_TOOL_FALLBACKS.filter(model2=>options.modelPricing.has(model2)):[];if(options.routingProfile!=="premium"){let fallbackCost=model2=>estimatedCost(model2,options,features.estimatedInputTokens,maxOutputTokens);verifiedToolFallbacks.sort((a,b)=>fallbackCost(a)-fallbackCost(b))}let chain3=[...new Set([...configuredCandidates,...evidenceCandidates(features.taskType),...verifiedToolFallbacks])].filter(model2=>typeof model2=="string"&&model2.length>0&&!unavailable.has(model2)),eligible=new Set(chain3.filter(model2=>isEligible(model2,features,maxOutputTokens,options))),eligibleCandidates=eligible.size>0?[...eligible]:chain3;if(eligibleCandidates.length===0)return base4;let profileName=options.routingProfile==="eco"?"eco":options.routingProfile==="premium"?"premium":"auto",portfolio=options.config.portfolio??DEFAULT_PORTFOLIO_WEIGHTS,band=affinityBand(features),affinityCache=new Map,getAffinity=model2=>{let value=affinityCache.get(model2);return value===void 0&&(value=affinityIn(band,model2),affinityCache.set(model2,value)),value},bestAffinity=Math.max(...eligibleCandidates.map(getAffinity)),specificAffinity=eligibleCandidates.filter(model2=>getAffinity(model2)>NEUTRAL_AFFINITY),affinityPool=specificAffinity.length>0?specificAffinity:[eligibleCandidates[0]],affinityFloorGap=features.terminalToolSignal?Math.max(portfolio.affinityFloorGap[profileName],features.terminalSafetySensitive?.15:.12):portfolio.affinityFloorGap[profileName],candidates=affinityPool.filter(model2=>getAffinity(model2)>=bestAffinity-affinityFloorGap),costs=candidates.map(model2=>estimatedCost(model2,options,features.estimatedInputTokens,maxOutputTokens)),finiteCosts=costs.filter(Number.isFinite),minCost=finiteCosts.length>0?Math.min(...finiteCosts):0,maxCost=finiteCosts.length>0?Math.max(...finiteCosts):1,now2=options.now??new Date,profileWeights=portfolio[profileName],rankedEntries=candidates.map((model2,index2)=>{let cost=costs[index2],costScore=Number.isFinite(cost)?maxCost>minCost?1-(cost-minCost)/(maxCost-minCost):.5:0,capabilityScore=eligible.has(model2)?1:0,profile=profileScore(model2,options,now2),observedQuality=profile?.quality===void 0?getAffinity(model2):getAffinity(model2)*(1-profile.freshness)+profile.quality*profile.freshness,observedSpeed=profile?profile.speed*profile.freshness+.5*(1-profile.freshness):.5,observedTailSpeed=profile?profile.tailSpeed*profile.freshness+.5*(1-profile.freshness):.5,observedReliability=profile?profile.reliability*profile.freshness+(1-profile.freshness):1,legacyScore=1-index2/Math.max(1,candidates.length-1),qualityWeight=profileWeights.quality+(features.highStakes?portfolio.highStakesBoost.quality:0),speedScore=features.latencySensitive?observedTailSpeed:observedSpeed,speedWeight=profileWeights.speed+(features.latencySensitive?portfolio.latencySensitiveSpeedBoost:0),reliabilityWeight=profileWeights.reliability+(features.highStakes?portfolio.highStakesBoost.reliability:0),score=observedQuality*qualityWeight+capabilityScore*profileWeights.capability+costScore*profileWeights.cost+speedScore*speedWeight+observedReliability*reliabilityWeight+legacyScore*profileWeights.legacy;return{model:model2,score,quality:observedQuality,cost:costScore,speed:speedScore,reliability:observedReliability}}).sort((a,b)=>b.score-a.score),scoredModels=rankedEntries.map(item=>item.model),webResearchFallbackOrder=["anthropic/claude-sonnet-5","openai/gpt-5.6-luna","google/gemini-3.6-flash","anthropic/claude-opus-5","anthropic/claude-opus-4.8","openai/gpt-5.3-codex"],ranked=features.agentDomain==="web_research"?[...scoredModels,...webResearchFallbackOrder.filter(model2=>eligibleCandidates.includes(model2)&&!scoredModels.includes(model2)),...eligibleCandidates.filter(model2=>!scoredModels.includes(model2)&&!webResearchFallbackOrder.includes(model2))]:[...scoredModels,...eligibleCandidates.filter(model2=>!scoredModels.includes(model2))],model=ranked[0]??base4.model,selectedTierConfigs={...tierConfigs,[targetTier]:{primary:model,fallback:ranked.slice(1)}};return{...selectModel(targetTier,base4.confidence,"portfolio",`${base4.reasoning} | v3 task=${features.taskType} agentRisk=${features.agentRisk} deepWebResearch=${features.deepWebResearch} terminalCode=${features.implicitTerminalCode} terminalSafety=${features.terminalSafetySensitive} candidates=${ranked.length}`,selectedTierConfigs,options.modelPricing,features.estimatedInputTokens,maxOutputTokens,options.routingProfile,base4.agenticScore),tierConfigs:selectedTierConfigs,profile:base4.profile,candidates:ranked,candidateScores:rankedEntries.map(({model:model2,score,quality,cost,speed,reliability})=>({model:model2,score,quality,cost,speed,reliability})),taskType:features.taskType,routerVersion:"v3-portfolio"}}};registerStrategy(new PortfolioStrategy)}});var init_router=__esm({"src/router/index.ts"(){"use strict";init_dist()}});import{appendFile,mkdir as mkdir2}from"fs/promises";import{join as join4}from"path";import{homedir as homedir3}from"os";async function ensureDir(){dirReady||(await mkdir2(LOG_DIR,{recursive:!0}),dirReady=!0)}async function logUsage(entry){try{await ensureDir();let date5=entry.timestamp.slice(0,10),file2=join4(LOG_DIR,`usage-${date5}.jsonl`);await appendFile(file2,JSON.stringify(entry)+`
|
|
2169
|
+
${value.slice(-suffixLength)}`}function applyPromotions(tierConfigs,promotions,profile,now2=new Date){if(!promotions||promotions.length===0)return tierConfigs;let result=tierConfigs;for(let promo of promotions){let start=Date.parse(promo.startDate),end=Date.parse(promo.endDate);if(!(!Number.isFinite(start)||!Number.isFinite(end))&&!(now2.getTime()<start||now2.getTime()>=end)&&!(promo.profiles&&!promo.profiles.includes(profile))){if(result===tierConfigs){result={...tierConfigs};for(let t of Object.keys(result))result[t]={...result[t]}}for(let[tier,override]of Object.entries(promo.tierOverrides))result[tier]&&(override.primary&&(result[tier].primary=override.primary),override.fallback&&(result[tier].fallback=override.fallback))}}return result}function applyUnavailableModels(tierConfigs,unavailableModels){if(!unavailableModels||unavailableModels.length===0)return tierConfigs;let dead=new Set(unavailableModels),result=tierConfigs;for(let tier of Object.keys(tierConfigs)){let config2=tierConfigs[tier],alive=[config2.primary,...config2.fallback].filter(model=>!dead.has(model));alive.length===0||alive[0]===config2.primary&&alive.length===config2.fallback.length+1||(result===tierConfigs&&(result={...tierConfigs}),result[tier]={primary:alive[0],fallback:alive.slice(1)})}return result}function getStrategy(name){let strategy=registry2.get(name);if(!strategy)throw new Error(`Unknown routing strategy: ${name}`);return strategy}function registerStrategy(strategy){registry2.set(strategy.name,strategy)}function inferToolRequirement(prompt,_systemPrompt,toolChoice){if(toolChoice==="none")return!1;if(toolChoice==="required"||typeof toolChoice=="object"&&toolChoice!==null&&toolChoice.type==="function")return!0;let text=prompt,explicitTool=/\b(?:use|call|invoke)\s+(?:the\s+)?[\w.-]+\s+(?:tool|function|api)\b|\btool[_ -]?call\b|使用.{0,20}(?:工具|函数|接口)|调用.{0,20}(?:工具|函数|接口)/i,codeEnvironment=/\b(?:run|execute)\s+(?:the\s+)?(?:tests?|command|script|build|linter)|\b(?:edit|modify|patch|create|write|save|delete|rename|move|inspect|read)\b.{0,60}\b(?:file|repository|repo|codebase|directory|folder)\b|\b(?:terminal|shell|bash|zsh|pytest|npm test|pnpm test|git\s+(?:status|diff|commit)|docker)\b|(?:运行|执行).{0,20}(?:测试|命令|脚本|构建)|(?:修改|编辑|修复|创建|读取|检查|保存).{0,30}(?:文件|仓库|代码库|目录)/i,webAction=/\b(?:browse|search|look up|fetch|open)\b.{0,80}\b(?:web|website|url|online|documentation|docs|news|weather|price)\b|(?:浏览|搜索|查询|打开).{0,30}(?:网页|网站|链接|文档|新闻|天气|价格)/i,statefulAction=/\b(?:refund|cancel|book|reserve|purchase|buy|return|exchange|transfer|update|change)\b.{0,80}\b(?:order|booking|reservation|account|address|payment|subscription|ticket|flight|item)\b|(?:退款|取消|预订|购买|退货|换货|转账|更新|修改).{0,30}(?:订单|预订|账户|地址|付款|订阅|票|航班|商品)/i;return explicitTool.test(text)||codeEnvironment.test(text)||webAction.test(text)||statefulAction.test(text)}function likelyNeedsParallelToolCalls(prompt,needsTools,toolCount,toolNames){if(!needsTools||toolCount===void 0||toolCount<1)return!1;let text=prompt.trim();if(/\b(?:in parallel|simultaneously|concurrently|for each|each of|every one|both|(?:two|three|multiple|several)\s+(?:cities|locations|items|tasks|orders|users|files))\b|并行|同时|分别|每个|各自|(?:两个|三个|多个)(?:城市|地点|项目|任务|订单|用户|文件)|cada uno|para cada|simult[aá]neamente/i.test(text))return!0;let sentenceClauses=text.split(/[.!?。!?]+/).map(part=>part.trim()).filter(part=>part.length>=8);if(/\b(?:also|additionally|furthermore)\b|另外|此外|그리고/i.test(text)&&sentenceClauses.length>=2||/\band\s+(?:also|for the)\b/i.test(text)||/\b\d+(?:\.\d+)?\s+(?:and|or)\s+\d+(?:\.\d+)?\s*(?:gb|mb|tb|kg|g|ml|oz|cups?|cores?|cpus?)\b/i.test(text))return!0;let operationTokens=new Set(["add","delete","remove","cancel","return","exchange","modify","book","transfer","send","upload","download","create","close"]),lowered=text.toLowerCase();if(new Set((toolNames??[]).flatMap(name=>name.toLowerCase().split(/[^a-z0-9\u3400-\u9fff]+/)).filter(token=>operationTokens.has(token)&&new RegExp(`\\b${token}(?:s|es|d|ed|ing)?\\b`).test(lowered))).size>=2)return!0;let nonEmptyLines=text.split(/\r?\n/).map(line=>line.trim()).filter(Boolean),quantityMentions=text.match(/\b(?:\d+(?:\.\d+)?|one|two|three|four|five|six|seven|eight|nine|ten)\s*(?:oz|ounce|ounces|g|gram|grams|kg|ml|cups?|pieces?|tablespoons?)\b/gi)??[];if(nonEmptyLines.length>=2&&quantityMentions.length>=2)return!0;let repeatedLookup=/\b(?:weather|climate|clima|tiempo|temperature|snow|news|report)\b|天气|气象|温度|降雪|新闻|报告/i.test(text),multiLocationConnector=/\b(?:and also|both)\b|\s(?:y|e)\s|还有|以及|和|、/i.test(text),commaSeparatedLocations=(text.match(/[,,]/g)??[]).length>=2;if(repeatedLookup&&(multiLocationConnector||commaSeparatedLocations))return!0;let distinctOrderParts=/\b(?:food|meal)\b[\s\S]*\bdrink\b|\bdrink\b[\s\S]*\b(?:food|meal)\b/i.test(text),koreanParallelClauses=(text.match(/,/g)??[]).length>=3&&/하고|그리고/.test(text);return distinctOrderParts||koreanParallelClauses}function classifyTask(prompt,systemPrompt,options){let fullText=`${systemPrompt??""} ${prompt}`,estimatedInputTokens=estimateTokens(fullText),limit=scanLimit(options.config.classifier.promptTruncationChars),scannedPrompt=sampleForScan(prompt,limit),scannedSystemPrompt=sampleForScan(systemPrompt??"",limit),scannedFullText=`${scannedSystemPrompt} ${scannedPrompt}`,text=scannedPrompt.toLowerCase(),explicitCodeSignal=/```|\b(?:typescript|javascript|python|rust|java|sql|stack trace|traceback|exception)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(scannedPrompt),codeConstructSignal=/\b(?:implement|refactor|debug|write|edit|modify|create|define|review|fix)\b[\s\S]{0,48}\b(?:api|function|class|method)\b|\b(?:api|function|class|method)\b[\s\S]{0,48}\b(?:code|implementation|typescript|javascript|python|rust|java)\b/i.test(scannedPrompt),nativeCodeSignal=/\b(?:programmed|written|implemented?|code)\s+(?:in|using)\s+(?:c\+\+|c|rust|go)\b/i.test(scannedPrompt),errorClassSignal=/\b[A-Z][A-Za-z]*(?:Error|Exception)\b/.test(scannedPrompt),hasCode=explicitCodeSignal||codeConstructSignal||nativeCodeSignal||errorClassSignal,codingAction=/\b(?:write|implement|refactor|debug|fix|patch|compile|build|run|test|script|program|code|function|class|module|repo(?:sitory)?)\b|编写|实现|重构|调试|修复|编译|脚本|代码/i.test(scannedPrompt),codeArtifact=/```|\b(?:stack trace|traceback)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(scannedPrompt)||codeConstructSignal||nativeCodeSignal||errorClassSignal,toolsAvailable=options.hasTools??!1,needsTools=options.requiresTools??(toolsAvailable&&inferToolRequirement(scannedPrompt,scannedSystemPrompt)),likelyParallelToolCalls=likelyNeedsParallelToolCalls(scannedPrompt,needsTools,options.toolCount,options.toolNames),normalizedToolNames=(options.toolNames??[]).map(name=>name.toLowerCase()),airlineToolSignal=normalizedToolNames.some(name=>/(?:flight|reservation|airport|baggage|passenger)/.test(name)),retailToolSignal=normalizedToolNames.some(name=>/(?:order|product|item|return|exchange|address)/.test(name)),webResearchToolSignal=normalizedToolNames.some(name=>/^(?:web_?search|web_?fetch)$/.test(name)),agentDomain=airlineToolSignal&&!retailToolSignal?"airline":retailToolSignal&&!airlineToolSignal?"retail":webResearchToolSignal?"web_research":"other",clueConnectors=scannedFullText.match(/\b(?:after|before|while|where|whose|which|in \d{4}|as of|over \d+|another|also|furthermore)\b|(?:之后|之前|其中|截至|超过|另一个|此外)/gi)??[],entityResolutionSignal=/\b(?:identify|who (?:is|was)|what (?:is|was) the name|which (?:person|player|company|country|city)|find the (?:person|player|name|entity))\b|(?:找出|识别|是谁|哪位|名称是什么)/i.test(scannedFullText),exactAnswerSignal=/\b(?:exact answer|single best-supported answer|following clues|multiple public sources)\b|(?:精确答案|根据.*线索|多个公开来源)/i.test(scannedFullText),deepWebResearch=agentDomain==="web_research"&&(exactAnswerSignal||entityResolutionSignal&&(clueConnectors.length>=3||prompt.length>=320)),globalOptimizationSignal=/\b(?:cheapest|lowest[- ]price|least expensive|most expensive|highest(?:[- ]priced)?|largest|smallest|maximum|minimum|best available|closest|not (?:cost|exceed))\b|最便宜|最低价|最贵|最高价|最大|最小/i.test(scannedPrompt),globalScopeSignal=/\b(?:everything|all (?:(?:my|your|their|the) )?(?:future |upcoming )?(?:items|orders|passengers|flights|reservations|bookings)|every (?:item|order|passenger|flight|reservation|booking))\b|全部|所有|每个/i.test(scannedPrompt),globalChoiceSignal=globalOptimizationSignal||globalScopeSignal,crossRecordSignal=/\b(?:another|other|different|previous)\s+(?:order|reservation|booking|account|address)\b|另一(?:个)?(?:订单|预订|账户|地址)|其他(?:订单|预订|账户|地址)/i.test(scannedPrompt),reservationIds=scannedPrompt.match(/\b(?=[A-Z0-9]*\d)(?=[A-Z0-9]*[A-Z])[A-Z0-9]{6}\b/g)??[],crossReservationBatchSignal=agentDomain==="airline"&&(/\b(?:two|three|multiple|several)(?:\s+of\s+(?:my|our|the))?\s+(?:upcoming\s+)?(?:reservations?|bookings?)\b|\b(?:a\s+)?(?:second|third)\s+(?:reservation|booking)\b/i.test(scannedPrompt)||new Set(reservationIds).size>=2),conditionalGlobalWorkflowSignal=agentDomain==="airline"&&globalScopeSignal&&/\b(?:if|that (?:contain|have)|longer than|shorter than|under|over|at (?:most|least)|wherever possible)\b|如果|超过|少于|不超过|尽可能/i.test(scannedPrompt)&&/\b(?:cancel|change|upgrade|move|book)\b[\s\S]*\b(?:cancel|change|upgrade|move|book)\b|取消[\s\S]*(?:升级|更改)|升级[\s\S]*(?:取消|更改)/i.test(scannedPrompt),policyExceptionSignal=agentDomain==="retail"&&/\b(?:return|refund|send back|get (?:my |the )?money back)\b|退货|退款|退回/i.test(scannedPrompt)&&/\b(?:amex|american express|visa|mastercard|credit card|debit card|different card|another card|other card)\b|信用卡|借记卡|其他卡|另一张卡/i.test(scannedPrompt),singleSelectedPolicyException=policyExceptionSignal&&/\b(?:return|refund|send back)\b[^.!?。!?]{0,96}\b(?:the )?(?:pricier|cheaper|more expensive|less expensive|costlier|one)\b/i.test(scannedPrompt),negotiatedWorkflowSignal=agentDomain==="retail"&&/\b(?:return|exchange)\b|退货|退回|换货|交换/i.test(scannedPrompt),numberedSteps=(scannedPrompt.match(/(?:^|\s)\d+(?:\.\d+)*[.)]\s+/g)??[]).length,complexMultiToolPlan=likelyParallelToolCalls&&((options.toolCount??0)>=6||numberedSteps>=3||prompt.length>1200),agentRisk=needsTools&&singleSelectedPolicyException?"policy_exception_simple":needsTools&&policyExceptionSignal?"policy_exception":needsTools&&agentDomain==="airline"&&(globalOptimizationSignal||conditionalGlobalWorkflowSignal)?"complex_high":needsTools&&(likelyParallelToolCalls||globalChoiceSignal||crossRecordSignal||crossReservationBatchSignal||negotiatedWorkflowSignal)?"high":"standard",needsVision=options.hasVision??!1,needsStructuredOutput=options.requiresStructuredOutput??!1,latencySensitive=/\b(?:urgent|asap|fast|quick|low latency|real[- ]time)\b|尽快|马上|快速|低延迟/i.test(scannedPrompt),highStakes=/\b(?:production|security|payment|legal|medical|financial|audit)\b|生产|安全|支付|法律|医疗|财务|审计/i.test(scannedPrompt),terminalToolSignal=normalizedToolNames.some(name=>/^(?:terminalexec|terminalinspect|terminalsendkeys)$/.test(name)),simpleTerminalArtifact=/\b(?:create|write|convert|generate|build|implement|run|fix|repair|debug|make)\b[\s\S]{0,120}\b(?:file|script|csv|parquet|json|txt|server|endpoint)\b/i.test(scannedPrompt),terminalComplexRepair=terminalToolSignal&&/\b(?:multiple|several)\s+(?:scripts?|files?|components?)\b|\b(?:pipeline|dependencies)\b[\s\S]{0,100}\b(?:fail|issue|fix|repair|run|execute)\b|\b(?:identify|find|fix|repair)\s+(?:and\s+)?(?:fix\s+)?all\s+(?:the\s+)?issues\b/i.test(scannedPrompt),mentionedTerminalRuntimes=new Set((scannedPrompt.match(/\b(?:gcc|clang|rustc|javac|go\s+build|node|python)\b/gi)??[]).map(name=>name.toLowerCase().replace(/\s+/g," "))),terminalCrossRuntimeArtifact=terminalToolSignal&&(/\bpolyglot\b/i.test(scannedPrompt)||/\b(?:both|each)\b[\s\S]{0,120}\b(?:compilers?|runtimes?|toolchains?)\b/i.test(scannedPrompt)||mentionedTerminalRuntimes.size>=2&&/\b(?:compile|build|run|execute)\b/i.test(scannedPrompt)),terminalFrameworkToNativeArtifact=terminalToolSignal&&/\b(?:pytorch|tensorflow|jax|onnx|state[_ -]?dict|checkpoint|safetensors?)\b|\.(?:pth|pt|onnx)\b/i.test(scannedPrompt)&&/\b(?:pure|native|programmed|written|implemented?)\s+(?:in|using)\s+(?:c\+\+|c|rust|go)\b|\b(?:c\+\+|c|rust|go)\s+(?:program|binary|executable|cli|tool|implementation)\b/i.test(scannedPrompt)&&/\b(?:inference|model|weights?|tensor|export|convert|load)\b/i.test(scannedPrompt);needsTools&&(terminalComplexRepair||terminalCrossRuntimeArtifact||terminalFrameworkToNativeArtifact)&&(agentRisk==="standard"||agentRisk==="high")&&(agentRisk="complex_high");let complexTerminalOperation=/\b(?:git|ssh|nginx|https|certificate|authentication|credential|deploy|production|encrypt|gpg|shred|securely delete|decommission|benchmark|evaluate|embedding|chess|image|search the web|schema|statistical|statistics|aggregate|join|multiple inputs?)\b/i.test(scannedPrompt),terminalCredentialSignal=/\b(?:ssh|nginx|certificate|authentication|credentials?|passwords?|api keys?|deploy|production|encrypt|gpg|shred|securely delete|decommission)\b/i.test(scannedPrompt)||/\b(?:access|auth|authentication|bearer|secret|api)\s+tokens?\b|\btokens?\s+(?:secret|credential|authentication)\b/i.test(scannedPrompt),terminalSafetySensitive=terminalToolSignal&&(highStakes||terminalCredentialSignal),implicitTerminalCode=needsTools&&terminalToolSignal&&agentRisk==="standard"&&!highStakes&&!complexTerminalOperation&&numberedSteps<3&&prompt.length<=1e3&&simpleTerminalArtifact,language=/[\u3400-\u9fff]/.test(scannedPrompt)&&!/[\u3040-\u30ff]/.test(scannedPrompt)?"zh":"other",multipleChoiceSignals=(scannedPrompt.match(/(?:^|\n)\s*[A-D][.)]\s+/gim)??[]).length,numericSignals=(scannedPrompt.match(/-?\d+(?:[.,]\d+)?/g)??[]).length,compactMathProblem=!hasCode&&prompt.length<2500&&numericSignals>=2&&(/[+×÷=%$€£¥]|\b(?:total|each|per|times|half|twice|percent|how many|how much|calculate)\b/i.test(scannedPrompt)||/[??]\s*$/.test(scannedPrompt.trim())||numericSignals>=3),taskType="chat";return needsVision?taskType="vision":estimatedInputTokens>8e4?taskType="long_context":needsTools&&(codeArtifact||hasCode&&codingAction||implicitTerminalCode)?taskType="code_agent":needsTools&&likelyParallelToolCalls&&!complexMultiToolPlan?taskType="tool_agent_parallel":needsTools?taskType="tool_agent":multipleChoiceSignals>=3?taskType="reasoning_mcq":compactMathProblem?taskType="reasoning_math":errorClassSignal||/\b(?:bug|debug|error|failure|failing|regression|crash)\b|修复|报错|错误|调试/i.test(text)?taskType="debug":hasCode||/\b(?:refactor|implement|patch|edit|rewrite)\b|重构|实现|修改/i.test(text)?taskType="code_edit":needsStructuredOutput||/\b(?:extract|json|schema|csv)\b|字段|提取/i.test(text)?taskType="extraction":/\b(?:prove|derive|theorem|formal|mathematical|reasoning)\b|证明|推导|定理|数学/i.test(text)&&(taskType="reasoning"),{taskType,estimatedInputTokens,hasCode,needsTools,toolsAvailable,needsVision,needsStructuredOutput,latencySensitive,highStakes,language,likelyParallelToolCalls,complexMultiToolPlan,agentDomain,deepWebResearch,agentRisk,terminalToolSignal,terminalSafetySensitive,implicitTerminalCode,codeArtifact}}function affinityBand(features){let{taskType,agentDomain,agentRisk,deepWebResearch,terminalToolSignal}=features,terminalSafety=features.terminalSafetySensitive;switch(taskType){case"code_agent":return terminalToolSignal&&agentRisk==="complex_high"?TERMINAL_COMPLEX_HIGH:AFFINITY.codeAgent;case"tool_agent":return terminalToolSignal&&agentRisk==="complex_high"?TERMINAL_COMPLEX_HIGH:terminalToolSignal?terminalSafety?AFFINITY.terminalToolSafety:AFFINITY.terminalTool:agentDomain==="web_research"?deepWebResearch?WEB_RESEARCH_DEEP:WEB_RESEARCH:agentDomain==="retail"?agentRisk==="standard"?AFFINITY.retailStandard:agentRisk==="policy_exception"?RETAIL_POLICY_EXCEPTION:agentRisk==="policy_exception_simple"?RETAIL_POLICY_EXCEPTION_SIMPLE:AFFINITY.retailHigh:agentDomain==="airline"?agentRisk==="complex_high"?AFFINITY.airlineComplex:AFFINITY.airlineStandard:AFFINITY.toolAgent;case"tool_agent_parallel":return terminalToolSignal?terminalSafety?AFFINITY.parallelTerminalSafety:AFFINITY.parallelTerminal:agentDomain==="web_research"?deepWebResearch?WEB_RESEARCH_DEEP:WEB_RESEARCH:agentDomain==="retail"?agentRisk==="policy_exception"?RETAIL_POLICY_EXCEPTION:agentRisk==="policy_exception_simple"?RETAIL_POLICY_EXCEPTION_SIMPLE:AFFINITY.parallelRetail:agentDomain==="airline"?agentRisk==="complex_high"?AFFINITY.parallelAirlineComplex:AFFINITY.parallelAirline:AFFINITY.parallel;case"code_edit":case"debug":return AFFINITY.codeEdit;case"reasoning":return AFFINITY.reasoning;case"reasoning_mcq":return AFFINITY.reasoningMcq;case"reasoning_math":return AFFINITY.reasoningMath;case"vision":return AFFINITY.vision;case"long_context":return AFFINITY.longContext;case"extraction":return features.language==="zh"?AFFINITY.extractionZh:AFFINITY.extraction;case"chat":return AFFINITY.chat}}function affinityIn(band,modelId){let name=modelId.toLowerCase().slice(modelId.indexOf("/")+1);return Math.max(NEUTRAL_AFFINITY,band[name]??0)}function evidenceCandidates(task){return task==="code_agent"?["openai/gpt-5.3-codex","anthropic/claude-sonnet-5","openai/gpt-5.6-luna","google/gemini-3.6-flash","moonshot/kimi-k3.1-pro","deepseek/deepseek-v4-pro"]:task==="tool_agent"?["anthropic/claude-sonnet-5","anthropic/claude-opus-5","openai/gpt-5.6-luna","openai/gpt-4.1","openai/gpt-4o-mini","google/gemini-3.6-flash","openai/gpt-5.3-codex","moonshot/kimi-k3.1-pro","deepseek/deepseek-v4-pro"]:task==="tool_agent_parallel"?["anthropic/claude-opus-5","anthropic/claude-opus-4.8","anthropic/claude-sonnet-5","openai/gpt-5.6-luna","openai/gpt-4.1","openai/gpt-4o-mini","xai/grok-4.5","google/gemini-3.6-flash","deepseek/deepseek-v4-pro"]:task==="long_context"?["google/gemini-3.1-pro","deepseek/deepseek-v4-pro","qwen/qwen3.7-max","zai/glm-5.3","google/gemini-3.6-flash"]:task==="reasoning_mcq"?["google/gemini-3-flash-preview","google/gemini-3.6-flash","xai/grok-4.5","anthropic/claude-sonnet-5","deepseek/deepseek-v4-pro"]:task==="extraction"?["moonshot/kimi-k3.1-pro","google/gemini-3.6-flash","anthropic/claude-sonnet-5"]:task==="reasoning_math"?["google/gemini-3.6-flash","xai/grok-4.5","anthropic/claude-sonnet-5","deepseek/deepseek-v4-pro","moonshot/kimi-k3.1-pro"]:[]}function isEligible(modelId,features,maxOutputTokens,options){let model=options.modelCapabilities?.[modelId]??DEFAULT_MODEL_CAPABILITIES[modelId];return model?features.needsTools&&!model.supportsTools||features.needsVision&&!model.supportsVision||features.needsStructuredOutput&&!model.supportsTools||model.maxOutputTokens<maxOutputTokens?!1:model.contextWindow>=(features.estimatedInputTokens+maxOutputTokens)*1.1:!0}function estimatedCost(modelId,options,inputTokens,outputTokens){let price2=usablePricing(options.modelPricing.get(modelId));return price2?price2.flatPrice!==void 0?price2.flatPrice:(inputTokens*price2.inputPrice+outputTokens*price2.outputPrice)/1e6:Number.POSITIVE_INFINITY}function profileScore(modelId,options,now2){let profile=options.modelPerformance?.[modelId]??LIVE_MODEL_PROFILES[modelId]??HISTORICAL_MODEL_PROFILES[modelId];if(!profile)return;let measuredAt=Date.parse(profile.measuredAt);if(!Number.isFinite(measuredAt))return;let finite=(value,optional2)=>value===void 0?optional2:Number.isFinite(value)&&value>=0;if(!finite(profile.latencyMs,!1)||!finite(profile.outputTokensPerSecond,!1)||!finite(profile.p95LatencyMs,!0)||!finite(profile.intelligenceIndex,!0)||!finite(profile.errorRate,!0)||!finite(profile.samples,!0))return;let ageDays=Math.max(0,(now2.getTime()-measuredAt)/864e5),sampleConfidence=profile.samples===void 0?1:Math.min(1,Math.max(0,profile.samples)/10),freshness=Math.pow(.5,ageDays/30)*sampleConfidence,quality=profile.intelligenceIndex===void 0?void 0:Math.min(1,profile.intelligenceIndex/50),speed=Math.min(1,(2e3/Math.max(500,profile.latencyMs)+profile.outputTokensPerSecond/250)/2),tailSpeed=Math.min(1,3e3/Math.max(750,profile.p95LatencyMs??profile.latencyMs)),reliability=Math.max(0,1-(profile.errorRate??0));return{quality,speed,tailSpeed,reliability,freshness}}function route(prompt,systemPrompt,maxOutputTokens,options){return getStrategy(options.config.strategy??"portfolio").route(prompt,systemPrompt,maxOutputTokens,options)}var UNSEGMENTED_SCRIPT,WORD_CHAR,ASCII_PHRASE,SEGMENTED_WORD_CHAR,BOUNDARY_BEFORE,BOUNDARY_AFTER,BOUNDED_LAST_WORD_LENGTH,SHORT_SUFFIXES,SIBILANT_PLURAL,MID_SUFFIXES,DROPPED_E_SUFFIXES,DOUBLED_CONSONANT_SUFFIXES,matcherCache,BASELINE_MODEL_ID,BASELINE_INPUT_PRICE,BASELINE_OUTPUT_PRICE,SERVER_MARGIN_PERCENT,MIN_PAYMENT_USD,CJK_CHARS,MAX_SCAN_CHARS,RulesStrategy,registry2,DEFAULT_ROUTING_CONFIG,DEFAULT_MODEL_CAPABILITIES,model_profiles_generated_default,LIVE_MODEL_PROFILES,HISTORICAL_MODEL_PROFILES,DEFAULT_PORTFOLIO_WEIGHTS,NEUTRAL_AFFINITY,TERMINAL_COMPLEX_HIGH,WEB_RESEARCH_DEEP,WEB_RESEARCH,RETAIL_POLICY_EXCEPTION,RETAIL_POLICY_EXCEPTION_SIMPLE,AFFINITY,VERIFIED_TOOL_FALLBACKS,PortfolioStrategy,init_dist=__esm({"node_modules/@blockrun/router-core/dist/index.js"(){"use strict";UNSEGMENTED_SCRIPT=/[-ۿ -ヿ㐀-䶿一-鿿가-豈--]/,WORD_CHAR=/[\p{L}\p{N}]/u,ASCII_PHRASE=/^[a-z0-9' -]+$/,SEGMENTED_WORD_CHAR="\\p{Script=Latin}\\p{Script=Cyrillic}\\p{Script=Greek}\\p{N}",BOUNDARY_BEFORE=`(?<![${SEGMENTED_WORD_CHAR}])`,BOUNDARY_AFTER=`(?![${SEGMENTED_WORD_CHAR}])`,BOUNDED_LAST_WORD_LENGTH=6,SHORT_SUFFIXES="(?:s|ed|ing)?",SIBILANT_PLURAL="es",MID_SUFFIXES="(?:s|es|ed|d|ing|er|ers|ly|ment|ments|ation|ations|e|en|n|a|as|o|os|em|et|ung|ungen)?",DROPPED_E_SUFFIXES="(?:ing|ed|es|er|ers|ation|ations)",DOUBLED_CONSONANT_SUFFIXES="(?:ing|ed|er|ers)",matcherCache=new Map;BASELINE_MODEL_ID="anthropic/claude-opus-4.7",BASELINE_INPUT_PRICE=5,BASELINE_OUTPUT_PRICE=25;SERVER_MARGIN_PERCENT=5,MIN_PAYMENT_USD=.001;CJK_CHARS=/[ -ヿ㐀-䶿一-鿿가-豈--]/g;MAX_SCAN_CHARS=8e3;RulesStrategy=class{name="rules";route(prompt,systemPrompt,maxOutputTokens,options){let{config:config2,modelPricing}=options,fullText=`${systemPrompt??""} ${prompt}`,estimatedTokens=estimateTokens(fullText),limit=scanLimit(config2.classifier.promptTruncationChars),scannedPrompt=sampleForScan(prompt,limit),scannedSystemPrompt=systemPrompt?sampleForScan(systemPrompt,limit):void 0,ruleResult=classifyByRules(scannedPrompt,scannedSystemPrompt,estimatedTokens,config2.scoring),{routingProfile}=options,tierConfigs,profileSuffix,profile;if(routingProfile==="eco")tierConfigs=config2.ecoTiers??config2.tiers,profileSuffix=config2.ecoTiers?" | eco":" | eco (default tiers)",profile="eco";else if(routingProfile==="premium")tierConfigs=config2.premiumTiers??config2.tiers,profileSuffix=config2.premiumTiers?" | premium":" | premium (default tiers)",profile="premium";else{let isAutoAgentic=(ruleResult.agenticScore??0)>=.5,agenticModeSetting=config2.overrides.agenticMode,hasToolsInRequest=options.requiresTools??options.hasTools??!1,useAgenticTiers;agenticModeSetting===!1?useAgenticTiers=!1:agenticModeSetting===!0?useAgenticTiers=config2.agenticTiers!=null:useAgenticTiers=(hasToolsInRequest||isAutoAgentic)&&config2.agenticTiers!=null,tierConfigs=useAgenticTiers?config2.agenticTiers:config2.tiers,profileSuffix=useAgenticTiers?` | agentic${hasToolsInRequest?" (tools)":""}`:"",profile=useAgenticTiers?"agentic":"auto"}tierConfigs=applyPromotions(tierConfigs,config2.promotions,profile,options.now),tierConfigs=applyUnavailableModels(tierConfigs,options.unavailableModels);let agenticScoreValue=ruleResult.agenticScore;if(estimatedTokens>config2.overrides.maxTokensForceComplex)return{...selectModel("COMPLEX",.95,"rules",`Input exceeds ${config2.overrides.maxTokensForceComplex} tokens${profileSuffix}`,tierConfigs,modelPricing,estimatedTokens,maxOutputTokens,routingProfile,agenticScoreValue),tierConfigs,profile};let hasStructuredOutput=options.requiresStructuredOutput===!0,tier,confidence,method="rules",reasoning=`score=${ruleResult.score.toFixed(2)} | ${ruleResult.signals.join(", ")}`;if(ruleResult.tier!==null?(tier=ruleResult.tier,confidence=ruleResult.confidence):(tier=config2.overrides.ambiguousDefaultTier,confidence=.5,reasoning+=` | ambiguous -> default: ${tier}`),hasStructuredOutput){let tierRank={SIMPLE:0,MEDIUM:1,COMPLEX:2,REASONING:3},minTier=config2.overrides.structuredOutputMinTier;tierRank[tier]<tierRank[minTier]&&(reasoning+=` | upgraded to ${minTier} (structured output)`,tier=minTier)}return reasoning+=profileSuffix,{...selectModel(tier,confidence,method,reasoning,tierConfigs,modelPricing,estimatedTokens,maxOutputTokens,routingProfile,agenticScoreValue),tierConfigs,profile}}},registry2=new Map;registry2.set("rules",new RulesStrategy);DEFAULT_ROUTING_CONFIG={version:"3.5",strategy:"portfolio",portfolio:{auto:{quality:.47,capability:.2,cost:.18,speed:.07,reliability:.03,legacy:.05},eco:{quality:.36,capability:.2,cost:.28,speed:.1,reliability:.04,legacy:.02},premium:{quality:.58,capability:.2,cost:.08,speed:.06,reliability:.06,legacy:.02},highStakesBoost:{quality:.08,reliability:.05},latencySensitiveSpeedBoost:.08,affinityFloorGap:{auto:.1,eco:.22,premium:.05}},classifier:{llmModel:"google/gemini-3.5-flash-lite",llmMaxTokens:10,llmTemperature:0,promptTruncationChars:500,cacheTtlMs:36e5},scoring:{tokenCountThresholds:{simple:50,complex:500},codeKeywords:["function","class","import","def","SELECT","async","await","const","let","var","return","```","\u51FD\u6570","\u7C7B","\u5BFC\u5165","\u5B9A\u4E49","\u67E5\u8BE2","\u5F02\u6B65","\u7B49\u5F85","\u5E38\u91CF","\u53D8\u91CF","\u8FD4\u56DE","\u95A2\u6570","\u30AF\u30E9\u30B9","\u30A4\u30F3\u30DD\u30FC\u30C8","\u975E\u540C\u671F","\u5B9A\u6570","\u5909\u6570","\u0444\u0443\u043D\u043A\u0446\u0438\u044F","\u043A\u043B\u0430\u0441\u0441","\u0438\u043C\u043F\u043E\u0440\u0442","\u043E\u043F\u0440\u0435\u0434\u0435\u043B","\u0437\u0430\u043F\u0440\u043E\u0441","\u0430\u0441\u0438\u043D\u0445\u0440\u043E\u043D\u043D\u044B\u0439","\u043E\u0436\u0438\u0434\u0430\u0442\u044C","\u043A\u043E\u043D\u0441\u0442\u0430\u043D\u0442\u0430","\u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F","\u0432\u0435\u0440\u043D\u0443\u0442\u044C","funktion","klasse","importieren","definieren","abfrage","asynchron","erwarten","konstante","variable","zur\xFCckgeben","funci\xF3n","clase","importar","definir","consulta","as\xEDncrono","esperar","constante","variable","retornar","fun\xE7\xE3o","classe","importar","definir","consulta","ass\xEDncrono","aguardar","constante","vari\xE1vel","retornar","\uD568\uC218","\uD074\uB798\uC2A4","\uAC00\uC838\uC624\uAE30","\uC815\uC758","\uCFFC\uB9AC","\uBE44\uB3D9\uAE30","\uB300\uAE30","\uC0C1\uC218","\uBCC0\uC218","\uBC18\uD658","\u062F\u0627\u0644\u0629","\u0641\u0626\u0629","\u0627\u0633\u062A\u064A\u0631\u0627\u062F","\u062A\u0639\u0631\u064A\u0641","\u0627\u0633\u062A\u0639\u0644\u0627\u0645","\u063A\u064A\u0631 \u0645\u062A\u0632\u0627\u0645\u0646","\u0627\u0646\u062A\u0638\u0627\u0631","\u062B\u0627\u0628\u062A","\u0645\u062A\u063A\u064A\u0631","\u0625\u0631\u062C\u0627\u0639"],reasoningKeywords:["prove","theorem","derive","step by step","chain of thought","formally","mathematical","proof","logically","\u8BC1\u660E","\u5B9A\u7406","\u63A8\u5BFC","\u9010\u6B65","\u601D\u7EF4\u94FE","\u5F62\u5F0F\u5316","\u6570\u5B66","\u903B\u8F91","\u8A3C\u660E","\u5B9A\u7406","\u5C0E\u51FA","\u30B9\u30C6\u30C3\u30D7\u30D0\u30A4\u30B9\u30C6\u30C3\u30D7","\u8AD6\u7406\u7684","\u0434\u043E\u043A\u0430\u0437\u0430\u0442\u044C","\u0434\u043E\u043A\u0430\u0436\u0438","\u0434\u043E\u043A\u0430\u0437\u0430\u0442\u0435\u043B\u044C\u0441\u0442\u0432","\u0442\u0435\u043E\u0440\u0435\u043C\u0430","\u0432\u044B\u0432\u0435\u0441\u0442\u0438","\u0448\u0430\u0433 \u0437\u0430 \u0448\u0430\u0433\u043E\u043C","\u043F\u043E\u0448\u0430\u0433\u043E\u0432\u043E","\u043F\u043E\u044D\u0442\u0430\u043F\u043D\u043E","\u0446\u0435\u043F\u043E\u0447\u043A\u0430 \u0440\u0430\u0441\u0441\u0443\u0436\u0434\u0435\u043D\u0438\u0439","\u0440\u0430\u0441\u0441\u0443\u0436\u0434\u0435\u043D\u0438","\u0444\u043E\u0440\u043C\u0430\u043B\u044C\u043D\u043E","\u043C\u0430\u0442\u0435\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438","\u043B\u043E\u0433\u0438\u0447\u0435\u0441\u043A\u0438","beweisen","beweis","theorem","ableiten","schritt f\xFCr schritt","gedankenkette","formal","mathematisch","logisch","demostrar","teorema","derivar","paso a paso","cadena de pensamiento","formalmente","matem\xE1tico","prueba","l\xF3gicamente","provar","teorema","derivar","passo a passo","cadeia de pensamento","formalmente","matem\xE1tico","prova","logicamente","\uC99D\uBA85","\uC815\uB9AC","\uB3C4\uCD9C","\uB2E8\uACC4\uBCC4","\uC0AC\uACE0\uC758 \uC5F0\uC1C4","\uD615\uC2DD\uC801","\uC218\uD559\uC801","\uB17C\uB9AC\uC801","\u0625\u062B\u0628\u0627\u062A","\u0646\u0638\u0631\u064A\u0629","\u0627\u0634\u062A\u0642\u0627\u0642","\u062E\u0637\u0648\u0629 \u0628\u062E\u0637\u0648\u0629","\u0633\u0644\u0633\u0644\u0629 \u0627\u0644\u062A\u0641\u0643\u064A\u0631","\u0631\u0633\u0645\u064A\u0627\u064B","\u0631\u064A\u0627\u0636\u064A","\u0628\u0631\u0647\u0627\u0646","\u0645\u0646\u0637\u0642\u064A\u0627\u064B"],simpleKeywords:["what is","define","translate","hello","yes or no","capital of","how old","who is","when was","\u4EC0\u4E48\u662F","\u5B9A\u4E49","\u7FFB\u8BD1","\u4F60\u597D","\u662F\u5426","\u9996\u90FD","\u591A\u5927","\u8C01\u662F","\u4F55\u65F6","\u3068\u306F","\u5B9A\u7FA9","\u7FFB\u8A33","\u3053\u3093\u306B\u3061\u306F","\u306F\u3044\u304B\u3044\u3044\u3048","\u9996\u90FD","\u8AB0","\u0447\u0442\u043E \u0442\u0430\u043A\u043E\u0435","\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435","\u043F\u0435\u0440\u0435\u0432\u0435\u0441\u0442\u0438","\u043F\u0435\u0440\u0435\u0432\u0435\u0434\u0438","\u043F\u0440\u0438\u0432\u0435\u0442","\u0434\u0430 \u0438\u043B\u0438 \u043D\u0435\u0442","\u0441\u0442\u043E\u043B\u0438\u0446\u0430","\u0441\u043A\u043E\u043B\u044C\u043A\u043E \u043B\u0435\u0442","\u043A\u0442\u043E \u0442\u0430\u043A\u043E\u0439","\u043A\u043E\u0433\u0434\u0430","\u043E\u0431\u044A\u044F\u0441\u043D\u0438","was ist","definiere","\xFCbersetze","hallo","ja oder nein","hauptstadt","wie alt","wer ist","wann","erkl\xE4re","qu\xE9 es","definir","traducir","hola","s\xED o no","capital de","cu\xE1ntos a\xF1os","qui\xE9n es","cu\xE1ndo","o que \xE9","definir","traduzir","ol\xE1","sim ou n\xE3o","capital de","quantos anos","quem \xE9","quando","\uBB34\uC5C7","\uC815\uC758","\uBC88\uC5ED","\uC548\uB155\uD558\uC138\uC694","\uC608 \uB610\uB294 \uC544\uB2C8\uC624","\uC218\uB3C4","\uB204\uAD6C","\uC5B8\uC81C","\u0645\u0627 \u0647\u0648","\u062A\u0639\u0631\u064A\u0641","\u062A\u0631\u062C\u0645","\u0645\u0631\u062D\u0628\u0627","\u0646\u0639\u0645 \u0623\u0648 \u0644\u0627","\u0639\u0627\u0635\u0645\u0629","\u0645\u0646 \u0647\u0648","\u0645\u062A\u0649"],technicalKeywords:["algorithm","optimize","architecture","distributed","kubernetes","microservice","database","infrastructure","\u7B97\u6CD5","\u4F18\u5316","\u67B6\u6784","\u5206\u5E03\u5F0F","\u5FAE\u670D\u52A1","\u6570\u636E\u5E93","\u57FA\u7840\u8BBE\u65BD","\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0","\u6700\u9069\u5316","\u30A2\u30FC\u30AD\u30C6\u30AF\u30C1\u30E3","\u5206\u6563","\u30DE\u30A4\u30AF\u30ED\u30B5\u30FC\u30D3\u30B9","\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9","\u0430\u043B\u0433\u043E\u0440\u0438\u0442\u043C","\u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u0442\u044C","\u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0430\u0446\u0438","\u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0438\u0440\u0443\u0439","\u0430\u0440\u0445\u0438\u0442\u0435\u043A\u0442\u0443\u0440\u0430","\u0440\u0430\u0441\u043F\u0440\u0435\u0434\u0435\u043B\u0451\u043D\u043D\u044B\u0439","\u043C\u0438\u043A\u0440\u043E\u0441\u0435\u0440\u0432\u0438\u0441","\u0431\u0430\u0437\u0430 \u0434\u0430\u043D\u043D\u044B\u0445","\u0438\u043D\u0444\u0440\u0430\u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0430","algorithmus","optimieren","architektur","verteilt","kubernetes","mikroservice","datenbank","infrastruktur","algoritmo","optimizar","arquitectura","distribuido","microservicio","base de datos","infraestructura","algoritmo","otimizar","arquitetura","distribu\xEDdo","microsservi\xE7o","banco de dados","infraestrutura","\uC54C\uACE0\uB9AC\uC998","\uCD5C\uC801\uD654","\uC544\uD0A4\uD14D\uCC98","\uBD84\uC0B0","\uB9C8\uC774\uD06C\uB85C\uC11C\uBE44\uC2A4","\uB370\uC774\uD130\uBCA0\uC774\uC2A4","\uC778\uD504\uB77C","\u062E\u0648\u0627\u0631\u0632\u0645\u064A\u0629","\u062A\u062D\u0633\u064A\u0646","\u0628\u0646\u064A\u0629","\u0645\u0648\u0632\u0639","\u062E\u062F\u0645\u0629 \u0645\u0635\u063A\u0631\u0629","\u0642\u0627\u0639\u062F\u0629 \u0628\u064A\u0627\u0646\u0627\u062A","\u0628\u0646\u064A\u0629 \u062A\u062D\u062A\u064A\u0629"],creativeKeywords:["story","poem","compose","brainstorm","creative","imagine","write a","\u6545\u4E8B","\u8BD7","\u521B\u4F5C","\u5934\u8111\u98CE\u66B4","\u521B\u610F","\u60F3\u8C61","\u5199\u4E00\u4E2A","\u7269\u8A9E","\u8A69","\u4F5C\u66F2","\u30D6\u30EC\u30A4\u30F3\u30B9\u30C8\u30FC\u30E0","\u5275\u9020\u7684","\u60F3\u50CF","\u0438\u0441\u0442\u043E\u0440\u0438\u044F","\u0440\u0430\u0441\u0441\u043A\u0430\u0437","\u0441\u0442\u0438\u0445\u043E\u0442\u0432\u043E\u0440\u0435\u043D\u0438\u0435","\u0441\u043E\u0447\u0438\u043D\u0438\u0442\u044C","\u0441\u043E\u0447\u0438\u043D\u0438","\u043C\u043E\u0437\u0433\u043E\u0432\u043E\u0439 \u0448\u0442\u0443\u0440\u043C","\u0442\u0432\u043E\u0440\u0447\u0435\u0441\u043A\u0438\u0439","\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u0442\u044C","\u043F\u0440\u0438\u0434\u0443\u043C\u0430\u0439","\u043D\u0430\u043F\u0438\u0448\u0438","geschichte","gedicht","komponieren","brainstorming","kreativ","vorstellen","schreibe","erz\xE4hlung","historia","poema","componer","lluvia de ideas","creativo","imaginar","escribe","hist\xF3ria","poema","compor","criativo","imaginar","escreva","\uC774\uC57C\uAE30","\uC2DC","\uC791\uACE1","\uBE0C\uB808\uC778\uC2A4\uD1A0\uBC0D","\uCC3D\uC758\uC801","\uC0C1\uC0C1","\uC791\uC131","\u0642\u0635\u0629","\u0642\u0635\u064A\u062F\u0629","\u062A\u0623\u0644\u064A\u0641","\u0639\u0635\u0641 \u0630\u0647\u0646\u064A","\u0625\u0628\u062F\u0627\u0639\u064A","\u062A\u062E\u064A\u0644","\u0627\u0643\u062A\u0628"],imperativeVerbs:["build","create","implement","design","develop","construct","generate","deploy","configure","set up","\u6784\u5EFA","\u521B\u5EFA","\u5B9E\u73B0","\u8BBE\u8BA1","\u5F00\u53D1","\u751F\u6210","\u90E8\u7F72","\u914D\u7F6E","\u8BBE\u7F6E","\u69CB\u7BC9","\u4F5C\u6210","\u5B9F\u88C5","\u8A2D\u8A08","\u958B\u767A","\u751F\u6210","\u30C7\u30D7\u30ED\u30A4","\u8A2D\u5B9A","\u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u044C","\u043F\u043E\u0441\u0442\u0440\u043E\u0439","\u0441\u043E\u0437\u0434\u0430\u0442\u044C","\u0441\u043E\u0437\u0434\u0430\u0439","\u0440\u0435\u0430\u043B\u0438\u0437\u043E\u0432\u0430\u0442\u044C","\u0440\u0435\u0430\u043B\u0438\u0437\u0443\u0439","\u0441\u043F\u0440\u043E\u0435\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C","\u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0430\u0442\u044C","\u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0430\u0439","\u0441\u043A\u043E\u043D\u0441\u0442\u0440\u0443\u0438\u0440\u043E\u0432\u0430\u0442\u044C","\u0441\u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C","\u0441\u0433\u0435\u043D\u0435\u0440\u0438\u0440\u0443\u0439","\u0440\u0430\u0437\u0432\u0435\u0440\u043D\u0443\u0442\u044C","\u0440\u0430\u0437\u0432\u0435\u0440\u043D\u0438","\u043D\u0430\u0441\u0442\u0440\u043E\u0438\u0442\u044C","\u043D\u0430\u0441\u0442\u0440\u043E\u0439","erstellen","bauen","implementieren","entwerfen","entwickeln","konstruieren","generieren","bereitstellen","konfigurieren","einrichten","construir","crear","implementar","dise\xF1ar","desarrollar","generar","desplegar","configurar","construir","criar","implementar","projetar","desenvolver","gerar","implantar","configurar","\uAD6C\uCD95","\uC0DD\uC131","\uAD6C\uD604","\uC124\uACC4","\uAC1C\uBC1C","\uBC30\uD3EC","\uC124\uC815","\u0628\u0646\u0627\u0621","\u0625\u0646\u0634\u0627\u0621","\u062A\u0646\u0641\u064A\u0630","\u062A\u0635\u0645\u064A\u0645","\u062A\u0637\u0648\u064A\u0631","\u062A\u0648\u0644\u064A\u062F","\u0646\u0634\u0631","\u0625\u0639\u062F\u0627\u062F"],constraintIndicators:["under","at most","at least","within","no more than","o(","maximum","minimum","limit","budget","\u4E0D\u8D85\u8FC7","\u81F3\u5C11","\u6700\u591A","\u5728\u5185","\u6700\u5927","\u6700\u5C0F","\u9650\u5236","\u9884\u7B97","\u4EE5\u4E0B","\u6700\u5927","\u6700\u5C0F","\u5236\u9650","\u4E88\u7B97","\u043D\u0435 \u0431\u043E\u043B\u0435\u0435","\u043D\u0435 \u043C\u0435\u043D\u0435\u0435","\u043A\u0430\u043A \u043C\u0438\u043D\u0438\u043C\u0443\u043C","\u0432 \u043F\u0440\u0435\u0434\u0435\u043B\u0430\u0445","\u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C","\u043C\u0438\u043D\u0438\u043C\u0443\u043C","\u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u0435","\u0431\u044E\u0434\u0436\u0435\u0442","h\xF6chstens","mindestens","innerhalb","nicht mehr als","maximal","minimal","grenze","budget","como m\xE1ximo","al menos","dentro de","no m\xE1s de","m\xE1ximo","m\xEDnimo","l\xEDmite","presupuesto","no m\xE1ximo","pelo menos","dentro de","n\xE3o mais que","m\xE1ximo","m\xEDnimo","limite","or\xE7amento","\uC774\uD558","\uC774\uC0C1","\uCD5C\uB300","\uCD5C\uC18C","\uC81C\uD55C","\uC608\uC0B0","\u0639\u0644\u0649 \u0627\u0644\u0623\u0643\u062B\u0631","\u0639\u0644\u0649 \u0627\u0644\u0623\u0642\u0644","\u0636\u0645\u0646","\u0644\u0627 \u064A\u0632\u064A\u062F \u0639\u0646","\u0623\u0642\u0635\u0649","\u0623\u062F\u0646\u0649","\u062D\u062F","\u0645\u064A\u0632\u0627\u0646\u064A\u0629"],outputFormatKeywords:["json","yaml","xml","table","csv","markdown","schema","format as","structured","\u8868\u683C","\u683C\u5F0F\u5316\u4E3A","\u7ED3\u6784\u5316","\u30C6\u30FC\u30D6\u30EB","\u30D5\u30A9\u30FC\u30DE\u30C3\u30C8","\u69CB\u9020\u5316","\u0442\u0430\u0431\u043B\u0438\u0446\u0430","\u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043A\u0430\u043A","\u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439","tabelle","formatieren als","strukturiert","tabla","formatear como","estructurado","tabela","formatar como","estruturado","\uD14C\uC774\uBE14","\uD615\uC2DD","\uAD6C\uC870\uD654","\u062C\u062F\u0648\u0644","\u062A\u0646\u0633\u064A\u0642","\u0645\u0646\u0638\u0645"],referenceKeywords:["above","below","previous","following","the docs","the api","the code","earlier","attached","\u4E0A\u9762","\u4E0B\u9762","\u4E4B\u524D","\u63A5\u4E0B\u6765","\u6587\u6863","\u4EE3\u7801","\u9644\u4EF6","\u4E0A\u8A18","\u4E0B\u8A18","\u524D\u306E","\u6B21\u306E","\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8","\u30B3\u30FC\u30C9","\u0432\u044B\u0448\u0435","\u043D\u0438\u0436\u0435","\u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0438\u0439","\u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0439","\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430\u0446\u0438\u044F","\u043A\u043E\u0434","\u0440\u0430\u043D\u0435\u0435","\u0432\u043B\u043E\u0436\u0435\u043D\u0438\u0435","oben","unten","vorherige","folgende","dokumentation","der code","fr\xFCher","anhang","arriba","abajo","anterior","siguiente","documentaci\xF3n","el c\xF3digo","adjunto","acima","abaixo","anterior","seguinte","documenta\xE7\xE3o","o c\xF3digo","anexo","\uC704","\uC544\uB798","\uC774\uC804","\uB2E4\uC74C","\uBB38\uC11C","\uCF54\uB4DC","\uCCA8\uBD80","\u0623\u0639\u0644\u0627\u0647","\u0623\u062F\u0646\u0627\u0647","\u0627\u0644\u0633\u0627\u0628\u0642","\u0627\u0644\u062A\u0627\u0644\u064A","\u0627\u0644\u0648\u062B\u0627\u0626\u0642","\u0627\u0644\u0643\u0648\u062F","\u0645\u0631\u0641\u0642"],negationKeywords:["don't","do not","avoid","never","without","except","exclude","no longer","\u4E0D\u8981","\u907F\u514D","\u4ECE\u4E0D","\u6CA1\u6709","\u9664\u4E86","\u6392\u9664","\u3057\u306A\u3044\u3067","\u907F\u3051\u308B","\u6C7A\u3057\u3066","\u306A\u3057\u3067","\u9664\u304F","\u043D\u0435 \u0434\u0435\u043B\u0430\u0439","\u043D\u0435 \u043D\u0430\u0434\u043E","\u043D\u0435\u043B\u044C\u0437\u044F","\u0438\u0437\u0431\u0435\u0433\u0430\u0442\u044C","\u043D\u0438\u043A\u043E\u0433\u0434\u0430","\u0431\u0435\u0437","\u043A\u0440\u043E\u043C\u0435","\u0438\u0441\u043A\u043B\u044E\u0447\u0438\u0442\u044C","\u0431\u043E\u043B\u044C\u0448\u0435 \u043D\u0435","nicht","vermeide","niemals","ohne","au\xDFer","ausschlie\xDFen","nicht mehr","no hagas","evitar","nunca","sin","excepto","excluir","n\xE3o fa\xE7a","evitar","nunca","sem","exceto","excluir","\uD558\uC9C0 \uB9C8","\uD53C\uD558\uB2E4","\uC808\uB300","\uC5C6\uC774","\uC81C\uC678","\u0644\u0627 \u062A\u0641\u0639\u0644","\u062A\u062C\u0646\u0628","\u0623\u0628\u062F\u0627\u064B","\u0628\u062F\u0648\u0646","\u0628\u0627\u0633\u062A\u062B\u0646\u0627\u0621","\u0627\u0633\u062A\u0628\u0639\u0627\u062F"],domainSpecificKeywords:["quantum","fpga","vlsi","risc-v","asic","photonics","genomics","proteomics","topological","homomorphic","zero-knowledge","lattice-based","\u91CF\u5B50","\u5149\u5B50\u5B66","\u57FA\u56E0\u7EC4\u5B66","\u86CB\u767D\u8D28\u7EC4\u5B66","\u62D3\u6251","\u540C\u6001","\u96F6\u77E5\u8BC6","\u683C\u5BC6\u7801","\u91CF\u5B50","\u30D5\u30A9\u30C8\u30CB\u30AF\u30B9","\u30B2\u30CE\u30DF\u30AF\u30B9","\u30C8\u30DD\u30ED\u30B8\u30AB\u30EB","\u043A\u0432\u0430\u043D\u0442\u043E\u0432\u044B\u0439","\u0444\u043E\u0442\u043E\u043D\u0438\u043A\u0430","\u0433\u0435\u043D\u043E\u043C\u0438\u043A\u0430","\u043F\u0440\u043E\u0442\u0435\u043E\u043C\u0438\u043A\u0430","\u0442\u043E\u043F\u043E\u043B\u043E\u0433\u0438\u0447\u0435\u0441\u043A\u0438\u0439","\u0433\u043E\u043C\u043E\u043C\u043E\u0440\u0444\u043D\u044B\u0439","\u0441 \u043D\u0443\u043B\u0435\u0432\u044B\u043C \u0440\u0430\u0437\u0433\u043B\u0430\u0448\u0435\u043D\u0438\u0435\u043C","\u043D\u0430 \u043E\u0441\u043D\u043E\u0432\u0435 \u0440\u0435\u0448\u0451\u0442\u043E\u043A","quanten","photonik","genomik","proteomik","topologisch","homomorph","zero-knowledge","gitterbasiert","cu\xE1ntico","fot\xF3nica","gen\xF3mica","prote\xF3mica","topol\xF3gico","homom\xF3rfico","qu\xE2ntico","fot\xF4nica","gen\xF4mica","prote\xF4mica","topol\xF3gico","homom\xF3rfico","\uC591\uC790","\uD3EC\uD1A0\uB2C9\uC2A4","\uC720\uC804\uCCB4\uD559","\uC704\uC0C1","\uB3D9\uD615","\u0643\u0645\u064A","\u0636\u0648\u0626\u064A\u0627\u062A","\u062C\u064A\u0646\u0648\u0645\u064A\u0627\u062A","\u0637\u0648\u0628\u0648\u0644\u0648\u062C\u064A","\u062A\u0645\u0627\u062B\u0644\u064A"],agenticTaskKeywords:["read file","read the file","look at","check the","open the","edit","modify","update the","change the","write to","create file","execute","deploy","install","npm","pip","compile","after that","and also","once done","step 1","step 2","fix","debug","until it works","keep trying","iterate","make sure","verify","confirm","\u8BFB\u53D6\u6587\u4EF6","\u67E5\u770B","\u6253\u5F00","\u7F16\u8F91","\u4FEE\u6539","\u66F4\u65B0","\u521B\u5EFA","\u6267\u884C","\u90E8\u7F72","\u5B89\u88C5","\u7B2C\u4E00\u6B65","\u7B2C\u4E8C\u6B65","\u4FEE\u590D","\u8C03\u8BD5","\u76F4\u5230","\u786E\u8BA4","\u9A8C\u8BC1","leer archivo","editar","modificar","actualizar","ejecutar","desplegar","instalar","paso 1","paso 2","arreglar","depurar","verificar","ler arquivo","editar","modificar","atualizar","executar","implantar","instalar","passo 1","passo 2","corrigir","depurar","verificar","\uD30C\uC77C \uC77D\uAE30","\uD3B8\uC9D1","\uC218\uC815","\uC5C5\uB370\uC774\uD2B8","\uC2E4\uD589","\uBC30\uD3EC","\uC124\uCE58","\uB2E8\uACC4 1","\uB2E8\uACC4 2","\uB514\uBC84\uADF8","\uD655\uC778","\u0642\u0631\u0627\u0621\u0629 \u0645\u0644\u0641","\u062A\u062D\u0631\u064A\u0631","\u062A\u0639\u062F\u064A\u0644","\u062A\u062D\u062F\u064A\u062B","\u062A\u0646\u0641\u064A\u0630","\u0646\u0634\u0631","\u062A\u062B\u0628\u064A\u062A","\u0627\u0644\u062E\u0637\u0648\u0629 1","\u0627\u0644\u062E\u0637\u0648\u0629 2","\u0625\u0635\u0644\u0627\u062D","\u062A\u0635\u062D\u064A\u062D","\u062A\u062D\u0642\u0642"],dimensionWeights:{tokenCount:.08,codePresence:.15,reasoningMarkers:.18,technicalTerms:.1,creativeMarkers:.05,simpleIndicators:.02,multiStepPatterns:.12,questionComplexity:.05,imperativeVerbs:.03,constraintCount:.04,outputFormat:.03,referenceComplexity:.02,negationComplexity:.01,domainSpecificity:.02,agenticTask:.04},tierBoundaries:{simpleMedium:0,mediumComplex:.3,complexReasoning:.5},confidenceSteepness:12,confidenceThreshold:.7},tiers:{SIMPLE:{primary:"google/gemini-3.5-flash-lite",fallback:["google/gemini-3-flash-preview","deepseek/deepseek-chat","google/gemini-3.1-flash-lite","openai/gpt-5.6-luna","openai/gpt-6-luna","google/gemini-2.5-flash-lite","nvidia/nemotron-3.5-lightning"]},MEDIUM:{primary:"google/gemini-3.6-flash",fallback:["zai/glm-5.3-flash","openai/gpt-5.6-terra","google/gemini-3-flash-preview","deepseek/deepseek-chat","google/gemini-3.5-flash-lite","minimax/minimax-m3","google/gemini-3.1-flash-lite","openai/gpt-5.6-luna","google/gemini-2.5-flash-lite"]},COMPLEX:{primary:"google/gemini-3.1-pro",fallback:["google/gemini-3.6-flash","anthropic/claude-sonnet-5","xai/grok-4.7","google/gemini-3.8-flash","anthropic/claude-sonnet-5.5","openai/gpt-5.6-terra","openai/gpt-6.2-sol","zai/glm-5.3","moonshot/kimi-k3.1-pro","deepseek/deepseek-v4-pro","deepseek/deepseek-chat","google/gemini-3.5-flash-lite"]},REASONING:{primary:"deepseek/deepseek-reasoner",fallback:["deepseek/deepseek-v4-pro","xai/grok-4.3","qwen/qwen3.7-plus","google/gemini-3.6-flash","openai/gpt-5.4-mini"]}},ecoTiers:{SIMPLE:{primary:"nvidia/nemotron-3.5-lightning",fallback:["nvidia/nemotron-3-nano-omni-30b-a3b-reasoning","google/gemini-2.5-flash-lite","zai/glm-5.3-flash","openai/gpt-5.6-luna","openai/gpt-6-luna","google/gemini-3.1-flash-lite"]},MEDIUM:{primary:"zai/glm-5.3-flash",fallback:["deepseek/deepseek-chat","google/gemini-3.1-flash-lite","openai/gpt-5.6-luna","openai/gpt-6-luna","google/gemini-2.5-flash-lite","google/gemini-3.5-flash-lite"]},COMPLEX:{primary:"zai/glm-5.3-flash",fallback:["deepseek/deepseek-chat","minimax/minimax-m3","deepseek/deepseek-v4-pro","google/gemini-3.1-flash-lite","google/gemini-3.5-flash-lite"]},REASONING:{primary:"deepseek/deepseek-reasoner",fallback:["deepseek/deepseek-v4-pro","qwen/qwen3.7-plus","minimax/minimax-m3","zai/glm-5.3-flash"]}},premiumTiers:{SIMPLE:{primary:"google/gemini-3.6-flash",fallback:["anthropic/claude-haiku-4.5","zai/glm-5.3","google/gemini-3.5-flash-lite","deepseek/deepseek-chat"]},MEDIUM:{primary:"openai/gpt-5.3-codex",fallback:["anthropic/claude-sonnet-5","moonshot/kimi-k3.1-pro","zai/glm-5.3","google/gemini-3.6-flash","google/gemini-3.8-flash","xai/grok-4.7","anthropic/claude-sonnet-5.5","openai/gpt-5.6-terra"]},COMPLEX:{primary:"anthropic/claude-opus-5.5",fallback:["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-sonnet-5.5","xai/grok-4.7","moonshot/kimi-k3.1-pro","openai/gpt-5.6-terra","openai/gpt-6.2-sol","openai/gpt-5.3-codex","zai/glm-5.3","deepseek/deepseek-v4-pro","deepseek/deepseek-chat","nvidia/nemotron-3.5-lightning"]},REASONING:{primary:"anthropic/claude-sonnet-5",fallback:["anthropic/claude-sonnet-5.5","anthropic/claude-opus-5.5","anthropic/claude-opus-5","xai/grok-4.7","deepseek/deepseek-v4-pro","xai/grok-4.3","openai/gpt-5.4-mini"]}},agenticTiers:{SIMPLE:{primary:"openai/gpt-4o-mini",fallback:["openai/gpt-5.6-luna","zai/glm-5.3-flash","anthropic/claude-haiku-4.5","google/gemini-3.5-flash-lite"]},MEDIUM:{primary:"openai/gpt-5.6-luna",fallback:["google/gemini-3.6-flash","zai/glm-5.3-flash","openai/gpt-5.6-terra","openai/gpt-4o-mini","anthropic/claude-haiku-4.5","deepseek/deepseek-chat","moonshot/kimi-k3.1-pro"]},COMPLEX:{primary:"anthropic/claude-sonnet-5",fallback:["anthropic/claude-sonnet-5.5","anthropic/claude-opus-5.5","anthropic/claude-opus-5","xai/grok-4.7","moonshot/kimi-k3.1-pro","openai/gpt-5.6-terra","openai/gpt-6.2-sol","openai/gpt-5.3-codex","zai/glm-5.3","deepseek/deepseek-v4-pro","deepseek/deepseek-chat","nvidia/nemotron-3.5-lightning"]},REASONING:{primary:"anthropic/claude-sonnet-5",fallback:["anthropic/claude-sonnet-5.5","anthropic/claude-opus-5.5","anthropic/claude-opus-5","xai/grok-4.7","deepseek/deepseek-v4-pro","deepseek/deepseek-reasoner"]}},promotions:[],overrides:{maxTokensForceComplex:1e5,structuredOutputMinTier:"MEDIUM",ambiguousDefaultTier:"MEDIUM"}},DEFAULT_MODEL_CAPABILITIES=Object.freeze({"anthropic/claude-fable-5":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-fable-5.1":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-fable-5.2":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-haiku-4.5":{contextWindow:2e5,maxOutputTokens:64e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-opus-4.5":{contextWindow:2e5,maxOutputTokens:64e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-opus-4.7":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-opus-4.8":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-opus-5":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-opus-5.5":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-sonnet-4.5":{contextWindow:2e5,maxOutputTokens:64e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-sonnet-4.6":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-sonnet-5":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"anthropic/claude-sonnet-5.5":{contextWindow:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"deepseek/deepseek-chat":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"deepseek/deepseek-reasoner":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"deepseek/deepseek-v4-flash-vision-exp":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!1,supportsVision:!0},"deepseek/deepseek-v4-pro":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"deepseek/deepseek-v4.1-flash":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"google/gemini-2.5-flash":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-2.5-flash-lite":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"google/gemini-2.5-pro":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-3-flash-preview":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-3.1-flash-lite":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"google/gemini-3.1-pro":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-3.5-flash-lite":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"google/gemini-3.6-flash":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-3.8-flash":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-4-argon":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-4-carbon":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-4-hydrogen":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"google/gemini-4-neon":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"minimax/minimax-m2.7":{contextWindow:204800,maxOutputTokens:16384,supportsTools:!0,supportsVision:!1},"minimax/minimax-m3":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"mistral/mistral-large-4":{contextWindow:524288,maxOutputTokens:262144,supportsTools:!1,supportsVision:!0},"moonshot/kimi-k3.1-pro":{contextWindow:1048576,maxOutputTokens:65536,supportsTools:!0,supportsVision:!0},"nvidia/minimax-m3.1-flash":{contextWindow:1048576,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"nvidia/muse-glimmer-30b":{contextWindow:131072,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning":{contextWindow:256e3,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"nvidia/nemotron-3-super-120b":{contextWindow:131072,maxOutputTokens:16384,supportsTools:!1,supportsVision:!0},"nvidia/nemotron-3-ultra-550b":{contextWindow:1e6,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"nvidia/nemotron-3.5-bolt":{contextWindow:131072,maxOutputTokens:16384,supportsTools:!0,supportsVision:!0},"nvidia/nemotron-3.5-lightning":{contextWindow:1e6,maxOutputTokens:16384,supportsTools:!1,supportsVision:!1},"openai/chat-latest":{contextWindow:128e3,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-4.1":{contextWindow:128e3,maxOutputTokens:32768,supportsTools:!0,supportsVision:!0},"openai/gpt-4.1-mini":{contextWindow:128e3,maxOutputTokens:32768,supportsTools:!0,supportsVision:!1},"openai/gpt-4o":{contextWindow:128e3,maxOutputTokens:16384,supportsTools:!0,supportsVision:!0},"openai/gpt-4o-mini":{contextWindow:128e3,maxOutputTokens:16384,supportsTools:!0,supportsVision:!1},"openai/gpt-5-mini":{contextWindow:2e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"openai/gpt-5.1":{contextWindow:4e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.2":{contextWindow:4e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.2-pro":{contextWindow:4e5,maxOutputTokens:128e3,supportsTools:!1,supportsVision:!0},"openai/gpt-5.3-codex":{contextWindow:4e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"openai/gpt-5.4":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.4-mini":{contextWindow:4e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.4-nano":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"openai/gpt-5.4-pro":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!1,supportsVision:!0},"openai/gpt-5.5":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.5-pro":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!1,supportsVision:!0},"openai/gpt-5.6-luna":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.6-luna-pro":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.6-sol":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.6-sol-pro":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.6-terra":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-5.6-terra-pro":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-6-astra":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-6-luna":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-6-sol":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-6.1-sol":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-6.2-astra":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/gpt-6.2-sol":{contextWindow:105e4,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!0},"openai/o3":{contextWindow:2e5,maxOutputTokens:1e5,supportsTools:!0,supportsVision:!1},"poolside/laguna-s-2.1":{contextWindow:1048576,maxOutputTokens:131072,supportsTools:!1,supportsVision:!1},"poolside/laguna-xs-2.1":{contextWindow:131072,maxOutputTokens:16384,supportsTools:!0,supportsVision:!1},"qwen/qwen3.7-flash":{contextWindow:1e6,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"qwen/qwen3.7-max":{contextWindow:1e6,maxOutputTokens:65536,supportsTools:!0,supportsVision:!1},"qwen/qwen3.7-plus":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!0,supportsVision:!1},"qwen/qwen3.8-flash":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!1,supportsVision:!0},"qwen/qwen3.8-max":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!1,supportsVision:!1},"tencent/hy4-preview":{contextWindow:1048576,maxOutputTokens:64e3,supportsTools:!1,supportsVision:!1},"xai/grok-4.3":{contextWindow:1e6,maxOutputTokens:16384,supportsTools:!0,supportsVision:!0},"xai/grok-4.5":{contextWindow:5e5,maxOutputTokens:16384,supportsTools:!0,supportsVision:!0},"xai/grok-4.6":{contextWindow:5e5,maxOutputTokens:16384,supportsTools:!0,supportsVision:!0},"xai/grok-4.7":{contextWindow:5e5,maxOutputTokens:16384,supportsTools:!0,supportsVision:!0},"xai/grok-build-0.1":{contextWindow:256e3,maxOutputTokens:16384,supportsTools:!0,supportsVision:!1},"xiaomi/mimo-v2.5":{contextWindow:1048576,maxOutputTokens:131072,supportsTools:!0,supportsVision:!0},"xiaomi/mimo-v2.5-pro":{contextWindow:1048576,maxOutputTokens:131072,supportsTools:!0,supportsVision:!1},"zai/glm-5":{contextWindow:2e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"zai/glm-5-turbo":{contextWindow:2e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"zai/glm-5.1":{contextWindow:2e5,maxOutputTokens:128e3,supportsTools:!0,supportsVision:!1},"zai/glm-5.2":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!0,supportsVision:!1},"zai/glm-5.3":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!0,supportsVision:!1},"zai/glm-5.3-flash":{contextWindow:1e6,maxOutputTokens:131072,supportsTools:!0,supportsVision:!0}}),model_profiles_generated_default={"anthropic/claude-fable-5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:9298.5,p95LatencyMs:9873.4,outputTokensPerSecond:55.17,errorRate:0,samples:3},"anthropic/claude-fable-5.2":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:5587.3,p95LatencyMs:6206.1,outputTokensPerSecond:92.94,errorRate:0,samples:3},"anthropic/claude-haiku-4.5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3157.4,p95LatencyMs:3170.7,outputTokensPerSecond:162.16,errorRate:0,samples:3},"anthropic/claude-opus-4.5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6497.7,p95LatencyMs:6953.7,outputTokensPerSecond:78.99,errorRate:0,samples:3},"anthropic/claude-opus-4.7":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5316.5,p95LatencyMs:6121.5,outputTokensPerSecond:97.34,errorRate:0,samples:3},"anthropic/claude-opus-4.8":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6216.1,p95LatencyMs:6847.7,outputTokensPerSecond:82.81,errorRate:0,samples:3},"anthropic/claude-opus-5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:7309,p95LatencyMs:7745.2,outputTokensPerSecond:70.17,errorRate:0,samples:3},"anthropic/claude-opus-5.5":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:6485.2,p95LatencyMs:6951.2,outputTokensPerSecond:79.15,errorRate:0,samples:3},"anthropic/claude-sonnet-4.5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6330.4,p95LatencyMs:6631.6,outputTokensPerSecond:81.03,errorRate:0,samples:3},"anthropic/claude-sonnet-4.6":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6508,p95LatencyMs:6698.3,outputTokensPerSecond:78.6,errorRate:0,samples:3},"anthropic/claude-sonnet-5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6165.4,p95LatencyMs:6582.9,outputTokensPerSecond:83.62,errorRate:0,samples:3},"anthropic/claude-sonnet-5.5":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:4770.2,p95LatencyMs:5352,outputTokensPerSecond:108.11,errorRate:0,samples:3},"deepseek/deepseek-chat":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4351.4,p95LatencyMs:4543.7,outputTokensPerSecond:117.78,errorRate:0,samples:3},"deepseek/deepseek-reasoner":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5201.2,p95LatencyMs:6079.6,outputTokensPerSecond:99.77,errorRate:0,samples:3},"deepseek/deepseek-v4-flash-vision-exp":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:4078.4,p95LatencyMs:4464.5,outputTokensPerSecond:127,errorRate:0,samples:3},"deepseek/deepseek-v4-pro":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:8781.2,p95LatencyMs:9881.1,outputTokensPerSecond:58.98,errorRate:0,samples:3},"deepseek/deepseek-v4.1-flash":{measuredAt:"2026-10-20T18:12:51Z",latencyMs:2383.5,p95LatencyMs:2547.8,outputTokensPerSecond:216.53,errorRate:0,samples:3},"google/gemini-2.5-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5416.4,p95LatencyMs:6442.8,outputTokensPerSecond:213.07,errorRate:0,samples:3},"google/gemini-2.5-flash-lite":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5002.6,p95LatencyMs:5780.3,outputTokensPerSecond:408.43,errorRate:0,samples:3},"google/gemini-2.5-pro":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:28169.5,p95LatencyMs:29491.4,outputTokensPerSecond:147.3,errorRate:0,samples:3},"google/gemini-3-flash-preview":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4717.1,p95LatencyMs:5037.1,outputTokensPerSecond:198.71,errorRate:0,samples:3},"google/gemini-3.1-flash-lite":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:2855.8,p95LatencyMs:3172.7,outputTokensPerSecond:286.91,errorRate:0,samples:3},"google/gemini-3.1-pro":{measuredAt:"2026-08-29T16:59:54Z",latencyMs:24194.1,p95LatencyMs:27269.6,outputTokensPerSecond:109.47,errorRate:0,samples:3},"google/gemini-3.5-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5320.6,p95LatencyMs:5429.8,outputTokensPerSecond:226.21,errorRate:0,samples:3},"google/gemini-3.5-flash-lite":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3515.8,p95LatencyMs:4363.4,outputTokensPerSecond:248.9,errorRate:0,samples:3},"google/gemini-3.6-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:13020,p95LatencyMs:15383.1,outputTokensPerSecond:187.87,errorRate:0,samples:3},"google/gemini-4-argon":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:9565.7,p95LatencyMs:10491.9,outputTokensPerSecond:53.87,errorRate:0,samples:3},"google/gemini-4-carbon":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:10692.9,p95LatencyMs:12609.2,outputTokensPerSecond:48.61,errorRate:0,samples:3},"google/gemini-4-hydrogen":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:4520.7,p95LatencyMs:4928.3,outputTokensPerSecond:113.78,errorRate:0,samples:3},"google/gemini-4-neon":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:6728,p95LatencyMs:8294.8,outputTokensPerSecond:78,errorRate:0,samples:3},"minimax/minimax-m2.7":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:8761.1,p95LatencyMs:10199.3,outputTokensPerSecond:59.18,errorRate:0,samples:3},"minimax/minimax-m3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:11101.9,p95LatencyMs:26087.1,outputTokensPerSecond:101.12,errorRate:0,samples:3},"moonshot/kimi-k3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:24498.9,p95LatencyMs:40365.3,outputTokensPerSecond:25.11,errorRate:0,samples:3},"moonshot/kimi-k3.1-pro":{measuredAt:"2026-11-23T20:18:18Z",latencyMs:9243.1,p95LatencyMs:10504.1,outputTokensPerSecond:55.89,errorRate:0,samples:3},"nvidia/mistral-nemotron":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:7349.6,p95LatencyMs:9932.3,outputTokensPerSecond:79.48,errorRate:.3333,samples:3},"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning":{measuredAt:"2026-08-29T16:59:54Z",latencyMs:9324.6,p95LatencyMs:12992,outputTokensPerSecond:64.96,errorRate:.3333,samples:3},"nvidia/nemotron-3.5-bolt":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:5670.2,p95LatencyMs:5688.6,outputTokensPerSecond:90.3,errorRate:0,samples:3},"nvidia/nemotron-nano-12b-v2-vl":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5846.9,p95LatencyMs:5846.9,outputTokensPerSecond:87.57,errorRate:.6667,samples:3},"nvidia/nemotron-nano-9b-v2":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5282.5,p95LatencyMs:5282.5,outputTokensPerSecond:96.92,errorRate:.6667,samples:3},"nvidia/step-3.7-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4617.4,p95LatencyMs:5237.4,outputTokensPerSecond:112.92,errorRate:.3333,samples:3},"openai/chat-latest":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3690.9,p95LatencyMs:4344,outputTokensPerSecond:111.85,errorRate:0,samples:3},"openai/gpt-4.1":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3527.9,p95LatencyMs:3831.7,outputTokensPerSecond:141.27,errorRate:0,samples:3},"openai/gpt-4.1-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4268.2,p95LatencyMs:5101.5,outputTokensPerSecond:103.42,errorRate:0,samples:3},"openai/gpt-4.1-nano":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3088.3,p95LatencyMs:3369.2,outputTokensPerSecond:150.31,errorRate:0,samples:3},"openai/gpt-4o":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:2995.2,p95LatencyMs:3174.2,outputTokensPerSecond:171.32,errorRate:0,samples:3},"openai/gpt-4o-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4751.5,p95LatencyMs:4930.4,outputTokensPerSecond:107.84,errorRate:0,samples:3},"openai/gpt-5-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4558.1,p95LatencyMs:5081.9,outputTokensPerSecond:113.25,errorRate:0,samples:3},"openai/gpt-5.2":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5436.6,p95LatencyMs:5928.8,outputTokensPerSecond:95.47,errorRate:0,samples:3},"openai/gpt-5.3-codex":{measuredAt:"2026-08-29T16:59:54Z",latencyMs:15290.4,p95LatencyMs:15290.4,outputTokensPerSecond:33.49,errorRate:.6667,samples:3},"openai/gpt-5.4":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5596,p95LatencyMs:5919.4,outputTokensPerSecond:91.67,errorRate:0,samples:3},"openai/gpt-5.4-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3377.8,p95LatencyMs:3646.8,outputTokensPerSecond:138.08,errorRate:0,samples:3},"openai/gpt-5.4-nano":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4040.4,p95LatencyMs:4205.9,outputTokensPerSecond:118.52,errorRate:0,samples:3},"openai/gpt-5.5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6367.8,p95LatencyMs:7330.7,outputTokensPerSecond:81.29,errorRate:0,samples:3},"openai/gpt-5.6-luna":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6064.5,p95LatencyMs:7347.3,outputTokensPerSecond:87.93,errorRate:0,samples:3},"openai/gpt-5.6-luna-pro":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:11046.8,p95LatencyMs:12033.6,outputTokensPerSecond:148.22,errorRate:0,samples:3},"openai/gpt-5.6-sol":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:7720.2,p95LatencyMs:9108.2,outputTokensPerSecond:67.47,errorRate:0,samples:3},"openai/gpt-5.6-sol-pro":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:11442.7,p95LatencyMs:13363.1,outputTokensPerSecond:148.75,errorRate:0,samples:3},"openai/gpt-5.6-terra":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4941,p95LatencyMs:5095.3,outputTokensPerSecond:103.69,errorRate:0,samples:3},"openai/gpt-5.6-terra-pro":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3574.1,p95LatencyMs:4126.3,outputTokensPerSecond:133.59,errorRate:0,samples:3},"openai/gpt-6.1-sol":{measuredAt:"2026-10-20T18:12:51Z",latencyMs:11324,p95LatencyMs:12747.6,outputTokensPerSecond:45.11,errorRate:0,samples:3},"openai/gpt-6.2-astra":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:7973.9,p95LatencyMs:9532.7,outputTokensPerSecond:47.21,errorRate:0,samples:3},"openai/gpt-6.2-sol":{measuredAt:"2026-11-27T23:25:03Z",latencyMs:6310.9,p95LatencyMs:6725.5,outputTokensPerSecond:58.01,errorRate:0,samples:3},"openai/o1":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4324.9,p95LatencyMs:5838.1,outputTokensPerSecond:125.86,errorRate:0,samples:3},"openai/o3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:5463.4,p95LatencyMs:5613.1,outputTokensPerSecond:93.8,errorRate:0,samples:3},"openai/o3-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:2912.7,p95LatencyMs:3092.1,outputTokensPerSecond:176.49,errorRate:0,samples:3},"openai/o4-mini":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:4958.7,p95LatencyMs:5313,outputTokensPerSecond:103.81,errorRate:0,samples:3},"qwen/qwen3.7-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:3385.5,p95LatencyMs:4042.7,outputTokensPerSecond:153.94,errorRate:0,samples:3},"qwen/qwen3.7-max":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:9387.1,p95LatencyMs:10490.2,outputTokensPerSecond:54.92,errorRate:0,samples:3},"qwen/qwen3.7-plus":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:9766.6,p95LatencyMs:9798.2,outputTokensPerSecond:52.42,errorRate:0,samples:3},"tencent/hy3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6062.3,p95LatencyMs:7070.2,outputTokensPerSecond:87.3,errorRate:0,samples:3},"xai/grok-4.3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:9467.7,p95LatencyMs:10087.9,outputTokensPerSecond:48.36,errorRate:0,samples:3},"xai/grok-4.5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:13564.8,p95LatencyMs:17351.9,outputTokensPerSecond:60.71,errorRate:0,samples:3},"xai/grok-build-0.1":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:16394.8,p95LatencyMs:18035.4,outputTokensPerSecond:96.86,errorRate:0,samples:3},"xiaomi/mimo-v2.5-pro":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:12070.7,p95LatencyMs:12386.8,outputTokensPerSecond:42.44,errorRate:0,samples:3},"zai/glm-5":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:6839.7,p95LatencyMs:7261.4,outputTokensPerSecond:75.16,errorRate:0,samples:3},"zai/glm-5-turbo":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:55348.5,p95LatencyMs:114086.6,outputTokensPerSecond:14.64,errorRate:0,samples:3},"zai/glm-5.1":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:15658.4,p95LatencyMs:17307.1,outputTokensPerSecond:32.9,errorRate:0,samples:3},"zai/glm-5.2":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:10308.5,p95LatencyMs:15127.6,outputTokensPerSecond:54.87,errorRate:0,samples:3},"zai/glm-5.3":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:7272.4,p95LatencyMs:7998.1,outputTokensPerSecond:71.09,errorRate:0,samples:3},"zai/glm-5.3-flash":{measuredAt:"2026-08-29T16:51:33Z",latencyMs:10545.3,p95LatencyMs:11672.4,outputTokensPerSecond:49.01,errorRate:0,samples:3}},LIVE_MODEL_PROFILES=Object.freeze(model_profiles_generated_default),HISTORICAL_MODEL_PROFILES=Object.freeze({"anthropic/claude-haiku-4.5":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:2305,outputTokensPerSecond:140.6},"anthropic/claude-sonnet-4.6":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:2110,outputTokensPerSecond:121.3},"deepseek/deepseek-chat":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:1431,outputTokensPerSecond:179.2,intelligenceIndex:32},"google/gemini-2.5-flash":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:1238,outputTokensPerSecond:207.6,intelligenceIndex:20},"google/gemini-2.5-flash-lite":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:1353,outputTokensPerSecond:192.5,intelligenceIndex:20},"google/gemini-2.5-pro":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:1294,outputTokensPerSecond:197.8},"google/gemini-3.1-pro":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:1609,outputTokensPerSecond:167.2},"openai/gpt-4o-mini":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:2764,outputTokensPerSecond:92.8},"openai/gpt-5.3-codex":{measuredAt:"2026-03-16T13:50:48Z",latencyMs:7935,outputTokensPerSecond:32.3}});DEFAULT_PORTFOLIO_WEIGHTS=DEFAULT_ROUTING_CONFIG.portfolio;NEUTRAL_AFFINITY=.68,TERMINAL_COMPLEX_HIGH={"claude-sonnet-5":1,"gpt-5.3-codex":.87,"gpt-5.6-luna":.78,"gemini-3.6-flash":.76},WEB_RESEARCH_DEEP={"claude-sonnet-5":1,"gpt-5.6-luna":.88,"gemini-3.6-flash":.84,"claude-opus-5":.8,"claude-opus-4.8":.78},WEB_RESEARCH={"claude-sonnet-5":1,"gpt-5.6-luna":.88,"gemini-3.6-flash":.86,"claude-opus-5":.84,"claude-opus-4.8":.82},RETAIL_POLICY_EXCEPTION={"gpt-4.1":1,"claude-sonnet-5":.9,"deepseek-v4-pro":.82,"gpt-5.6-luna":.8,"gpt-4o-mini":.76},RETAIL_POLICY_EXCEPTION_SIMPLE={"gpt-5.6-luna":1,"gpt-4.1":.86,"deepseek-v4-pro":.82,"gpt-4o-mini":.8},AFFINITY={codeAgent:{"gpt-5.3-codex":1,"claude-sonnet-5":.98,"gpt-5.6-luna":.96,"gemini-3.6-flash":.92,"kimi-k3.1-pro":.9,"deepseek-v4-pro":.88,"glm-5.3":.88},terminalTool:{"gpt-5.6-luna":1,"gpt-5.3-codex":.98,"claude-sonnet-5":.9,"gemini-3.6-flash":.89},terminalToolSafety:{"claude-sonnet-5":1,"claude-opus-4.8":.9,"gpt-5.3-codex":.84},retailStandard:{"gpt-5.6-luna":1,"claude-sonnet-5":.88,"gemini-3.6-flash":.82,"gpt-5.3-codex":.81,"kimi-k3.1-pro":.78,"deepseek-v4-pro":.76},retailHigh:{"deepseek-v4-pro":1,"claude-sonnet-5":.88,"gemini-3.6-flash":.82,"gpt-5.3-codex":.81,"kimi-k3.1-pro":.78,"gpt-5.6-luna":.76},airlineComplex:{"claude-sonnet-5":1,"gpt-5.6-luna":.78,"gemini-3.6-flash":.76,"deepseek-v4-pro":.74},airlineStandard:{"gpt-5.6-luna":1,"claude-sonnet-5":.9,"gemini-3.6-flash":.8,"deepseek-v4-pro":.76},toolAgent:{"claude-sonnet-5":1,"gemini-3.6-flash":.88,"gpt-5.3-codex":.87,"kimi-k3.1-pro":.85,"gpt-5.6-luna":.84,"deepseek-v4-pro":.82},parallelTerminalSafety:{"claude-sonnet-5":1,"claude-opus-4.8":.9,"gpt-5.3-codex":.86},parallelTerminal:{"gpt-5.6-luna":1,"gpt-5.3-codex":.98,"claude-sonnet-5":.92,"gemini-3.6-flash":.88},parallelRetail:{"deepseek-v4-pro":1,"claude-sonnet-5":.88,"claude-opus-4.8":.84,"gpt-5.6-luna":.78,"gemini-3.6-flash":.76},parallelAirlineComplex:{"claude-sonnet-5":1,"gpt-5.6-luna":.78,"claude-opus-4.8":.76,"gemini-3.6-flash":.74},parallelAirline:{"gpt-5.6-luna":1,"claude-sonnet-5":.9,"gemini-3.6-flash":.8},parallel:{"claude-opus-4.8":1,"claude-sonnet-5":.84,"grok-4.5":.82,"gemini-3.6-flash":.8,"deepseek-v4-pro":.78},codeEdit:{"gpt-5.3-codex":1,"claude-sonnet-5.5":.94,"glm-5.3":.9,"deepseek-v4-pro":.86},reasoning:{"claude-sonnet-5":.98,"claude-sonnet-5.5":.98,"deepseek-v4-pro":.95,"grok-4.7":.94,"gemini-3.1-pro":.92,"gemini-3.6-flash":.92},reasoningMcq:{"gemini-3-flash-preview":1,"gemini-3.6-flash":.91,"grok-4.5":.9,"claude-sonnet-5":.88,"deepseek-v4-pro":.84},reasoningMath:{"gemini-3.6-flash":1,"grok-4.5":.93,"claude-sonnet-5":.9,"deepseek-v4-pro":.9,"kimi-k3.1-pro":.88},vision:{"gemini-3.1-pro":.96,"qwen3.7-max":.9,"claude-sonnet-5.5":.9,"kimi-k3.1-pro":.9,"grok-4.3":.9},longContext:{"gemini-3.1-pro":1,"qwen3.7-max":.89,"glm-5.3":.89,"gemini-3.6-flash":.88,"deepseek-v4-pro":.85},extractionZh:{"kimi-k3.1-pro":1,"gemini-3.6-flash":.88,"gemini-3.5-flash-lite":.88,"gpt-4o-mini":.88,"claude-sonnet-5":.88,"claude-sonnet-5.5":.88},extraction:{"kimi-k3.1-pro":.9,"gemini-3.6-flash":.9,"gemini-3.5-flash-lite":.9,"gpt-4o-mini":.9,"claude-sonnet-5":.9,"claude-sonnet-5.5":.9},chat:{"gemini-3.6-flash":.86,"gemini-3.5-flash-lite":.86,"kimi-k3.1-pro":.86}};VERIFIED_TOOL_FALLBACKS=["anthropic/claude-fable-5.1","anthropic/claude-opus-5.5","anthropic/claude-sonnet-5.5","deepseek/deepseek-v4.1-flash","google/gemini-3.8-flash","google/gemini-4-argon","google/gemini-4-carbon","google/gemini-4-hydrogen","google/gemini-4-neon","openai/gpt-5.1","openai/gpt-5.6-luna-pro","openai/gpt-6-luna","openai/gpt-6.2-astra","openai/gpt-6.2-sol","xai/grok-4.6","xai/grok-4.7","xiaomi/mimo-v2.5"];PortfolioStrategy=class{name="portfolio";rules=new RulesStrategy;route(prompt,systemPrompt,maxOutputTokens,options){let features=classifyTask(prompt,systemPrompt,options),base4=this.rules.route(prompt,systemPrompt,maxOutputTokens,{...options,requiresTools:features.needsTools}),tierConfigs=base4.tierConfigs;if(!tierConfigs)return base4;let targetTier=(features.taskType==="reasoning_mcq"||features.taskType==="reasoning_math")&&(base4.tier==="SIMPLE"||base4.tier==="MEDIUM")?"REASONING":(features.taskType==="debug"||features.taskType==="code_edit")&&features.codeArtifact&&base4.tier==="SIMPLE"?"MEDIUM":base4.tier,configuredCandidates=tierConfigs[targetTier]?getFallbackChain(targetTier,tierConfigs):[],unavailable=new Set(options.unavailableModels??[]),verifiedToolFallbacks=features.needsTools?VERIFIED_TOOL_FALLBACKS.filter(model2=>options.modelPricing.has(model2)):[];if(options.routingProfile!=="premium"){let fallbackCost=model2=>estimatedCost(model2,options,features.estimatedInputTokens,maxOutputTokens);verifiedToolFallbacks.sort((a,b)=>fallbackCost(a)-fallbackCost(b))}let chain3=[...new Set([...configuredCandidates,...evidenceCandidates(features.taskType),...verifiedToolFallbacks])].filter(model2=>typeof model2=="string"&&model2.length>0&&!unavailable.has(model2)),eligible=new Set(chain3.filter(model2=>isEligible(model2,features,maxOutputTokens,options))),eligibleCandidates=eligible.size>0?[...eligible]:chain3;if(eligibleCandidates.length===0)return base4;let profileName=options.routingProfile==="eco"?"eco":options.routingProfile==="premium"?"premium":"auto",portfolio=options.config.portfolio??DEFAULT_PORTFOLIO_WEIGHTS,band=affinityBand(features),affinityCache=new Map,getAffinity=model2=>{let value=affinityCache.get(model2);return value===void 0&&(value=affinityIn(band,model2),affinityCache.set(model2,value)),value},bestAffinity=Math.max(...eligibleCandidates.map(getAffinity)),specificAffinity=eligibleCandidates.filter(model2=>getAffinity(model2)>NEUTRAL_AFFINITY),affinityPool=specificAffinity.length>0?specificAffinity:[eligibleCandidates[0]],affinityFloorGap=features.terminalToolSignal?Math.max(portfolio.affinityFloorGap[profileName],features.terminalSafetySensitive?.15:.12):portfolio.affinityFloorGap[profileName],candidates=affinityPool.filter(model2=>getAffinity(model2)>=bestAffinity-affinityFloorGap),costs=candidates.map(model2=>estimatedCost(model2,options,features.estimatedInputTokens,maxOutputTokens)),finiteCosts=costs.filter(Number.isFinite),minCost=finiteCosts.length>0?Math.min(...finiteCosts):0,maxCost=finiteCosts.length>0?Math.max(...finiteCosts):1,now2=options.now??new Date,profileWeights=portfolio[profileName],rankedEntries=candidates.map((model2,index2)=>{let cost=costs[index2],costScore=Number.isFinite(cost)?maxCost>minCost?1-(cost-minCost)/(maxCost-minCost):.5:0,capabilityScore=eligible.has(model2)?1:0,profile=profileScore(model2,options,now2),observedQuality=profile?.quality===void 0?getAffinity(model2):getAffinity(model2)*(1-profile.freshness)+profile.quality*profile.freshness,observedSpeed=profile?profile.speed*profile.freshness+.5*(1-profile.freshness):.5,observedTailSpeed=profile?profile.tailSpeed*profile.freshness+.5*(1-profile.freshness):.5,observedReliability=profile?profile.reliability*profile.freshness+(1-profile.freshness):1,legacyScore=1-index2/Math.max(1,candidates.length-1),qualityWeight=profileWeights.quality+(features.highStakes?portfolio.highStakesBoost.quality:0),speedScore=features.latencySensitive?observedTailSpeed:observedSpeed,speedWeight=profileWeights.speed+(features.latencySensitive?portfolio.latencySensitiveSpeedBoost:0),reliabilityWeight=profileWeights.reliability+(features.highStakes?portfolio.highStakesBoost.reliability:0),score=observedQuality*qualityWeight+capabilityScore*profileWeights.capability+costScore*profileWeights.cost+speedScore*speedWeight+observedReliability*reliabilityWeight+legacyScore*profileWeights.legacy;return{model:model2,score,quality:observedQuality,cost:costScore,speed:speedScore,reliability:observedReliability}}).sort((a,b)=>b.score-a.score),scoredModels=rankedEntries.map(item=>item.model),webResearchFallbackOrder=["anthropic/claude-sonnet-5","openai/gpt-5.6-luna","google/gemini-3.6-flash","anthropic/claude-opus-5","anthropic/claude-opus-4.8","openai/gpt-5.3-codex"],ranked=features.agentDomain==="web_research"?[...scoredModels,...webResearchFallbackOrder.filter(model2=>eligibleCandidates.includes(model2)&&!scoredModels.includes(model2)),...eligibleCandidates.filter(model2=>!scoredModels.includes(model2)&&!webResearchFallbackOrder.includes(model2))]:[...scoredModels,...eligibleCandidates.filter(model2=>!scoredModels.includes(model2))],model=ranked[0]??base4.model,selectedTierConfigs={...tierConfigs,[targetTier]:{primary:model,fallback:ranked.slice(1)}};return{...selectModel(targetTier,base4.confidence,"portfolio",`${base4.reasoning} | v3 task=${features.taskType} agentRisk=${features.agentRisk} deepWebResearch=${features.deepWebResearch} terminalCode=${features.implicitTerminalCode} terminalSafety=${features.terminalSafetySensitive} candidates=${ranked.length}`,selectedTierConfigs,options.modelPricing,features.estimatedInputTokens,maxOutputTokens,options.routingProfile,base4.agenticScore),tierConfigs:selectedTierConfigs,profile:base4.profile,candidates:ranked,candidateScores:rankedEntries.map(({model:model2,score,quality,cost,speed,reliability})=>({model:model2,score,quality,cost,speed,reliability})),taskType:features.taskType,routerVersion:"v3-portfolio"}}};registerStrategy(new PortfolioStrategy)}});var init_router=__esm({"src/router/index.ts"(){"use strict";init_dist()}});import{appendFile,mkdir as mkdir2}from"fs/promises";import{join as join4}from"path";import{homedir as homedir3}from"os";async function ensureDir(){dirReady||(await mkdir2(LOG_DIR,{recursive:!0}),dirReady=!0)}async function logUsage(entry){try{await ensureDir();let date5=entry.timestamp.slice(0,10),file2=join4(LOG_DIR,`usage-${date5}.jsonl`);await appendFile(file2,JSON.stringify(entry)+`
|
|
2170
2170
|
`)}catch{}}var LOG_DIR,dirReady,init_logger=__esm({"src/logger.ts"(){"use strict";LOG_DIR=join4(homedir3(),".openclaw","blockrun","logs"),dirReady=!1}});import{createRequire}from"module";import{fileURLToPath}from"url";import{dirname,join as join5}from"path";function clientTag(){let raw=(process.env.CLAWROUTER_CLIENT??"").trim();if(!raw)return"";let safe=raw.replace(/[^A-Za-z0-9._/+-]/g,"");return safe?` ${safe}`:""}var __filename2,__dirname,require2,pkg,VERSION,USER_AGENT,init_version4=__esm({"src/version.ts"(){"use strict";__filename2=fileURLToPath(import.meta.url),__dirname=dirname(__filename2),require2=createRequire(import.meta.url),pkg=require2(join5(__dirname,"..","package.json")),VERSION=pkg.version;USER_AGENT=`clawrouter/${VERSION}${clientTag()}`}});import{readdir,unlink}from"fs/promises";import{join as join6}from"path";import{homedir as homedir4}from"os";function resolveStatsDays(raw){let parsed=parseInt(raw??"",10);return!Number.isFinite(parsed)||parsed<=0?DEFAULT_STATS_DAYS:Math.min(parsed,MAX_STATS_DAYS)}async function parseLogFile(filePath){try{let lines=(await readTextFile(filePath)).trim().split(`
|
|
2171
2171
|
`).filter(Boolean),entries=[];for(let line of lines)try{let entry=JSON.parse(line);entries.push({timestamp:entry.timestamp||new Date().toISOString(),model:entry.model||"unknown",tier:entry.tier||"UNKNOWN",cost:entry.cost||0,baselineCost:entry.baselineCost||entry.cost||0,savings:entry.savings||0,latencyMs:entry.latencyMs||0,status:entry.status==="error"||entry.status==="success"?entry.status:void 0})}catch{}return entries}catch{return[]}}async function getLogFiles(){try{return(await readdir(LOG_DIR2)).filter(f=>f.startsWith("usage-")&&f.endsWith(".jsonl")).sort().reverse()}catch{return[]}}function aggregateDay(date5,entries){let byTier={},byModel={},totalLatency=0;for(let entry of entries)byTier[entry.tier]||(byTier[entry.tier]={count:0,cost:0}),byTier[entry.tier].count++,byTier[entry.tier].cost+=entry.cost,byModel[entry.model]||(byModel[entry.model]={count:0,cost:0}),byModel[entry.model].count++,byModel[entry.model].cost+=entry.cost,totalLatency+=entry.latencyMs;let totalCost=entries.reduce((sum,e7)=>sum+e7.cost,0),totalBaselineCost=entries.reduce((sum,e7)=>sum+e7.baselineCost,0);return{date:date5,totalRequests:entries.length,totalCost,totalBaselineCost,totalSavings:totalBaselineCost-totalCost,avgLatencyMs:entries.length>0?totalLatency/entries.length:0,byTier,byModel}}async function getStats(days=7){let window2=Number.isFinite(days)&&days>=1?Math.floor(days):DEFAULT_STATS_DAYS,filesToRead=(await getLogFiles()).slice(0,window2),dailyBreakdown=[],allByTier={},allByModel={},totalRequests=0,totalCost=0,totalBaselineCost=0,totalLatency=0,errorCount=0;for(let file2 of filesToRead){let date5=file2.replace("usage-","").replace(".jsonl",""),filePath=join6(LOG_DIR2,file2),entries=await parseLogFile(filePath);if(entries.length===0)continue;for(let entry of entries)entry.status==="error"&&errorCount++;let dayStats=aggregateDay(date5,entries);dailyBreakdown.push(dayStats),totalRequests+=dayStats.totalRequests,totalCost+=dayStats.totalCost,totalBaselineCost+=dayStats.totalBaselineCost,totalLatency+=dayStats.avgLatencyMs*dayStats.totalRequests;for(let[tier,stats]of Object.entries(dayStats.byTier))allByTier[tier]||(allByTier[tier]={count:0,cost:0}),allByTier[tier].count+=stats.count,allByTier[tier].cost+=stats.cost;for(let[model,stats]of Object.entries(dayStats.byModel))allByModel[model]||(allByModel[model]={count:0,cost:0}),allByModel[model].count+=stats.count,allByModel[model].cost+=stats.cost}let byTierWithPercentage={};for(let[tier,stats]of Object.entries(allByTier))byTierWithPercentage[tier]={...stats,percentage:totalRequests>0?stats.count/totalRequests*100:0};let byModelWithPercentage={};for(let[model,stats]of Object.entries(allByModel))byModelWithPercentage[model]={...stats,percentage:totalRequests>0?stats.count/totalRequests*100:0};let totalSavings=totalBaselineCost-totalCost,savingsPercentage=totalBaselineCost>0?totalSavings/totalBaselineCost*100:0,entriesWithBaseline=0;for(let day of dailyBreakdown)day.totalBaselineCost!==day.totalCost&&(entriesWithBaseline+=day.totalRequests);return{period:window2===1?"today":`last ${window2} days`,totalRequests,totalCost,totalBaselineCost,totalSavings,savingsPercentage,avgLatencyMs:totalRequests>0?totalLatency/totalRequests:0,avgCostPerRequest:totalRequests>0?totalCost/totalRequests:0,byTier:byTierWithPercentage,byModel:byModelWithPercentage,dailyBreakdown:dailyBreakdown.reverse(),entriesWithBaseline,errorCount}}function formatStatsAscii(stats){let lines=[];lines.push("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),lines.push(`\u2551 ClawRouter by BlockRun v${VERSION}`.padEnd(61)+"\u2551"),lines.push("\u2551 Usage Statistics \u2551"),lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),lines.push(`\u2551 Period: ${stats.period.padEnd(49)}\u2551`),lines.push(`\u2551 Total Requests: ${stats.totalRequests.toString().padEnd(41)}\u2551`),lines.push(`\u2551 Total Cost: $${stats.totalCost.toFixed(4).padEnd(43)}\u2551`),lines.push(`\u2551 Baseline Cost (Opus 4.5): $${stats.totalBaselineCost.toFixed(4).padEnd(30)}\u2551`);let savingsLine=`\u2551 \u{1F4B0} Total Saved: $${stats.totalSavings.toFixed(4)} (${stats.savingsPercentage.toFixed(1)}%)`;if(stats.entriesWithBaseline<stats.totalRequests&&stats.entriesWithBaseline>0){lines.push(savingsLine.padEnd(61)+"\u2551");let note=`\u2551 (based on ${stats.entriesWithBaseline}/${stats.totalRequests} tracked requests)`;lines.push(note.padEnd(61)+"\u2551")}else lines.push(savingsLine.padEnd(61)+"\u2551");lines.push(`\u2551 Avg Latency: ${stats.avgLatencyMs.toFixed(0)}ms`.padEnd(61)+"\u2551"),lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),lines.push("\u2551 Routing by Tier: \u2551");let knownTiers=["SIMPLE","MEDIUM","COMPLEX","REASONING","DIRECT"],otherTiers=Object.keys(stats.byTier).filter(t=>!knownTiers.includes(t)),tierOrder=[...knownTiers.filter(t=>stats.byTier[t]),...otherTiers];for(let tier of tierOrder){let data=stats.byTier[tier];if(data){let bar="\u2588".repeat(Math.min(20,Math.round(data.percentage/5))),line=`\u2551 ${(tier==="UNKNOWN"?"OTHER":tier).padEnd(10)} ${bar.padEnd(20)} ${data.percentage.toFixed(1).padStart(5)}% (${data.count})`;lines.push(line.padEnd(61)+"\u2551")}}lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),lines.push("\u2551 Top Models: \u2551");let sortedModels=Object.entries(stats.byModel).sort((a,b)=>b[1].count-a[1].count).slice(0,5);for(let[model,data]of sortedModels){let line=`\u2551 ${(model.length>25?model.slice(0,22)+"...":model).padEnd(25)} ${data.count.toString().padStart(5)} reqs $${data.cost.toFixed(4)}`;lines.push(line.padEnd(61)+"\u2551")}if(stats.dailyBreakdown.length>0){lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),lines.push("\u2551 Daily Breakdown: \u2551"),lines.push("\u2551 Date Requests Cost Saved \u2551");for(let day of stats.dailyBreakdown.slice(-7)){let saved=day.totalBaselineCost-day.totalCost,line=`\u2551 ${day.date} ${day.totalRequests.toString().padStart(6)} $${day.totalCost.toFixed(4).padStart(8)} $${saved.toFixed(4)}`;lines.push(line.padEnd(61)+"\u2551")}}return lines.push("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),lines.join(`
|
|
2172
2172
|
`)}async function formatRecentLogs(requestedDays=1){let days=Number.isFinite(requestedDays)&&requestedDays>0?Math.floor(requestedDays):1,filesToRead=(await getLogFiles()).slice(0,days),allEntries=[];for(let file2 of filesToRead){let entries=await parseLogFile(join6(LOG_DIR2,file2));allEntries.push(...entries)}allEntries.sort((a,b)=>a.timestamp.localeCompare(b.timestamp));let lines=[];lines.push("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),lines.push(`\u2551 ClawRouter Request Log \u2014 last ${days===1?"24h":`${days} days`}`.padEnd(72)+"\u2551"),lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),lines.push("\u2551 Time \u2551 Model \u2551 Cost \u2551 ms \u2551 Status \u2551"),lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256C\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256C\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256C\u2550\u2550\u2550\u2550\u2550\u2550\u256C\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),allEntries.length===0&&lines.push("\u2551 No requests found".padEnd(72)+"\u2551");let totalCost=0;for(let e7 of allEntries){let time3=e7.timestamp.slice(11,19),displayTime=`${e7.timestamp.slice(5,10)} ${time3}`,model=e7.model.length>24?e7.model.slice(0,21)+"...":e7.model,cost=`$${e7.cost.toFixed(4)}`,ms=e7.latencyMs>9999?`${(e7.latencyMs/1e3).toFixed(1)}s`:`${e7.latencyMs}ms`,status2=e7.status==="error"?" ERROR ":" OK ";totalCost+=e7.cost,lines.push(`\u2551 ${displayTime.padEnd(16)}\u2551 ${model.padEnd(24)}\u2551 ${cost.padStart(7)}\u2551 ${ms.padStart(4)}\u2551${status2}\u2551`)}return lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),lines.push(`\u2551 ${allEntries.length} request${allEntries.length!==1?"s":""} Total spent: $${totalCost.toFixed(4)}`.padEnd(72)+"\u2551"),lines.push("\u2551 Logs: ~/.openclaw/blockrun/logs/ (JSONL \u2014 one entry per request)".padEnd(72)+"\u2551"),lines.push("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),lines.join(`
|
|
2173
2173
|
`)}async function clearStats(){try{let logFiles=(await readdir(LOG_DIR2)).filter(f=>f.startsWith("usage-")&&f.endsWith(".jsonl"));return await Promise.all(logFiles.map(f=>unlink(join6(LOG_DIR2,f)))),{deletedFiles:logFiles.length}}catch{return{deletedFiles:0}}}var LOG_DIR2,DEFAULT_STATS_DAYS,MAX_STATS_DAYS,init_stats=__esm({"src/stats.ts"(){"use strict";init_fs_read();init_version4();LOG_DIR2=join6(homedir4(),".openclaw","blockrun","logs"),DEFAULT_STATS_DAYS=7,MAX_STATS_DAYS=30}});function stripLeadingTextBlockTimestamp(blocks){let stripped=!1;return blocks.map(block=>{if(!stripped&&block!==null&&typeof block=="object"&&block.type==="text"&&typeof block.text=="string"){stripped=!0;let b=block;return{...b,text:b.text.replace(TIMESTAMP_PATTERN,"")}}return block})}var TIMESTAMP_PATTERN,init_timestamp_strip=__esm({"src/timestamp-strip.ts"(){"use strict";TIMESTAMP_PATTERN=/^\[\w{3}\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+\w+\]\s*/}});import{createHash as createHash2}from"crypto";function canonicalize(obj){if(obj===null||typeof obj!="object")return obj;if(Array.isArray(obj))return obj.map(canonicalize);let sorted={};for(let key3 of Object.keys(obj).sort())sorted[key3]=canonicalize(obj[key3]);return sorted}function stripTimestamps(obj){if(obj===null||typeof obj!="object")return obj;if(Array.isArray(obj))return obj.map(stripTimestamps);let result={};for(let[key3,value]of Object.entries(obj))key3==="content"&&typeof value=="string"?result[key3]=value.replace(TIMESTAMP_PATTERN,""):key3==="content"&&Array.isArray(value)?result[key3]=stripLeadingTextBlockTimestamp(value.map(stripTimestamps)):result[key3]=stripTimestamps(value);return result}var DEFAULT_TTL_MS2,MAX_BODY_SIZE,RequestDeduplicator,init_dedup=__esm({"src/dedup.ts"(){"use strict";init_timestamp_strip();DEFAULT_TTL_MS2=3e4,MAX_BODY_SIZE=1048576;RequestDeduplicator=class{inflight=new Map;completed=new Map;ttlMs;constructor(ttlMs=DEFAULT_TTL_MS2){this.ttlMs=ttlMs}static hash(body){let content=body;try{let parsed=JSON.parse(body.toString()),stripped=stripTimestamps(parsed),canonical=canonicalize(stripped);content=Buffer.from(JSON.stringify(canonical))}catch{}return createHash2("sha256").update(content).digest("hex").slice(0,16)}getCached(key3){let entry=this.completed.get(key3);if(entry){if(Date.now()-entry.completedAt>this.ttlMs){this.completed.delete(key3);return}return entry}}getInflight(key3){let entry=this.inflight.get(key3);if(entry)return new Promise(resolve4=>{entry.resolvers.push(resolve4)})}markInflight(key3){this.inflight.set(key3,{resolvers:[]})}complete(key3,result){result.body.length<=MAX_BODY_SIZE&&this.completed.set(key3,result);let entry=this.inflight.get(key3);if(entry){for(let resolve4 of entry.resolvers)resolve4(result);this.inflight.delete(key3)}this.prune()}removeInflight(key3){let entry=this.inflight.get(key3);if(entry){let errorBody=Buffer.from(JSON.stringify({error:{message:"Original request failed, please retry",type:"dedup_origin_failed"}}));for(let resolve4 of entry.resolvers)resolve4({status:503,headers:{"content-type":"application/json"},body:errorBody,completedAt:Date.now()});this.inflight.delete(key3)}}prune(){let now2=Date.now();for(let[key3,entry]of this.completed)now2-entry.completedAt>this.ttlMs&&this.completed.delete(key3)}}}});import{createHash as createHash3}from"crypto";function canonicalize2(obj){if(obj===null||typeof obj!="object")return obj;if(Array.isArray(obj))return obj.map(canonicalize2);let sorted={};for(let key3 of Object.keys(obj).sort())sorted[key3]=canonicalize2(obj[key3]);return sorted}function normalizeForCache(obj){let result={};for(let[key3,value]of Object.entries(obj))["user","request_id","x-request-id"].includes(key3)||(key3==="messages"&&Array.isArray(value)?result[key3]=value.map(msg=>{if(typeof msg=="object"&&msg!==null){let m=msg;if(typeof m.content=="string")return{...m,content:m.content.replace(TIMESTAMP_PATTERN,"")};if(Array.isArray(m.content))return{...m,content:stripLeadingTextBlockTimestamp(m.content)}}return msg}):result[key3]=value);return result}var DEFAULT_CONFIG,ResponseCache,init_response_cache=__esm({"src/response-cache.ts"(){"use strict";init_timestamp_strip();DEFAULT_CONFIG={maxSize:200,defaultTTL:600,maxItemSize:1048576,enabled:!0};ResponseCache=class{cache=new Map;expirationHeap=[];config;stats={hits:0,misses:0,evictions:0};constructor(config2={}){let filtered=Object.fromEntries(Object.entries(config2).filter(([,v])=>v!==void 0));this.config={...DEFAULT_CONFIG,...filtered}}static generateKey(body){try{let parsed=JSON.parse(typeof body=="string"?body:body.toString()),normalized=normalizeForCache(parsed),canonical=canonicalize2(normalized),keyContent=JSON.stringify(canonical);return createHash3("sha256").update(keyContent).digest("hex").slice(0,32)}catch{let content=typeof body=="string"?body:body.toString();return createHash3("sha256").update(content).digest("hex").slice(0,32)}}shouldCache(body,headers){if(!this.config.enabled||/\bno-(?:cache|store)\b/i.test(headers?.["cache-control"]??""))return!1;try{let parsed=JSON.parse(typeof body=="string"?body:body.toString());if(parsed.cache===!1||parsed.no_cache===!0)return!1}catch{}return!0}get(key3){let entry=this.cache.get(key3);if(!entry){this.stats.misses++;return}if(Date.now()>entry.expiresAt){this.cache.delete(key3),this.stats.misses++;return}return this.stats.hits++,entry}set(key3,response,ttlSeconds){if(!this.config.enabled||this.config.maxSize<=0)return;if(response.body.length>this.config.maxItemSize){console.log(`[ResponseCache] Skipping cache - item too large: ${response.body.length} bytes`);return}if(response.status>=400)return;this.cache.size>=this.config.maxSize&&this.evict();let now2=Date.now(),ttl=ttlSeconds??this.config.defaultTTL,expiresAt=now2+ttl*1e3,entry={...response,cachedAt:now2,expiresAt};this.cache.set(key3,entry),this.expirationHeap.push({expiresAt,key:key3})}evict(){let now2=Date.now();for(this.expirationHeap.sort((a,b)=>a.expiresAt-b.expiresAt);this.expirationHeap.length>0;){let oldest=this.expirationHeap[0],entry=this.cache.get(oldest.key);if(!entry||entry.expiresAt!==oldest.expiresAt){this.expirationHeap.shift();continue}if(oldest.expiresAt<=now2)this.cache.delete(oldest.key),this.expirationHeap.shift(),this.stats.evictions++;else break}for(;this.cache.size>=this.config.maxSize&&this.expirationHeap.length>0;){let oldest=this.expirationHeap.shift();this.cache.has(oldest.key)&&(this.cache.delete(oldest.key),this.stats.evictions++)}}getStats(){let total=this.stats.hits+this.stats.misses,hitRate=total>0?(this.stats.hits/total*100).toFixed(1)+"%":"0%";return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,hitRate}}clear(){this.cache.clear(),this.expirationHeap=[]}isEnabled(){return this.config.enabled}}}});function isInsufficientFundsError(error62){return error62 instanceof Error&&error62.code==="INSUFFICIENT_FUNDS"}function isEmptyWalletError(error62){return error62 instanceof Error&&error62.code==="EMPTY_WALLET"}function isBalanceError(error62){return isInsufficientFundsError(error62)||isEmptyWalletError(error62)}function isRpcError2(error62){return error62 instanceof Error&&error62.code==="RPC_ERROR"}function describeFetchError(error62){let message=error62 instanceof Error?error62.message:String(error62),cause=error62?.cause;if(!(cause instanceof Error))return message;let detail=cause,host=detail.hostname||detail.address,where=host&&detail.port?`${host}:${detail.port}`:host,parts=[detail.code,where,detail.code?void 0:detail.message].filter(part=>typeof part=="string"&&part!=="");return parts.length>0?`${message} (${parts.join(" ")})`:message}var InsufficientFundsError2,EmptyWalletError,RpcError2,init_errors8=__esm({"src/errors.ts"(){"use strict";InsufficientFundsError2=class extends Error{code="INSUFFICIENT_FUNDS";currentBalanceUSD;requiredUSD;walletAddress;constructor(opts){let msg=[`Insufficient balance. Current: ${opts.currentBalanceUSD}, Required: ${opts.requiredUSD}`,"Options:",` 1. Fund wallet: ${opts.walletAddress}`," 2. Use free model: /model free"].join(`
|
|
2174
2174
|
`);super(msg),this.name="InsufficientFundsError",this.currentBalanceUSD=opts.currentBalanceUSD,this.requiredUSD=opts.requiredUSD,this.walletAddress=opts.walletAddress}},EmptyWalletError=class extends Error{code="EMPTY_WALLET";walletAddress;constructor(walletAddress){let msg=["No USDC balance.","Options:",` 1. Fund wallet: ${walletAddress}`," 2. Use free model: /model free"," 3. Uninstall: bash ~/.openclaw/extensions/blockrun-clawrouter/scripts/uninstall.sh"].join(`
|
|
2175
|
-
`);super(msg),this.name="EmptyWalletError",this.walletAddress=walletAddress}};RpcError2=class extends Error{code="RPC_ERROR";originalError;constructor(message,originalError){super(`RPC error: ${message}. Check network connectivity.`),this.name="RpcError",this.originalError=originalError}}}});async function fetchArcUsdcBalance(address3,fetchImpl=fetch){let url3=`${PAYMENT_CHAIN_GATEWAYS.arc}/v1/balance?address=${encodeURIComponent(address3)}`,res=await fetchImpl(url3,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(READ_TIMEOUT_MS)});if(!res.ok)throw new Error(`Arc balance read failed (HTTP ${res.status})`);let body=await res.json();if(typeof body.balance!="string"||!/^\d+$/.test(body.balance))throw new Error("Arc balance read returned no balance");return BigInt(body.balance)}var USDC_BASE,READ_TIMEOUT_MS,CACHE_TTL_MS,BALANCE_THRESHOLDS,BalanceMonitor,ApiKeyBalanceMonitor,init_balance=__esm({"src/balance.ts"(){"use strict";init_esm4();init_chains();init_errors8();init_payment_chain();USDC_BASE="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",READ_TIMEOUT_MS=1e4;CACHE_TTL_MS=3e4,BALANCE_THRESHOLDS={LOW_BALANCE_MICROS:1000000n,ZERO_THRESHOLD:100n},BalanceMonitor=class{client;walletAddress;chain;fetchImpl;cachedBalance=null;cachedAt=0;constructor(walletAddress,chain3="base",fetchImpl){this.walletAddress=walletAddress,this.chain=chain3,this.fetchImpl=fetchImpl??((...args)=>fetch(...args)),this.client=createPublicClient({chain:base,transport:http(void 0,{timeout:READ_TIMEOUT_MS})})}getChain(){return this.chain}async checkBalance(){let now2=Date.now();if(this.cachedBalance!==null&&this.cachedBalance>0n&&now2-this.cachedAt<CACHE_TTL_MS)return this.buildInfo(this.cachedBalance);let balance=await this.fetchBalance();return balance>0n&&(this.cachedBalance=balance,this.cachedAt=now2),this.buildInfo(balance)}async checkSufficient(estimatedCostMicros){let info=await this.checkBalance();if(info.balance>=estimatedCostMicros)return{sufficient:!0,info};let shortfall=estimatedCostMicros-info.balance;return{sufficient:!1,info,shortfall:this.formatUSDC(shortfall)}}deductEstimated(amountMicros){this.cachedBalance!==null&&this.cachedBalance>=amountMicros&&(this.cachedBalance-=amountMicros)}invalidate(){this.cachedBalance=null,this.cachedAt=0}async refresh(){return this.invalidate(),this.checkBalance()}formatUSDC(amountMicros){return`$${(Number(amountMicros)/1e6).toFixed(2)}`}getWalletAddress(){return this.walletAddress}async fetchBalance(){try{return this.chain==="arc"?await fetchArcUsdcBalance(this.walletAddress,this.fetchImpl):await this.client.readContract({address:USDC_BASE,abi:erc20Abi,functionName:"balanceOf",args:[this.walletAddress]})}catch(error62){throw new RpcError2(error62 instanceof Error?error62.message:"Unknown error",error62)}}buildInfo(balance){return{balance,balanceUSD:this.formatUSDC(balance),isLow:balance<BALANCE_THRESHOLDS.LOW_BALANCE_MICROS,isEmpty:balance<BALANCE_THRESHOLDS.ZERO_THRESHOLD,walletAddress:this.walletAddress}}},ApiKeyBalanceMonitor=class _ApiKeyBalanceMonitor{static UNMETERED=BigInt(Number.MAX_SAFE_INTEGER);async checkBalance(){return{balance:_ApiKeyBalanceMonitor.UNMETERED,balanceUSD:"account credit",isLow:!1,isEmpty:!1,walletAddress:""}}async checkSufficient(){return{sufficient:!0,info:await this.checkBalance()}}deductEstimated(){}invalidate(){}async refresh(){return this.checkBalance()}formatUSDC(amountMicros){return`$${(Number(amountMicros)/1e6).toFixed(2)}`}getWalletAddress(){return""}}}});function base2(ALPHABET3){if(ALPHABET3.length>=255)throw new TypeError("Alphabet too long");let BASE_MAP=new Uint8Array(256);for(let j=0;j<BASE_MAP.length;j++)BASE_MAP[j]=255;for(let i=0;i<ALPHABET3.length;i++){let x=ALPHABET3.charAt(i),xc=x.charCodeAt(0);if(BASE_MAP[xc]!==255)throw new TypeError(x+" is ambiguous");BASE_MAP[xc]=i}let BASE=ALPHABET3.length,LEADER=ALPHABET3.charAt(0),FACTOR=Math.log(BASE)/Math.log(256),iFACTOR=Math.log(256)/Math.log(BASE);function encode12(source){if(source instanceof Uint8Array||(ArrayBuffer.isView(source)?source=new Uint8Array(source.buffer,source.byteOffset,source.byteLength):Array.isArray(source)&&(source=Uint8Array.from(source))),!(source instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(source.length===0)return"";let zeroes=0,length=0,pbegin=0,pend=source.length;for(;pbegin!==pend&&source[pbegin]===0;)pbegin++,zeroes++;let size4=(pend-pbegin)*iFACTOR+1>>>0,b58=new Uint8Array(size4);for(;pbegin!==pend;){let carry2=source[pbegin],i=0;for(let it1=size4-1;(carry2!==0||i<length)&&it1!==-1;it1--,i++)carry2+=256*b58[it1]>>>0,b58[it1]=carry2%BASE>>>0,carry2=carry2/BASE>>>0;if(carry2!==0)throw new Error("Non-zero carry");length=i,pbegin++}let it2=size4-length;for(;it2!==size4&&b58[it2]===0;)it2++;let str=LEADER.repeat(zeroes);for(;it2<size4;++it2)str+=ALPHABET3.charAt(b58[it2]);return str}function decodeUnsafe(source){if(typeof source!="string")throw new TypeError("Expected String");if(source.length===0)return new Uint8Array;let psz=0,zeroes=0,length=0;for(;source[psz]===LEADER;)zeroes++,psz++;let size4=(source.length-psz)*FACTOR+1>>>0,b256=new Uint8Array(size4);for(;psz<source.length;){let charCode=source.charCodeAt(psz);if(charCode>255)return;let carry2=BASE_MAP[charCode];if(carry2===255)return;let i=0;for(let it3=size4-1;(carry2!==0||i<length)&&it3!==-1;it3--,i++)carry2+=BASE*b256[it3]>>>0,b256[it3]=carry2%256>>>0,carry2=carry2/256>>>0;if(carry2!==0)throw new Error("Non-zero carry");length=i,psz++}let it4=size4-length;for(;it4!==size4&&b256[it4]===0;)it4++;let vch=new Uint8Array(zeroes+(size4-it4)),j=zeroes;for(;it4!==size4;)vch[j++]=b256[it4++];return vch}function decode8(string4){let buffer2=decodeUnsafe(string4);if(buffer2)return buffer2;throw new Error("Non-base"+BASE+" character")}return{encode:encode12,decodeUnsafe,decode:decode8}}var esm_default,init_esm7=__esm({"node_modules/base-x/src/esm/index.js"(){"use strict";esm_default=base2}});var esm_exports3={};__export(esm_exports3,{default:()=>esm_default2});var ALPHABET,esm_default2,init_esm8=__esm({"node_modules/bs58/src/esm/index.js"(){"use strict";init_esm7();ALPHABET="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",esm_default2=esm_default(ALPHABET)}});function fromBig4(n,le=!1){return le?{h:Number(n&U32_MASK644),l:Number(n>>_32n4&U32_MASK644)}:{h:Number(n>>_32n4&U32_MASK644)|0,l:Number(n&U32_MASK644)|0}}function split4(lst,le=!1){let len=lst.length,Ah=new Uint32Array(len),Al=new Uint32Array(len);for(let i=0;i<len;i++){let{h,l:l2}=fromBig4(lst[i],le);[Ah[i],Al[i]]=[h,l2]}return[Ah,Al]}function setU64FromNum(view,byteOffset,n,isLE3){let h=fromNumH(n),l2=fromNumL(n);view.setUint32(byteOffset,isLE3?l2:h,isLE3),view.setUint32(byteOffset+4,isLE3?h:l2,isLE3)}function add3(Ah,Al,Bh,Bl){let l2=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l2/2**32|0)|0,l:l2|0}}var U32_MASK644,_32n4,fromNumH,fromNumL,shrSH3,shrSL3,rotrSH3,rotrSL3,rotrBH3,rotrBL3,add3L3,add3H3,add4L3,add4H3,add5L3,add5H3,init_u644=__esm({"node_modules/@noble/hashes/_u64.js"(){"use strict";U32_MASK644=BigInt(4294967295),_32n4=BigInt(32);fromNumH=n=>n/2**32|0,fromNumL=n=>n>>>0;shrSH3=(h,_l,s3)=>h>>>s3,shrSL3=(h,l2,s3)=>h<<32-s3|l2>>>s3,rotrSH3=(h,l2,s3)=>h>>>s3|l2<<32-s3,rotrSL3=(h,l2,s3)=>h<<32-s3|l2>>>s3,rotrBH3=(h,l2,s3)=>h<<64-s3|l2>>>s3-32,rotrBL3=(h,l2,s3)=>h>>>s3-32|l2<<64-s3;add3L3=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0),add3H3=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0,add4L3=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0),add4H3=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0,add5L3=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0),add5H3=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0}});function isBytes8(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in a&&a.BYTES_PER_ELEMENT===1}function anumber5(n,title=""){if(typeof n!="number")throw new TypeError(atitle(title)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(atitle(title)+"expected integer >= 0, got "+n);return n}function abytes6(value,length,title=""){if(isBytes8(value)&&(length===void 0||value.length===length))return value;length!==void 0&&anumber5(length,"length");let bytes=isBytes8(value),ofLen=length!==void 0?` of length ${length}`:"",got=bytes?`length=${value.length}`:`type=${typeof value}`,message=atitle(title)+"expected Uint8Array"+ofLen+", got "+got;throw bytes?new RangeError(message):new TypeError(message)}function ahash4(h){if(typeof h!="function"||typeof h.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(anumber5(h.outputLen),anumber5(h.blockLen),h.outputLen<1||h.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}function aexists4(instance,checkFinished=!0){if(instance.destroyed)throw new Error("hash was destroyed");if(checkFinished&&instance.finished)throw new Error("digest() was already called")}function aoutput4(out,instance){abytes6(out,void 0,"output");let min=instance.outputLen;if(!(out.length>=min))throw new RangeError('"output" expected length >= '+min)}function clean4(...arrays){for(let i=0;i<arrays.length;i++)arrays[i].fill(0)}function createView4(arr){return new DataView(arr.buffer,arr.byteOffset,arr.byteLength)}function rotr4(word,shift){return word<<32-shift|word>>>shift}function rotl2(word,shift){return word<<shift|word>>>32-shift>>>0}function bytesToHex4(bytes){if(abytes6(bytes),hasHexBuiltin3)return bytes.toHex();let hex3="";for(let i=0;i<bytes.length;i++)hex3+=hexes5[bytes[i]];return hex3}function asciiToBase163(ch){return ch>=48&&ch<=57?ch-48:ch>=65&&ch<=70?ch-55:ch>=97&&ch<=102?ch-87:void 0}function hexToBytes4(hex3){if(typeof hex3!="string")throw new TypeError("hex string expected, got "+typeof hex3);if(hasHexBuiltin3)try{return Uint8Array.fromHex(hex3)}catch(error62){throw error62 instanceof SyntaxError?new RangeError(error62.message):error62}let hl=hex3.length,al=hl/2;if(hl%2)throw new RangeError("hex string expected, got unpadded hex of length "+hl);let array2=new Uint8Array(al);for(let ai=0,hi=0;ai<al;ai++,hi+=2){let n1=asciiToBase163(hex3.charCodeAt(hi)),n2=asciiToBase163(hex3.charCodeAt(hi+1));if(n1===void 0||n2===void 0){let char=hex3[hi]+hex3[hi+1];throw new RangeError('hex string expected, got non-hex character "'+char+'" at index '+hi)}array2[ai]=n1*16+n2}return array2}function concatBytes6(...arrays){let sum=0;for(let i=0;i<arrays.length;i++){let a=arrays[i];abytes6(a),sum+=a.length}let res=new Uint8Array(sum);for(let i=0,pad4=0;i<arrays.length;i++){let a=arrays[i];res.set(a,pad4),pad4+=a.length}return res}function checkOpts2(defaults2,opts,title="opts"){return aopts(defaults2,"defaults"),opts!==void 0&&aopts(opts,title),Object.assign(Object.create(null),defaults2,opts)}function createHasher5(hashCons,info={}){if(typeof hashCons!="function")throw new TypeError('"hashCons" expected function, got type='+typeof hashCons);info=checkOpts2({},info,"info");let hashC=(msg,opts)=>hashCons(opts).update(msg).digest(),tmp=hashCons(void 0);return hashC.outputLen=tmp.outputLen,hashC.blockLen=tmp.blockLen,hashC.canXOF=tmp.canXOF,hashC.create=opts=>hashCons(opts),Object.assign(hashC,info),Object.freeze(hashC)}function randomBytes4(bytesLength=32){anumber5(bytesLength,"bytesLength");let cr=typeof globalThis=="object"?globalThis.crypto:null;if(typeof cr?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(bytesLength>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);return cr.getRandomValues(new Uint8Array(bytesLength))}var atitle,aobject,aopts,hasHexBuiltin3,hexes5,oidNist,init_utils15=__esm({"node_modules/@noble/hashes/utils.js"(){"use strict";atitle=title=>title?`"${title}" `:"";aobject=(value,label)=>{if(value===null||typeof value!="object"||Array.isArray(value))throw new TypeError((label==="object"?"":`"${label}" `)+"expected object, got type="+typeof value)},aopts=(value,label)=>{aobject(value,label);let proto=Object.getPrototypeOf(value);if(proto!==Object.prototype&&proto!==null)throw new TypeError(`"${label}" expected plain object`);if(Object.hasOwn(value,"__proto__"))throw new TypeError(`"${label}.__proto__" is not allowed`)};hasHexBuiltin3=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hexes5=Array.from({length:256},(_,i)=>i.toString(16).padStart(2,"0"));oidNist=suffix=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,suffix])})}});function Chi4(a,b,c){return a&b^~a&c}function Maj4(a,b,c){return a&b^a&c^b&c}var HashMD4,SHA256_IV4,SHA512_IV4,init_md4=__esm({"node_modules/@noble/hashes/_md.js"(){"use strict";init_u644();init_utils15();HashMD4=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(blockLen,outputLen,padOffset,isLE3){this.blockLen=blockLen,this.outputLen=outputLen,this.padOffset=padOffset,this.isLE=isLE3,this.buffer=new Uint8Array(blockLen),this.view=createView4(this.buffer)}update(data){aexists4(this),abytes6(data);let{view,buffer:buffer2,blockLen}=this,len=data.length,processed=!1;for(let pos=0;pos<len;){let take=Math.min(blockLen-this.pos,len-pos);if(take===blockLen){let dataView=createView4(data);for(;blockLen<=len-pos;pos+=blockLen)this.process(dataView,pos);processed=!0;continue}buffer2.set(pos===0&&take===len?data:data.subarray(pos,pos+take),this.pos),this.pos+=take,pos+=take,this.pos===blockLen&&(this.process(view,0),this.pos=0,processed=!0)}return this.length+=data.length,processed&&this.roundClean(),this}digestInto(out){aexists4(this),aoutput4(out,this),this.finished=!0;let{buffer:buffer2,view,blockLen,isLE:isLE3}=this,{pos}=this;buffer2[pos++]=128,buffer2.fill(0,pos),this.padOffset>blockLen-pos&&(this.process(view,0),buffer2.fill(0)),setU64FromNum(view,blockLen-8,this.length*8,isLE3),this.process(view,0),this.roundClean();let oview=out===buffer2?view:createView4(out),len=this.outputLen,outLen=len/4,state=this.get();if(len%4||outLen>state.length)throw new Error("invalid outputLen");for(let i=0;i<outLen;i++)oview.setUint32(4*i,state[i],isLE3)}digest(){let{buffer:buffer2,outputLen}=this;this.digestInto(buffer2);let res=buffer2.slice(0,outputLen);return this.destroy(),res}_cloneIntoMeta(to2){let{buffer:buffer2,length,finished:finished2,destroyed,pos}=this;return to2.destroyed=destroyed,to2.finished=finished2,to2.length=length,to2.pos=pos,pos&&to2.buffer.set(buffer2),to2}clone(){return this._cloneInto()}},SHA256_IV4=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA512_IV4=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])}});var SHA256_K4,SHA256_W4,SHA2_32B,_SHA256,K5123,SHA512_Kh3,SHA512_Kl3,SHA512_W_H3,SHA512_W_L3,SHA2_64B,_SHA512,sha2568,sha5123,init_sha24=__esm({"node_modules/@noble/hashes/sha2.js"(){"use strict";init_md4();init_u644();init_utils15();SHA256_K4=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),SHA256_W4=new Uint32Array(64),SHA2_32B=class extends HashMD4{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(outputLen,IV){super(64,outputLen,8,!1),this.A=IV[0]|0,this.B=IV[1]|0,this.C=IV[2]|0,this.D=IV[3]|0,this.E=IV[4]|0,this.F=IV[5]|0,this.G=IV[6]|0,this.H=IV[7]|0}get(){let{A,B,C,D:D2,E,F,G:G2,H}=this;return[A,B,C,D2,E,F,G2,H]}set(A,B,C,D2,E,F,G2,H){this.A=A|0,this.B=B|0,this.C=C|0,this.D=D2|0,this.E=E|0,this.F=F|0,this.G=G2|0,this.H=H|0}_cloneInto(to2){return(to2||=new this.constructor).set(...this.get()),this._cloneIntoMeta(to2)}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W4[i]=view.getUint32(offset,!1);for(let i=16;i<64;i++){let W15=SHA256_W4[i-15],W2=SHA256_W4[i-2],s0=rotr4(W15,7)^rotr4(W15,18)^W15>>>3,s1=rotr4(W2,17)^rotr4(W2,19)^W2>>>10;SHA256_W4[i]=s1+SHA256_W4[i-7]+s0+SHA256_W4[i-16]|0}let{A,B,C,D:D2,E,F,G:G2,H}=this;for(let i=0;i<64;i++){let sigma1=rotr4(E,6)^rotr4(E,11)^rotr4(E,25),T1=H+sigma1+Chi4(E,F,G2)+SHA256_K4[i]+SHA256_W4[i]|0,T2=(rotr4(A,2)^rotr4(A,13)^rotr4(A,22))+Maj4(A,B,C)|0;H=G2,G2=F,F=E,E=D2+T1|0,D2=C,C=B,B=A,A=T1+T2|0}A=A+this.A|0,B=B+this.B|0,C=C+this.C|0,D2=D2+this.D|0,E=E+this.E|0,F=F+this.F|0,G2=G2+this.G|0,H=H+this.H|0,this.set(A,B,C,D2,E,F,G2,H)}roundClean(){clean4(SHA256_W4)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),clean4(this.buffer)}},_SHA256=class extends SHA2_32B{constructor(){super(32,SHA256_IV4)}},K5123=split4(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))),SHA512_Kh3=K5123[0],SHA512_Kl3=K5123[1],SHA512_W_H3=new Uint32Array(80),SHA512_W_L3=new Uint32Array(80),SHA2_64B=class extends HashMD4{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(outputLen,IV){super(128,outputLen,16,!1),this.Ah=IV[0]|0,this.Al=IV[1]|0,this.Bh=IV[2]|0,this.Bl=IV[3]|0,this.Ch=IV[4]|0,this.Cl=IV[5]|0,this.Dh=IV[6]|0,this.Dl=IV[7]|0,this.Eh=IV[8]|0,this.El=IV[9]|0,this.Fh=IV[10]|0,this.Fl=IV[11]|0,this.Gh=IV[12]|0,this.Gl=IV[13]|0,this.Hh=IV[14]|0,this.Hl=IV[15]|0}get(){let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=Ah|0,this.Al=Al|0,this.Bh=Bh|0,this.Bl=Bl|0,this.Ch=Ch|0,this.Cl=Cl|0,this.Dh=Dh|0,this.Dl=Dl|0,this.Eh=Eh|0,this.El=El|0,this.Fh=Fh|0,this.Fl=Fl|0,this.Gh=Gh|0,this.Gl=Gl|0,this.Hh=Hh|0,this.Hl=Hl|0}_cloneInto(to2){return(to2||=new this.constructor).set(...this.get()),this._cloneIntoMeta(to2)}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA512_W_H3[i]=view.getUint32(offset),SHA512_W_L3[i]=view.getUint32(offset+=4);for(let i=16;i<80;i++){let W15h=SHA512_W_H3[i-15]|0,W15l=SHA512_W_L3[i-15]|0,s0h=rotrSH3(W15h,W15l,1)^rotrSH3(W15h,W15l,8)^shrSH3(W15h,W15l,7),s0l=rotrSL3(W15h,W15l,1)^rotrSL3(W15h,W15l,8)^shrSL3(W15h,W15l,7),W2h=SHA512_W_H3[i-2]|0,W2l=SHA512_W_L3[i-2]|0,s1h=rotrSH3(W2h,W2l,19)^rotrBH3(W2h,W2l,61)^shrSH3(W2h,W2l,6),s1l=rotrSL3(W2h,W2l,19)^rotrBL3(W2h,W2l,61)^shrSL3(W2h,W2l,6),SUMl=add4L3(s0l,s1l,SHA512_W_L3[i-7],SHA512_W_L3[i-16]),SUMh=add4H3(SUMl,s0h,s1h,SHA512_W_H3[i-7],SHA512_W_H3[i-16]);SHA512_W_H3[i]=SUMh|0,SHA512_W_L3[i]=SUMl|0}let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;for(let i=0;i<80;i++){let sigma1h=rotrSH3(Eh,El,14)^rotrSH3(Eh,El,18)^rotrBH3(Eh,El,41),sigma1l=rotrSL3(Eh,El,14)^rotrSL3(Eh,El,18)^rotrBL3(Eh,El,41),CHIh=Eh&Fh^~Eh&Gh,CHIl=El&Fl^~El&Gl,T1ll=add5L3(Hl,sigma1l,CHIl,SHA512_Kl3[i],SHA512_W_L3[i]),T1h=add5H3(T1ll,Hh,sigma1h,CHIh,SHA512_Kh3[i],SHA512_W_H3[i]),T1l=T1ll|0,sigma0h=rotrSH3(Ah,Al,28)^rotrBH3(Ah,Al,34)^rotrBH3(Ah,Al,39),sigma0l=rotrSL3(Ah,Al,28)^rotrBL3(Ah,Al,34)^rotrBL3(Ah,Al,39),MAJh=Ah&Bh^Ah&Ch^Bh&Ch,MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=Gh|0,Hl=Gl|0,Gh=Fh|0,Gl=Fl|0,Fh=Eh|0,Fl=El|0,{h:Eh,l:El}=add3(Dh|0,Dl|0,T1h|0,T1l|0),Dh=Ch|0,Dl=Cl|0,Ch=Bh|0,Cl=Bl|0,Bh=Ah|0,Bl=Al|0;let All=add3L3(T1l,sigma0l,MAJl);Ah=add3H3(All,T1h,sigma0h,MAJh),Al=All|0}({h:Ah,l:Al}=add3(this.Ah|0,this.Al|0,Ah|0,Al|0)),{h:Bh,l:Bl}=add3(this.Bh|0,this.Bl|0,Bh|0,Bl|0),{h:Ch,l:Cl}=add3(this.Ch|0,this.Cl|0,Ch|0,Cl|0),{h:Dh,l:Dl}=add3(this.Dh|0,this.Dl|0,Dh|0,Dl|0),{h:Eh,l:El}=add3(this.Eh|0,this.El|0,Eh|0,El|0),{h:Fh,l:Fl}=add3(this.Fh|0,this.Fl|0,Fh|0,Fl|0),{h:Gh,l:Gl}=add3(this.Gh|0,this.Gl|0,Gh|0,Gl|0),{h:Hh,l:Hl}=add3(this.Hh|0,this.Hl|0,Hh|0,Hl|0),this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){clean4(SHA512_W_H3,SHA512_W_L3)}destroy(){this.destroyed=!0,clean4(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},_SHA512=class extends SHA2_64B{constructor(){super(64,SHA512_IV4)}},sha2568=createHasher5(()=>new _SHA256,oidNist(1)),sha5123=createHasher5(()=>new _SHA512,oidNist(3))}});function aarray(item,title,inner=()=>{}){if(!Array.isArray(item))throw new TypeError(`"${title}" expected array, got type=${typeof item}`);for(let i=0;i<item.length;i++)inner(item[i],`${title}[${i}]`);return item}function astring(value,title=""){if(typeof value!="string"){let prefix=title&&`"${title}" `;throw new TypeError(prefix+"expected string, got type="+typeof value)}return value}function aobject2(value,title="object"){if(value===null||typeof value!="object"||Array.isArray(value))throw new TypeError(title==="object"?"expected valid options object":`"${title}" expected object, got type=${typeof value}`);return value}function afunction(value,title){if(typeof value!="function")throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);return value}function abool3(value,title=""){if(typeof value!="boolean")throw new TypeError(atitle2(title)+"expected boolean, got type="+typeof value);return value}function abignumber(n){if(typeof n=="bigint"){if(!isPosBig3(n))throw new RangeError("positive bigint expected, got "+n)}else anumber6(n);return n}function asafenumber(value,title=""){if(typeof value!="number"){let prefix=title&&`"${title}" `;throw new TypeError(prefix+"expected number, got type="+typeof value)}if(!Number.isSafeInteger(value)){let prefix=title&&`"${title}" `;throw new RangeError(prefix+"expected safe integer, got "+value)}}function numberToHexUnpadded3(num2){let hex3=abignumber(num2).toString(16);return hex3.length&1?"0"+hex3:hex3}function hexToNumber5(hex3){if(typeof hex3!="string")throw new TypeError("hex string expected, got "+typeof hex3);return hex3===""?_0n13:BigInt("0x"+hex3)}function bytesToNumberBE3(bytes){return hexToNumber5(bytesToHex4(bytes))}function bytesToNumberLE3(bytes){return hexToNumber5(bytesToHex4(copyBytes(abytes6(bytes)).reverse()))}function numberToBytesBE3(n,len){if(anumber5(len),len===0)throw new Error("zero output length is invalid");n=abignumber(n);let expectedLen=len*2,hex3=n.toString(16);if(hex3.length>expectedLen)throw new RangeError("number is too large");return hexToBytes4(hex3.padStart(expectedLen,"0"))}function numberToBytesLE3(n,len){return numberToBytesBE3(n,len).reverse()}function copyBytes(bytes){return Uint8Array.from(abytes7(bytes))}function isPosBig3(n){return typeof n=="bigint"&&_0n13<=n}function inRange3(n,min,max){return isPosBig3(n)&&isPosBig3(min)&&isPosBig3(max)&&min<=n&&n<max}function aInRange3(title,n,min,max){if(!inRange3(n,min,max))throw new RangeError("expected valid "+title+": "+min+" <= n < "+max+", got "+n)}function bitLen3(n){if(n<_0n13)throw new Error("expected non-negative bigint, got "+n);return n===_0n13?0:n.toString(2).length}function createHmacDrbg3(hashLen,qByteLen,hmacFn){if(anumber5(hashLen,"hashLen"),anumber5(qByteLen,"qByteLen"),typeof hmacFn!="function")throw new TypeError("hmacFn must be a function");let u8n3=len=>new Uint8Array(len),NULL=Uint8Array.of(),byte0=Uint8Array.of(0),byte1=Uint8Array.of(1),_maxDrbgIters=1e3,v=u8n3(hashLen),k=u8n3(hashLen),i=0,reset2=()=>{v.fill(1),k.fill(0),i=0},h=(...msgs)=>hmacFn(k,concatBytes7(v,...msgs)),reseed2=(seed=NULL)=>{k=h(byte0,seed),v=h(),seed.length!==0&&(k=h(byte1,seed),v=h())},gen3=()=>{if(i++>=_maxDrbgIters)throw new Error("drbg: tried max amount of iterations");let len=0,out=[];for(;len<qByteLen;){v=h();let sl=v.slice();out.push(sl),len+=v.length}return concatBytes7(...out)};return(seed,pred)=>{reset2(),reseed2(seed);let res;for(;(res=pred(gen3()))===void 0;)reseed2();return reset2(),res}}function validateObject3(object2,fields={},optFields={},title="object"){aobject2(object2,title),aobject2(fields,"fields"),aobject2(optFields,"optFields");function checkField(fieldName,expectedType,isOpt){let label=title==="object"?`param "${String(fieldName)}"`:`"${title}.${String(fieldName)}"`,val=object2[fieldName];if(!Object.hasOwn(object2,fieldName)&&(isOpt?val!==void 0:expectedType!=="function"))throw new TypeError(`${label} is invalid: expected own property`);if(isOpt&&val===void 0)return;let current=typeof val;if(current!==expectedType||val===null)throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`)}let iter=(f,isOpt)=>Object.entries(f).forEach(([k,v])=>checkField(k,v,isOpt));iter(fields,!1),iter(optFields,!0)}var abytes7,anumber6,bytesToHex5,concatBytes7,hexToBytes5,isBytes9,randomBytes5,_0n13,_1n13,atitle2,bitMask3,init_utils16=__esm({"node_modules/@noble/curves/utils.js"(){"use strict";init_utils15();abytes7=(value,length,title)=>abytes6(value,length,title),anumber6=anumber5;bytesToHex5=bytesToHex4,concatBytes7=(...arrays)=>concatBytes6(...arrays),hexToBytes5=hex3=>hexToBytes4(hex3),isBytes9=isBytes8,randomBytes5=bytesLength=>randomBytes4(bytesLength),_0n13=BigInt(0),_1n13=BigInt(1),atitle2=title=>title?`"${title}" `:"";bitMask3=n=>(asafenumber(n,"n"),(_1n13<<BigInt(n))-_1n13)}});function mod3(a,b){if(b<=_0n14)throw new Error("mod: expected positive modulus, got "+b);let result=a%b;return result>=_0n14?result:b+result}function pow(num2,power,modulo2){if(modulo2<=_1n14)throw new Error("pow: expected modulus > 1, got "+modulo2);if(typeof power!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof power);if(power<_0n14)throw new Error("invalid exponent, negatives unsupported");if(power===_0n14)return _1n14;if(power===_1n14)return num2;let d=num2%modulo2;if(d<_0n14&&(d+=modulo2),power<POW_WINDOWED_MIN){let p2=_1n14;for(;power>_0n14;)power&_1n14&&(p2=p2*d%modulo2),d=d*d%modulo2,power>>=_1n14;return p2}let digits=[];for(;power>_0n14;)digits.push(Number(power&_15n)),power>>=_4n5;let table=new Array(16);table[0]=_1n14,table[1]=d;for(let i=2;i<16;i++)table[i]=table[i-1]*d%modulo2;let p=table[digits[digits.length-1]];for(let w=digits.length-2;w>=0;w--){p=p*p%modulo2,p=p*p%modulo2,p=p*p%modulo2,p=p*p%modulo2;let digit=digits[w];digit!==0&&(p=p*table[digit]%modulo2)}return p}function pow23(x,power,modulo2){if(modulo2<=_1n14)throw new Error("pow2: expected modulus > 1, got "+modulo2);if(power<_0n14)throw new Error("pow2: expected non-negative exponent, got "+power);let res=x;for(;power-- >_0n14;)res*=res,res%=modulo2;return res}function invert3(number4,modulo2){if(number4===_0n14)throw new Error("invert: expected non-zero number");if(modulo2<=_1n14)throw new Error("invert: expected modulus > 1, got "+modulo2);let a=mod3(number4,modulo2),b=modulo2,x=_0n14,u=_1n14;for(;a!==_0n14;){let q=b/a,r2=b-a*q,m=x-u*q;b=a,a=r2,x=u,u=m}if(b!==_1n14)throw new Error("invert: does not exist");return mod3(x,modulo2)}function invertCt(a,prime){if(prime<=_1n14)throw new Error("invertCt: expected prime modulus > 1, got "+prime);let an=mod3(a,prime);if(an===_0n14)throw new Error("invertCt: expected non-zero number");let inverse=pow(an,prime-_2n9,prime);if(mod3(an*inverse,prime)!==_1n14)throw new Error("invertCt: does not exist");return inverse}function assertIsSquare(Fp,root2,n){let F=Fp;if(!F.eql(F.sqr(root2),n))throw new Error("Cannot find square root")}function aoddModulus(order,fnName){if((order&_1n14)===_0n14)throw new Error(fnName+": expected odd modulus, got "+order)}function sqrt3mod43(Fp,n){let F=Fp,p1div4=(F.ORDER+_1n14)/_4n5,root2=F.pow(n,p1div4);return assertIsSquare(F,root2,n),root2}function sqrt5mod83(Fp,n){let F=Fp,p5div8=(F.ORDER-_5n3)/_8n3,n2=F.mul(n,_2n9),v=F.pow(n2,p5div8),nv=F.mul(n,v),i=F.mul(F.mul(nv,_2n9),v),root2=F.mul(nv,F.sub(i,F.ONE));return assertIsSquare(F,root2,n),root2}function sqrt9mod16(P3){let Fp_=Field3(P3),tn=tonelliShanks3(P3),c1=tn(Fp_,Fp_.neg(Fp_.ONE)),c2=tn(Fp_,c1),c3=tn(Fp_,Fp_.neg(c1)),c4=(P3+_7n3)/_16n;return((Fp,n)=>{let F=Fp,tv1=F.pow(n,c4),tv2=F.mul(tv1,c1),tv3=F.mul(tv1,c2),tv4=F.mul(tv1,c3),e1=F.eql(F.sqr(tv2),n),e22=F.eql(F.sqr(tv3),n);tv1=F.cmov(tv1,tv2,e1),tv2=F.cmov(tv4,tv3,e22);let e32=F.eql(F.sqr(tv2),n),root2=F.cmov(tv1,tv2,e32);return assertIsSquare(F,root2,n),root2})}function tonelliShanks3(P3){if(P3<_3n5)throw new Error("sqrt is not defined for small field");aoddModulus(P3,"tonelliShanks");let Q=P3-_1n14,S=0;for(;Q%_2n9===_0n14;)Q/=_2n9,S++;let Z=_2n9,_Fp=Field3(P3);for(;FpLegendre3(_Fp,Z)===1;)if(Z++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(S===1)return sqrt3mod43;let cc=_Fp.pow(Z,Q),Q1div2=(Q+_1n14)/_2n9;return function(Fp,n){let F=Fp;if(F.is0(n))return n;if(FpLegendre3(F,n)!==1)throw new Error("Cannot find square root");let M=S,c=F.mul(F.ONE,cc),t=F.pow(n,Q),R=F.pow(n,Q1div2);for(;!F.eql(t,F.ONE);){if(F.is0(t))throw new Error("Cannot find square root: probably non-prime P");let i=1,t_tmp=F.sqr(t);for(;!F.eql(t_tmp,F.ONE);)if(i++,t_tmp=F.sqr(t_tmp),i===M)throw new Error("Cannot find square root");let exponent=_1n14<<BigInt(M-i-1),b=F.pow(c,exponent);M=i,c=F.sqr(b),t=F.mul(t,c),R=F.mul(R,b)}return R}}function FpSqrt3(P3){return aoddModulus(P3,"Fp.sqrt"),P3%_4n5===_3n5?sqrt3mod43:P3%_8n3===_5n3?sqrt5mod83:P3%_16n===_9n?sqrt9mod16(P3):tonelliShanks3(P3)}function validateField4(field){if(aobject2(field,"field"),typeof field.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof field.ORDER);asafenumber(field.BYTES,"BYTES"),asafenumber(field.BITS,"BITS");for(let name of FIELD_FIELDS3)afunction(field[name],"field."+name);if(field.BYTES<1||field.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(field.ORDER<=_1n14)throw new Error("invalid field: expected ORDER > 1, got "+field.ORDER);return field}function FpInvertBatch3(Fp,nums,passZero=!1){validateField4(Fp),aarray(nums,"nums"),abool3(passZero,"passZero");let F=Fp,inverted=new Array(nums.length).fill(passZero?F.ZERO:void 0),multipliedAcc=nums.reduce((acc,num2,i)=>F.is0(num2)?acc:(inverted[i]=acc,F.mul(acc,num2)),F.ONE),invertedAcc=F.inv(multipliedAcc);return nums.reduceRight((acc,num2,i)=>F.is0(num2)?acc:(inverted[i]=F.mul(acc,inverted[i]),F.mul(acc,num2)),invertedAcc),inverted}function FpLegendre3(Fp,n){validateField4(Fp);let F=Fp;aoddModulus(F.ORDER,"FpLegendre");let p1mod2=(F.ORDER-_1n14)/_2n9,powered=F.pow(n,p1mod2),yes=F.eql(powered,F.ONE),zero=F.eql(powered,F.ZERO),no=F.eql(powered,F.neg(F.ONE));if(!yes&&!zero&&!no)throw new Error("invalid Legendre symbol result");return yes?1:zero?0:-1}function nLength3(n,nBitLength){if(nBitLength!==void 0&&anumber6(nBitLength),n<=_0n14)throw new Error("invalid n length: expected positive n, got "+n);if(nBitLength!==void 0&&nBitLength<1)throw new Error("invalid n length: expected positive bit length, got "+nBitLength);let bits=bitLen3(n);if(nBitLength!==void 0&&nBitLength<bits)throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);let _nBitLength=nBitLength!==void 0?nBitLength:bits,nByteLength=Math.ceil(_nBitLength/8);return{nBitLength:_nBitLength,nByteLength}}function Field3(ORDER,opts={}){return Object.freeze(_Field.prototype),new _Field(ORDER,opts)}function getFieldBytesLength3(fieldOrder){if(typeof fieldOrder!="bigint")throw new Error("field order must be bigint");if(fieldOrder<=_1n14)throw new Error("field order must be greater than 1");let bitLength=bitLen3(fieldOrder-_1n14);return Math.ceil(bitLength/8)}function getMinHashLength3(fieldOrder){let length=getFieldBytesLength3(fieldOrder);return length+Math.ceil(length/2)}function mapHashToField3(key3,fieldOrder,isLE3=!1){abytes7(key3);let len=key3.length,fieldLen=getFieldBytesLength3(fieldOrder),minLen=Math.max(getMinHashLength3(fieldOrder),16);if(len<minLen||len>1024)throw new Error("expected "+minLen+"-1024 bytes of input, got "+len);let num2=isLE3?bytesToNumberLE3(key3):bytesToNumberBE3(key3),reduced=mod3(num2,fieldOrder-_1n14)+_1n14;return isLE3?numberToBytesLE3(reduced,fieldLen):numberToBytesBE3(reduced,fieldLen)}var _0n14,_1n14,_2n9,_3n5,_4n5,_5n3,_7n3,_8n3,_9n,_15n,_16n,POW_WINDOWED_MIN,FIELD_FIELDS3,FIELD_SQRT,_Field,init_modular3=__esm({"node_modules/@noble/curves/abstract/modular.js"(){"use strict";init_utils16();_0n14=BigInt(0),_1n14=BigInt(1),_2n9=BigInt(2),_3n5=BigInt(3),_4n5=BigInt(4),_5n3=BigInt(5),_7n3=BigInt(7),_8n3=BigInt(8),_9n=BigInt(9),_15n=BigInt(15),_16n=BigInt(16),POW_WINDOWED_MIN=BigInt("0x10000000000000000");FIELD_FIELDS3=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];FIELD_SQRT=new WeakMap,_Field=class{ORDER;BITS;BYTES;isLE;ZERO=_0n14;ONE=_1n14;_lengths;_mod;constructor(ORDER,opts={}){if(ORDER<=_1n14)throw new Error("invalid field: expected ORDER > 1, got "+ORDER);let _nbitLength;this.isLE=!1,opts!=null&&typeof opts=="object"&&(typeof opts.BITS=="number"&&(_nbitLength=opts.BITS),typeof opts.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:opts.sqrt,enumerable:!0}),typeof opts.isLE=="boolean"&&(this.isLE=opts.isLE),opts.allowedLengths&&(this._lengths=Object.freeze(opts.allowedLengths.slice())),typeof opts.modFromBytes=="boolean"&&(this._mod=opts.modFromBytes));let{nBitLength,nByteLength}=nLength3(ORDER,_nbitLength);if(nByteLength>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=ORDER,this.BITS=nBitLength,this.BYTES=nByteLength,Object.freeze(this)}create(num2){return mod3(num2,this.ORDER)}isValid(num2){if(typeof num2!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof num2);return _0n14<=num2&&num2<this.ORDER}is0(num2){return num2===_0n14}isValidNot0(num2){return!this.is0(num2)&&this.isValid(num2)}isOdd(num2){return(num2&_1n14)===_1n14}neg(num2){return mod3(-num2,this.ORDER)}eql(lhs,rhs){return lhs===rhs}sqr(num2){return mod3(num2*num2,this.ORDER)}add(lhs,rhs){return mod3(lhs+rhs,this.ORDER)}sub(lhs,rhs){return mod3(lhs-rhs,this.ORDER)}mul(lhs,rhs){return mod3(lhs*rhs,this.ORDER)}pow(num2,power){return pow(num2,power,this.ORDER)}div(lhs,rhs){return mod3(lhs*invert3(rhs,this.ORDER),this.ORDER)}sqrN(num2){return num2*num2}addN(lhs,rhs){return lhs+rhs}subN(lhs,rhs){return lhs-rhs}mulN(lhs,rhs){return lhs*rhs}inv(num2){return invert3(num2,this.ORDER)}sqrt(num2){let sqrt=FIELD_SQRT.get(this);return sqrt||FIELD_SQRT.set(this,sqrt=FpSqrt3(this.ORDER)),sqrt(this,num2)}toBytes(num2){return this.isLE?numberToBytesLE3(num2,this.BYTES):numberToBytesBE3(num2,this.BYTES)}fromBytes(bytes,skipValidation=!1){abytes7(bytes);let{_lengths:allowedLengths,BYTES,isLE:isLE3,ORDER,_mod:modFromBytes}=this;if(allowedLengths){if(bytes.length<1||!allowedLengths.includes(bytes.length)||bytes.length>BYTES)throw new Error("Field.fromBytes: expected "+allowedLengths+" bytes, got "+bytes.length);let padded=new Uint8Array(BYTES);padded.set(bytes,isLE3?0:padded.length-bytes.length),bytes=padded}if(bytes.length!==BYTES)throw new Error("Field.fromBytes: expected "+BYTES+" bytes, got "+bytes.length);let scalar=isLE3?bytesToNumberLE3(bytes):bytesToNumberBE3(bytes);if(modFromBytes&&(scalar=mod3(scalar,ORDER)),!skipValidation&&!this.isValid(scalar))throw new Error("invalid field element: outside of range 0..ORDER");return scalar}invertBatch(lst){return FpInvertBatch3(this,lst,!0)}cmov(a,b,condition){return abool3(condition,"condition"),condition?b:a}}}});function validatePointCons(Point4){let pc=Point4;if(typeof pc!="function")throw new TypeError('"Point" expected constructor, got type='+typeof Point4);afunction(pc.fromAffine,"Point.fromAffine"),afunction(pc.fromBytes,"Point.fromBytes"),afunction(pc.fromHex,"Point.fromHex"),aobject2(pc.BASE,"Point.BASE"),aobject2(pc.ZERO,"Point.ZERO"),validateField4(pc.Fp),validateField4(pc.Fn)}function normalizeZ(c,points){validatePointCons(c),validateMSMPoints3(points,c);let invertedZs=FpInvertBatch3(c.Fp,points.map(p=>p.Z));return points.map((p,i)=>c.fromAffine(p.toAffine(invertedZs[i])))}function validateW3(W,bits,min=1){if(!Number.isSafeInteger(W)||W<min||W>bits)throw new Error("invalid window size, expected ["+min+".."+bits+"], got W="+W)}function validateTableBytes(numPoints,fpBytes){let bytes=numPoints*(4*fpBytes+128);if(bytes>TABLE_BYTES_MAX)throw new Error("invalid window size: table would need ~"+Math.ceil(bytes/2**20)+" MiB, max "+TABLE_BYTES_MAX/2**20+" MiB")}function probeRandomBytes(randomBytes9,length){if(randomBytes9!==void 0){afunction(randomBytes9,"randomBytes");try{let probe=randomBytes9(length);if(!isBytes9(probe)||probe.length!==length)return}catch{return}return randomBytes9}}function validateMSMPoints3(points,c){aarray(points,"points"),points.forEach((p,i)=>{if(!(p instanceof c))throw new Error("invalid point at index "+i)})}function validateMSMScalars3(scalars,field,maxScalar){if(!Array.isArray(scalars))throw new Error("array of scalars expected");scalars.forEach((s3,i)=>{if(!(maxScalar===void 0?field.isValid(s3):isPosBig3(s3)&&s3<maxScalar))throw new Error("invalid scalar at index "+i)})}function getWindowSize(P3){return pointWindowSizes3.get(P3)||1}function oddMultiples(p,size4){let dbl3=p.double(),t=[p];for(let j=1;j<size4;j++)t.push(t[j-1].add(dbl3));return t}function wnafDigits(n,W){let size4=2**W,half=size4/2,mask=BigInt(size4-1),d=[];for(;n>_0n15;){let w=0;n&_1n15&&(w=Number(n&mask),w>=half&&(w-=size4),n-=BigInt(w)),d.push(w),n>>=_1n15}return d}function signedWindowDigits(n,W,windows){let size4=2**W,half=size4/2,mask=BigInt(size4-1),shiftBy=BigInt(W),d=[];for(let w=0;w<windows;w++){let v=Number(n&mask);n>>=shiftBy,v>half&&(v-=size4,n+=_1n15),d.push(v)}if(n!==_0n15)throw new Error("invalid wnaf");return d}function wnafWalk(zero,tables,digits){let max=0;for(let d of digits)max=Math.max(max,d.length);let acc=zero;for(let bit=max-1;bit>=0;bit--){bit!==max-1&&(acc=acc.double());for(let i=0;i<digits.length;i++){let w=digits[i][bit];if(w){let item=tables[i][Math.abs(w)-1>>1];acc=acc.add(w<0?item.negate():item)}}}return acc}function mulAddUnsafe(c,points,scalars,allowOversized=!1){if(validatePointCons(c),validateMSMPoints3(points,c),abool3(allowOversized,"allowOversized"),validateMSMScalars3(scalars,c.Fn,allowOversized?c.Fn.ORDER**_4n6:void 0),points.length!==scalars.length)throw new Error("arrays of points and scalars must have equal length");let tables=points.map(p=>oddMultiples(p,4)),digits=scalars.map(n=>wnafDigits(n,4));return wnafWalk(c.ZERO,tables,digits)}function createField(order,field,isLE3){if(field){if(field.ORDER!==order)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return validateField4(field),field}else return Field3(order,{isLE:isLE3})}function createCurveFields(type2,CURVE,curveOpts={},FpFnLE){if(type2!=="weierstrass"&&type2!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(FpFnLE===void 0&&(FpFnLE=type2==="edwards"),!CURVE||typeof CURVE!="object")throw new Error(`expected valid ${type2} CURVE object`);validateObject3(curveOpts);for(let p of["p","n","h"]){let val=CURVE[p];if(!(isPosBig3(val)&&val!==_0n15))throw new Error(`CURVE.${p} must be positive bigint`)}let Fp=createField(CURVE.p,curveOpts.Fp,FpFnLE),Fn2=createField(CURVE.n,curveOpts.Fn,FpFnLE),params=["Gx","Gy","a",type2==="weierstrass"?"b":"d"];for(let p of params)if(!Fp.isValid(CURVE[p]))throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);return CURVE=Object.freeze(Object.assign({},CURVE)),{CURVE,Fp,Fn:Fn2}}function createKeygen(randomSecretKey,getPublicKey){return function(seed){let secretKey=randomSecretKey(seed);return{secretKey,publicKey:getPublicKey(secretKey)}}}var _0n15,_1n15,_4n6,BLIND_BYTES,BLIND_BITS,FW_WINDOW,TABLE_BYTES_MAX,pointWindowSizes3,ScalarMultiplier,init_curve3=__esm({"node_modules/@noble/curves/abstract/curve.js"(){"use strict";init_utils16();init_modular3();_0n15=BigInt(0),_1n15=BigInt(1),_4n6=BigInt(4),BLIND_BYTES=16,BLIND_BITS=128,FW_WINDOW=5,TABLE_BYTES_MAX=2**31;pointWindowSizes3=new WeakMap;ScalarMultiplier=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(Point4,randomBytes9){validatePointCons(Point4),this.randomBytes=probeRandomBytes(randomBytes9,BLIND_BYTES),this.Point=Point4,this.BASE=Point4.BASE,this.ZERO=Point4.ZERO,this.bits=Point4.Fn.BITS}buildWnafTable(point3,W,bits){let windows=Math.ceil(bits/W)+1,half=2**(W-1),comp=[],base4=point3;for(let w=0;w<windows;w++){let acc=base4;for(let i=0;i<half;i++)comp.push(acc),acc=acc.add(base4);base4=comp[comp.length-1].double()}return{W,bits,windows,comp}}wnafCachedCT(precomputes,n){let{W,windows,comp}=precomputes,half=2**(W-1),digits=signedWindowDigits(n,W,windows),p=this.ZERO,f=this.BASE;for(let w=0;w<windows;w++){let digit=digits[w],start=w*half,idx=Math.abs(digit)-1,sel=comp[start];for(let i=1;i<half;i++)sel=i===idx?comp[start+i]:sel;let neg3=sel.negate();digit===0?f=f.add(comp[start]):p=p.add(digit<0?neg3:sel)}return{p,f}}getWnafPrecomputes(W,point3,bits,transform3){let entries=this.wnafPrecomputes.get(point3),comp=entries?.find(entry=>entry.W===W&&entry.bits===bits);return comp||(comp=this.buildWnafTable(point3,W,bits),typeof transform3=="function"&&(comp={...comp,comp:transform3(comp.comp)}),entries||(entries=[],this.wnafPrecomputes.set(point3,entries)),entries.push(comp)),comp}assertPoint(point3){if(!(point3 instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof point3)}validateMulInput(point3,scalar){if(this.assertPoint(point3),!inRange3(scalar,_1n15,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(point3,n,bits,transform3){let W=getWindowSize(point3);return W===1?this.fixedWindowCT(point3,n,bits):this.wnafCachedCT(this.getWnafPrecomputes(W,point3,bits,transform3),n)}mulCT(point3,scalar,transform3){return this.validateMulInput(point3,scalar),this.runCT(point3,scalar,this.bits,transform3)}mulCTBlinded(point3,scalar,transform3){if(this.validateMulInput(point3,scalar),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let bits=this.Point.Fn.BITS+BLIND_BITS,blind=this.randomBytes(BLIND_BYTES);if(!isBytes9(blind)||blind.length!==BLIND_BYTES)throw new Error("randomBytes returned invalid byte array");blind[0]=blind[0]&63|128;let n=scalar+bytesToNumberBE3(blind)*this.Point.Fn.ORDER;return this.runCT(point3,n,bits,transform3)}fixedWindowCT(point3,n,bits){let W=FW_WINDOW,size4=1<<W,mask=bitMask3(W),table=new Array(size4);table[0]=this.ZERO;for(let i=1;i<size4;i++)table[i]=table[i-1].add(point3);let windows=Math.ceil(bits/W),acc=this.ZERO;for(let window2=windows-1;window2>=0;window2--){if(window2!==windows-1)for(let d=0;d<W;d++)acc=acc.double();let digit=Number(n>>BigInt(window2*W)&mask),sel=table[0];for(let i=1;i<size4;i++)sel=i===digit?table[i]:sel;acc=acc.add(sel)}return{p:acc,f:acc}}shouldBlind(point3,cofactor){return this.randomBytes===void 0?!1:cofactor===_1n15?!0:point3!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(point3,scalar,cofactor,transform3){return this.shouldBlind(point3,cofactor)?this.mulCTBlinded(point3,scalar,transform3):this.mulCT(point3,scalar,transform3)}mulUnsafe(point3,scalar,transform3){if(this.assertPoint(point3),!isPosBig3(scalar))throw new Error("invalid scalar");let W=getWindowSize(point3);if(W===1||scalar>=this.Point.Fn.ORDER)return mulAddUnsafe(this.Point,[point3],[scalar],!0);let precomputes=this.getWnafPrecomputes(W,point3,this.bits,transform3);return this.wnafCachedCT(precomputes,scalar).p}setWindowSize(point3,W){this.assertPoint(point3),validateW3(W,this.bits);let windows=Math.ceil((this.bits+BLIND_BITS)/W)+1;validateTableBytes(windows*2**(W-1),this.Point.Fp.BYTES),pointWindowSizes3.set(point3,W),this.wnafPrecomputes.delete(point3)}hasWindowSize(point3){return getWindowSize(point3)!==1}}}});var _HMAC,hmac4,init_hmac4=__esm({"node_modules/@noble/hashes/hmac.js"(){"use strict";init_utils15();_HMAC=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(hash8,key3){if(ahash4(hash8),abytes6(key3,void 0,"key"),this.iHash=hash8.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let blockLen=this.blockLen,pad4=new Uint8Array(blockLen);pad4.set(key3.length>blockLen?hash8.create().update(key3).digest():key3);for(let i=0;i<pad4.length;i++)pad4[i]^=54;this.iHash.update(pad4),this.oHash=hash8.create();for(let i=0;i<pad4.length;i++)pad4[i]^=106;this.oHash.update(pad4),clean4(pad4)}update(buf){return aexists4(this),this.iHash.update(buf),this}digestInto(out){aexists4(this),aoutput4(out,this),this.finished=!0;let buf=out.subarray(0,this.outputLen);this.iHash.digestInto(buf),this.oHash.update(buf),this.oHash.digestInto(buf),this.destroy()}digest(){let out=new Uint8Array(this.oHash.outputLen);return this.digestInto(out),out}_cloneInto(to2){to2||=Object.create(Object.getPrototypeOf(this),{});let{oHash,iHash,finished:finished2,destroyed,blockLen,outputLen,canXOF}=this;return to2=to2,to2.finished=finished2,to2.destroyed=destroyed,to2.blockLen=blockLen,to2.outputLen=outputLen,to2.canXOF=canXOF,to2.oHash=oHash._cloneInto(to2.oHash),to2.iHash=iHash._cloneInto(to2.iHash),to2}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},hmac4=(()=>{let hmac_=((hash8,key3,message)=>new _HMAC(hash8,key3).update(message).digest());return hmac_.create=(hash8,key3)=>new _HMAC(hash8,key3),hmac_})()}});var _0n16,DERErr3,_DER,DER3,init_der=__esm({"node_modules/@noble/curves/abstract/der.js"(){"use strict";init_utils16();_0n16=BigInt(0),DERErr3=class extends Error{constructor(m=""){super(m)}},_DER={Err:DERErr3,_tlv:{encode:(tag,data)=>{let{Err:E}=_DER;if(asafenumber(tag,"tag"),tag<0||tag>255)throw new E("tlv.encode: wrong tag");if(astring(data,"data"),data.length&1)throw new E("tlv.encode: unpadded data");let dataLen=data.length/2,len=numberToHexUnpadded3(dataLen);if(len.length/2&128)throw new E("tlv.encode: long form length too big");let lenLen=dataLen>127?numberToHexUnpadded3(len.length/2|128):"";return numberToHexUnpadded3(tag)+lenLen+len+data},decode(tag,data){let{Err:E}=_DER;data=abytes7(data,void 0,"DER data");let pos=0;if(tag<0||tag>255)throw new E("tlv.decode: wrong tag");if(data.length<2||data[pos++]!==tag)throw new E("tlv.decode: wrong tlv");let first=data[pos++],isLong=!!(first&128),length=0;if(!isLong)length=first;else{let lenLen=first&127;if(!lenLen)throw new E("tlv.decode(long): indefinite length not supported");if(lenLen>4)throw new E("tlv.decode(long): byte length is too big");let lengthBytes=data.subarray(pos,pos+lenLen);if(lengthBytes.length!==lenLen)throw new E("tlv.decode: length bytes not complete");if(lengthBytes[0]===0)throw new E("tlv.decode(long): zero leftmost byte");for(let b of lengthBytes)length=length<<8|b;if(pos+=lenLen,length<128)throw new E("tlv.decode(long): not minimal encoding")}let v=data.subarray(pos,pos+length);if(v.length!==length)throw new E("tlv.decode: wrong value length");return{v,l:data.subarray(pos+length)}}},_int:{encode(num2){let{Err:E}=_DER;if(abignumber(num2),num2<_0n16)throw new E("integer: negative integers are not allowed");let hex3=numberToHexUnpadded3(num2);if(Number.parseInt(hex3[0],16)&8&&(hex3="00"+hex3),hex3.length&1)throw new E("unexpected DER parsing assertion: unpadded hex");return hex3},decode(data){let{Err:E}=_DER;if(data.length<1)throw new E("invalid signature integer: empty");if(data[0]&128)throw new E("invalid signature integer: negative");if(data.length>1&&data[0]===0&&!(data[1]&128))throw new E("invalid signature integer: unnecessary leading zero");return bytesToNumberBE3(data)}},toSig(bytes,maxScalarBytes){let{Err:E,_int:int2,_tlv:tlv}=_DER;if(maxScalarBytes!==void 0&&(asafenumber(maxScalarBytes,"maxScalarBytes"),maxScalarBytes<1))throw new E("invalid signature: maxScalarBytes must be positive");let data=abytes7(bytes,void 0,"signature"),{v:seqBytes,l:seqLeftBytes}=tlv.decode(48,data);if(seqLeftBytes.length)throw new E("invalid signature: left bytes after parsing");let{v:rBytes,l:rLeftBytes}=tlv.decode(2,seqBytes),{v:sBytes,l:sLeftBytes}=tlv.decode(2,rLeftBytes);if(sLeftBytes.length)throw new E("invalid signature: left bytes after parsing");if(maxScalarBytes!==void 0&&(rBytes.length>maxScalarBytes||sBytes.length>maxScalarBytes))throw new E("invalid signature: integer too large");return{r:int2.decode(rBytes),s:int2.decode(sBytes)}},hexFromSig(sig){let{_tlv:tlv,_int:int2}=_DER;validateObject3(sig,{r:"bigint",s:"bigint"},{},"sig");let rs=tlv.encode(2,int2.encode(sig.r)),ss=tlv.encode(2,int2.encode(sig.s)),seq=rs+ss;return tlv.encode(48,seq)}},DER3=(Object.freeze(_DER._tlv),Object.freeze(_DER._int),Object.freeze(_DER))}});function _splitEndoScalar(k,basis,n){aInRange3("scalar",k,_0n17,n);let[[a1,b1],[a2,b2]]=basis,c1=divNearest3(b2*k,n),c2=divNearest3(-b1*k,n),k1=k-c1*a1-c2*a2,k2=-c1*b1-c2*b2,k1neg=k1<_0n17,k2neg=k2<_0n17;k1neg&&(k1=-k1),k2neg&&(k2=-k2);let MAX_NUM=bitMask3(Math.ceil(bitLen3(n)/2))+_1n16;if(k1<_0n17||k1>=MAX_NUM||k2<_0n17||k2>=MAX_NUM)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg,k1,k2neg,k2}}function validateSigFormat(format3){if(!["compact","recovered","der"].includes(format3))throw new Error('Signature format must be "compact", "recovered", or "der"');return format3}function validateSigOpts(opts,def){validateObject3(opts);let optsn={};for(let optName of Object.keys(def))optsn[optName]=opts[optName]===void 0?def[optName]:opts[optName];return abool3(optsn.lowS,"lowS"),abool3(optsn.prehash,"prehash"),optsn.format!==void 0&&validateSigFormat(optsn.format),optsn}function weierstrass3(params,extraOpts={}){let validated=createCurveFields("weierstrass",params,extraOpts),Fp=validated.Fp,Fn2=validated.Fn,CURVE=validated.CURVE,{h:cofactor,n:CURVE_ORDER}=CURVE;validateObject3(extraOpts,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:endoOpts,allowInfinityPoint,clearCofactor,isTorsionFree,fromBytes:fromBytes6,toBytes:toBytes8}=extraOpts,randomBytes9=extraOpts.randomBytes===void 0?randomBytes5:extraOpts.randomBytes;if(endoOpts&&(!Fp.is0(CURVE.a)||typeof endoOpts.beta!="bigint"||!Array.isArray(endoOpts.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let endo=endoOpts?{beta:endoOpts.beta,basises:endoOpts.basises.map(basis=>[...basis])}:void 0,lengths=getWLengths(Fp,Fn2);function assertCompressionIsSupported(){if(!Fp.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function pointToBytes2(_c,point3,isCompressed){if(point3.is0()){if(!allowInfinityPoint)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x,y}=point3.toAffine(),bx=Fp.toBytes(x);if(abool3(isCompressed,"isCompressed"),isCompressed){assertCompressionIsSupported();let hasEvenY=!Fp.isOdd(y);return concatBytes7(pprefix(hasEvenY),bx)}else return concatBytes7(Uint8Array.of(4),bx,Fp.toBytes(y))}function pointFromBytes(bytes){abytes7(bytes,void 0,"Point");let{publicKey:comp,publicKeyUncompressed:uncomp}=lengths,length=bytes.length,head=bytes[0],tail=bytes.subarray(1);if(allowInfinityPoint&&length===1&&head===0)return{x:Fp.ZERO,y:Fp.ZERO};if(length===comp&&(head===2||head===3)){let x=Fp.fromBytes(tail);if(!Fp.isValid(x))throw new Error("bad point: is not on curve, wrong x");let y2=weierstrassEquation(x),y;try{y=Fp.sqrt(y2)}catch(sqrtError){let err=sqrtError instanceof Error?": "+sqrtError.message:"";throw new Error("bad point: is not on curve, sqrt error"+err)}assertCompressionIsSupported();let evenY=Fp.isOdd(y);return(head&1)===1!==evenY&&(y=Fp.neg(y)),{x,y}}else if(length===uncomp&&head===4){let L=Fp.BYTES,x=Fp.fromBytes(tail.subarray(0,L)),y=Fp.fromBytes(tail.subarray(L,L*2));if(!isValidXY(x,y))throw new Error("bad point: is not on curve");return{x,y}}else throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`)}let encodePoint=toBytes8===void 0?pointToBytes2:toBytes8,decodePoint2=fromBytes6===void 0?pointFromBytes:fromBytes6,b32=Fp.mul(CURVE.b,_3n6),mulA=Fp.is0(CURVE.a)?_=>Fp.ZERO:x=>Fp.mul(CURVE.a,x);function weierstrassEquation(x){let x2=Fp.sqr(x),x3=Fp.mul(x2,x);return Fp.add(Fp.add(x3,Fp.mul(x,CURVE.a)),CURVE.b)}function isValidXY(x,y){let left=Fp.sqr(y),right=weierstrassEquation(x);return Fp.eql(left,right)}if(!isValidXY(CURVE.Gx,CURVE.Gy))throw new Error("bad curve params: generator point");let _4a3=Fp.mul(Fp.pow(CURVE.a,_3n6),_4n7),_27b2=Fp.mul(Fp.sqr(CURVE.b),BigInt(27));if(Fp.is0(Fp.add(_4a3,_27b2)))throw new Error("bad curve params: a or b");function acoord(title,n,banZero=!1){if(!Fp.isValid(n)||banZero&&Fp.is0(n))throw new Error(`bad point coordinate ${title}`);return typeof n=="object"&&n!==null?Fp.create(n):n}function aprjpoint(other){if(!(other instanceof Point4))throw new Error("Weierstrass Point expected")}function splitEndoScalarN(k){if(!endo||!endo.basises)throw new Error("no endo");return _splitEndoScalar(k,endo.basises,Fn2.ORDER)}function pushWnafPair(points,scalars,p,k){if(!Fn2.isValid(k))throw new RangeError("invalid scalar: out of range");if(endo){let{k1neg,k1,k2neg,k2}=splitEndoScalarN(k),psi=new Point4(Fp.mul(p.X,endo.beta),p.Y,p.Z);points.push(k1neg?p.negate():p,k2neg?psi.negate():psi),scalars.push(k1,k2)}else points.push(p),scalars.push(k)}let validityCache=new WeakSet;class Point4{static BASE=new Point4(CURVE.Gx,CURVE.Gy,Fp.ONE);static ZERO=new Point4(Fp.ZERO,Fp.ONE,Fp.ZERO);static Fp=Fp;static Fn=Fn2;X;Y;Z;constructor(X,Y,Z){this.X=acoord("x",X),this.Y=acoord("y",Y,!0),this.Z=acoord("z",Z),Object.freeze(this)}static CURVE(){return CURVE}static fromAffine(p){let{x,y}=p||{};if(!p||!Fp.isValid(x)||!Fp.isValid(y))throw new Error("invalid affine point");if(p instanceof Point4)throw new Error("projective point not allowed");return Fp.is0(x)&&Fp.is0(y)?Point4.ZERO:new Point4(x,y,Fp.ONE)}static fromBytes(bytes){let P3=Point4.fromAffine(decodePoint2(abytes7(bytes,void 0,"point")));return P3.assertValidity(),P3}static fromHex(hex3){return Point4.fromBytes(hexToBytes5(hex3))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(windowSize=6,isLazy=!0){return wnaf.setWindowSize(this,windowSize),isLazy||this.multiply(_3n6),this}assertValidity(){let p=this;if(p.is0()){if(allowInfinityPoint&&Fp.is0(p.X)&&Fp.eql(p.Y,Fp.ONE)&&Fp.is0(p.Z))return;throw new Error("bad point: ZERO")}if(validityCache.has(p))return;let{x,y}=p.toAffine();if(!Fp.isValid(x)||!Fp.isValid(y))throw new Error("bad point: x or y not field elements");if(!isValidXY(x,y))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");validityCache.add(p)}hasEvenY(){let{y}=this.toAffine();if(!Fp.isOdd)throw new Error("Field doesn't support isOdd");return!Fp.isOdd(y)}equals(other){aprjpoint(other);let{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=other,U1=Fp.eql(Fp.mul(X1,Z2),Fp.mul(X2,Z1)),U2=Fp.eql(Fp.mul(Y1,Z2),Fp.mul(Y2,Z1));return U1&&U2}negate(){return new Point4(this.X,Fp.neg(this.Y),this.Z)}double(){let{X:X1,Y:Y1,Z:Z1}=this,X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO,t0=Fp.mul(X1,X1),t1=Fp.mul(Y1,Y1),t2=Fp.mul(Z1,Z1),t3=Fp.mul(X1,Y1);return t3=Fp.add(t3,t3),Z3=Fp.mul(X1,Z1),Z3=Fp.add(Z3,Z3),X3=mulA(Z3),Y3=Fp.mul(b32,t2),Y3=Fp.add(X3,Y3),X3=Fp.sub(t1,Y3),Y3=Fp.add(t1,Y3),Y3=Fp.mul(X3,Y3),X3=Fp.mul(t3,X3),Z3=Fp.mul(b32,Z3),t2=mulA(t2),t3=Fp.sub(t0,t2),t3=mulA(t3),t3=Fp.add(t3,Z3),Z3=Fp.add(t0,t0),t0=Fp.add(Z3,t0),t0=Fp.add(t0,t2),t0=Fp.mul(t0,t3),Y3=Fp.add(Y3,t0),t2=Fp.mul(Y1,Z1),t2=Fp.add(t2,t2),t0=Fp.mul(t2,t3),X3=Fp.sub(X3,t0),Z3=Fp.mul(t2,t1),Z3=Fp.add(Z3,Z3),Z3=Fp.add(Z3,Z3),new Point4(X3,Y3,Z3)}add(other){aprjpoint(other);let{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=other,X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO,t0=Fp.mul(X1,X2),t1=Fp.mul(Y1,Y2),t2=Fp.mul(Z1,Z2),t3=Fp.add(X1,Y1),t4=Fp.add(X2,Y2);t3=Fp.mul(t3,t4),t4=Fp.add(t0,t1),t3=Fp.sub(t3,t4),t4=Fp.add(X1,Z1);let t5=Fp.add(X2,Z2);return t4=Fp.mul(t4,t5),t5=Fp.add(t0,t2),t4=Fp.sub(t4,t5),t5=Fp.add(Y1,Z1),X3=Fp.add(Y2,Z2),t5=Fp.mul(t5,X3),X3=Fp.add(t1,t2),t5=Fp.sub(t5,X3),Z3=mulA(t4),X3=Fp.mul(b32,t2),Z3=Fp.add(X3,Z3),X3=Fp.sub(t1,Z3),Z3=Fp.add(t1,Z3),Y3=Fp.mul(X3,Z3),t1=Fp.add(t0,t0),t1=Fp.add(t1,t0),t2=mulA(t2),t4=Fp.mul(b32,t4),t1=Fp.add(t1,t2),t2=Fp.sub(t0,t2),t2=mulA(t2),t4=Fp.add(t4,t2),t0=Fp.mul(t1,t4),Y3=Fp.add(Y3,t0),t0=Fp.mul(t5,t4),X3=Fp.mul(t3,X3),X3=Fp.sub(X3,t0),t0=Fp.mul(t3,t1),Z3=Fp.mul(t5,Z3),Z3=Fp.add(Z3,t0),new Point4(X3,Y3,Z3)}subtract(other){return aprjpoint(other),this.add(other.negate())}is0(){return this.equals(Point4.ZERO)}multiply(scalar){if(!Fn2.isValidNot0(scalar))throw new RangeError("invalid scalar: out of range");let{p,f}=wnaf.mulSecret(this,scalar,cofactor,normalize4);return normalize4([p,f])[0]}multiplyUnsafe(scalar){let p=this,sc=scalar;if(!Fn2.isValid(sc))throw new RangeError("invalid scalar: out of range");if(sc===_0n17||p.is0())return Point4.ZERO;if(sc===_1n16)return p;if(wnaf.hasWindowSize(this))return wnaf.mulUnsafe(p,sc,normalize4);let points=[],scalars=[];return pushWnafPair(points,scalars,p,sc),mulAddUnsafe(Point4,points,scalars)}mulAddUnsafe(a,other,b){aprjpoint(other);let points=[],scalars=[];return pushWnafPair(points,scalars,this,a),pushWnafPair(points,scalars,other,b),mulAddUnsafe(Point4,points,scalars)}toAffine(invertedZ){let p=this,iz=invertedZ;if(iz!=null&&!Fp.isValid(iz))throw new RangeError('"invertedZ" expected valid field element');let{X,Y,Z}=p;if(Fp.eql(Z,Fp.ONE))return{x:X,y:Y};let is0=p.is0();iz==null&&(iz=is0?Fp.ONE:Fp.inv(Z));let x=Fp.mul(X,iz),y=Fp.mul(Y,iz),zz=Fp.mul(Z,iz);if(is0)return{x:Fp.ZERO,y:Fp.ZERO};if(!Fp.eql(zz,Fp.ONE))throw new Error("invZ was invalid");return{x,y}}isTorsionFree(){return cofactor===_1n16?!0:isTorsionFree?isTorsionFree(Point4,this):wnaf.mulUnsafe(this,CURVE_ORDER).is0()}clearCofactor(){return cofactor===_1n16?this:clearCofactor?clearCofactor(Point4,this):this.multiplyUnsafe(cofactor)}isSmallOrder(){return cofactor===_1n16?this.is0():this.clearCofactor().is0()}toBytes(isCompressed=!0){return abool3(isCompressed,"isCompressed"),this.assertValidity(),encodePoint(Point4,this,isCompressed)}toHex(isCompressed=!0){return bytesToHex5(this.toBytes(isCompressed))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let normalize4=points=>normalizeZ(Point4,points),wnaf=new ScalarMultiplier(Point4,randomBytes9);return wnaf.bits>=6&&Point4.BASE.precompute(6),Object.freeze(Point4.prototype),Object.freeze(Point4),Point4}function pprefix(hasEvenY){return Uint8Array.of(hasEvenY?2:3)}function getWLengths(Fp,Fn2){return{secretKey:Fn2.BYTES,publicKey:1+Fp.BYTES,publicKeyUncompressed:1+2*Fp.BYTES,publicKeyHasPrefix:!0,signature:2*Fn2.BYTES}}function ecdh(Point4,ecdhOpts={}){validatePointCons(Point4);let{Fn:Fn2}=Point4,randomBytes_=ecdhOpts.randomBytes===void 0?randomBytes5:ecdhOpts.randomBytes,lengths=Object.assign(getWLengths(Point4.Fp,Fn2),{seed:Math.max(getMinHashLength3(Fn2.ORDER),16)});function isValidSecretKey(secretKey){try{let num2=Fn2.fromBytes(secretKey);return Fn2.isValidNot0(num2)}catch{return!1}}function isValidPublicKey(publicKey,isCompressed){let{publicKey:comp,publicKeyUncompressed}=lengths;try{let l2=publicKey.length;return isCompressed===!0&&l2!==comp||isCompressed===!1&&l2!==publicKeyUncompressed?!1:!Point4.fromBytes(publicKey).is0()}catch{return!1}}function randomSecretKey(seed){return seed=seed===void 0?randomBytes_(lengths.seed):seed,mapHashToField3(abytes7(seed,lengths.seed,"seed"),Fn2.ORDER)}function getPublicKey(secretKey,isCompressed=!0){return Point4.BASE.multiply(Fn2.fromBytes(secretKey)).toBytes(isCompressed)}function isProbPub(item){let{secretKey,publicKey,publicKeyUncompressed}=lengths,allowedLengths=Fn2._lengths;if(!isBytes9(item))return;let l2=abytes7(item,void 0,"key").length,isPub=l2===publicKey||l2===publicKeyUncompressed,isSec=l2===secretKey||!!allowedLengths?.includes(l2);if(!(isPub&&isSec))return isPub}function getSharedSecret(secretKeyA,publicKeyB,isCompressed=!0){if(isProbPub(secretKeyA)===!0)throw new Error("first arg must be private key");if(isProbPub(publicKeyB)===!1)throw new Error("second arg must be public key");let s3=Fn2.fromBytes(secretKeyA),b=Point4.fromBytes(publicKeyB);if(b.is0())throw new Error("invalid public key: point at infinity");return b.multiply(s3).toBytes(isCompressed)}let utils2={isValidSecretKey,isValidPublicKey,randomSecretKey},keygen=createKeygen(randomSecretKey,getPublicKey);return Object.freeze(utils2),Object.freeze(lengths),Object.freeze({getPublicKey,getSharedSecret,keygen,Point:Point4,utils:utils2,lengths})}function ecdsa(Point4,hash8,ecdsaOpts={}){validatePointCons(Point4);let hash_=hash8;ahash4(hash_),validateObject3(ecdsaOpts,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let opts=Object.assign({},ecdsaOpts),randomBytes9=opts.randomBytes===void 0?randomBytes5:opts.randomBytes,hmac6=opts.hmac===void 0?(key3,msg)=>hmac4(hash_,key3,msg):opts.hmac,{Fp,Fn:Fn2}=Point4,{ORDER:CURVE_ORDER,BITS:fnBits}=Fn2,blindLength=getMinHashLength3(CURVE_ORDER),csprng=probeRandomBytes(randomBytes9,blindLength),{keygen,getPublicKey,getSharedSecret,utils:utils2,lengths}=ecdh(Point4,opts),defaultSigOpts={prehash:!0,lowS:typeof opts.lowS=="boolean"?opts.lowS:!0,format:"compact",extraEntropy:!1},hasLargeRecoveryLifts=CURVE_ORDER*_2n10+_1n16<Fp.ORDER;function isBiggerThanHalfOrder(number4){let HALF=CURVE_ORDER>>_1n16;return number4>HALF}function validateRS(title,num2){if(!Fn2.isValidNot0(num2))throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);return num2}function assertFieldSignIsSupported(){if(!Fp.isOdd)throw new Error("Field doesn't support isOdd")}function getRecoveryBit(x,y,r2){return assertFieldSignIsSupported(),(x===r2?0:2)|Number(Fp.isOdd(y))}function assertRecoverableCurve(){if(hasLargeRecoveryLifts)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function validateSigLength(bytes,format3){validateSigFormat(format3);let size4=lengths.signature,sizer=format3==="compact"?size4:format3==="recovered"?size4+1:void 0;return abytes7(bytes,sizer)}class Signature2{r;s;recovery;constructor(r2,s3,recovery){if(this.r=validateRS("r",r2),this.s=validateRS("s",s3),recovery!=null){if(assertRecoverableCurve(),![0,1,2,3].includes(recovery))throw new Error("invalid recovery id");this.recovery=recovery}Object.freeze(this)}static fromBytes(bytes,format3=defaultSigOpts.format){validateSigLength(bytes,format3);let recid;if(format3==="der"){if(bytes.length>2*Fn2.BYTES+16)throw new DER3.Err("invalid signature: DER signature too long");let{r:r3,s:s4}=DER3.toSig(abytes7(bytes),Fn2.BYTES+1);return new Signature2(r3,s4)}format3==="recovered"&&(recid=bytes[0],format3="compact",bytes=bytes.subarray(1));let L=lengths.signature/2,r2=bytes.subarray(0,L),s3=bytes.subarray(L,L*2);return new Signature2(Fn2.fromBytes(r2),Fn2.fromBytes(s3),recid)}static fromHex(hex3,format3){return this.fromBytes(hexToBytes5(hex3),format3)}assertRecovery(){let{recovery}=this;if(recovery==null)throw new Error("invalid recovery id: must be present");return recovery}addRecoveryBit(recovery){return new Signature2(this.r,this.s,recovery)}recoverPublicKey(messageHash){let{r:r2,s:s3}=this,recovery=this.assertRecovery(),radj=recovery===2||recovery===3?r2+CURVE_ORDER:r2;if(!Fp.isValid(radj))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let x=Fp.toBytes(radj),R=Point4.fromBytes(concatBytes7(pprefix((recovery&1)===0),x)),ir=Fn2.inv(radj),h=bits2int_modN(abytes7(messageHash,void 0,"msgHash")),u1=Fn2.create(-h*ir),u2=Fn2.create(s3*ir),Q=Point4.BASE.mulAddUnsafe(u1,R,u2);if(Q.is0())throw new Error("invalid recovery: point at infinify");return Q.assertValidity(),Q}hasHighS(){return isBiggerThanHalfOrder(this.s)}toBytes(format3=defaultSigOpts.format){if(validateSigFormat(format3),format3==="der")return hexToBytes5(DER3.hexFromSig(this));let{r:r2,s:s3}=this,rb=Fn2.toBytes(r2),sb=Fn2.toBytes(s3);return format3==="recovered"?(assertRecoverableCurve(),concatBytes7(Uint8Array.of(this.assertRecovery()),rb,sb)):concatBytes7(rb,sb)}toHex(format3){return bytesToHex5(this.toBytes(format3))}}Object.freeze(Signature2.prototype),Object.freeze(Signature2);let bits2int=opts.bits2int===void 0?function(bytes){if(bytes.length>8192)throw new Error("input is too large");let num2=bytesToNumberBE3(bytes),delta=bytes.length*8-fnBits;return delta>0?num2>>BigInt(delta):num2}:opts.bits2int,bits2int_modN=opts.bits2int_modN===void 0?function(bytes){return Fn2.create(bits2int(bytes))}:opts.bits2int_modN,ORDER_MASK=bitMask3(fnBits);function int2octets(num2){return aInRange3("num < 2^"+fnBits,num2,_0n17,ORDER_MASK),Fn2.toBytes(num2)}function validateMsgAndHash(message,prehash){return abytes7(message,void 0,"message"),prehash?abytes7(hash_(message),void 0,"prehashed message"):message}function prepSig(message,secretKey,opts2){let{lowS,prehash,extraEntropy:extraEntropy2}=validateSigOpts(opts2,defaultSigOpts);message=validateMsgAndHash(message,prehash);let h1int=bits2int_modN(message),d=Fn2.fromBytes(secretKey);if(!Fn2.isValidNot0(d))throw new Error("invalid private key");let seedArgs=[int2octets(d),int2octets(h1int)];if(extraEntropy2!=null&&extraEntropy2!==!1){let e7=extraEntropy2===!0?randomBytes9(lengths.secretKey):extraEntropy2;seedArgs.push(abytes7(e7,void 0,"extraEntropy"))}let seed=concatBytes7(...seedArgs),m=h1int;function k2sig(kBytes){let k=bits2int(kBytes);if(!Fn2.isValidNot0(k))return;let q=Point4.BASE.multiply(k).toAffine(),r2=Fn2.create(q.x);if(r2===_0n17)return;let s3;if(csprng!==void 0){let b=bytesToNumberBE3(mapHashToField3(csprng(blindLength),CURVE_ORDER)),ibk=Fn2.inv(Fn2.mul(b,k)),bm=Fn2.mul(b,m),bd=Fn2.mul(b,d);s3=Fn2.create(ibk*Fn2.create(bm+bd*r2))}else{let ik=invertCt(k,CURVE_ORDER);s3=Fn2.create(ik*Fn2.create(m+r2*d))}if(s3===_0n17)return;let recovery=getRecoveryBit(q.x,q.y,r2),normS=s3;return lowS&&isBiggerThanHalfOrder(s3)&&(normS=Fn2.neg(s3),recovery^=1),new Signature2(r2,normS,hasLargeRecoveryLifts?void 0:recovery)}return{seed,k2sig}}function sign5(message,secretKey,opts2={}){let{seed,k2sig}=prepSig(message,secretKey,opts2);return createHmacDrbg3(hash_.outputLen,Fn2.BYTES,hmac6)(seed,k2sig).toBytes(opts2.format)}function verify8(signature3,message,publicKey,opts2={}){let{lowS,prehash,format:format3}=validateSigOpts(opts2,defaultSigOpts);if(publicKey=abytes7(publicKey,void 0,"publicKey"),message=validateMsgAndHash(message,prehash),!isBytes9(signature3)){let end=signature3 instanceof Signature2?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+end)}validateSigLength(signature3,format3);try{let sig=Signature2.fromBytes(signature3,format3),P3=Point4.fromBytes(publicKey);if(P3.is0()||lowS&&sig.hasHighS())return!1;let{r:r2,s:s3}=sig,h=bits2int_modN(message),is=Fn2.inv(s3),u1=Fn2.create(h*is),u2=Fn2.create(r2*is),R=Point4.BASE.mulAddUnsafe(u1,P3,u2);if(R.is0())return!1;let q=R.toAffine();return!(Fn2.create(q.x)!==r2||format3==="recovered"&&sig.recovery!==getRecoveryBit(q.x,q.y,r2))}catch{return!1}}function recoverPublicKey4(signature3,message,opts2={}){let{prehash}=validateSigOpts(opts2,defaultSigOpts);return message=validateMsgAndHash(message,prehash),Signature2.fromBytes(signature3,"recovered").recoverPublicKey(message).toBytes()}return Object.freeze({keygen,getPublicKey,getSharedSecret,utils:utils2,lengths,Point:Point4,sign:sign5,verify:verify8,recoverPublicKey:recoverPublicKey4,Signature:Signature2,hash:hash_})}var divNearest3,_0n17,_1n16,_2n10,_3n6,_4n7,init_weierstrass3=__esm({"node_modules/@noble/curves/abstract/weierstrass.js"(){"use strict";init_hmac4();init_utils15();init_utils16();init_curve3();init_der();init_modular3();divNearest3=(num2,den)=>(num2+(num2>=0?den:-den)/_2n10)/den;_0n17=BigInt(0),_1n16=BigInt(1),_2n10=BigInt(2),_3n6=BigInt(3),_4n7=BigInt(4)}});function sqrtMod3(y){let P3=secp256k1_CURVE.p,_3n7=BigInt(3),_6n=BigInt(6),_11n=BigInt(11),_22n=BigInt(22),_23n=BigInt(23),_44n=BigInt(44),_88n=BigInt(88),b2=y*y*y%P3,b32=b2*b2*y%P3,b6=pow23(b32,_3n7,P3)*b32%P3,b9=pow23(b6,_3n7,P3)*b32%P3,b11=pow23(b9,_2n11,P3)*b2%P3,b22=pow23(b11,_11n,P3)*b11%P3,b44=pow23(b22,_22n,P3)*b22%P3,b88=pow23(b44,_44n,P3)*b44%P3,b176=pow23(b88,_88n,P3)*b88%P3,b220=pow23(b176,_44n,P3)*b44%P3,b223=pow23(b220,_3n7,P3)*b32%P3,t1=pow23(b223,_23n,P3)*b22%P3,t2=pow23(t1,_6n,P3)*b2%P3,root2=pow23(t2,_2n11,P3);if(!Fpk13.eql(Fpk13.sqr(root2),y))throw new Error("Cannot find square root");return root2}var secp256k1_CURVE,secp256k1_ENDO,_2n11,Fpk13,Pointk1,secp256k13,init_secp256k13=__esm({"node_modules/@noble/curves/secp256k1.js"(){"use strict";init_sha24();init_modular3();init_weierstrass3();secp256k1_CURVE={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},secp256k1_ENDO={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},_2n11=BigInt(2);Fpk13=Field3(secp256k1_CURVE.p,{sqrt:sqrtMod3}),Pointk1=weierstrass3(secp256k1_CURVE,{Fp:Fpk13,endo:secp256k1_ENDO}),secp256k13=ecdsa(Pointk1,sha2568)}});function ripemd_f2(group,x,y,z2){return group===0?x^y^z2:group===1?x&y|~x&z2:group===2?(x|~y)^z2:group===3?x&z2|y&~z2:x^(y|~z2)}var Rho1602,Id1602,Pi1602,idxLR2,idxL2,idxR2,shifts1602,shiftsL1602,shiftsR1602,Kl1602,Kr1602,BUF_1602,_RIPEMD160,ripemd1604,init_legacy2=__esm({"node_modules/@noble/hashes/legacy.js"(){"use strict";init_md4();init_utils15();Rho1602=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Id1602=Uint8Array.from(new Array(16).fill(0).map((_,i)=>i)),Pi1602=Id1602.map(i=>(9*i+5)%16),idxLR2=(()=>{let res=[[Id1602],[Pi1602]];for(let i=0;i<4;i++)for(let j of res)j.push(j[i].map(k=>Rho1602[k]));return res})(),idxL2=idxLR2[0],idxR2=idxLR2[1],shifts1602=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(i=>Uint8Array.from(i)),shiftsL1602=idxL2.map((idx,i)=>idx.map(j=>shifts1602[i][j])),shiftsR1602=idxR2.map((idx,i)=>idx.map(j=>shifts1602[i][j])),Kl1602=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Kr1602=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);BUF_1602=new Uint32Array(16),_RIPEMD160=class extends HashMD4{h0=1732584193;h1=-271733879;h2=-1732584194;h3=271733878;h4=-1009589776;constructor(){super(64,20,8,!0)}get(){let{h0,h1,h2,h3,h4}=this;return[h0,h1,h2,h3,h4]}set(h0,h1,h2,h3,h4){this.h0=h0|0,this.h1=h1|0,this.h2=h2|0,this.h3=h3|0,this.h4=h4|0}_cloneInto(to2){return(to2||=new this.constructor).set(...this.get()),this._cloneIntoMeta(to2)}process(view,offset){for(let i=0;i<16;i++,offset+=4)BUF_1602[i]=view.getUint32(offset,!0);let al=this.h0|0,ar=al,bl=this.h1|0,br=bl,cl=this.h2|0,cr=cl,dl=this.h3|0,dr=dl,el=this.h4|0,er=el;for(let group=0;group<5;group++){let rGroup=4-group,hbl=Kl1602[group],hbr=Kr1602[group],rl=idxL2[group],rr=idxR2[group],sl=shiftsL1602[group],sr=shiftsR1602[group];for(let i=0;i<16;i++){let tl=rotl2(al+ripemd_f2(group,bl,cl,dl)+BUF_1602[rl[i]]+hbl,sl[i])+el|0;al=el,el=dl,dl=rotl2(cl,10)|0,cl=bl,bl=tl}for(let i=0;i<16;i++){let tr=rotl2(ar+ripemd_f2(rGroup,br,cr,dr)+BUF_1602[rr[i]]+hbr,sr[i])+er|0;ar=er,er=dr,dr=rotl2(cr,10)|0,cr=br,br=tr}}this.set(this.h1+cl+dr|0,this.h2+dl+er|0,this.h3+el+ar|0,this.h4+al+br|0,this.h0+bl+cr|0)}roundClean(){clean4(BUF_1602)}destroy(){this.destroyed=!0,clean4(this.buffer),this.set(0,0,0,0,0)}},ripemd1604=createHasher5(()=>new _RIPEMD160)}});function isBytes10(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in a&&a.BYTES_PER_ELEMENT===1}function abytes8(b){if(!isBytes10(b))throw new TypeError("Uint8Array expected")}function afn2(input2){if(typeof input2!="function")throw new TypeError("function expected");return!0}function astr2(label,input2){if(typeof input2!="string")throw new TypeError(`${label}: string expected`);return!0}function anumber7(n,title="number"){if(typeof n!="number")throw new TypeError(`${title}: expected number, got ${typeof n}`);if(!Number.isSafeInteger(n))throw new RangeError(`${title}: expected safe integer, got ${n}`)}function chain2(...args){let id2=a=>a,wrap3=(a,b)=>c=>a(b(c)),encode12=args.map(x=>x.encode).reduceRight(wrap3,id2),decode8=args.map(x=>x.decode).reduce(wrap3,id2);return{encode:encode12,decode:decode8}}function charcodesToString(codes){let len=codes.length;if(asciiDecoder!==void 0&&len>=12)return asciiDecoder.decode(codes);if(len<=B2S_CHUNK)return String.fromCharCode.apply(null,codes);let res="";for(let i=0;i<len;i+=B2S_CHUNK)res+=String.fromCharCode.apply(null,codes.subarray(i,i+B2S_CHUNK));return res}function alphabet2(letters,aliases){let len=letters.length;if(len>128)throw new Error("alphabet: max 128 letters");let encTable=new Uint8Array(len),decTable=new Int8Array(128).fill(-1);for(let i=0;i<len;i++){let code=letters.charCodeAt(i);if(letters.codePointAt(i)!==code||code>127)throw new Error("alphabet: single-char ASCII letters only");encTable[i]=code,decTable[code]=i}if(aliases!==void 0)for(let alias of Object.keys(aliases)){let code=alias.charCodeAt(0),target=decTable[aliases[alias].charCodeAt(0)];if(alias.length!==1||code>127||target===void 0||target===-1)throw new Error(`alphabet: invalid alias ${alias}`);decTable[code]=target}return{encode:digits=>{let codes=new Uint8Array(digits.length);for(let i=0;i<digits.length;i++){let d=digits[i],code=encTable[d];if(code===void 0)throw new Error(`alphabet.encode: invalid digit ${d}`);codes[i]=code}return charcodesToString(codes)},decode:input2=>{astr2("decode",input2);let slen=input2.length,digits=new Uint8Array(slen);for(let i=0;i<slen;i++){let code=input2.charCodeAt(i),digit=code<128?decTable[code]:-1;if(digit===-1)throw new Error(`Unknown letter "${input2[i]}". Allowed: ${letters}`);digits[i]=digit}return digits}}}function checksum4(len,fn){if(anumber7(len),len<=0)throw new RangeError(`checksum length must be positive: ${len}`);afn2(fn);let _fn=fn;return{encode(data){abytes8(data);let sum=_fn(data).slice(0,len),res=new Uint8Array(data.length+len);return res.set(data),res.set(sum,data.length),res},decode(data){abytes8(data);let payload=data.slice(0,-len),oldChecksum=data.slice(-len),newChecksum=_fn(payload).slice(0,len);for(let i=0;i<len;i++)if(newChecksum[i]!==oldChecksum[i])throw new Error("Invalid checksum");return payload}}}var freeze,asciiDecoder,B2S_CHUNK,B58_GROUP,RADIX_BASE_N_MAX_LENGTH,BASE_N_MAX_BYTES,BASE_N_MAX_CHARS,radixBaseN,genBaseN,radix58,genBase58,base58,createBase58check,init_base3=__esm({"node_modules/@scure/base/index.js"(){"use strict";freeze=fn=>Object.freeze(fn());asciiDecoder=(()=>{try{let decoder3=new TextDecoder;return decoder3.decode(Uint8Array.of(65,48,43,127))==="A0+\x7F"?decoder3:void 0}catch{return}})(),B2S_CHUNK=8192;B58_GROUP=656356768,RADIX_BASE_N_MAX_LENGTH=65536,BASE_N_MAX_BYTES=2048,BASE_N_MAX_CHARS=4096,radixBaseN=(BASE,GROUP)=>({encode:bytes=>{abytes8(bytes);let blen=bytes.length;if(blen===0)return new Uint8Array(0);if(blen>=RADIX_BASE_N_MAX_LENGTH)throw new Error("invalid length");let zeros2=0;for(;zeros2<blen-1&&bytes[zeros2]===0;)zeros2++;let nlimbs=Math.ceil(blen/2),limbs=new Uint16Array(nlimbs),odd=blen&1;odd&&(limbs[0]=bytes[0]);for(let i=odd,j2=odd;i<blen;i+=2,j2++)limbs[j2]=bytes[i]<<8|bytes[i+1];let groups=[],pos=0;for(;pos<nlimbs;){let carry2=0;for(let i=pos;i<nlimbs;i++){let cur=carry2*65536+limbs[i],q=Math.floor(cur/GROUP);carry2=cur-q*GROUP,limbs[i]=q,q===0&&i===pos&&pos++}groups.push(carry2)}let top=groups.length-1,sig=top*5;for(let v=groups[top];sig++,!(v<BASE);v=Math.floor(v/BASE));let res=new Uint8Array(zeros2+sig),j=res.length-1;for(let g=0;g<top;g++){let v=groups[g];for(let k=0;k<5;k++)res[j--]=v%BASE,v=Math.floor(v/BASE)}for(let v=groups[top];j>=zeros2;v=Math.floor(v/BASE))res[j--]=v%BASE;return res},decode:digits=>{abytes8(digits);let dlen=digits.length;if(dlen===0)return new Uint8Array(0);if(dlen>=RADIX_BASE_N_MAX_LENGTH)throw new Error("invalid length");let zeros2=0;for(;zeros2<dlen-1&&digits[zeros2]===0;)zeros2++;let limbs=new Uint16Array(Math.ceil(dlen*6/16)+1),used=0,i=0,group=dlen%5||5;for(;i<dlen;){let gval=0,factor=1;for(let end=i+group;i<end;i++){let d=digits[i];if(d>=BASE)throw new Error(`invalid integer: ${d}`);gval=gval*BASE+d,factor*=BASE}group=5;let carry2=gval;for(let k=0;k<used;k++){let cur=limbs[k]*factor+carry2;carry2=Math.floor(cur/65536),limbs[k]=cur-carry2*65536}for(;carry2>0;carry2=Math.floor(carry2/65536))limbs[used++]=carry2%65536}let valueBytes=used===0?1:used*2-(limbs[used-1]<256?1:0),res=new Uint8Array(zeros2+valueBytes),j=res.length-1;for(let k=0;k<used;k++){let limb=limbs[k];res[j--]=limb&255,j>=zeros2&&(res[j--]=limb>>8)}return res}}),genBaseN=(radix3,abc)=>{let letters=alphabet2(abc);return{encode(bytes){if(abytes8(bytes),bytes.length>BASE_N_MAX_BYTES)throw new Error("invalid length");return letters.encode(radix3.encode(bytes))},decode(str){if(astr2("baseN.decode",str),str.length>BASE_N_MAX_CHARS)throw new Error("invalid length");return radix3.decode(letters.decode(str))}}},radix58=radixBaseN(58,B58_GROUP),genBase58=abc=>genBaseN(radix58,abc),base58=freeze(()=>genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),createBase58check=sha25613=>{afn2(sha25613);let _sha256=sha25613;return chain2(checksum4(4,data=>_sha256(_sha256(data))),base58)}}});var Point2,Fn,base58check,MASTER_SECRET,BITCOIN_VERSIONS,HARDENED_OFFSET,MAX_DEPTH,hash160,fromU32,toU32,validateVersions,HDKey,init_bip32=__esm({"node_modules/@scure/bip32/index.js"(){"use strict";init_secp256k13();init_hmac4();init_legacy2();init_sha24();init_utils15();init_base3();Point2=secp256k13.Point,Fn=Point2.Fn,base58check=createBase58check(sha2568),MASTER_SECRET=Uint8Array.from("Bitcoin seed".split(""),char=>char.charCodeAt(0)),BITCOIN_VERSIONS={private:76066276,public:76067358},HARDENED_OFFSET=2147483648,MAX_DEPTH=255,hash160=data=>ripemd1604(sha2568(data)),fromU32=data=>createView4(data).getUint32(0,!1),toU32=(n,title="number")=>{if(typeof n!="number")throw new TypeError(`"${title}" expected number, got type=${typeof n}`);if(!Number.isSafeInteger(n)||n<0||n>2**32-1)throw new RangeError(`"${title}" expected integer in range 0..2**32-1, got ${n}`);let buf=new Uint8Array(4);return createView4(buf).setUint32(0,n,!1),buf},validateVersions=(versions,title="versions")=>{if(!(typeof versions=="object"&&versions!==null))throw new Error("versions must be an object");return toU32(versions.private,`${title}.private`),toU32(versions.public,`${title}.public`),versions},HDKey=class _HDKey{get fingerprint(){if(!this._pubHash)throw new Error("No publicKey set!");return fromU32(this._pubHash)}get identifier(){return this._pubHash?Uint8Array.from(this._pubHash):void 0}get pubKeyHash(){return this._pubHash?Uint8Array.from(this._pubHash):void 0}get privateKey(){return this._privateKey?Uint8Array.from(this._privateKey):null}get publicKey(){return this._publicKey?Uint8Array.from(this._publicKey):null}get chainCode(){return this._chainCode?Uint8Array.from(this._chainCode):null}get privateExtendedKey(){let priv=this._privateKey;if(!priv)throw new Error("No private key");return base58check.encode(this.serialize(this.versions.private,concatBytes6(Uint8Array.of(0),priv)))}get publicExtendedKey(){if(!this._publicKey)throw new Error("No public key");return base58check.encode(this.serialize(this.versions.public,this._publicKey))}static fromMasterSeed(seed,versions=BITCOIN_VERSIONS){if(abytes6(seed),versions=validateVersions(versions),8*seed.length<128||8*seed.length>512)throw new RangeError("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got "+seed.length);let I=hmac4(sha5123,MASTER_SECRET,seed),privateKey=I.slice(0,32),chainCode=I.slice(32);return new _HDKey({versions,chainCode,privateKey})}static fromExtendedKey(base58key,versions=BITCOIN_VERSIONS){versions=validateVersions(versions);let keyBuffer=base58check.decode(base58key);if(keyBuffer.length!==78)throw new Error(`HDKey: invalid extended key length: expected 78 bytes, got ${keyBuffer.length}`);let keyView=createView4(keyBuffer),version31=keyView.getUint32(0,!1),opt={versions,depth:keyBuffer[4],parentFingerprint:keyView.getUint32(5,!1),index:keyView.getUint32(9,!1),chainCode:keyBuffer.slice(13,45)},key3=keyBuffer.slice(45),isPriv=key3[0]===0;if(version31!==versions[isPriv?"private":"public"])throw new Error("Version mismatch");return isPriv?new _HDKey({...opt,privateKey:key3.slice(1)}):new _HDKey({...opt,publicKey:key3})}static fromJSON(json2){return _HDKey.fromExtendedKey("xpriv"in json2?json2.xpriv:json2.xpub)}versions;depth=0;index=0;parentFingerprint=0;_chainCode=null;_privateKey;_publicKey;_pubHash;constructor(opt){if(!opt||typeof opt!="object")throw new Error("HDKey.constructor must not be called directly");let depth=opt.depth??0,index2=opt.index??0,parentFingerprint=opt.parentFingerprint??0;if(!Number.isSafeInteger(depth)||depth<0||depth>MAX_DEPTH)throw new RangeError("HDKey: depth must be an integer in range 0..255");if(toU32(index2,"index"),toU32(parentFingerprint,"parentFingerprint"),depth===0&&(index2!==0||parentFingerprint!==0))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");if(this.versions=opt.versions?validateVersions(opt.versions):BITCOIN_VERSIONS,this.depth=depth,opt.chainCode&&abytes6(opt.chainCode,32),this._chainCode=opt.chainCode?Uint8Array.from(opt.chainCode):null,this.index=index2,this.parentFingerprint=parentFingerprint,opt.publicKey&&opt.privateKey)throw new Error("HDKey: publicKey and privateKey at same time.");if(opt.privateKey){if(!secp256k13.utils.isValidSecretKey(opt.privateKey))throw new Error("Invalid private key");this._privateKey=Uint8Array.from(opt.privateKey),this._publicKey=secp256k13.getPublicKey(this._privateKey,!0)}else if(opt.publicKey)this._publicKey=Point2.fromBytes(opt.publicKey).toBytes(!0);else throw new Error("HDKey: no public or private key provided");this._pubHash=hash160(this._publicKey)}derive(path8){if(!/^[mM]'?/.test(path8))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(path8))return this;let parts=path8.replace(/^[mM]'?\//,"").split("/");if(parts.length>MAX_DEPTH-this.depth)throw new Error("HDKey: path exceeds the serializable depth 255");let child=this;for(let c of parts){let m=/^(\d+)('?)$/.exec(c),m1=m&&m[1];if(!m||m.length!==3||typeof m1!="string")throw new Error("invalid child index: "+c);let idx=+m1;if(!Number.isSafeInteger(idx)||idx>=HARDENED_OFFSET)throw new Error("Invalid index");m[2]==="'"&&(idx+=HARDENED_OFFSET),child=child.deriveChild(idx)}return child}deriveChild(index2){return this._deriveChild(index2)}_deriveChild(index2,_I){if(!this._publicKey||!this._chainCode)throw new Error("No publicKey or chainCode set");let data=toU32(index2,"index");if(index2>=HARDENED_OFFSET){let priv=this._privateKey;if(!priv)throw new Error("Could not derive hardened child key");data=concatBytes6(Uint8Array.of(0),priv,data)}else data=concatBytes6(this._publicKey,data);let out=_I||hmac4(sha5123,this._chainCode,data);abytes6(out,64);let childTweak=out.slice(0,32),chainCode=out.slice(32),opt={versions:this.versions,chainCode,depth:this.depth+1,parentFingerprint:this.fingerprint,index:index2};if(opt.depth>MAX_DEPTH)throw new Error("HDKey: depth exceeds the serializable value 255");let retry=()=>{let maxIndex=this._privateKey?4294967295:HARDENED_OFFSET-1;if(index2>=maxIndex)throw new Error(`HDKey: cannot retry child derivation at index ${index2}`);return this.deriveChild(index2+1)},ctweak=Fn.fromBytes(childTweak,!0);if(!Fn.isValid(ctweak))return retry();if(this._privateKey){let added=Fn.create(Fn.fromBytes(this._privateKey)+ctweak);if(!Fn.isValidNot0(added))return retry();opt.privateKey=Fn.toBytes(added)}else{let point3=Point2.fromBytes(this._publicKey),added=ctweak===0n?point3:point3.add(Point2.BASE.multiply(ctweak));if(added.equals(Point2.ZERO))return retry();opt.publicKey=added.toBytes(!0)}return new _HDKey(opt)}sign(hash8){if(!this._privateKey)throw new Error("No privateKey set!");return abytes6(hash8,32),secp256k13.sign(hash8,this._privateKey,{prehash:!1})}verify(hash8,signature3){if(abytes6(hash8,32),abytes6(signature3,64),!this._publicKey)throw new Error("No publicKey set!");return secp256k13.verify(signature3,hash8,this._publicKey,{prehash:!1})}wipePrivateData(){return this._privateKey&&(this._privateKey.fill(0),this._privateKey=void 0),this}toJSON(){return this.toPrivateJSON()}toPrivateJSON(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}}serialize(version31,key3){if(!this._chainCode)throw new Error("No chainCode set");return abytes6(key3,33),concatBytes6(toU32(version31,"version"),new Uint8Array([this.depth]),toU32(this.parentFingerprint,"parentFingerprint"),toU32(this.index,"index"),this._chainCode,key3)}}}});function deriveSolanaKeyBytes(mnemonic){let seed=mnemonicToSeedSync(mnemonic),digest=hmac4(sha5123,new TextEncoder().encode("ed25519 seed"),seed),key3=digest.slice(0,32),chainCode=digest.slice(32);for(let index2 of SOLANA_HARDENED_INDICES){let data=new Uint8Array(37);data[0]=0,data.set(key3,1),data[33]=index2>>>24&255,data[34]=index2>>>16&255,data[35]=index2>>>8&255,data[36]=index2&255,digest=hmac4(sha5123,chainCode,data),key3=digest.slice(0,32),chainCode=digest.slice(32)}return new Uint8Array(key3)}var SOLANA_HARDENED_INDICES,init_solana_key=__esm({"src/solana-key.ts"(){"use strict";init_hmac4();init_sha24();init_esm3();SOLANA_HARDENED_INDICES=[2147483692,2147484149,2147483648,2147483648]}});function encodeValue(value){return Array.isArray(value)?"%5B"+value.map(encodeValue).join("%2C%20")+"%5D":typeof value=="bigint"?`${value}n`:encodeURIComponent(String(value!=null&&Object.getPrototypeOf(value)===null?{...value}:value))}function encodeObjectContextEntry([key3,value]){return`${key3}=${encodeValue(value)}`}function encodeContextObject(context){let searchParamsString=Object.entries(context).map(encodeObjectContextEntry).join("&");return Buffer.from(searchParamsString,"utf8").toString("base64")}function getHumanReadableErrorMessage(code,context={}){let messageFormatString=SolanaErrorMessages[code];if(messageFormatString.length===0)return"";let state;function commitStateUpTo(endIndex){if(state[TYPE]===2){let variableName=messageFormatString.slice(state[START_INDEX]+1,endIndex);fragments.push(variableName in context?`${context[variableName]}`:`$${variableName}`)}else state[TYPE]===1&&fragments.push(messageFormatString.slice(state[START_INDEX],endIndex))}let fragments=[];messageFormatString.split("").forEach((char,ii)=>{if(ii===0){state={[START_INDEX]:0,[TYPE]:messageFormatString[0]==="\\"?0:messageFormatString[0]==="$"?2:1};return}let nextState;switch(state[TYPE]){case 0:nextState={[START_INDEX]:ii,[TYPE]:1};break;case 1:char==="\\"?nextState={[START_INDEX]:ii,[TYPE]:0}:char==="$"&&(nextState={[START_INDEX]:ii,[TYPE]:2});break;case 2:char==="\\"?nextState={[START_INDEX]:ii,[TYPE]:0}:char==="$"?nextState={[START_INDEX]:ii,[TYPE]:2}:char.match(/\w/)||(nextState={[START_INDEX]:ii,[TYPE]:1});break}nextState&&(state!==nextState&&commitStateUpTo(ii),state=nextState)}),commitStateUpTo();let message=fragments.join("");return code>=SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN&&code<SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN+INSTRUCTION_ERROR_RANGE_SIZE&&"index"in context&&(message+=` (instruction #${context.index+1})`),message}function getErrorMessage(code,context={}){if(process.env.NODE_ENV!=="production")return getHumanReadableErrorMessage(code,context);{let decodingAdviceMessage=`Solana error #${code}; Decode this error by running \`npx @solana/errors decode -- ${code}`;return Object.keys(context).length&&(decodingAdviceMessage+=` '${encodeContextObject(context)}'`),`${decodingAdviceMessage}\``}}function isSolanaError(e7,code){return e7 instanceof Error&&e7.name==="SolanaError"?code!==void 0?e7.context.__code===code:!0:!1}function safeCaptureStackTrace(...args){"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...args)}function getSolanaErrorFromRpcError({errorCodeBaseOffset,getErrorContext,orderedErrorNames,rpcEnumError},constructorOpt){let rpcErrorName,rpcErrorContext;typeof rpcEnumError=="string"?rpcErrorName=rpcEnumError:(rpcErrorName=Object.keys(rpcEnumError)[0],rpcErrorContext=rpcEnumError[rpcErrorName]);let codeOffset=orderedErrorNames.indexOf(rpcErrorName),errorCode=errorCodeBaseOffset+codeOffset,errorContext=getErrorContext(errorCode,rpcErrorName,rpcErrorContext),err=new SolanaError(errorCode,errorContext);return safeCaptureStackTrace(err,constructorOpt),err}function getSolanaErrorFromInstructionError(index2,instructionError){let numberIndex=Number(index2);return getSolanaErrorFromRpcError({errorCodeBaseOffset:4615001,getErrorContext(errorCode,rpcErrorName,rpcErrorContext){return errorCode===SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN?{errorName:rpcErrorName,index:numberIndex,...rpcErrorContext!==void 0?{instructionErrorContext:rpcErrorContext}:null}:errorCode===SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM?{code:Number(rpcErrorContext),index:numberIndex}:{index:numberIndex}},orderedErrorNames:ORDERED_ERROR_NAMES,rpcEnumError:instructionError},getSolanaErrorFromInstructionError)}function getSolanaErrorFromTransactionError(transactionError){return typeof transactionError=="object"&&"InstructionError"in transactionError?getSolanaErrorFromInstructionError(...transactionError.InstructionError):getSolanaErrorFromRpcError({errorCodeBaseOffset:7050001,getErrorContext(errorCode,rpcErrorName,rpcErrorContext){if(errorCode===SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN)return{errorName:rpcErrorName,...rpcErrorContext!==void 0?{transactionErrorContext:rpcErrorContext}:null};if(errorCode===SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION)return{index:Number(rpcErrorContext)};if(errorCode===SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT||errorCode===SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED)return{accountIndex:Number(rpcErrorContext.account_index)}},orderedErrorNames:ORDERED_ERROR_NAMES2,rpcEnumError:transactionError},getSolanaErrorFromTransactionError)}function getSolanaErrorFromJsonRpcError(putativeErrorResponse){let out;if(isRpcErrorResponse(putativeErrorResponse)){let{code:rawCode,data,message}=putativeErrorResponse,code=Number(rawCode);if(code===SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE){let{err,...preflightErrorContext}=data,causeObject=err?{cause:getSolanaErrorFromTransactionError(err)}:null;out=new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,{...preflightErrorContext,...causeObject})}else{let errorContext;switch(code){case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR:case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS:case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST:case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND:case SOLANA_ERROR__JSON_RPC__PARSE_ERROR:case SOLANA_ERROR__JSON_RPC__SCAN_ERROR:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:errorContext={__serverMessage:message};break;default:typeof data=="object"&&!Array.isArray(data)&&(errorContext=data)}out=new SolanaError(code,errorContext)}}else{let message=typeof putativeErrorResponse=="object"&&putativeErrorResponse!==null&&"message"in putativeErrorResponse&&typeof putativeErrorResponse.message=="string"?putativeErrorResponse.message:"Malformed JSON-RPC error with no message attribute";out=new SolanaError(SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,{error:putativeErrorResponse,message})}return safeCaptureStackTrace(out,getSolanaErrorFromJsonRpcError),out}function isRpcErrorResponse(value){return typeof value=="object"&&value!==null&&"code"in value&&"message"in value&&(typeof value.code=="number"||typeof value.code=="bigint")&&typeof value.message=="string"}function unwrapSimulationError(error62){let simulationCodes=[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS];return isSolanaError(error62)&&error62.cause&&simulationCodes.includes(error62.context.__code)?error62.cause:error62}var SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,SOLANA_ERROR__INVALID_NONCE,SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE,SOLANA_ERROR__MALFORMED_BIGINT_STRING,SOLANA_ERROR__MALFORMED_NUMBER_STRING,SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION,SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS,SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION,SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS,SOLANA_ERROR__JSON_RPC__PARSE_ERROR,SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SLOT_HISTORY,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH,SOLANA_ERROR__JSON_RPC__SCAN_ERROR,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY,SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS,SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED,SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX,SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT,SOLANA_ERROR__KEYS__VERIFICATION_REQUIRES_EXTRACTABLE_PUBLIC_KEY,SOLANA_ERROR__FS__UNSUPPORTED_ENVIRONMENT,SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED,SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION,SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE,SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,SOLANA_ERROR__OFFCHAIN_MESSAGE__CONTENT_DOES_NOT_MATCH_EXPECTED,SOLANA_ERROR__OFFCHAIN_MESSAGE__REQUIRED_SIGNATORIES_DO_NOT_MATCH_EXPECTED,SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING,SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE,SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES,SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,SOLANA_ERROR__TRANSACTION__MALFORMED_MESSAGE_BYTES,SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_MESSAGE_BYTES,SOLANA_ERROR__TRANSACTION__CANNOT_DECODE_EMPTY_TRANSACTION_BYTES,SOLANA_ERROR__TRANSACTION__VERSION_ZERO_MUST_BE_ENCODED_WITH_SIGNATURES_FIRST,SOLANA_ERROR__TRANSACTION__SIGNATURE_COUNT_TOO_HIGH_FOR_TRANSACTION_BYTES,SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_ACCOUNT_INDEX,SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_VALUE_KIND,SOLANA_ERROR__TRANSACTION__INSTRUCTION_HEADERS_PAYLOADS_MISMATCH,SOLANA_ERROR__TRANSACTION__TOO_MANY_SIGNER_ADDRESSES,SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNT_ADDRESSES,SOLANA_ERROR__TRANSACTION__TOO_MANY_INSTRUCTIONS,SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNTS_IN_INSTRUCTION,SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_LOADED_ACCOUNTS_DATA_SIZE_LIMIT,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_ACCOUNT_INDEX_OUT_OF_RANGE,SOLANA_ERROR__TRANSACTION__COMPUTE_UNIT_LIMIT_OUT_OF_RANGE,SOLANA_ERROR__TRANSACTION__INVALID_HEAP_SIZE,SOLANA_ERROR__TRANSACTION_INTROSPECTION__CANNOT_DECODE_JSON_PARSED_TRANSACTION,SOLANA_ERROR__TRANSACTION_INTROSPECTION__UNRECOGNIZED_GET_TRANSACTION_RESPONSE,SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND,SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND,SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE,SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED,SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND,SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP,SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX,SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION,SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE,SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS,SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED,SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED,SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,SOLANA_ERROR__INSTRUCTION_PLANS__MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED,SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_REJECTED_BY_PACKER,SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,SOLANA_ERROR__CODECS__INVALID_CONSTANT,SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE,SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES,SOLANA_ERROR__CODECS__INVALID_UTF8_BYTES,SOLANA_ERROR__CODECS__INVALID_UTF8_STRING,SOLANA_ERROR__CODECS__SENTINEL_MISSING_AT_END_OF_BYTES,SOLANA_ERROR__CODECS__SENTINEL_MUST_NOT_BE_EMPTY,SOLANA_ERROR__CODECS__UNEXPECTED_ZERO_FIXED_SIZE_ITEM_FOR_ARRAY_LIKE_SIZE_STRATEGY,SOLANA_ERROR__FIXED_POINTS__INVALID_TOTAL_BITS,SOLANA_ERROR__FIXED_POINTS__INVALID_FRACTIONAL_BITS,SOLANA_ERROR__FIXED_POINTS__INVALID_DECIMALS,SOLANA_ERROR__FIXED_POINTS__FRACTIONAL_BITS_EXCEED_TOTAL_BITS,SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE,SOLANA_ERROR__FIXED_POINTS__INVALID_STRING,SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO,SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW,SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH,SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO,SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS,SOLANA_ERROR__FIXED_POINTS__MALFORMED_RAW_VALUE,SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED,SOLANA_ERROR__RPC__INTEGER_OVERFLOW,SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED,SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR,SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE,SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION,SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE,SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL,SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_ACCOUNT_TYPE,SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_SIGNER,SOLANA_ERROR__WALLET__NOT_CONNECTED,SOLANA_ERROR__WALLET__NO_SIGNER_CONNECTED,SOLANA_ERROR__WALLET__SIGNER_NOT_AVAILABLE,SOLANA_ERROR__WALLET__ACCOUNT_NOT_AVAILABLE,SOLANA_ERROR__WALLET__INVALID_MESSAGE_SIGNATURE,SOLANA_ERROR__WALLET__INVALID_SIGN_IN_OUTPUT,SOLANA_ERROR__WALLET__INVALID_NUMBER_OF_OUTPUTS,SOLANA_ERROR__WALLET__FEATURE_VERSION_UNSUPPORTED,SOLANA_ERROR__REACT__MISSING_PROVIDER,SOLANA_ERROR__REACT__MISSING_CAPABILITY,SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR,SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,SolanaErrorMessages,INSTRUCTION_ERROR_RANGE_SIZE,START_INDEX,TYPE,SolanaError,ORDERED_ERROR_NAMES,ORDERED_ERROR_NAMES2,init_index_node=__esm({"node_modules/@solana/errors/dist/index.node.mjs"(){"use strict";SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED=1,SOLANA_ERROR__INVALID_NONCE=2,SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND=3,SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE=4,SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH=5,SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE=6,SOLANA_ERROR__MALFORMED_BIGINT_STRING=7,SOLANA_ERROR__MALFORMED_NUMBER_STRING=8,SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE=9,SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR=10,SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION=11,SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS=12,SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION=13,SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS=14,SOLANA_ERROR__JSON_RPC__PARSE_ERROR=-32700,SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR=-32603,SOLANA_ERROR__JSON_RPC__INVALID_PARAMS=-32602,SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND=-32601,SOLANA_ERROR__JSON_RPC__INVALID_REQUEST=-32600,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SLOT_HISTORY=-32021,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND=-32020,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE=-32019,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY=-32018,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE=-32017,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED=-32016,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION=-32015,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET=-32014,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH=-32013,SOLANA_ERROR__JSON_RPC__SCAN_ERROR=-32012,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE=-32011,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX=-32010,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED=-32009,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT=-32008,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED=-32007,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE=-32006,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY=-32005,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE=-32004,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE=-32003,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE=-32002,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP=-32001,SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH=28e5,SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE=2800001,SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS=2800002,SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY=2800003,SOLANA_ERROR__ADDRESSES__MALFORMED_PDA=2800004,SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE=2800005,SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED=2800006,SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED=2800007,SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE=2800008,SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED=2800009,SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER=2800010,SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS=2800011,SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND=323e4,SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND=32300001,SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT=3230002,SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT=3230003,SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED=3230004,SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT=361e4,SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED=3610001,SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED=3610002,SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED=3610003,SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED=3610004,SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED=3610005,SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED=3610006,SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY=3610007,SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED=3611e3,SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH=3704e3,SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH=3704001,SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH=3704002,SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE=3704003,SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY=3704004,SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX=3704005,SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT=3704006,SOLANA_ERROR__KEYS__VERIFICATION_REQUIRES_EXTRACTABLE_PUBLIC_KEY=3704007,SOLANA_ERROR__FS__UNSUPPORTED_ENVIRONMENT=3712e3,SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS=4128e3,SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA=4128001,SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH=4128002,SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN=4615e3,SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR=4615001,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT=4615002,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA=4615003,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA=4615004,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL=4615005,SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS=4615006,SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID=4615007,SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE=4615008,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED=4615009,SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT=4615010,SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION=4615011,SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID=4615012,SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND=4615013,SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED=4615014,SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE=4615015,SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED=4615016,SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX=4615017,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED=4615018,SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED=4615019,SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS=4615020,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED=4615021,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE=4615022,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED=4615023,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING=4615024,SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC=4615025,SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM=4615026,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR=4615027,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED=4615028,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE=4615029,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT=4615030,SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID=4615031,SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH=4615032,SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT=4615033,SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED=4615034,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED=4615035,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS=4615036,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC=4615037,SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED=4615038,SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION=4615039,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE=4615040,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE=4615041,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE=4615042,SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE=4615043,SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY=4615044,SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR=4615045,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT=4615046,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER=4615047,SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW=4615048,SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR=4615049,SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER=4615050,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED=4615051,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED=4615052,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED=4615053,SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS=4615054,SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS=5508e3,SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER=5508001,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER=5508002,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER=5508003,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER=5508004,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER=5508005,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER=5508006,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER=5508007,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER=5508008,SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS=5508009,SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING=5508010,SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED=5508011,SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION=5508012,SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED=5607e3,SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE=5607001,SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE=5607002,SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH=5607003,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH=5607004,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO=5607005,SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED=5607006,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH=5607007,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH=5607008,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY=5607009,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO=5607010,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING=5607011,SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH=5607012,SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE=5607013,SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION=5607014,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED=5607015,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE=5607016,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE=5607017,SOLANA_ERROR__OFFCHAIN_MESSAGE__CONTENT_DOES_NOT_MATCH_EXPECTED=5607018,SOLANA_ERROR__OFFCHAIN_MESSAGE__REQUIRED_SIGNATORIES_DO_NOT_MATCH_EXPECTED=5607019,SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES=5663e3,SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE=5663001,SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME=5663002,SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME=5663003,SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE=5663004,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING=5663005,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE=5663006,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND=5663007,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING=5663008,SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING=5663009,SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING=5663010,SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING=5663011,SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING=5663012,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING=5663013,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE=5663014,SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION=5663015,SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES=5663016,SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH=5663017,SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT=5663018,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT=5663019,SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT=5663020,SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED=5663021,SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE=5663022,SOLANA_ERROR__TRANSACTION__MALFORMED_MESSAGE_BYTES=5663023,SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_MESSAGE_BYTES=5663024,SOLANA_ERROR__TRANSACTION__CANNOT_DECODE_EMPTY_TRANSACTION_BYTES=5663025,SOLANA_ERROR__TRANSACTION__VERSION_ZERO_MUST_BE_ENCODED_WITH_SIGNATURES_FIRST=5663026,SOLANA_ERROR__TRANSACTION__SIGNATURE_COUNT_TOO_HIGH_FOR_TRANSACTION_BYTES=5663027,SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS=5663028,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_ACCOUNT_INDEX=5663029,SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_VALUE_KIND=5663030,SOLANA_ERROR__TRANSACTION__INSTRUCTION_HEADERS_PAYLOADS_MISMATCH=5663031,SOLANA_ERROR__TRANSACTION__TOO_MANY_SIGNER_ADDRESSES=5663032,SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNT_ADDRESSES=5663033,SOLANA_ERROR__TRANSACTION__TOO_MANY_INSTRUCTIONS=5663034,SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNTS_IN_INSTRUCTION=5663035,SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_LOADED_ACCOUNTS_DATA_SIZE_LIMIT=5663036,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS=5663037,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_ACCOUNT_INDEX_OUT_OF_RANGE=5663038,SOLANA_ERROR__TRANSACTION__COMPUTE_UNIT_LIMIT_OUT_OF_RANGE=5663039,SOLANA_ERROR__TRANSACTION__INVALID_HEAP_SIZE=5663040,SOLANA_ERROR__TRANSACTION_INTROSPECTION__CANNOT_DECODE_JSON_PARSED_TRANSACTION=5664e3,SOLANA_ERROR__TRANSACTION_INTROSPECTION__UNRECOGNIZED_GET_TRANSACTION_RESPONSE=5664001,SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN=705e4,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE=7050001,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE=7050002,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND=7050003,SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND=7050004,SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE=7050005,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE=7050006,SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED=7050007,SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND=7050008,SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP=7050009,SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE=7050010,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX=7050011,SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE=7050012,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION=7050013,SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE=7050014,SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE=7050015,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING=7050016,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT=7050017,SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION=7050018,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT=7050019,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT=7050020,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT=7050021,SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS=7050022,SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND=7050023,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER=7050024,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA=7050025,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX=7050026,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT=7050027,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT=7050028,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT=7050029,SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION=7050030,SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT=7050031,SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED=7050032,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT=7050033,SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED=7050034,SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED=7050035,SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION=7050036,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN=7618e3,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE=7618001,SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN=7618002,SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN=7618003,SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED=7618004,SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND=7618005,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN=7618006,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN=7618007,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT=7618008,SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT=7618009,SOLANA_ERROR__INSTRUCTION_PLANS__MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED=7618010,SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION=7618011,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_REJECTED_BY_PACKER=7618012,SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY=8078e3,SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH=8078001,SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH=8078002,SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH=8078003,SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH=8078004,SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH=8078005,SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH=8078006,SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS=8078007,SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE=8078008,SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT=8078009,SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT=8078010,SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE=8078011,SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE=8078012,SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH=8078013,SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE=8078014,SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT=8078015,SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE=8078016,SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE=8078017,SOLANA_ERROR__CODECS__INVALID_CONSTANT=8078018,SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE=8078019,SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL=8078020,SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES=8078021,SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS=8078022,SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY=8078023,SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE=8078024,SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES=8078025,SOLANA_ERROR__CODECS__INVALID_UTF8_BYTES=8078026,SOLANA_ERROR__CODECS__INVALID_UTF8_STRING=8078027,SOLANA_ERROR__CODECS__SENTINEL_MISSING_AT_END_OF_BYTES=8078028,SOLANA_ERROR__CODECS__SENTINEL_MUST_NOT_BE_EMPTY=8078029,SOLANA_ERROR__CODECS__UNEXPECTED_ZERO_FIXED_SIZE_ITEM_FOR_ARRAY_LIKE_SIZE_STRATEGY=8078030,SOLANA_ERROR__FIXED_POINTS__INVALID_TOTAL_BITS=809e4,SOLANA_ERROR__FIXED_POINTS__INVALID_FRACTIONAL_BITS=8090001,SOLANA_ERROR__FIXED_POINTS__INVALID_DECIMALS=8090002,SOLANA_ERROR__FIXED_POINTS__FRACTIONAL_BITS_EXCEED_TOTAL_BITS=8090003,SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE=8090004,SOLANA_ERROR__FIXED_POINTS__INVALID_STRING=8090005,SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO=8090006,SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW=8090007,SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH=8090008,SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO=8090009,SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS=8090010,SOLANA_ERROR__FIXED_POINTS__MALFORMED_RAW_VALUE=8090011,SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED=8090012,SOLANA_ERROR__RPC__INTEGER_OVERFLOW=81e5,SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN=8100001,SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR=8100002,SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD=8100003,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN=819e4,SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID=8190001,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED=8190002,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED=8190003,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT=8190004,SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED=8195e3,SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR=8195001,SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS=85e5,SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE=8500001,SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION=8500002,SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE=8500003,SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL=8500004,SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_ACCOUNT_TYPE=8500005,SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT=8500006,SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_SIGNER=8500007,SOLANA_ERROR__WALLET__NOT_CONNECTED=89e5,SOLANA_ERROR__WALLET__NO_SIGNER_CONNECTED=8900001,SOLANA_ERROR__WALLET__SIGNER_NOT_AVAILABLE=8900002,SOLANA_ERROR__WALLET__ACCOUNT_NOT_AVAILABLE=8900003,SOLANA_ERROR__WALLET__INVALID_MESSAGE_SIGNATURE=8900004,SOLANA_ERROR__WALLET__INVALID_SIGN_IN_OUTPUT=8900005,SOLANA_ERROR__WALLET__INVALID_NUMBER_OF_OUTPUTS=8900006,SOLANA_ERROR__WALLET__FEATURE_VERSION_UNSUPPORTED=8900007,SOLANA_ERROR__REACT__MISSING_PROVIDER=9e6,SOLANA_ERROR__REACT__MISSING_CAPABILITY=9000001,SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR=9000002,SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING=99e5,SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE=9900001,SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING=9900002,SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE=9900003,SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED=9900004,SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND=9900005,SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND=9900006;SolanaErrorMessages={[SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]:"Account not found at address: $address",[SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]:"Expected decoded account at address: $address",[SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]:"Failed to decode account data at address: $address",[SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]:"Accounts not found at addresses: $addresses",[SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]:"Unable to find a viable program address bump seed.",[SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]:"$putativeAddress is not a base58-encoded address.",[SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]:"The `CryptoKey` must be an `Ed25519` public key.",[SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]:"Invalid seeds; point must fall off the Ed25519 curve.",[SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]:"Program address cannot end with PDA marker.",[SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]:"Expected base58-encoded blockhash string of length in the range [32, 44]. Actual length: $actualLength.",[SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]:"The network has progressed past the last block for which this transaction could have been committed.",[SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]:"Codec [$codecDescription] cannot decode empty byte arrays.",[SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]:"Encoder and decoder must either both be fixed-size or variable-size.",[SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]:"Expected a fixed-size codec, got a variable-size one.",[SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]:"Expected a variable-size codec, got a fixed-size one.",[SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[SOLANA_ERROR__CODECS__INVALID_CONSTANT]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]:"Invalid literal union variant. Expected one of [$variants], got $value.",[SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]:"Expected [$codecDescription] to have $expected items, got $actual.",[SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]:"Invalid value $value for base $base with alphabet $alphabet.",[SOLANA_ERROR__CODECS__INVALID_UTF8_BYTES]:"Invalid UTF-8 byte sequence at offset $offset.",[SOLANA_ERROR__CODECS__INVALID_UTF8_STRING]:"Invalid UTF-8 string. Found a lone surrogate at index $index.",[SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[SOLANA_ERROR__CODECS__SENTINEL_MISSING_AT_END_OF_BYTES]:"Codec [$codecDescription] expected sentinel [$hexSentinel] to terminate the collection, but reached the end of the byte array without it.",[SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[SOLANA_ERROR__CODECS__SENTINEL_MUST_NOT_BE_EMPTY]:"The sentinel must not be empty.",[SOLANA_ERROR__CODECS__UNEXPECTED_ZERO_FIXED_SIZE_ITEM_FOR_ARRAY_LIKE_SIZE_STRATEGY]:"Codec [$codecDescription] cannot use the [$sizeStrategy] size strategy: the item codec has a fixed size of zero and consumes no bytes.",[SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]:"This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?",[SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE]:"Invalid pattern match value. The provided value does not match any of the specified patterns.",[SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES]:"Invalid pattern match bytes. The provided byte array does not match any of the specified patterns.",[SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]:"No random values implementation could be found.",[SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION]:"Failed to send transaction$causeMessage",[SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS]:"Failed to send transactions$causeMessages",[SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION]:"Failed to sign transaction$causeMessage",[SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS]:"Failed to sign transactions$causeMessages",[SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW]:"Fixed-point operation `$operation` of kind `$kind` overflowed. Expected a raw bigint in [$min, $max], got $result.",[SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO]:"Fixed-point division by zero for value of kind `$kind` ($signedness, $totalBits bits).",[SOLANA_ERROR__FIXED_POINTS__FRACTIONAL_BITS_EXCEED_TOTAL_BITS]:"`fractionalBits` ($fractionalBits) must not exceed `totalBits` ($totalBits).",[SOLANA_ERROR__FIXED_POINTS__INVALID_DECIMALS]:"Invalid `decimals`. Expected a non-negative integer, got $decimals.",[SOLANA_ERROR__FIXED_POINTS__INVALID_FRACTIONAL_BITS]:"Invalid `fractionalBits`. Expected a non-negative integer, got $fractionalBits.",[SOLANA_ERROR__FIXED_POINTS__INVALID_STRING]:"Invalid string `$input` for fixed-point value of kind `$kind`.",[SOLANA_ERROR__FIXED_POINTS__INVALID_TOTAL_BITS]:"Invalid `totalBits`. Expected a positive integer, got $totalBits.",[SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO]:"Invalid ratio $numerator/$denominator for fixed-point value of kind `$kind`. Denominator must be non-zero.",[SOLANA_ERROR__FIXED_POINTS__MALFORMED_RAW_VALUE]:"Fixed-point value of kind `$kind` has a malformed `raw` field. Expected a bigint, got `$raw`.",[SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH]:"Fixed-point `$operation` operation expected $expectedKind ($expectedSignedness, $expectedTotalBits bits, $expectedScale $expectedScaleLabel); got $actualKind ($actualSignedness, $actualTotalBits bits, $actualScale $actualScaleLabel).",[SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS]:"Fixed-point operation `$operation` of kind `$kind` cannot be performed exactly; pass a rounding mode other than `strict` to allow a rounded result.",[SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED]:"Fixed-point codec of kind `$kind` requires `totalBits` to be a multiple of 8; got $totalBits.",[SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE]:"Fixed-point value of kind `$kind` is out of range for $signedness $totalBits-bit storage. Expected a raw bigint in [$min, $max], got $raw.",[SOLANA_ERROR__FS__UNSUPPORTED_ENVIRONMENT]:"Filesystem operation `$operation` is not supported in this environment.",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]:"Instruction requires an uninitialized account",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]:"Instruction tries to borrow reference for an account which is already borrowed",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:"Instruction left account with an outstanding borrowed reference",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]:"Program other than the account's owner changed the size of the account data",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]:"Account data too small for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]:"Instruction expected an executable account",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]:"An account does not have enough lamports to be rent-exempt",[SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]:"Program arithmetic overflowed",[SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]:"Failed to serialize or deserialize account data",[SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]:"Builtin programs must consume compute units",[SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]:"Cross-program invocation call depth too deep",[SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]:"Computational budget exceeded",[SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]:"Custom program error: #$code",[SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]:"Instruction contains duplicate accounts",[SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]:"Instruction modifications of multiply-passed account differ",[SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]:"Executable accounts must be rent exempt",[SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]:"Instruction changed executable accounts data",[SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]:"Instruction changed the balance of an executable account",[SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]:"Instruction changed executable bit of an account",[SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]:"Instruction modified data of an account it does not own",[SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]:"Instruction spent from the balance of an account it does not own",[SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]:"Generic instruction error",[SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]:"Provided owner is not allowed",[SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]:"Account is immutable",[SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]:"Incorrect authority provided",[SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]:"Incorrect program id for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]:"Insufficient funds for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]:"Invalid account data for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]:"Invalid account owner",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]:"Invalid program argument",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]:"Program returned invalid error code",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]:"Invalid instruction data",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]:"Failed to reallocate account data",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]:"Provided seeds do not result in a valid address",[SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]:"Accounts data allocations exceeded the maximum allowed per transaction",[SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]:"Max accounts exceeded",[SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]:"Max instruction trace length exceeded",[SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]:"Length of the seed is too long for address generation",[SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]:"An account required by the instruction is missing",[SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]:"Missing required signature for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]:"Instruction illegally modified the program id of an account",[SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]:"Insufficient account keys for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]:"Cross-program invocation with unauthorized signer or writable account",[SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]:"Failed to create program execution environment",[SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]:"Program failed to compile",[SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]:"Program failed to complete",[SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]:"Instruction modified data of a read-only account",[SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]:"Instruction changed the balance of a read-only account",[SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]:"Cross-program invocation reentrancy not allowed for this instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]:"Instruction modified rent epoch of an account",[SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]:"Sum of account balances before and after instruction do not match",[SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]:"Instruction requires an initialized account",[SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]:"The instruction failed with the error: $errorName",[SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]:"Unsupported program id",[SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]:"Unsupported sysvar",[SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]:"Invalid instruction plan kind: $kind.",[SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN]:"The provided instruction plan is empty.",[SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]:"No failed transaction plan result was found in the provided transaction plan result.",[SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED]:"This transaction plan executor does not support non-divisible sequential plans. To support them, you may create your own executor such that multi-transaction atomicity is preserved \u2014 e.g. by targetting RPCs that support transaction bundles.",[SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]:"The provided transaction plan failed to execute. See the `transactionPlanResult` attribute for more details. Note that the `cause` property is deprecated, and a future version will not set it.",[SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION]:"The configured maximum of $maxInstructions instructions per transaction is invalid. It must be a positive integer no greater than the transaction format limit of $transactionInstructionLimit instructions per transaction. Provide a `maxInstructionsPerTransaction` (on the transaction planner) or `maxInstructions` (on the message packer) value between 1 and $transactionInstructionLimit.",[SOLANA_ERROR__INSTRUCTION_PLANS__MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED]:"Planning this transaction message would require $numInstructions instructions, which exceeds the configured maximum of $maxInstructions instructions per transaction. This limit is configurable, and intended to leave headroom for inner instructions which are included in the maximum instruction limit for transactions. Increase `maxInstructionsPerTransaction` on the transaction planner (or `maxInstructions` on the message packer) to allow more instructions per transaction.",[SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]:"The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).",[SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]:"Invalid transaction plan kind: $kind.",[SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE]:"No more instructions to pack; the message packer has completed the instruction plan.",[SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_REJECTED_BY_PACKER]:"The message packer rejected the provided transaction message: $reason.",[SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]:"Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.",[SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]:"Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.",[SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]:"Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.",[SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]:"Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.",[SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]:"The instruction does not have any accounts.",[SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]:"The instruction does not have any data.",[SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[SOLANA_ERROR__INVALID_NONCE]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]:"Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]:"Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]:"Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]:"Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[SOLANA_ERROR__JSON_RPC__PARSE_ERROR]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[SOLANA_ERROR__JSON_RPC__SCAN_ERROR]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]:"Epoch rewards period still active at slot $slot",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE]:"Failed to query long-term storage; please try again",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]:"Minimum context slot has not been reached",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]:"Node is unhealthy; behind by $numSlotsBehind slots",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SLOT_HISTORY]:"No slot history",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]:"No snapshot",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]:"Transaction simulation failed",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]:"Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]:"Transaction history is not available from this node",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]:"Transaction signature length mismatch",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]:"Transaction signature verification failure",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]:"$__serverMessage",[SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX]:"The grind regex `/$source/` contains the character `$character`, which is not in the base58 alphabet and can never match a Solana address.",[SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]:"Key pair bytes must be of length 64, got $byteLength.",[SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]:"Expected private key bytes with length 32. Actual length: $actualLength.",[SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]:"The provided private key does not match the provided public key.",[SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[SOLANA_ERROR__KEYS__VERIFICATION_REQUIRES_EXTRACTABLE_PUBLIC_KEY]:"Signatures can only be verified using an extractable public key. The bytes of the public key must be readable. If you imported the public key yourself, set `extractable` to `true`.",[SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT]:"Writing a key pair to disk is not supported in this environment.",[SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]:"Lamports value must be in the range [0, 2e64-1]",[SOLANA_ERROR__MALFORMED_BIGINT_STRING]:"`$value` cannot be parsed as a `BigInt`",[SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]:"$message",[SOLANA_ERROR__MALFORMED_NUMBER_STRING]:"`$value` cannot be parsed as a `Number`",[SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]:"No nonce account could be found at address `$nonceAccountAddress`",[SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]:"Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]:"Attempted to sign an offchain message with an address that is not a signer for it",[SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]:"Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__CONTENT_DOES_NOT_MATCH_EXPECTED]:"The content of the offchain message does not match the content that was expected. Expected content with a byte-length of $expectedBytes; got content with a byte-length of $actualBytes. The signer may have signed different data than was requested; do not trust its signature.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]:"The signer addresses in this offchain message envelope do not match the list of required signers in the message preamble. These unexpected signers were present in the envelope: `[$unexpectedSigners]`. These required signers were missing from the envelope `[$missingSigners]`.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]:"The message body provided has a byte-length of $actualBytes. The maximum allowable byte-length is $maxBytes",[SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]:"Expected message format $expectedMessageFormat, got $actualMessageFormat",[SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]:"The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY]:"Offchain message content must be non-empty",[SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO]:"Offchain message must specify the address of at least one required signer",[SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO]:"Offchain message envelope must reserve space for at least one signature",[SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]:"The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__REQUIRED_SIGNATORIES_DO_NOT_MATCH_EXPECTED]:"The offchain message lists different required signatories than was expected. Expected [$expectedAddresses]. Got [$actualAddresses]. The signer may have signed different data than was requested; do not trust its signature.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED]:"The signatories of this offchain message must be listed in lexicographical order",[SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE]:"An address must be listed no more than once among the signatories of an offchain message",[SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]:"Offchain message is missing signatures for addresses: $addresses.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]:"Offchain message signature verification failed. Signature mismatch for required signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories [$signatoriesWithMissingSignatures]",[SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE]:"The message body provided contains characters whose codes fall outside the allowed range. In order to ensure clear-signing compatiblity with hardware wallets, the message may only contain line feeds and characters in the range [\\x20-\\x7e].",[SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]:"Expected offchain message version $expectedVersion. Got $actualVersion.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]:"This version of Kit does not support decoding offchain messages with version $unsupportedVersion. The current max supported version is 0.",[SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT]:"The provided account could not be identified as an account from the $programName program.",[SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION]:"The provided instruction could not be identified as an instruction from the $programName program.",[SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS]:"The provided instruction is missing some accounts. Expected at least $expectedAccountMetas account(s), got $actualAccountMetas.",[SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL]:"Expected resolved instruction input '$inputName' to be non-null.",[SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_SIGNER]:"Expected resolved instruction input '$inputName' to be a `TransactionSigner` because the instruction requires this account to sign the transaction. If its signature is provided by other means, use `createNoopSigner()` from `@solana/signers` to satisfy this requirement.",[SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE]:"Expected resolved instruction input '$inputName' to be of type `$expectedType`.",[SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_ACCOUNT_TYPE]:"Unrecognized account type '$accountType' for the $programName program.",[SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE]:"Unrecognized instruction type '$instructionType' for the $programName program.",[SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]:"WebSocket was closed before payload could be added to the send buffer",[SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]:"WebSocket connection closed",[SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]:"WebSocket failed to connect",[SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]:"Failed to obtain a subscription id from the server",[SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]:"Could not find an API plan for RPC method: `$method`",[SOLANA_ERROR__RPC__INTEGER_OVERFLOW]:"The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",[SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]:"HTTP error ($statusCode): $message",[SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]:"The provided value does not implement the `KeyPairSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]:"The provided value does not implement the `MessageModifyingSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]:"The provided value does not implement the `MessagePartialSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]:"The provided value does not implement any of the `MessageSigner` interfaces",[SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]:"The provided value does not implement the `TransactionModifyingSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]:"The provided value does not implement the `TransactionPartialSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]:"The provided value does not implement the `TransactionSendingSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]:"The provided value does not implement any of the `TransactionSigner` interfaces",[SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]:"More than one `TransactionSendingSigner` was identified.",[SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION]:"The wallet account $address cannot be used to create a transaction signer because it does not implement either the `solana:signTransaction` or `solana:signAndSendTransaction` feature. At least one of these features is required. The account supports the following features: $supportedFeatures.",[SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED]:"This `ReactiveStreamStore` does not support retry. Use `createReactiveStoreFromDataPublisherFactory` to construct a retryable store.",[SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR]:"The stream store closed in an error state but did not report an error.",[SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]:"Cannot export a non-extractable key.",[SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]:"No digest implementation could be found.",[SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]:`This runtime does not support the generation of Ed25519 key pairs.
|
|
2175
|
+
`);super(msg),this.name="EmptyWalletError",this.walletAddress=walletAddress}};RpcError2=class extends Error{code="RPC_ERROR";originalError;constructor(message,originalError){super(`RPC error: ${message}. Check network connectivity.`),this.name="RpcError",this.originalError=originalError}}}});async function fetchArcUsdcBalance(address3,fetchImpl=fetch){let url3=`${PAYMENT_CHAIN_GATEWAYS.arc}/v1/balance?address=${encodeURIComponent(address3)}`,res=await fetchImpl(url3,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(READ_TIMEOUT_MS)});if(!res.ok)throw new Error(`Arc balance read failed (HTTP ${res.status})`);let body=await res.json();if(typeof body.balance!="string"||!/^\d+$/.test(body.balance))throw new Error("Arc balance read returned no balance");return BigInt(body.balance)}var USDC_BASE,READ_TIMEOUT_MS,CACHE_TTL_MS,BALANCE_THRESHOLDS,BalanceMonitor,ApiKeyBalanceMonitor,init_balance=__esm({"src/balance.ts"(){"use strict";init_esm4();init_chains();init_errors8();init_payment_chain();USDC_BASE="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",READ_TIMEOUT_MS=1e4;CACHE_TTL_MS=3e4,BALANCE_THRESHOLDS={LOW_BALANCE_MICROS:1000000n,ZERO_THRESHOLD:100n},BalanceMonitor=class{client;walletAddress;chain;fetchImpl;cachedBalance=null;cachedAt=0;inflightFetch=null;cacheEpoch=0;constructor(walletAddress,chain3="base",fetchImpl){this.walletAddress=walletAddress,this.chain=chain3,this.fetchImpl=fetchImpl??((...args)=>fetch(...args)),this.client=createPublicClient({chain:base,transport:http(void 0,{timeout:READ_TIMEOUT_MS})})}getChain(){return this.chain}async checkBalance(){let now2=Date.now();if(this.cachedBalance!==null&&this.cachedBalance>0n&&now2-this.cachedAt<CACHE_TTL_MS)return this.buildInfo(this.cachedBalance);let pending=this.inflightFetch;if(!pending){let epoch=this.cacheEpoch;pending=this.fetchBalance().then(balance2=>(this.cacheEpoch===epoch&&(balance2>0n?(this.cachedBalance=balance2,this.cachedAt=Date.now()):(this.cachedBalance=null,this.cachedAt=0)),balance2)).finally(()=>{this.inflightFetch===pending&&(this.inflightFetch=null)}),this.inflightFetch=pending}let balance=await pending;return this.buildInfo(balance)}async checkSufficient(estimatedCostMicros){let info=await this.checkBalance();if(info.balance>=estimatedCostMicros)return{sufficient:!0,info};let shortfall=estimatedCostMicros-info.balance;return{sufficient:!1,info,shortfall:this.formatUSDC(shortfall)}}deductEstimated(amountMicros){this.cachedBalance!==null&&this.cachedBalance>=amountMicros&&(this.cachedBalance-=amountMicros)}invalidate(){this.cacheEpoch++,this.cachedBalance=null,this.cachedAt=0,this.inflightFetch=null}async refresh(){return this.invalidate(),this.checkBalance()}formatUSDC(amountMicros){return`$${(Number(amountMicros)/1e6).toFixed(2)}`}getWalletAddress(){return this.walletAddress}async fetchBalance(){try{return this.chain==="arc"?await fetchArcUsdcBalance(this.walletAddress,this.fetchImpl):await this.client.readContract({address:USDC_BASE,abi:erc20Abi,functionName:"balanceOf",args:[this.walletAddress]})}catch(error62){throw new RpcError2(error62 instanceof Error?error62.message:"Unknown error",error62)}}buildInfo(balance){return{balance,balanceUSD:this.formatUSDC(balance),isLow:balance<BALANCE_THRESHOLDS.LOW_BALANCE_MICROS,isEmpty:balance<BALANCE_THRESHOLDS.ZERO_THRESHOLD,walletAddress:this.walletAddress}}},ApiKeyBalanceMonitor=class _ApiKeyBalanceMonitor{static UNMETERED=BigInt(Number.MAX_SAFE_INTEGER);async checkBalance(){return{balance:_ApiKeyBalanceMonitor.UNMETERED,balanceUSD:"account credit",isLow:!1,isEmpty:!1,walletAddress:""}}async checkSufficient(){return{sufficient:!0,info:await this.checkBalance()}}deductEstimated(){}invalidate(){}async refresh(){return this.checkBalance()}formatUSDC(amountMicros){return`$${(Number(amountMicros)/1e6).toFixed(2)}`}getWalletAddress(){return""}}}});function base2(ALPHABET3){if(ALPHABET3.length>=255)throw new TypeError("Alphabet too long");let BASE_MAP=new Uint8Array(256);for(let j=0;j<BASE_MAP.length;j++)BASE_MAP[j]=255;for(let i=0;i<ALPHABET3.length;i++){let x=ALPHABET3.charAt(i),xc=x.charCodeAt(0);if(BASE_MAP[xc]!==255)throw new TypeError(x+" is ambiguous");BASE_MAP[xc]=i}let BASE=ALPHABET3.length,LEADER=ALPHABET3.charAt(0),FACTOR=Math.log(BASE)/Math.log(256),iFACTOR=Math.log(256)/Math.log(BASE);function encode12(source){if(source instanceof Uint8Array||(ArrayBuffer.isView(source)?source=new Uint8Array(source.buffer,source.byteOffset,source.byteLength):Array.isArray(source)&&(source=Uint8Array.from(source))),!(source instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(source.length===0)return"";let zeroes=0,length=0,pbegin=0,pend=source.length;for(;pbegin!==pend&&source[pbegin]===0;)pbegin++,zeroes++;let size4=(pend-pbegin)*iFACTOR+1>>>0,b58=new Uint8Array(size4);for(;pbegin!==pend;){let carry2=source[pbegin],i=0;for(let it1=size4-1;(carry2!==0||i<length)&&it1!==-1;it1--,i++)carry2+=256*b58[it1]>>>0,b58[it1]=carry2%BASE>>>0,carry2=carry2/BASE>>>0;if(carry2!==0)throw new Error("Non-zero carry");length=i,pbegin++}let it2=size4-length;for(;it2!==size4&&b58[it2]===0;)it2++;let str=LEADER.repeat(zeroes);for(;it2<size4;++it2)str+=ALPHABET3.charAt(b58[it2]);return str}function decodeUnsafe(source){if(typeof source!="string")throw new TypeError("Expected String");if(source.length===0)return new Uint8Array;let psz=0,zeroes=0,length=0;for(;source[psz]===LEADER;)zeroes++,psz++;let size4=(source.length-psz)*FACTOR+1>>>0,b256=new Uint8Array(size4);for(;psz<source.length;){let charCode=source.charCodeAt(psz);if(charCode>255)return;let carry2=BASE_MAP[charCode];if(carry2===255)return;let i=0;for(let it3=size4-1;(carry2!==0||i<length)&&it3!==-1;it3--,i++)carry2+=BASE*b256[it3]>>>0,b256[it3]=carry2%256>>>0,carry2=carry2/256>>>0;if(carry2!==0)throw new Error("Non-zero carry");length=i,psz++}let it4=size4-length;for(;it4!==size4&&b256[it4]===0;)it4++;let vch=new Uint8Array(zeroes+(size4-it4)),j=zeroes;for(;it4!==size4;)vch[j++]=b256[it4++];return vch}function decode8(string4){let buffer2=decodeUnsafe(string4);if(buffer2)return buffer2;throw new Error("Non-base"+BASE+" character")}return{encode:encode12,decodeUnsafe,decode:decode8}}var esm_default,init_esm7=__esm({"node_modules/base-x/src/esm/index.js"(){"use strict";esm_default=base2}});var esm_exports3={};__export(esm_exports3,{default:()=>esm_default2});var ALPHABET,esm_default2,init_esm8=__esm({"node_modules/bs58/src/esm/index.js"(){"use strict";init_esm7();ALPHABET="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",esm_default2=esm_default(ALPHABET)}});function fromBig4(n,le=!1){return le?{h:Number(n&U32_MASK644),l:Number(n>>_32n4&U32_MASK644)}:{h:Number(n>>_32n4&U32_MASK644)|0,l:Number(n&U32_MASK644)|0}}function split4(lst,le=!1){let len=lst.length,Ah=new Uint32Array(len),Al=new Uint32Array(len);for(let i=0;i<len;i++){let{h,l:l2}=fromBig4(lst[i],le);[Ah[i],Al[i]]=[h,l2]}return[Ah,Al]}function setU64FromNum(view,byteOffset,n,isLE3){let h=fromNumH(n),l2=fromNumL(n);view.setUint32(byteOffset,isLE3?l2:h,isLE3),view.setUint32(byteOffset+4,isLE3?h:l2,isLE3)}function add3(Ah,Al,Bh,Bl){let l2=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l2/2**32|0)|0,l:l2|0}}var U32_MASK644,_32n4,fromNumH,fromNumL,shrSH3,shrSL3,rotrSH3,rotrSL3,rotrBH3,rotrBL3,add3L3,add3H3,add4L3,add4H3,add5L3,add5H3,init_u644=__esm({"node_modules/@noble/hashes/_u64.js"(){"use strict";U32_MASK644=BigInt(4294967295),_32n4=BigInt(32);fromNumH=n=>n/2**32|0,fromNumL=n=>n>>>0;shrSH3=(h,_l,s3)=>h>>>s3,shrSL3=(h,l2,s3)=>h<<32-s3|l2>>>s3,rotrSH3=(h,l2,s3)=>h>>>s3|l2<<32-s3,rotrSL3=(h,l2,s3)=>h<<32-s3|l2>>>s3,rotrBH3=(h,l2,s3)=>h<<64-s3|l2>>>s3-32,rotrBL3=(h,l2,s3)=>h>>>s3-32|l2<<64-s3;add3L3=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0),add3H3=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0,add4L3=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0),add4H3=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0,add5L3=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0),add5H3=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0}});function isBytes8(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in a&&a.BYTES_PER_ELEMENT===1}function anumber5(n,title=""){if(typeof n!="number")throw new TypeError(atitle(title)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(atitle(title)+"expected integer >= 0, got "+n);return n}function abytes6(value,length,title=""){if(isBytes8(value)&&(length===void 0||value.length===length))return value;length!==void 0&&anumber5(length,"length");let bytes=isBytes8(value),ofLen=length!==void 0?` of length ${length}`:"",got=bytes?`length=${value.length}`:`type=${typeof value}`,message=atitle(title)+"expected Uint8Array"+ofLen+", got "+got;throw bytes?new RangeError(message):new TypeError(message)}function ahash4(h){if(typeof h!="function"||typeof h.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(anumber5(h.outputLen),anumber5(h.blockLen),h.outputLen<1||h.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}function aexists4(instance,checkFinished=!0){if(instance.destroyed)throw new Error("hash was destroyed");if(checkFinished&&instance.finished)throw new Error("digest() was already called")}function aoutput4(out,instance){abytes6(out,void 0,"output");let min=instance.outputLen;if(!(out.length>=min))throw new RangeError('"output" expected length >= '+min)}function clean4(...arrays){for(let i=0;i<arrays.length;i++)arrays[i].fill(0)}function createView4(arr){return new DataView(arr.buffer,arr.byteOffset,arr.byteLength)}function rotr4(word,shift){return word<<32-shift|word>>>shift}function rotl2(word,shift){return word<<shift|word>>>32-shift>>>0}function bytesToHex4(bytes){if(abytes6(bytes),hasHexBuiltin3)return bytes.toHex();let hex3="";for(let i=0;i<bytes.length;i++)hex3+=hexes5[bytes[i]];return hex3}function asciiToBase163(ch){return ch>=48&&ch<=57?ch-48:ch>=65&&ch<=70?ch-55:ch>=97&&ch<=102?ch-87:void 0}function hexToBytes4(hex3){if(typeof hex3!="string")throw new TypeError("hex string expected, got "+typeof hex3);if(hasHexBuiltin3)try{return Uint8Array.fromHex(hex3)}catch(error62){throw error62 instanceof SyntaxError?new RangeError(error62.message):error62}let hl=hex3.length,al=hl/2;if(hl%2)throw new RangeError("hex string expected, got unpadded hex of length "+hl);let array2=new Uint8Array(al);for(let ai=0,hi=0;ai<al;ai++,hi+=2){let n1=asciiToBase163(hex3.charCodeAt(hi)),n2=asciiToBase163(hex3.charCodeAt(hi+1));if(n1===void 0||n2===void 0){let char=hex3[hi]+hex3[hi+1];throw new RangeError('hex string expected, got non-hex character "'+char+'" at index '+hi)}array2[ai]=n1*16+n2}return array2}function concatBytes6(...arrays){let sum=0;for(let i=0;i<arrays.length;i++){let a=arrays[i];abytes6(a),sum+=a.length}let res=new Uint8Array(sum);for(let i=0,pad4=0;i<arrays.length;i++){let a=arrays[i];res.set(a,pad4),pad4+=a.length}return res}function checkOpts2(defaults2,opts,title="opts"){return aopts(defaults2,"defaults"),opts!==void 0&&aopts(opts,title),Object.assign(Object.create(null),defaults2,opts)}function createHasher5(hashCons,info={}){if(typeof hashCons!="function")throw new TypeError('"hashCons" expected function, got type='+typeof hashCons);info=checkOpts2({},info,"info");let hashC=(msg,opts)=>hashCons(opts).update(msg).digest(),tmp=hashCons(void 0);return hashC.outputLen=tmp.outputLen,hashC.blockLen=tmp.blockLen,hashC.canXOF=tmp.canXOF,hashC.create=opts=>hashCons(opts),Object.assign(hashC,info),Object.freeze(hashC)}function randomBytes4(bytesLength=32){anumber5(bytesLength,"bytesLength");let cr=typeof globalThis=="object"?globalThis.crypto:null;if(typeof cr?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(bytesLength>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);return cr.getRandomValues(new Uint8Array(bytesLength))}var atitle,aobject,aopts,hasHexBuiltin3,hexes5,oidNist,init_utils15=__esm({"node_modules/@noble/hashes/utils.js"(){"use strict";atitle=title=>title?`"${title}" `:"";aobject=(value,label)=>{if(value===null||typeof value!="object"||Array.isArray(value))throw new TypeError((label==="object"?"":`"${label}" `)+"expected object, got type="+typeof value)},aopts=(value,label)=>{aobject(value,label);let proto=Object.getPrototypeOf(value);if(proto!==Object.prototype&&proto!==null)throw new TypeError(`"${label}" expected plain object`);if(Object.hasOwn(value,"__proto__"))throw new TypeError(`"${label}.__proto__" is not allowed`)};hasHexBuiltin3=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hexes5=Array.from({length:256},(_,i)=>i.toString(16).padStart(2,"0"));oidNist=suffix=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,suffix])})}});function Chi4(a,b,c){return a&b^~a&c}function Maj4(a,b,c){return a&b^a&c^b&c}var HashMD4,SHA256_IV4,SHA512_IV4,init_md4=__esm({"node_modules/@noble/hashes/_md.js"(){"use strict";init_u644();init_utils15();HashMD4=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(blockLen,outputLen,padOffset,isLE3){this.blockLen=blockLen,this.outputLen=outputLen,this.padOffset=padOffset,this.isLE=isLE3,this.buffer=new Uint8Array(blockLen),this.view=createView4(this.buffer)}update(data){aexists4(this),abytes6(data);let{view,buffer:buffer2,blockLen}=this,len=data.length,processed=!1;for(let pos=0;pos<len;){let take=Math.min(blockLen-this.pos,len-pos);if(take===blockLen){let dataView=createView4(data);for(;blockLen<=len-pos;pos+=blockLen)this.process(dataView,pos);processed=!0;continue}buffer2.set(pos===0&&take===len?data:data.subarray(pos,pos+take),this.pos),this.pos+=take,pos+=take,this.pos===blockLen&&(this.process(view,0),this.pos=0,processed=!0)}return this.length+=data.length,processed&&this.roundClean(),this}digestInto(out){aexists4(this),aoutput4(out,this),this.finished=!0;let{buffer:buffer2,view,blockLen,isLE:isLE3}=this,{pos}=this;buffer2[pos++]=128,buffer2.fill(0,pos),this.padOffset>blockLen-pos&&(this.process(view,0),buffer2.fill(0)),setU64FromNum(view,blockLen-8,this.length*8,isLE3),this.process(view,0),this.roundClean();let oview=out===buffer2?view:createView4(out),len=this.outputLen,outLen=len/4,state=this.get();if(len%4||outLen>state.length)throw new Error("invalid outputLen");for(let i=0;i<outLen;i++)oview.setUint32(4*i,state[i],isLE3)}digest(){let{buffer:buffer2,outputLen}=this;this.digestInto(buffer2);let res=buffer2.slice(0,outputLen);return this.destroy(),res}_cloneIntoMeta(to2){let{buffer:buffer2,length,finished:finished2,destroyed,pos}=this;return to2.destroyed=destroyed,to2.finished=finished2,to2.length=length,to2.pos=pos,pos&&to2.buffer.set(buffer2),to2}clone(){return this._cloneInto()}},SHA256_IV4=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA512_IV4=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])}});var SHA256_K4,SHA256_W4,SHA2_32B,_SHA256,K5123,SHA512_Kh3,SHA512_Kl3,SHA512_W_H3,SHA512_W_L3,SHA2_64B,_SHA512,sha2568,sha5123,init_sha24=__esm({"node_modules/@noble/hashes/sha2.js"(){"use strict";init_md4();init_u644();init_utils15();SHA256_K4=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),SHA256_W4=new Uint32Array(64),SHA2_32B=class extends HashMD4{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(outputLen,IV){super(64,outputLen,8,!1),this.A=IV[0]|0,this.B=IV[1]|0,this.C=IV[2]|0,this.D=IV[3]|0,this.E=IV[4]|0,this.F=IV[5]|0,this.G=IV[6]|0,this.H=IV[7]|0}get(){let{A,B,C,D:D2,E,F,G:G2,H}=this;return[A,B,C,D2,E,F,G2,H]}set(A,B,C,D2,E,F,G2,H){this.A=A|0,this.B=B|0,this.C=C|0,this.D=D2|0,this.E=E|0,this.F=F|0,this.G=G2|0,this.H=H|0}_cloneInto(to2){return(to2||=new this.constructor).set(...this.get()),this._cloneIntoMeta(to2)}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W4[i]=view.getUint32(offset,!1);for(let i=16;i<64;i++){let W15=SHA256_W4[i-15],W2=SHA256_W4[i-2],s0=rotr4(W15,7)^rotr4(W15,18)^W15>>>3,s1=rotr4(W2,17)^rotr4(W2,19)^W2>>>10;SHA256_W4[i]=s1+SHA256_W4[i-7]+s0+SHA256_W4[i-16]|0}let{A,B,C,D:D2,E,F,G:G2,H}=this;for(let i=0;i<64;i++){let sigma1=rotr4(E,6)^rotr4(E,11)^rotr4(E,25),T1=H+sigma1+Chi4(E,F,G2)+SHA256_K4[i]+SHA256_W4[i]|0,T2=(rotr4(A,2)^rotr4(A,13)^rotr4(A,22))+Maj4(A,B,C)|0;H=G2,G2=F,F=E,E=D2+T1|0,D2=C,C=B,B=A,A=T1+T2|0}A=A+this.A|0,B=B+this.B|0,C=C+this.C|0,D2=D2+this.D|0,E=E+this.E|0,F=F+this.F|0,G2=G2+this.G|0,H=H+this.H|0,this.set(A,B,C,D2,E,F,G2,H)}roundClean(){clean4(SHA256_W4)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),clean4(this.buffer)}},_SHA256=class extends SHA2_32B{constructor(){super(32,SHA256_IV4)}},K5123=split4(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))),SHA512_Kh3=K5123[0],SHA512_Kl3=K5123[1],SHA512_W_H3=new Uint32Array(80),SHA512_W_L3=new Uint32Array(80),SHA2_64B=class extends HashMD4{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(outputLen,IV){super(128,outputLen,16,!1),this.Ah=IV[0]|0,this.Al=IV[1]|0,this.Bh=IV[2]|0,this.Bl=IV[3]|0,this.Ch=IV[4]|0,this.Cl=IV[5]|0,this.Dh=IV[6]|0,this.Dl=IV[7]|0,this.Eh=IV[8]|0,this.El=IV[9]|0,this.Fh=IV[10]|0,this.Fl=IV[11]|0,this.Gh=IV[12]|0,this.Gl=IV[13]|0,this.Hh=IV[14]|0,this.Hl=IV[15]|0}get(){let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=Ah|0,this.Al=Al|0,this.Bh=Bh|0,this.Bl=Bl|0,this.Ch=Ch|0,this.Cl=Cl|0,this.Dh=Dh|0,this.Dl=Dl|0,this.Eh=Eh|0,this.El=El|0,this.Fh=Fh|0,this.Fl=Fl|0,this.Gh=Gh|0,this.Gl=Gl|0,this.Hh=Hh|0,this.Hl=Hl|0}_cloneInto(to2){return(to2||=new this.constructor).set(...this.get()),this._cloneIntoMeta(to2)}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA512_W_H3[i]=view.getUint32(offset),SHA512_W_L3[i]=view.getUint32(offset+=4);for(let i=16;i<80;i++){let W15h=SHA512_W_H3[i-15]|0,W15l=SHA512_W_L3[i-15]|0,s0h=rotrSH3(W15h,W15l,1)^rotrSH3(W15h,W15l,8)^shrSH3(W15h,W15l,7),s0l=rotrSL3(W15h,W15l,1)^rotrSL3(W15h,W15l,8)^shrSL3(W15h,W15l,7),W2h=SHA512_W_H3[i-2]|0,W2l=SHA512_W_L3[i-2]|0,s1h=rotrSH3(W2h,W2l,19)^rotrBH3(W2h,W2l,61)^shrSH3(W2h,W2l,6),s1l=rotrSL3(W2h,W2l,19)^rotrBL3(W2h,W2l,61)^shrSL3(W2h,W2l,6),SUMl=add4L3(s0l,s1l,SHA512_W_L3[i-7],SHA512_W_L3[i-16]),SUMh=add4H3(SUMl,s0h,s1h,SHA512_W_H3[i-7],SHA512_W_H3[i-16]);SHA512_W_H3[i]=SUMh|0,SHA512_W_L3[i]=SUMl|0}let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;for(let i=0;i<80;i++){let sigma1h=rotrSH3(Eh,El,14)^rotrSH3(Eh,El,18)^rotrBH3(Eh,El,41),sigma1l=rotrSL3(Eh,El,14)^rotrSL3(Eh,El,18)^rotrBL3(Eh,El,41),CHIh=Eh&Fh^~Eh&Gh,CHIl=El&Fl^~El&Gl,T1ll=add5L3(Hl,sigma1l,CHIl,SHA512_Kl3[i],SHA512_W_L3[i]),T1h=add5H3(T1ll,Hh,sigma1h,CHIh,SHA512_Kh3[i],SHA512_W_H3[i]),T1l=T1ll|0,sigma0h=rotrSH3(Ah,Al,28)^rotrBH3(Ah,Al,34)^rotrBH3(Ah,Al,39),sigma0l=rotrSL3(Ah,Al,28)^rotrBL3(Ah,Al,34)^rotrBL3(Ah,Al,39),MAJh=Ah&Bh^Ah&Ch^Bh&Ch,MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=Gh|0,Hl=Gl|0,Gh=Fh|0,Gl=Fl|0,Fh=Eh|0,Fl=El|0,{h:Eh,l:El}=add3(Dh|0,Dl|0,T1h|0,T1l|0),Dh=Ch|0,Dl=Cl|0,Ch=Bh|0,Cl=Bl|0,Bh=Ah|0,Bl=Al|0;let All=add3L3(T1l,sigma0l,MAJl);Ah=add3H3(All,T1h,sigma0h,MAJh),Al=All|0}({h:Ah,l:Al}=add3(this.Ah|0,this.Al|0,Ah|0,Al|0)),{h:Bh,l:Bl}=add3(this.Bh|0,this.Bl|0,Bh|0,Bl|0),{h:Ch,l:Cl}=add3(this.Ch|0,this.Cl|0,Ch|0,Cl|0),{h:Dh,l:Dl}=add3(this.Dh|0,this.Dl|0,Dh|0,Dl|0),{h:Eh,l:El}=add3(this.Eh|0,this.El|0,Eh|0,El|0),{h:Fh,l:Fl}=add3(this.Fh|0,this.Fl|0,Fh|0,Fl|0),{h:Gh,l:Gl}=add3(this.Gh|0,this.Gl|0,Gh|0,Gl|0),{h:Hh,l:Hl}=add3(this.Hh|0,this.Hl|0,Hh|0,Hl|0),this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){clean4(SHA512_W_H3,SHA512_W_L3)}destroy(){this.destroyed=!0,clean4(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},_SHA512=class extends SHA2_64B{constructor(){super(64,SHA512_IV4)}},sha2568=createHasher5(()=>new _SHA256,oidNist(1)),sha5123=createHasher5(()=>new _SHA512,oidNist(3))}});function aarray(item,title,inner=()=>{}){if(!Array.isArray(item))throw new TypeError(`"${title}" expected array, got type=${typeof item}`);for(let i=0;i<item.length;i++)inner(item[i],`${title}[${i}]`);return item}function astring(value,title=""){if(typeof value!="string"){let prefix=title&&`"${title}" `;throw new TypeError(prefix+"expected string, got type="+typeof value)}return value}function aobject2(value,title="object"){if(value===null||typeof value!="object"||Array.isArray(value))throw new TypeError(title==="object"?"expected valid options object":`"${title}" expected object, got type=${typeof value}`);return value}function afunction(value,title){if(typeof value!="function")throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);return value}function abool3(value,title=""){if(typeof value!="boolean")throw new TypeError(atitle2(title)+"expected boolean, got type="+typeof value);return value}function abignumber(n){if(typeof n=="bigint"){if(!isPosBig3(n))throw new RangeError("positive bigint expected, got "+n)}else anumber6(n);return n}function asafenumber(value,title=""){if(typeof value!="number"){let prefix=title&&`"${title}" `;throw new TypeError(prefix+"expected number, got type="+typeof value)}if(!Number.isSafeInteger(value)){let prefix=title&&`"${title}" `;throw new RangeError(prefix+"expected safe integer, got "+value)}}function numberToHexUnpadded3(num2){let hex3=abignumber(num2).toString(16);return hex3.length&1?"0"+hex3:hex3}function hexToNumber5(hex3){if(typeof hex3!="string")throw new TypeError("hex string expected, got "+typeof hex3);return hex3===""?_0n13:BigInt("0x"+hex3)}function bytesToNumberBE3(bytes){return hexToNumber5(bytesToHex4(bytes))}function bytesToNumberLE3(bytes){return hexToNumber5(bytesToHex4(copyBytes(abytes6(bytes)).reverse()))}function numberToBytesBE3(n,len){if(anumber5(len),len===0)throw new Error("zero output length is invalid");n=abignumber(n);let expectedLen=len*2,hex3=n.toString(16);if(hex3.length>expectedLen)throw new RangeError("number is too large");return hexToBytes4(hex3.padStart(expectedLen,"0"))}function numberToBytesLE3(n,len){return numberToBytesBE3(n,len).reverse()}function copyBytes(bytes){return Uint8Array.from(abytes7(bytes))}function isPosBig3(n){return typeof n=="bigint"&&_0n13<=n}function inRange3(n,min,max){return isPosBig3(n)&&isPosBig3(min)&&isPosBig3(max)&&min<=n&&n<max}function aInRange3(title,n,min,max){if(!inRange3(n,min,max))throw new RangeError("expected valid "+title+": "+min+" <= n < "+max+", got "+n)}function bitLen3(n){if(n<_0n13)throw new Error("expected non-negative bigint, got "+n);return n===_0n13?0:n.toString(2).length}function createHmacDrbg3(hashLen,qByteLen,hmacFn){if(anumber5(hashLen,"hashLen"),anumber5(qByteLen,"qByteLen"),typeof hmacFn!="function")throw new TypeError("hmacFn must be a function");let u8n3=len=>new Uint8Array(len),NULL=Uint8Array.of(),byte0=Uint8Array.of(0),byte1=Uint8Array.of(1),_maxDrbgIters=1e3,v=u8n3(hashLen),k=u8n3(hashLen),i=0,reset2=()=>{v.fill(1),k.fill(0),i=0},h=(...msgs)=>hmacFn(k,concatBytes7(v,...msgs)),reseed2=(seed=NULL)=>{k=h(byte0,seed),v=h(),seed.length!==0&&(k=h(byte1,seed),v=h())},gen3=()=>{if(i++>=_maxDrbgIters)throw new Error("drbg: tried max amount of iterations");let len=0,out=[];for(;len<qByteLen;){v=h();let sl=v.slice();out.push(sl),len+=v.length}return concatBytes7(...out)};return(seed,pred)=>{reset2(),reseed2(seed);let res;for(;(res=pred(gen3()))===void 0;)reseed2();return reset2(),res}}function validateObject3(object2,fields={},optFields={},title="object"){aobject2(object2,title),aobject2(fields,"fields"),aobject2(optFields,"optFields");function checkField(fieldName,expectedType,isOpt){let label=title==="object"?`param "${String(fieldName)}"`:`"${title}.${String(fieldName)}"`,val=object2[fieldName];if(!Object.hasOwn(object2,fieldName)&&(isOpt?val!==void 0:expectedType!=="function"))throw new TypeError(`${label} is invalid: expected own property`);if(isOpt&&val===void 0)return;let current=typeof val;if(current!==expectedType||val===null)throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`)}let iter=(f,isOpt)=>Object.entries(f).forEach(([k,v])=>checkField(k,v,isOpt));iter(fields,!1),iter(optFields,!0)}var abytes7,anumber6,bytesToHex5,concatBytes7,hexToBytes5,isBytes9,randomBytes5,_0n13,_1n13,atitle2,bitMask3,init_utils16=__esm({"node_modules/@noble/curves/utils.js"(){"use strict";init_utils15();abytes7=(value,length,title)=>abytes6(value,length,title),anumber6=anumber5;bytesToHex5=bytesToHex4,concatBytes7=(...arrays)=>concatBytes6(...arrays),hexToBytes5=hex3=>hexToBytes4(hex3),isBytes9=isBytes8,randomBytes5=bytesLength=>randomBytes4(bytesLength),_0n13=BigInt(0),_1n13=BigInt(1),atitle2=title=>title?`"${title}" `:"";bitMask3=n=>(asafenumber(n,"n"),(_1n13<<BigInt(n))-_1n13)}});function mod3(a,b){if(b<=_0n14)throw new Error("mod: expected positive modulus, got "+b);let result=a%b;return result>=_0n14?result:b+result}function pow(num2,power,modulo2){if(modulo2<=_1n14)throw new Error("pow: expected modulus > 1, got "+modulo2);if(typeof power!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof power);if(power<_0n14)throw new Error("invalid exponent, negatives unsupported");if(power===_0n14)return _1n14;if(power===_1n14)return num2;let d=num2%modulo2;if(d<_0n14&&(d+=modulo2),power<POW_WINDOWED_MIN){let p2=_1n14;for(;power>_0n14;)power&_1n14&&(p2=p2*d%modulo2),d=d*d%modulo2,power>>=_1n14;return p2}let digits=[];for(;power>_0n14;)digits.push(Number(power&_15n)),power>>=_4n5;let table=new Array(16);table[0]=_1n14,table[1]=d;for(let i=2;i<16;i++)table[i]=table[i-1]*d%modulo2;let p=table[digits[digits.length-1]];for(let w=digits.length-2;w>=0;w--){p=p*p%modulo2,p=p*p%modulo2,p=p*p%modulo2,p=p*p%modulo2;let digit=digits[w];digit!==0&&(p=p*table[digit]%modulo2)}return p}function pow23(x,power,modulo2){if(modulo2<=_1n14)throw new Error("pow2: expected modulus > 1, got "+modulo2);if(power<_0n14)throw new Error("pow2: expected non-negative exponent, got "+power);let res=x;for(;power-- >_0n14;)res*=res,res%=modulo2;return res}function invert3(number4,modulo2){if(number4===_0n14)throw new Error("invert: expected non-zero number");if(modulo2<=_1n14)throw new Error("invert: expected modulus > 1, got "+modulo2);let a=mod3(number4,modulo2),b=modulo2,x=_0n14,u=_1n14;for(;a!==_0n14;){let q=b/a,r2=b-a*q,m=x-u*q;b=a,a=r2,x=u,u=m}if(b!==_1n14)throw new Error("invert: does not exist");return mod3(x,modulo2)}function invertCt(a,prime){if(prime<=_1n14)throw new Error("invertCt: expected prime modulus > 1, got "+prime);let an=mod3(a,prime);if(an===_0n14)throw new Error("invertCt: expected non-zero number");let inverse=pow(an,prime-_2n9,prime);if(mod3(an*inverse,prime)!==_1n14)throw new Error("invertCt: does not exist");return inverse}function assertIsSquare(Fp,root2,n){let F=Fp;if(!F.eql(F.sqr(root2),n))throw new Error("Cannot find square root")}function aoddModulus(order,fnName){if((order&_1n14)===_0n14)throw new Error(fnName+": expected odd modulus, got "+order)}function sqrt3mod43(Fp,n){let F=Fp,p1div4=(F.ORDER+_1n14)/_4n5,root2=F.pow(n,p1div4);return assertIsSquare(F,root2,n),root2}function sqrt5mod83(Fp,n){let F=Fp,p5div8=(F.ORDER-_5n3)/_8n3,n2=F.mul(n,_2n9),v=F.pow(n2,p5div8),nv=F.mul(n,v),i=F.mul(F.mul(nv,_2n9),v),root2=F.mul(nv,F.sub(i,F.ONE));return assertIsSquare(F,root2,n),root2}function sqrt9mod16(P3){let Fp_=Field3(P3),tn=tonelliShanks3(P3),c1=tn(Fp_,Fp_.neg(Fp_.ONE)),c2=tn(Fp_,c1),c3=tn(Fp_,Fp_.neg(c1)),c4=(P3+_7n3)/_16n;return((Fp,n)=>{let F=Fp,tv1=F.pow(n,c4),tv2=F.mul(tv1,c1),tv3=F.mul(tv1,c2),tv4=F.mul(tv1,c3),e1=F.eql(F.sqr(tv2),n),e22=F.eql(F.sqr(tv3),n);tv1=F.cmov(tv1,tv2,e1),tv2=F.cmov(tv4,tv3,e22);let e32=F.eql(F.sqr(tv2),n),root2=F.cmov(tv1,tv2,e32);return assertIsSquare(F,root2,n),root2})}function tonelliShanks3(P3){if(P3<_3n5)throw new Error("sqrt is not defined for small field");aoddModulus(P3,"tonelliShanks");let Q=P3-_1n14,S=0;for(;Q%_2n9===_0n14;)Q/=_2n9,S++;let Z=_2n9,_Fp=Field3(P3);for(;FpLegendre3(_Fp,Z)===1;)if(Z++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(S===1)return sqrt3mod43;let cc=_Fp.pow(Z,Q),Q1div2=(Q+_1n14)/_2n9;return function(Fp,n){let F=Fp;if(F.is0(n))return n;if(FpLegendre3(F,n)!==1)throw new Error("Cannot find square root");let M=S,c=F.mul(F.ONE,cc),t=F.pow(n,Q),R=F.pow(n,Q1div2);for(;!F.eql(t,F.ONE);){if(F.is0(t))throw new Error("Cannot find square root: probably non-prime P");let i=1,t_tmp=F.sqr(t);for(;!F.eql(t_tmp,F.ONE);)if(i++,t_tmp=F.sqr(t_tmp),i===M)throw new Error("Cannot find square root");let exponent=_1n14<<BigInt(M-i-1),b=F.pow(c,exponent);M=i,c=F.sqr(b),t=F.mul(t,c),R=F.mul(R,b)}return R}}function FpSqrt3(P3){return aoddModulus(P3,"Fp.sqrt"),P3%_4n5===_3n5?sqrt3mod43:P3%_8n3===_5n3?sqrt5mod83:P3%_16n===_9n?sqrt9mod16(P3):tonelliShanks3(P3)}function validateField4(field){if(aobject2(field,"field"),typeof field.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof field.ORDER);asafenumber(field.BYTES,"BYTES"),asafenumber(field.BITS,"BITS");for(let name of FIELD_FIELDS3)afunction(field[name],"field."+name);if(field.BYTES<1||field.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(field.ORDER<=_1n14)throw new Error("invalid field: expected ORDER > 1, got "+field.ORDER);return field}function FpInvertBatch3(Fp,nums,passZero=!1){validateField4(Fp),aarray(nums,"nums"),abool3(passZero,"passZero");let F=Fp,inverted=new Array(nums.length).fill(passZero?F.ZERO:void 0),multipliedAcc=nums.reduce((acc,num2,i)=>F.is0(num2)?acc:(inverted[i]=acc,F.mul(acc,num2)),F.ONE),invertedAcc=F.inv(multipliedAcc);return nums.reduceRight((acc,num2,i)=>F.is0(num2)?acc:(inverted[i]=F.mul(acc,inverted[i]),F.mul(acc,num2)),invertedAcc),inverted}function FpLegendre3(Fp,n){validateField4(Fp);let F=Fp;aoddModulus(F.ORDER,"FpLegendre");let p1mod2=(F.ORDER-_1n14)/_2n9,powered=F.pow(n,p1mod2),yes=F.eql(powered,F.ONE),zero=F.eql(powered,F.ZERO),no=F.eql(powered,F.neg(F.ONE));if(!yes&&!zero&&!no)throw new Error("invalid Legendre symbol result");return yes?1:zero?0:-1}function nLength3(n,nBitLength){if(nBitLength!==void 0&&anumber6(nBitLength),n<=_0n14)throw new Error("invalid n length: expected positive n, got "+n);if(nBitLength!==void 0&&nBitLength<1)throw new Error("invalid n length: expected positive bit length, got "+nBitLength);let bits=bitLen3(n);if(nBitLength!==void 0&&nBitLength<bits)throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);let _nBitLength=nBitLength!==void 0?nBitLength:bits,nByteLength=Math.ceil(_nBitLength/8);return{nBitLength:_nBitLength,nByteLength}}function Field3(ORDER,opts={}){return Object.freeze(_Field.prototype),new _Field(ORDER,opts)}function getFieldBytesLength3(fieldOrder){if(typeof fieldOrder!="bigint")throw new Error("field order must be bigint");if(fieldOrder<=_1n14)throw new Error("field order must be greater than 1");let bitLength=bitLen3(fieldOrder-_1n14);return Math.ceil(bitLength/8)}function getMinHashLength3(fieldOrder){let length=getFieldBytesLength3(fieldOrder);return length+Math.ceil(length/2)}function mapHashToField3(key3,fieldOrder,isLE3=!1){abytes7(key3);let len=key3.length,fieldLen=getFieldBytesLength3(fieldOrder),minLen=Math.max(getMinHashLength3(fieldOrder),16);if(len<minLen||len>1024)throw new Error("expected "+minLen+"-1024 bytes of input, got "+len);let num2=isLE3?bytesToNumberLE3(key3):bytesToNumberBE3(key3),reduced=mod3(num2,fieldOrder-_1n14)+_1n14;return isLE3?numberToBytesLE3(reduced,fieldLen):numberToBytesBE3(reduced,fieldLen)}var _0n14,_1n14,_2n9,_3n5,_4n5,_5n3,_7n3,_8n3,_9n,_15n,_16n,POW_WINDOWED_MIN,FIELD_FIELDS3,FIELD_SQRT,_Field,init_modular3=__esm({"node_modules/@noble/curves/abstract/modular.js"(){"use strict";init_utils16();_0n14=BigInt(0),_1n14=BigInt(1),_2n9=BigInt(2),_3n5=BigInt(3),_4n5=BigInt(4),_5n3=BigInt(5),_7n3=BigInt(7),_8n3=BigInt(8),_9n=BigInt(9),_15n=BigInt(15),_16n=BigInt(16),POW_WINDOWED_MIN=BigInt("0x10000000000000000");FIELD_FIELDS3=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];FIELD_SQRT=new WeakMap,_Field=class{ORDER;BITS;BYTES;isLE;ZERO=_0n14;ONE=_1n14;_lengths;_mod;constructor(ORDER,opts={}){if(ORDER<=_1n14)throw new Error("invalid field: expected ORDER > 1, got "+ORDER);let _nbitLength;this.isLE=!1,opts!=null&&typeof opts=="object"&&(typeof opts.BITS=="number"&&(_nbitLength=opts.BITS),typeof opts.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:opts.sqrt,enumerable:!0}),typeof opts.isLE=="boolean"&&(this.isLE=opts.isLE),opts.allowedLengths&&(this._lengths=Object.freeze(opts.allowedLengths.slice())),typeof opts.modFromBytes=="boolean"&&(this._mod=opts.modFromBytes));let{nBitLength,nByteLength}=nLength3(ORDER,_nbitLength);if(nByteLength>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=ORDER,this.BITS=nBitLength,this.BYTES=nByteLength,Object.freeze(this)}create(num2){return mod3(num2,this.ORDER)}isValid(num2){if(typeof num2!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof num2);return _0n14<=num2&&num2<this.ORDER}is0(num2){return num2===_0n14}isValidNot0(num2){return!this.is0(num2)&&this.isValid(num2)}isOdd(num2){return(num2&_1n14)===_1n14}neg(num2){return mod3(-num2,this.ORDER)}eql(lhs,rhs){return lhs===rhs}sqr(num2){return mod3(num2*num2,this.ORDER)}add(lhs,rhs){return mod3(lhs+rhs,this.ORDER)}sub(lhs,rhs){return mod3(lhs-rhs,this.ORDER)}mul(lhs,rhs){return mod3(lhs*rhs,this.ORDER)}pow(num2,power){return pow(num2,power,this.ORDER)}div(lhs,rhs){return mod3(lhs*invert3(rhs,this.ORDER),this.ORDER)}sqrN(num2){return num2*num2}addN(lhs,rhs){return lhs+rhs}subN(lhs,rhs){return lhs-rhs}mulN(lhs,rhs){return lhs*rhs}inv(num2){return invert3(num2,this.ORDER)}sqrt(num2){let sqrt=FIELD_SQRT.get(this);return sqrt||FIELD_SQRT.set(this,sqrt=FpSqrt3(this.ORDER)),sqrt(this,num2)}toBytes(num2){return this.isLE?numberToBytesLE3(num2,this.BYTES):numberToBytesBE3(num2,this.BYTES)}fromBytes(bytes,skipValidation=!1){abytes7(bytes);let{_lengths:allowedLengths,BYTES,isLE:isLE3,ORDER,_mod:modFromBytes}=this;if(allowedLengths){if(bytes.length<1||!allowedLengths.includes(bytes.length)||bytes.length>BYTES)throw new Error("Field.fromBytes: expected "+allowedLengths+" bytes, got "+bytes.length);let padded=new Uint8Array(BYTES);padded.set(bytes,isLE3?0:padded.length-bytes.length),bytes=padded}if(bytes.length!==BYTES)throw new Error("Field.fromBytes: expected "+BYTES+" bytes, got "+bytes.length);let scalar=isLE3?bytesToNumberLE3(bytes):bytesToNumberBE3(bytes);if(modFromBytes&&(scalar=mod3(scalar,ORDER)),!skipValidation&&!this.isValid(scalar))throw new Error("invalid field element: outside of range 0..ORDER");return scalar}invertBatch(lst){return FpInvertBatch3(this,lst,!0)}cmov(a,b,condition){return abool3(condition,"condition"),condition?b:a}}}});function validatePointCons(Point4){let pc=Point4;if(typeof pc!="function")throw new TypeError('"Point" expected constructor, got type='+typeof Point4);afunction(pc.fromAffine,"Point.fromAffine"),afunction(pc.fromBytes,"Point.fromBytes"),afunction(pc.fromHex,"Point.fromHex"),aobject2(pc.BASE,"Point.BASE"),aobject2(pc.ZERO,"Point.ZERO"),validateField4(pc.Fp),validateField4(pc.Fn)}function normalizeZ(c,points){validatePointCons(c),validateMSMPoints3(points,c);let invertedZs=FpInvertBatch3(c.Fp,points.map(p=>p.Z));return points.map((p,i)=>c.fromAffine(p.toAffine(invertedZs[i])))}function validateW3(W,bits,min=1){if(!Number.isSafeInteger(W)||W<min||W>bits)throw new Error("invalid window size, expected ["+min+".."+bits+"], got W="+W)}function validateTableBytes(numPoints,fpBytes){let bytes=numPoints*(4*fpBytes+128);if(bytes>TABLE_BYTES_MAX)throw new Error("invalid window size: table would need ~"+Math.ceil(bytes/2**20)+" MiB, max "+TABLE_BYTES_MAX/2**20+" MiB")}function probeRandomBytes(randomBytes9,length){if(randomBytes9!==void 0){afunction(randomBytes9,"randomBytes");try{let probe=randomBytes9(length);if(!isBytes9(probe)||probe.length!==length)return}catch{return}return randomBytes9}}function validateMSMPoints3(points,c){aarray(points,"points"),points.forEach((p,i)=>{if(!(p instanceof c))throw new Error("invalid point at index "+i)})}function validateMSMScalars3(scalars,field,maxScalar){if(!Array.isArray(scalars))throw new Error("array of scalars expected");scalars.forEach((s3,i)=>{if(!(maxScalar===void 0?field.isValid(s3):isPosBig3(s3)&&s3<maxScalar))throw new Error("invalid scalar at index "+i)})}function getWindowSize(P3){return pointWindowSizes3.get(P3)||1}function oddMultiples(p,size4){let dbl3=p.double(),t=[p];for(let j=1;j<size4;j++)t.push(t[j-1].add(dbl3));return t}function wnafDigits(n,W){let size4=2**W,half=size4/2,mask=BigInt(size4-1),d=[];for(;n>_0n15;){let w=0;n&_1n15&&(w=Number(n&mask),w>=half&&(w-=size4),n-=BigInt(w)),d.push(w),n>>=_1n15}return d}function signedWindowDigits(n,W,windows){let size4=2**W,half=size4/2,mask=BigInt(size4-1),shiftBy=BigInt(W),d=[];for(let w=0;w<windows;w++){let v=Number(n&mask);n>>=shiftBy,v>half&&(v-=size4,n+=_1n15),d.push(v)}if(n!==_0n15)throw new Error("invalid wnaf");return d}function wnafWalk(zero,tables,digits){let max=0;for(let d of digits)max=Math.max(max,d.length);let acc=zero;for(let bit=max-1;bit>=0;bit--){bit!==max-1&&(acc=acc.double());for(let i=0;i<digits.length;i++){let w=digits[i][bit];if(w){let item=tables[i][Math.abs(w)-1>>1];acc=acc.add(w<0?item.negate():item)}}}return acc}function mulAddUnsafe(c,points,scalars,allowOversized=!1){if(validatePointCons(c),validateMSMPoints3(points,c),abool3(allowOversized,"allowOversized"),validateMSMScalars3(scalars,c.Fn,allowOversized?c.Fn.ORDER**_4n6:void 0),points.length!==scalars.length)throw new Error("arrays of points and scalars must have equal length");let tables=points.map(p=>oddMultiples(p,4)),digits=scalars.map(n=>wnafDigits(n,4));return wnafWalk(c.ZERO,tables,digits)}function createField(order,field,isLE3){if(field){if(field.ORDER!==order)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return validateField4(field),field}else return Field3(order,{isLE:isLE3})}function createCurveFields(type2,CURVE,curveOpts={},FpFnLE){if(type2!=="weierstrass"&&type2!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(FpFnLE===void 0&&(FpFnLE=type2==="edwards"),!CURVE||typeof CURVE!="object")throw new Error(`expected valid ${type2} CURVE object`);validateObject3(curveOpts);for(let p of["p","n","h"]){let val=CURVE[p];if(!(isPosBig3(val)&&val!==_0n15))throw new Error(`CURVE.${p} must be positive bigint`)}let Fp=createField(CURVE.p,curveOpts.Fp,FpFnLE),Fn2=createField(CURVE.n,curveOpts.Fn,FpFnLE),params=["Gx","Gy","a",type2==="weierstrass"?"b":"d"];for(let p of params)if(!Fp.isValid(CURVE[p]))throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);return CURVE=Object.freeze(Object.assign({},CURVE)),{CURVE,Fp,Fn:Fn2}}function createKeygen(randomSecretKey,getPublicKey){return function(seed){let secretKey=randomSecretKey(seed);return{secretKey,publicKey:getPublicKey(secretKey)}}}var _0n15,_1n15,_4n6,BLIND_BYTES,BLIND_BITS,FW_WINDOW,TABLE_BYTES_MAX,pointWindowSizes3,ScalarMultiplier,init_curve3=__esm({"node_modules/@noble/curves/abstract/curve.js"(){"use strict";init_utils16();init_modular3();_0n15=BigInt(0),_1n15=BigInt(1),_4n6=BigInt(4),BLIND_BYTES=16,BLIND_BITS=128,FW_WINDOW=5,TABLE_BYTES_MAX=2**31;pointWindowSizes3=new WeakMap;ScalarMultiplier=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(Point4,randomBytes9){validatePointCons(Point4),this.randomBytes=probeRandomBytes(randomBytes9,BLIND_BYTES),this.Point=Point4,this.BASE=Point4.BASE,this.ZERO=Point4.ZERO,this.bits=Point4.Fn.BITS}buildWnafTable(point3,W,bits){let windows=Math.ceil(bits/W)+1,half=2**(W-1),comp=[],base4=point3;for(let w=0;w<windows;w++){let acc=base4;for(let i=0;i<half;i++)comp.push(acc),acc=acc.add(base4);base4=comp[comp.length-1].double()}return{W,bits,windows,comp}}wnafCachedCT(precomputes,n){let{W,windows,comp}=precomputes,half=2**(W-1),digits=signedWindowDigits(n,W,windows),p=this.ZERO,f=this.BASE;for(let w=0;w<windows;w++){let digit=digits[w],start=w*half,idx=Math.abs(digit)-1,sel=comp[start];for(let i=1;i<half;i++)sel=i===idx?comp[start+i]:sel;let neg3=sel.negate();digit===0?f=f.add(comp[start]):p=p.add(digit<0?neg3:sel)}return{p,f}}getWnafPrecomputes(W,point3,bits,transform3){let entries=this.wnafPrecomputes.get(point3),comp=entries?.find(entry=>entry.W===W&&entry.bits===bits);return comp||(comp=this.buildWnafTable(point3,W,bits),typeof transform3=="function"&&(comp={...comp,comp:transform3(comp.comp)}),entries||(entries=[],this.wnafPrecomputes.set(point3,entries)),entries.push(comp)),comp}assertPoint(point3){if(!(point3 instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof point3)}validateMulInput(point3,scalar){if(this.assertPoint(point3),!inRange3(scalar,_1n15,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(point3,n,bits,transform3){let W=getWindowSize(point3);return W===1?this.fixedWindowCT(point3,n,bits):this.wnafCachedCT(this.getWnafPrecomputes(W,point3,bits,transform3),n)}mulCT(point3,scalar,transform3){return this.validateMulInput(point3,scalar),this.runCT(point3,scalar,this.bits,transform3)}mulCTBlinded(point3,scalar,transform3){if(this.validateMulInput(point3,scalar),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let bits=this.Point.Fn.BITS+BLIND_BITS,blind=this.randomBytes(BLIND_BYTES);if(!isBytes9(blind)||blind.length!==BLIND_BYTES)throw new Error("randomBytes returned invalid byte array");blind[0]=blind[0]&63|128;let n=scalar+bytesToNumberBE3(blind)*this.Point.Fn.ORDER;return this.runCT(point3,n,bits,transform3)}fixedWindowCT(point3,n,bits){let W=FW_WINDOW,size4=1<<W,mask=bitMask3(W),table=new Array(size4);table[0]=this.ZERO;for(let i=1;i<size4;i++)table[i]=table[i-1].add(point3);let windows=Math.ceil(bits/W),acc=this.ZERO;for(let window2=windows-1;window2>=0;window2--){if(window2!==windows-1)for(let d=0;d<W;d++)acc=acc.double();let digit=Number(n>>BigInt(window2*W)&mask),sel=table[0];for(let i=1;i<size4;i++)sel=i===digit?table[i]:sel;acc=acc.add(sel)}return{p:acc,f:acc}}shouldBlind(point3,cofactor){return this.randomBytes===void 0?!1:cofactor===_1n15?!0:point3!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(point3,scalar,cofactor,transform3){return this.shouldBlind(point3,cofactor)?this.mulCTBlinded(point3,scalar,transform3):this.mulCT(point3,scalar,transform3)}mulUnsafe(point3,scalar,transform3){if(this.assertPoint(point3),!isPosBig3(scalar))throw new Error("invalid scalar");let W=getWindowSize(point3);if(W===1||scalar>=this.Point.Fn.ORDER)return mulAddUnsafe(this.Point,[point3],[scalar],!0);let precomputes=this.getWnafPrecomputes(W,point3,this.bits,transform3);return this.wnafCachedCT(precomputes,scalar).p}setWindowSize(point3,W){this.assertPoint(point3),validateW3(W,this.bits);let windows=Math.ceil((this.bits+BLIND_BITS)/W)+1;validateTableBytes(windows*2**(W-1),this.Point.Fp.BYTES),pointWindowSizes3.set(point3,W),this.wnafPrecomputes.delete(point3)}hasWindowSize(point3){return getWindowSize(point3)!==1}}}});var _HMAC,hmac4,init_hmac4=__esm({"node_modules/@noble/hashes/hmac.js"(){"use strict";init_utils15();_HMAC=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(hash8,key3){if(ahash4(hash8),abytes6(key3,void 0,"key"),this.iHash=hash8.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let blockLen=this.blockLen,pad4=new Uint8Array(blockLen);pad4.set(key3.length>blockLen?hash8.create().update(key3).digest():key3);for(let i=0;i<pad4.length;i++)pad4[i]^=54;this.iHash.update(pad4),this.oHash=hash8.create();for(let i=0;i<pad4.length;i++)pad4[i]^=106;this.oHash.update(pad4),clean4(pad4)}update(buf){return aexists4(this),this.iHash.update(buf),this}digestInto(out){aexists4(this),aoutput4(out,this),this.finished=!0;let buf=out.subarray(0,this.outputLen);this.iHash.digestInto(buf),this.oHash.update(buf),this.oHash.digestInto(buf),this.destroy()}digest(){let out=new Uint8Array(this.oHash.outputLen);return this.digestInto(out),out}_cloneInto(to2){to2||=Object.create(Object.getPrototypeOf(this),{});let{oHash,iHash,finished:finished2,destroyed,blockLen,outputLen,canXOF}=this;return to2=to2,to2.finished=finished2,to2.destroyed=destroyed,to2.blockLen=blockLen,to2.outputLen=outputLen,to2.canXOF=canXOF,to2.oHash=oHash._cloneInto(to2.oHash),to2.iHash=iHash._cloneInto(to2.iHash),to2}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},hmac4=(()=>{let hmac_=((hash8,key3,message)=>new _HMAC(hash8,key3).update(message).digest());return hmac_.create=(hash8,key3)=>new _HMAC(hash8,key3),hmac_})()}});var _0n16,DERErr3,_DER,DER3,init_der=__esm({"node_modules/@noble/curves/abstract/der.js"(){"use strict";init_utils16();_0n16=BigInt(0),DERErr3=class extends Error{constructor(m=""){super(m)}},_DER={Err:DERErr3,_tlv:{encode:(tag,data)=>{let{Err:E}=_DER;if(asafenumber(tag,"tag"),tag<0||tag>255)throw new E("tlv.encode: wrong tag");if(astring(data,"data"),data.length&1)throw new E("tlv.encode: unpadded data");let dataLen=data.length/2,len=numberToHexUnpadded3(dataLen);if(len.length/2&128)throw new E("tlv.encode: long form length too big");let lenLen=dataLen>127?numberToHexUnpadded3(len.length/2|128):"";return numberToHexUnpadded3(tag)+lenLen+len+data},decode(tag,data){let{Err:E}=_DER;data=abytes7(data,void 0,"DER data");let pos=0;if(tag<0||tag>255)throw new E("tlv.decode: wrong tag");if(data.length<2||data[pos++]!==tag)throw new E("tlv.decode: wrong tlv");let first=data[pos++],isLong=!!(first&128),length=0;if(!isLong)length=first;else{let lenLen=first&127;if(!lenLen)throw new E("tlv.decode(long): indefinite length not supported");if(lenLen>4)throw new E("tlv.decode(long): byte length is too big");let lengthBytes=data.subarray(pos,pos+lenLen);if(lengthBytes.length!==lenLen)throw new E("tlv.decode: length bytes not complete");if(lengthBytes[0]===0)throw new E("tlv.decode(long): zero leftmost byte");for(let b of lengthBytes)length=length<<8|b;if(pos+=lenLen,length<128)throw new E("tlv.decode(long): not minimal encoding")}let v=data.subarray(pos,pos+length);if(v.length!==length)throw new E("tlv.decode: wrong value length");return{v,l:data.subarray(pos+length)}}},_int:{encode(num2){let{Err:E}=_DER;if(abignumber(num2),num2<_0n16)throw new E("integer: negative integers are not allowed");let hex3=numberToHexUnpadded3(num2);if(Number.parseInt(hex3[0],16)&8&&(hex3="00"+hex3),hex3.length&1)throw new E("unexpected DER parsing assertion: unpadded hex");return hex3},decode(data){let{Err:E}=_DER;if(data.length<1)throw new E("invalid signature integer: empty");if(data[0]&128)throw new E("invalid signature integer: negative");if(data.length>1&&data[0]===0&&!(data[1]&128))throw new E("invalid signature integer: unnecessary leading zero");return bytesToNumberBE3(data)}},toSig(bytes,maxScalarBytes){let{Err:E,_int:int2,_tlv:tlv}=_DER;if(maxScalarBytes!==void 0&&(asafenumber(maxScalarBytes,"maxScalarBytes"),maxScalarBytes<1))throw new E("invalid signature: maxScalarBytes must be positive");let data=abytes7(bytes,void 0,"signature"),{v:seqBytes,l:seqLeftBytes}=tlv.decode(48,data);if(seqLeftBytes.length)throw new E("invalid signature: left bytes after parsing");let{v:rBytes,l:rLeftBytes}=tlv.decode(2,seqBytes),{v:sBytes,l:sLeftBytes}=tlv.decode(2,rLeftBytes);if(sLeftBytes.length)throw new E("invalid signature: left bytes after parsing");if(maxScalarBytes!==void 0&&(rBytes.length>maxScalarBytes||sBytes.length>maxScalarBytes))throw new E("invalid signature: integer too large");return{r:int2.decode(rBytes),s:int2.decode(sBytes)}},hexFromSig(sig){let{_tlv:tlv,_int:int2}=_DER;validateObject3(sig,{r:"bigint",s:"bigint"},{},"sig");let rs=tlv.encode(2,int2.encode(sig.r)),ss=tlv.encode(2,int2.encode(sig.s)),seq=rs+ss;return tlv.encode(48,seq)}},DER3=(Object.freeze(_DER._tlv),Object.freeze(_DER._int),Object.freeze(_DER))}});function _splitEndoScalar(k,basis,n){aInRange3("scalar",k,_0n17,n);let[[a1,b1],[a2,b2]]=basis,c1=divNearest3(b2*k,n),c2=divNearest3(-b1*k,n),k1=k-c1*a1-c2*a2,k2=-c1*b1-c2*b2,k1neg=k1<_0n17,k2neg=k2<_0n17;k1neg&&(k1=-k1),k2neg&&(k2=-k2);let MAX_NUM=bitMask3(Math.ceil(bitLen3(n)/2))+_1n16;if(k1<_0n17||k1>=MAX_NUM||k2<_0n17||k2>=MAX_NUM)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg,k1,k2neg,k2}}function validateSigFormat(format3){if(!["compact","recovered","der"].includes(format3))throw new Error('Signature format must be "compact", "recovered", or "der"');return format3}function validateSigOpts(opts,def){validateObject3(opts);let optsn={};for(let optName of Object.keys(def))optsn[optName]=opts[optName]===void 0?def[optName]:opts[optName];return abool3(optsn.lowS,"lowS"),abool3(optsn.prehash,"prehash"),optsn.format!==void 0&&validateSigFormat(optsn.format),optsn}function weierstrass3(params,extraOpts={}){let validated=createCurveFields("weierstrass",params,extraOpts),Fp=validated.Fp,Fn2=validated.Fn,CURVE=validated.CURVE,{h:cofactor,n:CURVE_ORDER}=CURVE;validateObject3(extraOpts,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:endoOpts,allowInfinityPoint,clearCofactor,isTorsionFree,fromBytes:fromBytes6,toBytes:toBytes8}=extraOpts,randomBytes9=extraOpts.randomBytes===void 0?randomBytes5:extraOpts.randomBytes;if(endoOpts&&(!Fp.is0(CURVE.a)||typeof endoOpts.beta!="bigint"||!Array.isArray(endoOpts.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let endo=endoOpts?{beta:endoOpts.beta,basises:endoOpts.basises.map(basis=>[...basis])}:void 0,lengths=getWLengths(Fp,Fn2);function assertCompressionIsSupported(){if(!Fp.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function pointToBytes2(_c,point3,isCompressed){if(point3.is0()){if(!allowInfinityPoint)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x,y}=point3.toAffine(),bx=Fp.toBytes(x);if(abool3(isCompressed,"isCompressed"),isCompressed){assertCompressionIsSupported();let hasEvenY=!Fp.isOdd(y);return concatBytes7(pprefix(hasEvenY),bx)}else return concatBytes7(Uint8Array.of(4),bx,Fp.toBytes(y))}function pointFromBytes(bytes){abytes7(bytes,void 0,"Point");let{publicKey:comp,publicKeyUncompressed:uncomp}=lengths,length=bytes.length,head=bytes[0],tail=bytes.subarray(1);if(allowInfinityPoint&&length===1&&head===0)return{x:Fp.ZERO,y:Fp.ZERO};if(length===comp&&(head===2||head===3)){let x=Fp.fromBytes(tail);if(!Fp.isValid(x))throw new Error("bad point: is not on curve, wrong x");let y2=weierstrassEquation(x),y;try{y=Fp.sqrt(y2)}catch(sqrtError){let err=sqrtError instanceof Error?": "+sqrtError.message:"";throw new Error("bad point: is not on curve, sqrt error"+err)}assertCompressionIsSupported();let evenY=Fp.isOdd(y);return(head&1)===1!==evenY&&(y=Fp.neg(y)),{x,y}}else if(length===uncomp&&head===4){let L=Fp.BYTES,x=Fp.fromBytes(tail.subarray(0,L)),y=Fp.fromBytes(tail.subarray(L,L*2));if(!isValidXY(x,y))throw new Error("bad point: is not on curve");return{x,y}}else throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`)}let encodePoint=toBytes8===void 0?pointToBytes2:toBytes8,decodePoint2=fromBytes6===void 0?pointFromBytes:fromBytes6,b32=Fp.mul(CURVE.b,_3n6),mulA=Fp.is0(CURVE.a)?_=>Fp.ZERO:x=>Fp.mul(CURVE.a,x);function weierstrassEquation(x){let x2=Fp.sqr(x),x3=Fp.mul(x2,x);return Fp.add(Fp.add(x3,Fp.mul(x,CURVE.a)),CURVE.b)}function isValidXY(x,y){let left=Fp.sqr(y),right=weierstrassEquation(x);return Fp.eql(left,right)}if(!isValidXY(CURVE.Gx,CURVE.Gy))throw new Error("bad curve params: generator point");let _4a3=Fp.mul(Fp.pow(CURVE.a,_3n6),_4n7),_27b2=Fp.mul(Fp.sqr(CURVE.b),BigInt(27));if(Fp.is0(Fp.add(_4a3,_27b2)))throw new Error("bad curve params: a or b");function acoord(title,n,banZero=!1){if(!Fp.isValid(n)||banZero&&Fp.is0(n))throw new Error(`bad point coordinate ${title}`);return typeof n=="object"&&n!==null?Fp.create(n):n}function aprjpoint(other){if(!(other instanceof Point4))throw new Error("Weierstrass Point expected")}function splitEndoScalarN(k){if(!endo||!endo.basises)throw new Error("no endo");return _splitEndoScalar(k,endo.basises,Fn2.ORDER)}function pushWnafPair(points,scalars,p,k){if(!Fn2.isValid(k))throw new RangeError("invalid scalar: out of range");if(endo){let{k1neg,k1,k2neg,k2}=splitEndoScalarN(k),psi=new Point4(Fp.mul(p.X,endo.beta),p.Y,p.Z);points.push(k1neg?p.negate():p,k2neg?psi.negate():psi),scalars.push(k1,k2)}else points.push(p),scalars.push(k)}let validityCache=new WeakSet;class Point4{static BASE=new Point4(CURVE.Gx,CURVE.Gy,Fp.ONE);static ZERO=new Point4(Fp.ZERO,Fp.ONE,Fp.ZERO);static Fp=Fp;static Fn=Fn2;X;Y;Z;constructor(X,Y,Z){this.X=acoord("x",X),this.Y=acoord("y",Y,!0),this.Z=acoord("z",Z),Object.freeze(this)}static CURVE(){return CURVE}static fromAffine(p){let{x,y}=p||{};if(!p||!Fp.isValid(x)||!Fp.isValid(y))throw new Error("invalid affine point");if(p instanceof Point4)throw new Error("projective point not allowed");return Fp.is0(x)&&Fp.is0(y)?Point4.ZERO:new Point4(x,y,Fp.ONE)}static fromBytes(bytes){let P3=Point4.fromAffine(decodePoint2(abytes7(bytes,void 0,"point")));return P3.assertValidity(),P3}static fromHex(hex3){return Point4.fromBytes(hexToBytes5(hex3))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(windowSize=6,isLazy=!0){return wnaf.setWindowSize(this,windowSize),isLazy||this.multiply(_3n6),this}assertValidity(){let p=this;if(p.is0()){if(allowInfinityPoint&&Fp.is0(p.X)&&Fp.eql(p.Y,Fp.ONE)&&Fp.is0(p.Z))return;throw new Error("bad point: ZERO")}if(validityCache.has(p))return;let{x,y}=p.toAffine();if(!Fp.isValid(x)||!Fp.isValid(y))throw new Error("bad point: x or y not field elements");if(!isValidXY(x,y))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");validityCache.add(p)}hasEvenY(){let{y}=this.toAffine();if(!Fp.isOdd)throw new Error("Field doesn't support isOdd");return!Fp.isOdd(y)}equals(other){aprjpoint(other);let{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=other,U1=Fp.eql(Fp.mul(X1,Z2),Fp.mul(X2,Z1)),U2=Fp.eql(Fp.mul(Y1,Z2),Fp.mul(Y2,Z1));return U1&&U2}negate(){return new Point4(this.X,Fp.neg(this.Y),this.Z)}double(){let{X:X1,Y:Y1,Z:Z1}=this,X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO,t0=Fp.mul(X1,X1),t1=Fp.mul(Y1,Y1),t2=Fp.mul(Z1,Z1),t3=Fp.mul(X1,Y1);return t3=Fp.add(t3,t3),Z3=Fp.mul(X1,Z1),Z3=Fp.add(Z3,Z3),X3=mulA(Z3),Y3=Fp.mul(b32,t2),Y3=Fp.add(X3,Y3),X3=Fp.sub(t1,Y3),Y3=Fp.add(t1,Y3),Y3=Fp.mul(X3,Y3),X3=Fp.mul(t3,X3),Z3=Fp.mul(b32,Z3),t2=mulA(t2),t3=Fp.sub(t0,t2),t3=mulA(t3),t3=Fp.add(t3,Z3),Z3=Fp.add(t0,t0),t0=Fp.add(Z3,t0),t0=Fp.add(t0,t2),t0=Fp.mul(t0,t3),Y3=Fp.add(Y3,t0),t2=Fp.mul(Y1,Z1),t2=Fp.add(t2,t2),t0=Fp.mul(t2,t3),X3=Fp.sub(X3,t0),Z3=Fp.mul(t2,t1),Z3=Fp.add(Z3,Z3),Z3=Fp.add(Z3,Z3),new Point4(X3,Y3,Z3)}add(other){aprjpoint(other);let{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=other,X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO,t0=Fp.mul(X1,X2),t1=Fp.mul(Y1,Y2),t2=Fp.mul(Z1,Z2),t3=Fp.add(X1,Y1),t4=Fp.add(X2,Y2);t3=Fp.mul(t3,t4),t4=Fp.add(t0,t1),t3=Fp.sub(t3,t4),t4=Fp.add(X1,Z1);let t5=Fp.add(X2,Z2);return t4=Fp.mul(t4,t5),t5=Fp.add(t0,t2),t4=Fp.sub(t4,t5),t5=Fp.add(Y1,Z1),X3=Fp.add(Y2,Z2),t5=Fp.mul(t5,X3),X3=Fp.add(t1,t2),t5=Fp.sub(t5,X3),Z3=mulA(t4),X3=Fp.mul(b32,t2),Z3=Fp.add(X3,Z3),X3=Fp.sub(t1,Z3),Z3=Fp.add(t1,Z3),Y3=Fp.mul(X3,Z3),t1=Fp.add(t0,t0),t1=Fp.add(t1,t0),t2=mulA(t2),t4=Fp.mul(b32,t4),t1=Fp.add(t1,t2),t2=Fp.sub(t0,t2),t2=mulA(t2),t4=Fp.add(t4,t2),t0=Fp.mul(t1,t4),Y3=Fp.add(Y3,t0),t0=Fp.mul(t5,t4),X3=Fp.mul(t3,X3),X3=Fp.sub(X3,t0),t0=Fp.mul(t3,t1),Z3=Fp.mul(t5,Z3),Z3=Fp.add(Z3,t0),new Point4(X3,Y3,Z3)}subtract(other){return aprjpoint(other),this.add(other.negate())}is0(){return this.equals(Point4.ZERO)}multiply(scalar){if(!Fn2.isValidNot0(scalar))throw new RangeError("invalid scalar: out of range");let{p,f}=wnaf.mulSecret(this,scalar,cofactor,normalize4);return normalize4([p,f])[0]}multiplyUnsafe(scalar){let p=this,sc=scalar;if(!Fn2.isValid(sc))throw new RangeError("invalid scalar: out of range");if(sc===_0n17||p.is0())return Point4.ZERO;if(sc===_1n16)return p;if(wnaf.hasWindowSize(this))return wnaf.mulUnsafe(p,sc,normalize4);let points=[],scalars=[];return pushWnafPair(points,scalars,p,sc),mulAddUnsafe(Point4,points,scalars)}mulAddUnsafe(a,other,b){aprjpoint(other);let points=[],scalars=[];return pushWnafPair(points,scalars,this,a),pushWnafPair(points,scalars,other,b),mulAddUnsafe(Point4,points,scalars)}toAffine(invertedZ){let p=this,iz=invertedZ;if(iz!=null&&!Fp.isValid(iz))throw new RangeError('"invertedZ" expected valid field element');let{X,Y,Z}=p;if(Fp.eql(Z,Fp.ONE))return{x:X,y:Y};let is0=p.is0();iz==null&&(iz=is0?Fp.ONE:Fp.inv(Z));let x=Fp.mul(X,iz),y=Fp.mul(Y,iz),zz=Fp.mul(Z,iz);if(is0)return{x:Fp.ZERO,y:Fp.ZERO};if(!Fp.eql(zz,Fp.ONE))throw new Error("invZ was invalid");return{x,y}}isTorsionFree(){return cofactor===_1n16?!0:isTorsionFree?isTorsionFree(Point4,this):wnaf.mulUnsafe(this,CURVE_ORDER).is0()}clearCofactor(){return cofactor===_1n16?this:clearCofactor?clearCofactor(Point4,this):this.multiplyUnsafe(cofactor)}isSmallOrder(){return cofactor===_1n16?this.is0():this.clearCofactor().is0()}toBytes(isCompressed=!0){return abool3(isCompressed,"isCompressed"),this.assertValidity(),encodePoint(Point4,this,isCompressed)}toHex(isCompressed=!0){return bytesToHex5(this.toBytes(isCompressed))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let normalize4=points=>normalizeZ(Point4,points),wnaf=new ScalarMultiplier(Point4,randomBytes9);return wnaf.bits>=6&&Point4.BASE.precompute(6),Object.freeze(Point4.prototype),Object.freeze(Point4),Point4}function pprefix(hasEvenY){return Uint8Array.of(hasEvenY?2:3)}function getWLengths(Fp,Fn2){return{secretKey:Fn2.BYTES,publicKey:1+Fp.BYTES,publicKeyUncompressed:1+2*Fp.BYTES,publicKeyHasPrefix:!0,signature:2*Fn2.BYTES}}function ecdh(Point4,ecdhOpts={}){validatePointCons(Point4);let{Fn:Fn2}=Point4,randomBytes_=ecdhOpts.randomBytes===void 0?randomBytes5:ecdhOpts.randomBytes,lengths=Object.assign(getWLengths(Point4.Fp,Fn2),{seed:Math.max(getMinHashLength3(Fn2.ORDER),16)});function isValidSecretKey(secretKey){try{let num2=Fn2.fromBytes(secretKey);return Fn2.isValidNot0(num2)}catch{return!1}}function isValidPublicKey(publicKey,isCompressed){let{publicKey:comp,publicKeyUncompressed}=lengths;try{let l2=publicKey.length;return isCompressed===!0&&l2!==comp||isCompressed===!1&&l2!==publicKeyUncompressed?!1:!Point4.fromBytes(publicKey).is0()}catch{return!1}}function randomSecretKey(seed){return seed=seed===void 0?randomBytes_(lengths.seed):seed,mapHashToField3(abytes7(seed,lengths.seed,"seed"),Fn2.ORDER)}function getPublicKey(secretKey,isCompressed=!0){return Point4.BASE.multiply(Fn2.fromBytes(secretKey)).toBytes(isCompressed)}function isProbPub(item){let{secretKey,publicKey,publicKeyUncompressed}=lengths,allowedLengths=Fn2._lengths;if(!isBytes9(item))return;let l2=abytes7(item,void 0,"key").length,isPub=l2===publicKey||l2===publicKeyUncompressed,isSec=l2===secretKey||!!allowedLengths?.includes(l2);if(!(isPub&&isSec))return isPub}function getSharedSecret(secretKeyA,publicKeyB,isCompressed=!0){if(isProbPub(secretKeyA)===!0)throw new Error("first arg must be private key");if(isProbPub(publicKeyB)===!1)throw new Error("second arg must be public key");let s3=Fn2.fromBytes(secretKeyA),b=Point4.fromBytes(publicKeyB);if(b.is0())throw new Error("invalid public key: point at infinity");return b.multiply(s3).toBytes(isCompressed)}let utils2={isValidSecretKey,isValidPublicKey,randomSecretKey},keygen=createKeygen(randomSecretKey,getPublicKey);return Object.freeze(utils2),Object.freeze(lengths),Object.freeze({getPublicKey,getSharedSecret,keygen,Point:Point4,utils:utils2,lengths})}function ecdsa(Point4,hash8,ecdsaOpts={}){validatePointCons(Point4);let hash_=hash8;ahash4(hash_),validateObject3(ecdsaOpts,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let opts=Object.assign({},ecdsaOpts),randomBytes9=opts.randomBytes===void 0?randomBytes5:opts.randomBytes,hmac6=opts.hmac===void 0?(key3,msg)=>hmac4(hash_,key3,msg):opts.hmac,{Fp,Fn:Fn2}=Point4,{ORDER:CURVE_ORDER,BITS:fnBits}=Fn2,blindLength=getMinHashLength3(CURVE_ORDER),csprng=probeRandomBytes(randomBytes9,blindLength),{keygen,getPublicKey,getSharedSecret,utils:utils2,lengths}=ecdh(Point4,opts),defaultSigOpts={prehash:!0,lowS:typeof opts.lowS=="boolean"?opts.lowS:!0,format:"compact",extraEntropy:!1},hasLargeRecoveryLifts=CURVE_ORDER*_2n10+_1n16<Fp.ORDER;function isBiggerThanHalfOrder(number4){let HALF=CURVE_ORDER>>_1n16;return number4>HALF}function validateRS(title,num2){if(!Fn2.isValidNot0(num2))throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);return num2}function assertFieldSignIsSupported(){if(!Fp.isOdd)throw new Error("Field doesn't support isOdd")}function getRecoveryBit(x,y,r2){return assertFieldSignIsSupported(),(x===r2?0:2)|Number(Fp.isOdd(y))}function assertRecoverableCurve(){if(hasLargeRecoveryLifts)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function validateSigLength(bytes,format3){validateSigFormat(format3);let size4=lengths.signature,sizer=format3==="compact"?size4:format3==="recovered"?size4+1:void 0;return abytes7(bytes,sizer)}class Signature2{r;s;recovery;constructor(r2,s3,recovery){if(this.r=validateRS("r",r2),this.s=validateRS("s",s3),recovery!=null){if(assertRecoverableCurve(),![0,1,2,3].includes(recovery))throw new Error("invalid recovery id");this.recovery=recovery}Object.freeze(this)}static fromBytes(bytes,format3=defaultSigOpts.format){validateSigLength(bytes,format3);let recid;if(format3==="der"){if(bytes.length>2*Fn2.BYTES+16)throw new DER3.Err("invalid signature: DER signature too long");let{r:r3,s:s4}=DER3.toSig(abytes7(bytes),Fn2.BYTES+1);return new Signature2(r3,s4)}format3==="recovered"&&(recid=bytes[0],format3="compact",bytes=bytes.subarray(1));let L=lengths.signature/2,r2=bytes.subarray(0,L),s3=bytes.subarray(L,L*2);return new Signature2(Fn2.fromBytes(r2),Fn2.fromBytes(s3),recid)}static fromHex(hex3,format3){return this.fromBytes(hexToBytes5(hex3),format3)}assertRecovery(){let{recovery}=this;if(recovery==null)throw new Error("invalid recovery id: must be present");return recovery}addRecoveryBit(recovery){return new Signature2(this.r,this.s,recovery)}recoverPublicKey(messageHash){let{r:r2,s:s3}=this,recovery=this.assertRecovery(),radj=recovery===2||recovery===3?r2+CURVE_ORDER:r2;if(!Fp.isValid(radj))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let x=Fp.toBytes(radj),R=Point4.fromBytes(concatBytes7(pprefix((recovery&1)===0),x)),ir=Fn2.inv(radj),h=bits2int_modN(abytes7(messageHash,void 0,"msgHash")),u1=Fn2.create(-h*ir),u2=Fn2.create(s3*ir),Q=Point4.BASE.mulAddUnsafe(u1,R,u2);if(Q.is0())throw new Error("invalid recovery: point at infinify");return Q.assertValidity(),Q}hasHighS(){return isBiggerThanHalfOrder(this.s)}toBytes(format3=defaultSigOpts.format){if(validateSigFormat(format3),format3==="der")return hexToBytes5(DER3.hexFromSig(this));let{r:r2,s:s3}=this,rb=Fn2.toBytes(r2),sb=Fn2.toBytes(s3);return format3==="recovered"?(assertRecoverableCurve(),concatBytes7(Uint8Array.of(this.assertRecovery()),rb,sb)):concatBytes7(rb,sb)}toHex(format3){return bytesToHex5(this.toBytes(format3))}}Object.freeze(Signature2.prototype),Object.freeze(Signature2);let bits2int=opts.bits2int===void 0?function(bytes){if(bytes.length>8192)throw new Error("input is too large");let num2=bytesToNumberBE3(bytes),delta=bytes.length*8-fnBits;return delta>0?num2>>BigInt(delta):num2}:opts.bits2int,bits2int_modN=opts.bits2int_modN===void 0?function(bytes){return Fn2.create(bits2int(bytes))}:opts.bits2int_modN,ORDER_MASK=bitMask3(fnBits);function int2octets(num2){return aInRange3("num < 2^"+fnBits,num2,_0n17,ORDER_MASK),Fn2.toBytes(num2)}function validateMsgAndHash(message,prehash){return abytes7(message,void 0,"message"),prehash?abytes7(hash_(message),void 0,"prehashed message"):message}function prepSig(message,secretKey,opts2){let{lowS,prehash,extraEntropy:extraEntropy2}=validateSigOpts(opts2,defaultSigOpts);message=validateMsgAndHash(message,prehash);let h1int=bits2int_modN(message),d=Fn2.fromBytes(secretKey);if(!Fn2.isValidNot0(d))throw new Error("invalid private key");let seedArgs=[int2octets(d),int2octets(h1int)];if(extraEntropy2!=null&&extraEntropy2!==!1){let e7=extraEntropy2===!0?randomBytes9(lengths.secretKey):extraEntropy2;seedArgs.push(abytes7(e7,void 0,"extraEntropy"))}let seed=concatBytes7(...seedArgs),m=h1int;function k2sig(kBytes){let k=bits2int(kBytes);if(!Fn2.isValidNot0(k))return;let q=Point4.BASE.multiply(k).toAffine(),r2=Fn2.create(q.x);if(r2===_0n17)return;let s3;if(csprng!==void 0){let b=bytesToNumberBE3(mapHashToField3(csprng(blindLength),CURVE_ORDER)),ibk=Fn2.inv(Fn2.mul(b,k)),bm=Fn2.mul(b,m),bd=Fn2.mul(b,d);s3=Fn2.create(ibk*Fn2.create(bm+bd*r2))}else{let ik=invertCt(k,CURVE_ORDER);s3=Fn2.create(ik*Fn2.create(m+r2*d))}if(s3===_0n17)return;let recovery=getRecoveryBit(q.x,q.y,r2),normS=s3;return lowS&&isBiggerThanHalfOrder(s3)&&(normS=Fn2.neg(s3),recovery^=1),new Signature2(r2,normS,hasLargeRecoveryLifts?void 0:recovery)}return{seed,k2sig}}function sign5(message,secretKey,opts2={}){let{seed,k2sig}=prepSig(message,secretKey,opts2);return createHmacDrbg3(hash_.outputLen,Fn2.BYTES,hmac6)(seed,k2sig).toBytes(opts2.format)}function verify8(signature3,message,publicKey,opts2={}){let{lowS,prehash,format:format3}=validateSigOpts(opts2,defaultSigOpts);if(publicKey=abytes7(publicKey,void 0,"publicKey"),message=validateMsgAndHash(message,prehash),!isBytes9(signature3)){let end=signature3 instanceof Signature2?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+end)}validateSigLength(signature3,format3);try{let sig=Signature2.fromBytes(signature3,format3),P3=Point4.fromBytes(publicKey);if(P3.is0()||lowS&&sig.hasHighS())return!1;let{r:r2,s:s3}=sig,h=bits2int_modN(message),is=Fn2.inv(s3),u1=Fn2.create(h*is),u2=Fn2.create(r2*is),R=Point4.BASE.mulAddUnsafe(u1,P3,u2);if(R.is0())return!1;let q=R.toAffine();return!(Fn2.create(q.x)!==r2||format3==="recovered"&&sig.recovery!==getRecoveryBit(q.x,q.y,r2))}catch{return!1}}function recoverPublicKey4(signature3,message,opts2={}){let{prehash}=validateSigOpts(opts2,defaultSigOpts);return message=validateMsgAndHash(message,prehash),Signature2.fromBytes(signature3,"recovered").recoverPublicKey(message).toBytes()}return Object.freeze({keygen,getPublicKey,getSharedSecret,utils:utils2,lengths,Point:Point4,sign:sign5,verify:verify8,recoverPublicKey:recoverPublicKey4,Signature:Signature2,hash:hash_})}var divNearest3,_0n17,_1n16,_2n10,_3n6,_4n7,init_weierstrass3=__esm({"node_modules/@noble/curves/abstract/weierstrass.js"(){"use strict";init_hmac4();init_utils15();init_utils16();init_curve3();init_der();init_modular3();divNearest3=(num2,den)=>(num2+(num2>=0?den:-den)/_2n10)/den;_0n17=BigInt(0),_1n16=BigInt(1),_2n10=BigInt(2),_3n6=BigInt(3),_4n7=BigInt(4)}});function sqrtMod3(y){let P3=secp256k1_CURVE.p,_3n7=BigInt(3),_6n=BigInt(6),_11n=BigInt(11),_22n=BigInt(22),_23n=BigInt(23),_44n=BigInt(44),_88n=BigInt(88),b2=y*y*y%P3,b32=b2*b2*y%P3,b6=pow23(b32,_3n7,P3)*b32%P3,b9=pow23(b6,_3n7,P3)*b32%P3,b11=pow23(b9,_2n11,P3)*b2%P3,b22=pow23(b11,_11n,P3)*b11%P3,b44=pow23(b22,_22n,P3)*b22%P3,b88=pow23(b44,_44n,P3)*b44%P3,b176=pow23(b88,_88n,P3)*b88%P3,b220=pow23(b176,_44n,P3)*b44%P3,b223=pow23(b220,_3n7,P3)*b32%P3,t1=pow23(b223,_23n,P3)*b22%P3,t2=pow23(t1,_6n,P3)*b2%P3,root2=pow23(t2,_2n11,P3);if(!Fpk13.eql(Fpk13.sqr(root2),y))throw new Error("Cannot find square root");return root2}var secp256k1_CURVE,secp256k1_ENDO,_2n11,Fpk13,Pointk1,secp256k13,init_secp256k13=__esm({"node_modules/@noble/curves/secp256k1.js"(){"use strict";init_sha24();init_modular3();init_weierstrass3();secp256k1_CURVE={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},secp256k1_ENDO={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},_2n11=BigInt(2);Fpk13=Field3(secp256k1_CURVE.p,{sqrt:sqrtMod3}),Pointk1=weierstrass3(secp256k1_CURVE,{Fp:Fpk13,endo:secp256k1_ENDO}),secp256k13=ecdsa(Pointk1,sha2568)}});function ripemd_f2(group,x,y,z2){return group===0?x^y^z2:group===1?x&y|~x&z2:group===2?(x|~y)^z2:group===3?x&z2|y&~z2:x^(y|~z2)}var Rho1602,Id1602,Pi1602,idxLR2,idxL2,idxR2,shifts1602,shiftsL1602,shiftsR1602,Kl1602,Kr1602,BUF_1602,_RIPEMD160,ripemd1604,init_legacy2=__esm({"node_modules/@noble/hashes/legacy.js"(){"use strict";init_md4();init_utils15();Rho1602=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Id1602=Uint8Array.from(new Array(16).fill(0).map((_,i)=>i)),Pi1602=Id1602.map(i=>(9*i+5)%16),idxLR2=(()=>{let res=[[Id1602],[Pi1602]];for(let i=0;i<4;i++)for(let j of res)j.push(j[i].map(k=>Rho1602[k]));return res})(),idxL2=idxLR2[0],idxR2=idxLR2[1],shifts1602=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(i=>Uint8Array.from(i)),shiftsL1602=idxL2.map((idx,i)=>idx.map(j=>shifts1602[i][j])),shiftsR1602=idxR2.map((idx,i)=>idx.map(j=>shifts1602[i][j])),Kl1602=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Kr1602=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);BUF_1602=new Uint32Array(16),_RIPEMD160=class extends HashMD4{h0=1732584193;h1=-271733879;h2=-1732584194;h3=271733878;h4=-1009589776;constructor(){super(64,20,8,!0)}get(){let{h0,h1,h2,h3,h4}=this;return[h0,h1,h2,h3,h4]}set(h0,h1,h2,h3,h4){this.h0=h0|0,this.h1=h1|0,this.h2=h2|0,this.h3=h3|0,this.h4=h4|0}_cloneInto(to2){return(to2||=new this.constructor).set(...this.get()),this._cloneIntoMeta(to2)}process(view,offset){for(let i=0;i<16;i++,offset+=4)BUF_1602[i]=view.getUint32(offset,!0);let al=this.h0|0,ar=al,bl=this.h1|0,br=bl,cl=this.h2|0,cr=cl,dl=this.h3|0,dr=dl,el=this.h4|0,er=el;for(let group=0;group<5;group++){let rGroup=4-group,hbl=Kl1602[group],hbr=Kr1602[group],rl=idxL2[group],rr=idxR2[group],sl=shiftsL1602[group],sr=shiftsR1602[group];for(let i=0;i<16;i++){let tl=rotl2(al+ripemd_f2(group,bl,cl,dl)+BUF_1602[rl[i]]+hbl,sl[i])+el|0;al=el,el=dl,dl=rotl2(cl,10)|0,cl=bl,bl=tl}for(let i=0;i<16;i++){let tr=rotl2(ar+ripemd_f2(rGroup,br,cr,dr)+BUF_1602[rr[i]]+hbr,sr[i])+er|0;ar=er,er=dr,dr=rotl2(cr,10)|0,cr=br,br=tr}}this.set(this.h1+cl+dr|0,this.h2+dl+er|0,this.h3+el+ar|0,this.h4+al+br|0,this.h0+bl+cr|0)}roundClean(){clean4(BUF_1602)}destroy(){this.destroyed=!0,clean4(this.buffer),this.set(0,0,0,0,0)}},ripemd1604=createHasher5(()=>new _RIPEMD160)}});function isBytes10(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in a&&a.BYTES_PER_ELEMENT===1}function abytes8(b){if(!isBytes10(b))throw new TypeError("Uint8Array expected")}function afn2(input2){if(typeof input2!="function")throw new TypeError("function expected");return!0}function astr2(label,input2){if(typeof input2!="string")throw new TypeError(`${label}: string expected`);return!0}function anumber7(n,title="number"){if(typeof n!="number")throw new TypeError(`${title}: expected number, got ${typeof n}`);if(!Number.isSafeInteger(n))throw new RangeError(`${title}: expected safe integer, got ${n}`)}function chain2(...args){let id2=a=>a,wrap3=(a,b)=>c=>a(b(c)),encode12=args.map(x=>x.encode).reduceRight(wrap3,id2),decode8=args.map(x=>x.decode).reduce(wrap3,id2);return{encode:encode12,decode:decode8}}function charcodesToString(codes){let len=codes.length;if(asciiDecoder!==void 0&&len>=12)return asciiDecoder.decode(codes);if(len<=B2S_CHUNK)return String.fromCharCode.apply(null,codes);let res="";for(let i=0;i<len;i+=B2S_CHUNK)res+=String.fromCharCode.apply(null,codes.subarray(i,i+B2S_CHUNK));return res}function alphabet2(letters,aliases){let len=letters.length;if(len>128)throw new Error("alphabet: max 128 letters");let encTable=new Uint8Array(len),decTable=new Int8Array(128).fill(-1);for(let i=0;i<len;i++){let code=letters.charCodeAt(i);if(letters.codePointAt(i)!==code||code>127)throw new Error("alphabet: single-char ASCII letters only");encTable[i]=code,decTable[code]=i}if(aliases!==void 0)for(let alias of Object.keys(aliases)){let code=alias.charCodeAt(0),target=decTable[aliases[alias].charCodeAt(0)];if(alias.length!==1||code>127||target===void 0||target===-1)throw new Error(`alphabet: invalid alias ${alias}`);decTable[code]=target}return{encode:digits=>{let codes=new Uint8Array(digits.length);for(let i=0;i<digits.length;i++){let d=digits[i],code=encTable[d];if(code===void 0)throw new Error(`alphabet.encode: invalid digit ${d}`);codes[i]=code}return charcodesToString(codes)},decode:input2=>{astr2("decode",input2);let slen=input2.length,digits=new Uint8Array(slen);for(let i=0;i<slen;i++){let code=input2.charCodeAt(i),digit=code<128?decTable[code]:-1;if(digit===-1)throw new Error(`Unknown letter "${input2[i]}". Allowed: ${letters}`);digits[i]=digit}return digits}}}function checksum4(len,fn){if(anumber7(len),len<=0)throw new RangeError(`checksum length must be positive: ${len}`);afn2(fn);let _fn=fn;return{encode(data){abytes8(data);let sum=_fn(data).slice(0,len),res=new Uint8Array(data.length+len);return res.set(data),res.set(sum,data.length),res},decode(data){abytes8(data);let payload=data.slice(0,-len),oldChecksum=data.slice(-len),newChecksum=_fn(payload).slice(0,len);for(let i=0;i<len;i++)if(newChecksum[i]!==oldChecksum[i])throw new Error("Invalid checksum");return payload}}}var freeze,asciiDecoder,B2S_CHUNK,B58_GROUP,RADIX_BASE_N_MAX_LENGTH,BASE_N_MAX_BYTES,BASE_N_MAX_CHARS,radixBaseN,genBaseN,radix58,genBase58,base58,createBase58check,init_base3=__esm({"node_modules/@scure/base/index.js"(){"use strict";freeze=fn=>Object.freeze(fn());asciiDecoder=(()=>{try{let decoder3=new TextDecoder;return decoder3.decode(Uint8Array.of(65,48,43,127))==="A0+\x7F"?decoder3:void 0}catch{return}})(),B2S_CHUNK=8192;B58_GROUP=656356768,RADIX_BASE_N_MAX_LENGTH=65536,BASE_N_MAX_BYTES=2048,BASE_N_MAX_CHARS=4096,radixBaseN=(BASE,GROUP)=>({encode:bytes=>{abytes8(bytes);let blen=bytes.length;if(blen===0)return new Uint8Array(0);if(blen>=RADIX_BASE_N_MAX_LENGTH)throw new Error("invalid length");let zeros2=0;for(;zeros2<blen-1&&bytes[zeros2]===0;)zeros2++;let nlimbs=Math.ceil(blen/2),limbs=new Uint16Array(nlimbs),odd=blen&1;odd&&(limbs[0]=bytes[0]);for(let i=odd,j2=odd;i<blen;i+=2,j2++)limbs[j2]=bytes[i]<<8|bytes[i+1];let groups=[],pos=0;for(;pos<nlimbs;){let carry2=0;for(let i=pos;i<nlimbs;i++){let cur=carry2*65536+limbs[i],q=Math.floor(cur/GROUP);carry2=cur-q*GROUP,limbs[i]=q,q===0&&i===pos&&pos++}groups.push(carry2)}let top=groups.length-1,sig=top*5;for(let v=groups[top];sig++,!(v<BASE);v=Math.floor(v/BASE));let res=new Uint8Array(zeros2+sig),j=res.length-1;for(let g=0;g<top;g++){let v=groups[g];for(let k=0;k<5;k++)res[j--]=v%BASE,v=Math.floor(v/BASE)}for(let v=groups[top];j>=zeros2;v=Math.floor(v/BASE))res[j--]=v%BASE;return res},decode:digits=>{abytes8(digits);let dlen=digits.length;if(dlen===0)return new Uint8Array(0);if(dlen>=RADIX_BASE_N_MAX_LENGTH)throw new Error("invalid length");let zeros2=0;for(;zeros2<dlen-1&&digits[zeros2]===0;)zeros2++;let limbs=new Uint16Array(Math.ceil(dlen*6/16)+1),used=0,i=0,group=dlen%5||5;for(;i<dlen;){let gval=0,factor=1;for(let end=i+group;i<end;i++){let d=digits[i];if(d>=BASE)throw new Error(`invalid integer: ${d}`);gval=gval*BASE+d,factor*=BASE}group=5;let carry2=gval;for(let k=0;k<used;k++){let cur=limbs[k]*factor+carry2;carry2=Math.floor(cur/65536),limbs[k]=cur-carry2*65536}for(;carry2>0;carry2=Math.floor(carry2/65536))limbs[used++]=carry2%65536}let valueBytes=used===0?1:used*2-(limbs[used-1]<256?1:0),res=new Uint8Array(zeros2+valueBytes),j=res.length-1;for(let k=0;k<used;k++){let limb=limbs[k];res[j--]=limb&255,j>=zeros2&&(res[j--]=limb>>8)}return res}}),genBaseN=(radix3,abc)=>{let letters=alphabet2(abc);return{encode(bytes){if(abytes8(bytes),bytes.length>BASE_N_MAX_BYTES)throw new Error("invalid length");return letters.encode(radix3.encode(bytes))},decode(str){if(astr2("baseN.decode",str),str.length>BASE_N_MAX_CHARS)throw new Error("invalid length");return radix3.decode(letters.decode(str))}}},radix58=radixBaseN(58,B58_GROUP),genBase58=abc=>genBaseN(radix58,abc),base58=freeze(()=>genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),createBase58check=sha25613=>{afn2(sha25613);let _sha256=sha25613;return chain2(checksum4(4,data=>_sha256(_sha256(data))),base58)}}});var Point2,Fn,base58check,MASTER_SECRET,BITCOIN_VERSIONS,HARDENED_OFFSET,MAX_DEPTH,hash160,fromU32,toU32,validateVersions,HDKey,init_bip32=__esm({"node_modules/@scure/bip32/index.js"(){"use strict";init_secp256k13();init_hmac4();init_legacy2();init_sha24();init_utils15();init_base3();Point2=secp256k13.Point,Fn=Point2.Fn,base58check=createBase58check(sha2568),MASTER_SECRET=Uint8Array.from("Bitcoin seed".split(""),char=>char.charCodeAt(0)),BITCOIN_VERSIONS={private:76066276,public:76067358},HARDENED_OFFSET=2147483648,MAX_DEPTH=255,hash160=data=>ripemd1604(sha2568(data)),fromU32=data=>createView4(data).getUint32(0,!1),toU32=(n,title="number")=>{if(typeof n!="number")throw new TypeError(`"${title}" expected number, got type=${typeof n}`);if(!Number.isSafeInteger(n)||n<0||n>2**32-1)throw new RangeError(`"${title}" expected integer in range 0..2**32-1, got ${n}`);let buf=new Uint8Array(4);return createView4(buf).setUint32(0,n,!1),buf},validateVersions=(versions,title="versions")=>{if(!(typeof versions=="object"&&versions!==null))throw new Error("versions must be an object");return toU32(versions.private,`${title}.private`),toU32(versions.public,`${title}.public`),versions},HDKey=class _HDKey{get fingerprint(){if(!this._pubHash)throw new Error("No publicKey set!");return fromU32(this._pubHash)}get identifier(){return this._pubHash?Uint8Array.from(this._pubHash):void 0}get pubKeyHash(){return this._pubHash?Uint8Array.from(this._pubHash):void 0}get privateKey(){return this._privateKey?Uint8Array.from(this._privateKey):null}get publicKey(){return this._publicKey?Uint8Array.from(this._publicKey):null}get chainCode(){return this._chainCode?Uint8Array.from(this._chainCode):null}get privateExtendedKey(){let priv=this._privateKey;if(!priv)throw new Error("No private key");return base58check.encode(this.serialize(this.versions.private,concatBytes6(Uint8Array.of(0),priv)))}get publicExtendedKey(){if(!this._publicKey)throw new Error("No public key");return base58check.encode(this.serialize(this.versions.public,this._publicKey))}static fromMasterSeed(seed,versions=BITCOIN_VERSIONS){if(abytes6(seed),versions=validateVersions(versions),8*seed.length<128||8*seed.length>512)throw new RangeError("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got "+seed.length);let I=hmac4(sha5123,MASTER_SECRET,seed),privateKey=I.slice(0,32),chainCode=I.slice(32);return new _HDKey({versions,chainCode,privateKey})}static fromExtendedKey(base58key,versions=BITCOIN_VERSIONS){versions=validateVersions(versions);let keyBuffer=base58check.decode(base58key);if(keyBuffer.length!==78)throw new Error(`HDKey: invalid extended key length: expected 78 bytes, got ${keyBuffer.length}`);let keyView=createView4(keyBuffer),version31=keyView.getUint32(0,!1),opt={versions,depth:keyBuffer[4],parentFingerprint:keyView.getUint32(5,!1),index:keyView.getUint32(9,!1),chainCode:keyBuffer.slice(13,45)},key3=keyBuffer.slice(45),isPriv=key3[0]===0;if(version31!==versions[isPriv?"private":"public"])throw new Error("Version mismatch");return isPriv?new _HDKey({...opt,privateKey:key3.slice(1)}):new _HDKey({...opt,publicKey:key3})}static fromJSON(json2){return _HDKey.fromExtendedKey("xpriv"in json2?json2.xpriv:json2.xpub)}versions;depth=0;index=0;parentFingerprint=0;_chainCode=null;_privateKey;_publicKey;_pubHash;constructor(opt){if(!opt||typeof opt!="object")throw new Error("HDKey.constructor must not be called directly");let depth=opt.depth??0,index2=opt.index??0,parentFingerprint=opt.parentFingerprint??0;if(!Number.isSafeInteger(depth)||depth<0||depth>MAX_DEPTH)throw new RangeError("HDKey: depth must be an integer in range 0..255");if(toU32(index2,"index"),toU32(parentFingerprint,"parentFingerprint"),depth===0&&(index2!==0||parentFingerprint!==0))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");if(this.versions=opt.versions?validateVersions(opt.versions):BITCOIN_VERSIONS,this.depth=depth,opt.chainCode&&abytes6(opt.chainCode,32),this._chainCode=opt.chainCode?Uint8Array.from(opt.chainCode):null,this.index=index2,this.parentFingerprint=parentFingerprint,opt.publicKey&&opt.privateKey)throw new Error("HDKey: publicKey and privateKey at same time.");if(opt.privateKey){if(!secp256k13.utils.isValidSecretKey(opt.privateKey))throw new Error("Invalid private key");this._privateKey=Uint8Array.from(opt.privateKey),this._publicKey=secp256k13.getPublicKey(this._privateKey,!0)}else if(opt.publicKey)this._publicKey=Point2.fromBytes(opt.publicKey).toBytes(!0);else throw new Error("HDKey: no public or private key provided");this._pubHash=hash160(this._publicKey)}derive(path8){if(!/^[mM]'?/.test(path8))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(path8))return this;let parts=path8.replace(/^[mM]'?\//,"").split("/");if(parts.length>MAX_DEPTH-this.depth)throw new Error("HDKey: path exceeds the serializable depth 255");let child=this;for(let c of parts){let m=/^(\d+)('?)$/.exec(c),m1=m&&m[1];if(!m||m.length!==3||typeof m1!="string")throw new Error("invalid child index: "+c);let idx=+m1;if(!Number.isSafeInteger(idx)||idx>=HARDENED_OFFSET)throw new Error("Invalid index");m[2]==="'"&&(idx+=HARDENED_OFFSET),child=child.deriveChild(idx)}return child}deriveChild(index2){return this._deriveChild(index2)}_deriveChild(index2,_I){if(!this._publicKey||!this._chainCode)throw new Error("No publicKey or chainCode set");let data=toU32(index2,"index");if(index2>=HARDENED_OFFSET){let priv=this._privateKey;if(!priv)throw new Error("Could not derive hardened child key");data=concatBytes6(Uint8Array.of(0),priv,data)}else data=concatBytes6(this._publicKey,data);let out=_I||hmac4(sha5123,this._chainCode,data);abytes6(out,64);let childTweak=out.slice(0,32),chainCode=out.slice(32),opt={versions:this.versions,chainCode,depth:this.depth+1,parentFingerprint:this.fingerprint,index:index2};if(opt.depth>MAX_DEPTH)throw new Error("HDKey: depth exceeds the serializable value 255");let retry=()=>{let maxIndex=this._privateKey?4294967295:HARDENED_OFFSET-1;if(index2>=maxIndex)throw new Error(`HDKey: cannot retry child derivation at index ${index2}`);return this.deriveChild(index2+1)},ctweak=Fn.fromBytes(childTweak,!0);if(!Fn.isValid(ctweak))return retry();if(this._privateKey){let added=Fn.create(Fn.fromBytes(this._privateKey)+ctweak);if(!Fn.isValidNot0(added))return retry();opt.privateKey=Fn.toBytes(added)}else{let point3=Point2.fromBytes(this._publicKey),added=ctweak===0n?point3:point3.add(Point2.BASE.multiply(ctweak));if(added.equals(Point2.ZERO))return retry();opt.publicKey=added.toBytes(!0)}return new _HDKey(opt)}sign(hash8){if(!this._privateKey)throw new Error("No privateKey set!");return abytes6(hash8,32),secp256k13.sign(hash8,this._privateKey,{prehash:!1})}verify(hash8,signature3){if(abytes6(hash8,32),abytes6(signature3,64),!this._publicKey)throw new Error("No publicKey set!");return secp256k13.verify(signature3,hash8,this._publicKey,{prehash:!1})}wipePrivateData(){return this._privateKey&&(this._privateKey.fill(0),this._privateKey=void 0),this}toJSON(){return this.toPrivateJSON()}toPrivateJSON(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}}serialize(version31,key3){if(!this._chainCode)throw new Error("No chainCode set");return abytes6(key3,33),concatBytes6(toU32(version31,"version"),new Uint8Array([this.depth]),toU32(this.parentFingerprint,"parentFingerprint"),toU32(this.index,"index"),this._chainCode,key3)}}}});function deriveSolanaKeyBytes(mnemonic){let seed=mnemonicToSeedSync(mnemonic),digest=hmac4(sha5123,new TextEncoder().encode("ed25519 seed"),seed),key3=digest.slice(0,32),chainCode=digest.slice(32);for(let index2 of SOLANA_HARDENED_INDICES){let data=new Uint8Array(37);data[0]=0,data.set(key3,1),data[33]=index2>>>24&255,data[34]=index2>>>16&255,data[35]=index2>>>8&255,data[36]=index2&255,digest=hmac4(sha5123,chainCode,data),key3=digest.slice(0,32),chainCode=digest.slice(32)}return new Uint8Array(key3)}var SOLANA_HARDENED_INDICES,init_solana_key=__esm({"src/solana-key.ts"(){"use strict";init_hmac4();init_sha24();init_esm3();SOLANA_HARDENED_INDICES=[2147483692,2147484149,2147483648,2147483648]}});function encodeValue(value){return Array.isArray(value)?"%5B"+value.map(encodeValue).join("%2C%20")+"%5D":typeof value=="bigint"?`${value}n`:encodeURIComponent(String(value!=null&&Object.getPrototypeOf(value)===null?{...value}:value))}function encodeObjectContextEntry([key3,value]){return`${key3}=${encodeValue(value)}`}function encodeContextObject(context){let searchParamsString=Object.entries(context).map(encodeObjectContextEntry).join("&");return Buffer.from(searchParamsString,"utf8").toString("base64")}function getHumanReadableErrorMessage(code,context={}){let messageFormatString=SolanaErrorMessages[code];if(messageFormatString.length===0)return"";let state;function commitStateUpTo(endIndex){if(state[TYPE]===2){let variableName=messageFormatString.slice(state[START_INDEX]+1,endIndex);fragments.push(variableName in context?`${context[variableName]}`:`$${variableName}`)}else state[TYPE]===1&&fragments.push(messageFormatString.slice(state[START_INDEX],endIndex))}let fragments=[];messageFormatString.split("").forEach((char,ii)=>{if(ii===0){state={[START_INDEX]:0,[TYPE]:messageFormatString[0]==="\\"?0:messageFormatString[0]==="$"?2:1};return}let nextState;switch(state[TYPE]){case 0:nextState={[START_INDEX]:ii,[TYPE]:1};break;case 1:char==="\\"?nextState={[START_INDEX]:ii,[TYPE]:0}:char==="$"&&(nextState={[START_INDEX]:ii,[TYPE]:2});break;case 2:char==="\\"?nextState={[START_INDEX]:ii,[TYPE]:0}:char==="$"?nextState={[START_INDEX]:ii,[TYPE]:2}:char.match(/\w/)||(nextState={[START_INDEX]:ii,[TYPE]:1});break}nextState&&(state!==nextState&&commitStateUpTo(ii),state=nextState)}),commitStateUpTo();let message=fragments.join("");return code>=SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN&&code<SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN+INSTRUCTION_ERROR_RANGE_SIZE&&"index"in context&&(message+=` (instruction #${context.index+1})`),message}function getErrorMessage(code,context={}){if(process.env.NODE_ENV!=="production")return getHumanReadableErrorMessage(code,context);{let decodingAdviceMessage=`Solana error #${code}; Decode this error by running \`npx @solana/errors decode -- ${code}`;return Object.keys(context).length&&(decodingAdviceMessage+=` '${encodeContextObject(context)}'`),`${decodingAdviceMessage}\``}}function isSolanaError(e7,code){return e7 instanceof Error&&e7.name==="SolanaError"?code!==void 0?e7.context.__code===code:!0:!1}function safeCaptureStackTrace(...args){"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...args)}function getSolanaErrorFromRpcError({errorCodeBaseOffset,getErrorContext,orderedErrorNames,rpcEnumError},constructorOpt){let rpcErrorName,rpcErrorContext;typeof rpcEnumError=="string"?rpcErrorName=rpcEnumError:(rpcErrorName=Object.keys(rpcEnumError)[0],rpcErrorContext=rpcEnumError[rpcErrorName]);let codeOffset=orderedErrorNames.indexOf(rpcErrorName),errorCode=errorCodeBaseOffset+codeOffset,errorContext=getErrorContext(errorCode,rpcErrorName,rpcErrorContext),err=new SolanaError(errorCode,errorContext);return safeCaptureStackTrace(err,constructorOpt),err}function getSolanaErrorFromInstructionError(index2,instructionError){let numberIndex=Number(index2);return getSolanaErrorFromRpcError({errorCodeBaseOffset:4615001,getErrorContext(errorCode,rpcErrorName,rpcErrorContext){return errorCode===SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN?{errorName:rpcErrorName,index:numberIndex,...rpcErrorContext!==void 0?{instructionErrorContext:rpcErrorContext}:null}:errorCode===SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM?{code:Number(rpcErrorContext),index:numberIndex}:{index:numberIndex}},orderedErrorNames:ORDERED_ERROR_NAMES,rpcEnumError:instructionError},getSolanaErrorFromInstructionError)}function getSolanaErrorFromTransactionError(transactionError){return typeof transactionError=="object"&&"InstructionError"in transactionError?getSolanaErrorFromInstructionError(...transactionError.InstructionError):getSolanaErrorFromRpcError({errorCodeBaseOffset:7050001,getErrorContext(errorCode,rpcErrorName,rpcErrorContext){if(errorCode===SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN)return{errorName:rpcErrorName,...rpcErrorContext!==void 0?{transactionErrorContext:rpcErrorContext}:null};if(errorCode===SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION)return{index:Number(rpcErrorContext)};if(errorCode===SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT||errorCode===SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED)return{accountIndex:Number(rpcErrorContext.account_index)}},orderedErrorNames:ORDERED_ERROR_NAMES2,rpcEnumError:transactionError},getSolanaErrorFromTransactionError)}function getSolanaErrorFromJsonRpcError(putativeErrorResponse){let out;if(isRpcErrorResponse(putativeErrorResponse)){let{code:rawCode,data,message}=putativeErrorResponse,code=Number(rawCode);if(code===SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE){let{err,...preflightErrorContext}=data,causeObject=err?{cause:getSolanaErrorFromTransactionError(err)}:null;out=new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,{...preflightErrorContext,...causeObject})}else{let errorContext;switch(code){case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR:case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS:case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST:case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND:case SOLANA_ERROR__JSON_RPC__PARSE_ERROR:case SOLANA_ERROR__JSON_RPC__SCAN_ERROR:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:errorContext={__serverMessage:message};break;default:typeof data=="object"&&!Array.isArray(data)&&(errorContext=data)}out=new SolanaError(code,errorContext)}}else{let message=typeof putativeErrorResponse=="object"&&putativeErrorResponse!==null&&"message"in putativeErrorResponse&&typeof putativeErrorResponse.message=="string"?putativeErrorResponse.message:"Malformed JSON-RPC error with no message attribute";out=new SolanaError(SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,{error:putativeErrorResponse,message})}return safeCaptureStackTrace(out,getSolanaErrorFromJsonRpcError),out}function isRpcErrorResponse(value){return typeof value=="object"&&value!==null&&"code"in value&&"message"in value&&(typeof value.code=="number"||typeof value.code=="bigint")&&typeof value.message=="string"}function unwrapSimulationError(error62){let simulationCodes=[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS];return isSolanaError(error62)&&error62.cause&&simulationCodes.includes(error62.context.__code)?error62.cause:error62}var SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,SOLANA_ERROR__INVALID_NONCE,SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE,SOLANA_ERROR__MALFORMED_BIGINT_STRING,SOLANA_ERROR__MALFORMED_NUMBER_STRING,SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION,SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS,SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION,SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS,SOLANA_ERROR__JSON_RPC__PARSE_ERROR,SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SLOT_HISTORY,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH,SOLANA_ERROR__JSON_RPC__SCAN_ERROR,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY,SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS,SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED,SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX,SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT,SOLANA_ERROR__KEYS__VERIFICATION_REQUIRES_EXTRACTABLE_PUBLIC_KEY,SOLANA_ERROR__FS__UNSUPPORTED_ENVIRONMENT,SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED,SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION,SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE,SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,SOLANA_ERROR__OFFCHAIN_MESSAGE__CONTENT_DOES_NOT_MATCH_EXPECTED,SOLANA_ERROR__OFFCHAIN_MESSAGE__REQUIRED_SIGNATORIES_DO_NOT_MATCH_EXPECTED,SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING,SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE,SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES,SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,SOLANA_ERROR__TRANSACTION__MALFORMED_MESSAGE_BYTES,SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_MESSAGE_BYTES,SOLANA_ERROR__TRANSACTION__CANNOT_DECODE_EMPTY_TRANSACTION_BYTES,SOLANA_ERROR__TRANSACTION__VERSION_ZERO_MUST_BE_ENCODED_WITH_SIGNATURES_FIRST,SOLANA_ERROR__TRANSACTION__SIGNATURE_COUNT_TOO_HIGH_FOR_TRANSACTION_BYTES,SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_ACCOUNT_INDEX,SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_VALUE_KIND,SOLANA_ERROR__TRANSACTION__INSTRUCTION_HEADERS_PAYLOADS_MISMATCH,SOLANA_ERROR__TRANSACTION__TOO_MANY_SIGNER_ADDRESSES,SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNT_ADDRESSES,SOLANA_ERROR__TRANSACTION__TOO_MANY_INSTRUCTIONS,SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNTS_IN_INSTRUCTION,SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_LOADED_ACCOUNTS_DATA_SIZE_LIMIT,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_ACCOUNT_INDEX_OUT_OF_RANGE,SOLANA_ERROR__TRANSACTION__COMPUTE_UNIT_LIMIT_OUT_OF_RANGE,SOLANA_ERROR__TRANSACTION__INVALID_HEAP_SIZE,SOLANA_ERROR__TRANSACTION_INTROSPECTION__CANNOT_DECODE_JSON_PARSED_TRANSACTION,SOLANA_ERROR__TRANSACTION_INTROSPECTION__UNRECOGNIZED_GET_TRANSACTION_RESPONSE,SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND,SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND,SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE,SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED,SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND,SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP,SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX,SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION,SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE,SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS,SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT,SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED,SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED,SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,SOLANA_ERROR__INSTRUCTION_PLANS__MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED,SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_REJECTED_BY_PACKER,SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,SOLANA_ERROR__CODECS__INVALID_CONSTANT,SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE,SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES,SOLANA_ERROR__CODECS__INVALID_UTF8_BYTES,SOLANA_ERROR__CODECS__INVALID_UTF8_STRING,SOLANA_ERROR__CODECS__SENTINEL_MISSING_AT_END_OF_BYTES,SOLANA_ERROR__CODECS__SENTINEL_MUST_NOT_BE_EMPTY,SOLANA_ERROR__CODECS__UNEXPECTED_ZERO_FIXED_SIZE_ITEM_FOR_ARRAY_LIKE_SIZE_STRATEGY,SOLANA_ERROR__FIXED_POINTS__INVALID_TOTAL_BITS,SOLANA_ERROR__FIXED_POINTS__INVALID_FRACTIONAL_BITS,SOLANA_ERROR__FIXED_POINTS__INVALID_DECIMALS,SOLANA_ERROR__FIXED_POINTS__FRACTIONAL_BITS_EXCEED_TOTAL_BITS,SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE,SOLANA_ERROR__FIXED_POINTS__INVALID_STRING,SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO,SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW,SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH,SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO,SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS,SOLANA_ERROR__FIXED_POINTS__MALFORMED_RAW_VALUE,SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED,SOLANA_ERROR__RPC__INTEGER_OVERFLOW,SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED,SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR,SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE,SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION,SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE,SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL,SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_ACCOUNT_TYPE,SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_SIGNER,SOLANA_ERROR__WALLET__NOT_CONNECTED,SOLANA_ERROR__WALLET__NO_SIGNER_CONNECTED,SOLANA_ERROR__WALLET__SIGNER_NOT_AVAILABLE,SOLANA_ERROR__WALLET__ACCOUNT_NOT_AVAILABLE,SOLANA_ERROR__WALLET__INVALID_MESSAGE_SIGNATURE,SOLANA_ERROR__WALLET__INVALID_SIGN_IN_OUTPUT,SOLANA_ERROR__WALLET__INVALID_NUMBER_OF_OUTPUTS,SOLANA_ERROR__WALLET__FEATURE_VERSION_UNSUPPORTED,SOLANA_ERROR__REACT__MISSING_PROVIDER,SOLANA_ERROR__REACT__MISSING_CAPABILITY,SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR,SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,SolanaErrorMessages,INSTRUCTION_ERROR_RANGE_SIZE,START_INDEX,TYPE,SolanaError,ORDERED_ERROR_NAMES,ORDERED_ERROR_NAMES2,init_index_node=__esm({"node_modules/@solana/errors/dist/index.node.mjs"(){"use strict";SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED=1,SOLANA_ERROR__INVALID_NONCE=2,SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND=3,SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE=4,SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH=5,SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE=6,SOLANA_ERROR__MALFORMED_BIGINT_STRING=7,SOLANA_ERROR__MALFORMED_NUMBER_STRING=8,SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE=9,SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR=10,SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION=11,SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS=12,SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION=13,SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS=14,SOLANA_ERROR__JSON_RPC__PARSE_ERROR=-32700,SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR=-32603,SOLANA_ERROR__JSON_RPC__INVALID_PARAMS=-32602,SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND=-32601,SOLANA_ERROR__JSON_RPC__INVALID_REQUEST=-32600,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SLOT_HISTORY=-32021,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND=-32020,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE=-32019,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY=-32018,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE=-32017,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED=-32016,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION=-32015,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET=-32014,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH=-32013,SOLANA_ERROR__JSON_RPC__SCAN_ERROR=-32012,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE=-32011,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX=-32010,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED=-32009,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT=-32008,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED=-32007,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE=-32006,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY=-32005,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE=-32004,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE=-32003,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE=-32002,SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP=-32001,SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH=28e5,SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE=2800001,SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS=2800002,SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY=2800003,SOLANA_ERROR__ADDRESSES__MALFORMED_PDA=2800004,SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE=2800005,SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED=2800006,SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED=2800007,SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE=2800008,SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED=2800009,SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER=2800010,SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS=2800011,SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND=323e4,SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND=32300001,SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT=3230002,SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT=3230003,SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED=3230004,SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT=361e4,SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED=3610001,SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED=3610002,SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED=3610003,SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED=3610004,SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED=3610005,SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED=3610006,SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY=3610007,SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED=3611e3,SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH=3704e3,SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH=3704001,SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH=3704002,SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE=3704003,SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY=3704004,SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX=3704005,SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT=3704006,SOLANA_ERROR__KEYS__VERIFICATION_REQUIRES_EXTRACTABLE_PUBLIC_KEY=3704007,SOLANA_ERROR__FS__UNSUPPORTED_ENVIRONMENT=3712e3,SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS=4128e3,SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA=4128001,SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH=4128002,SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN=4615e3,SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR=4615001,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT=4615002,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA=4615003,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA=4615004,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL=4615005,SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS=4615006,SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID=4615007,SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE=4615008,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED=4615009,SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT=4615010,SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION=4615011,SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID=4615012,SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND=4615013,SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED=4615014,SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE=4615015,SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED=4615016,SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX=4615017,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED=4615018,SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED=4615019,SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS=4615020,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED=4615021,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE=4615022,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED=4615023,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING=4615024,SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC=4615025,SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM=4615026,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR=4615027,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED=4615028,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE=4615029,SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT=4615030,SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID=4615031,SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH=4615032,SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT=4615033,SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED=4615034,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED=4615035,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS=4615036,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC=4615037,SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED=4615038,SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION=4615039,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE=4615040,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE=4615041,SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE=4615042,SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE=4615043,SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY=4615044,SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR=4615045,SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT=4615046,SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER=4615047,SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW=4615048,SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR=4615049,SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER=4615050,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED=4615051,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED=4615052,SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED=4615053,SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS=4615054,SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS=5508e3,SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER=5508001,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER=5508002,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER=5508003,SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER=5508004,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER=5508005,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER=5508006,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER=5508007,SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER=5508008,SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS=5508009,SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING=5508010,SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED=5508011,SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION=5508012,SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED=5607e3,SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE=5607001,SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE=5607002,SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH=5607003,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH=5607004,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO=5607005,SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED=5607006,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH=5607007,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH=5607008,SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY=5607009,SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO=5607010,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING=5607011,SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH=5607012,SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE=5607013,SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION=5607014,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED=5607015,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE=5607016,SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE=5607017,SOLANA_ERROR__OFFCHAIN_MESSAGE__CONTENT_DOES_NOT_MATCH_EXPECTED=5607018,SOLANA_ERROR__OFFCHAIN_MESSAGE__REQUIRED_SIGNATORIES_DO_NOT_MATCH_EXPECTED=5607019,SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES=5663e3,SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE=5663001,SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME=5663002,SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME=5663003,SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE=5663004,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING=5663005,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE=5663006,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND=5663007,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING=5663008,SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING=5663009,SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING=5663010,SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING=5663011,SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING=5663012,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING=5663013,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE=5663014,SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION=5663015,SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES=5663016,SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH=5663017,SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT=5663018,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT=5663019,SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT=5663020,SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED=5663021,SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE=5663022,SOLANA_ERROR__TRANSACTION__MALFORMED_MESSAGE_BYTES=5663023,SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_MESSAGE_BYTES=5663024,SOLANA_ERROR__TRANSACTION__CANNOT_DECODE_EMPTY_TRANSACTION_BYTES=5663025,SOLANA_ERROR__TRANSACTION__VERSION_ZERO_MUST_BE_ENCODED_WITH_SIGNATURES_FIRST=5663026,SOLANA_ERROR__TRANSACTION__SIGNATURE_COUNT_TOO_HIGH_FOR_TRANSACTION_BYTES=5663027,SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_MASK_PRIORITY_FEE_BITS=5663028,SOLANA_ERROR__TRANSACTION__INVALID_NONCE_ACCOUNT_INDEX=5663029,SOLANA_ERROR__TRANSACTION__INVALID_CONFIG_VALUE_KIND=5663030,SOLANA_ERROR__TRANSACTION__INSTRUCTION_HEADERS_PAYLOADS_MISMATCH=5663031,SOLANA_ERROR__TRANSACTION__TOO_MANY_SIGNER_ADDRESSES=5663032,SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNT_ADDRESSES=5663033,SOLANA_ERROR__TRANSACTION__TOO_MANY_INSTRUCTIONS=5663034,SOLANA_ERROR__TRANSACTION__TOO_MANY_ACCOUNTS_IN_INSTRUCTION=5663035,SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_LOADED_ACCOUNTS_DATA_SIZE_LIMIT=5663036,SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_RESOURCE_LIMITS=5663037,SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_ACCOUNT_INDEX_OUT_OF_RANGE=5663038,SOLANA_ERROR__TRANSACTION__COMPUTE_UNIT_LIMIT_OUT_OF_RANGE=5663039,SOLANA_ERROR__TRANSACTION__INVALID_HEAP_SIZE=5663040,SOLANA_ERROR__TRANSACTION_INTROSPECTION__CANNOT_DECODE_JSON_PARSED_TRANSACTION=5664e3,SOLANA_ERROR__TRANSACTION_INTROSPECTION__UNRECOGNIZED_GET_TRANSACTION_RESPONSE=5664001,SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN=705e4,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE=7050001,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE=7050002,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND=7050003,SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND=7050004,SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE=7050005,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE=7050006,SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED=7050007,SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND=7050008,SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP=7050009,SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE=7050010,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX=7050011,SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE=7050012,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION=7050013,SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE=7050014,SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE=7050015,SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING=7050016,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT=7050017,SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION=7050018,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT=7050019,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT=7050020,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT=7050021,SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS=7050022,SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND=7050023,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER=7050024,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA=7050025,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX=7050026,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT=7050027,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT=7050028,SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT=7050029,SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION=7050030,SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT=7050031,SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED=7050032,SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT=7050033,SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED=7050034,SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED=7050035,SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION=7050036,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN=7618e3,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE=7618001,SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN=7618002,SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN=7618003,SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED=7618004,SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND=7618005,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN=7618006,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN=7618007,SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT=7618008,SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT=7618009,SOLANA_ERROR__INSTRUCTION_PLANS__MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED=7618010,SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION=7618011,SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_REJECTED_BY_PACKER=7618012,SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY=8078e3,SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH=8078001,SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH=8078002,SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH=8078003,SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH=8078004,SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH=8078005,SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH=8078006,SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS=8078007,SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE=8078008,SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT=8078009,SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT=8078010,SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE=8078011,SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE=8078012,SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH=8078013,SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE=8078014,SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT=8078015,SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE=8078016,SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE=8078017,SOLANA_ERROR__CODECS__INVALID_CONSTANT=8078018,SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE=8078019,SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL=8078020,SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES=8078021,SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS=8078022,SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY=8078023,SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE=8078024,SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES=8078025,SOLANA_ERROR__CODECS__INVALID_UTF8_BYTES=8078026,SOLANA_ERROR__CODECS__INVALID_UTF8_STRING=8078027,SOLANA_ERROR__CODECS__SENTINEL_MISSING_AT_END_OF_BYTES=8078028,SOLANA_ERROR__CODECS__SENTINEL_MUST_NOT_BE_EMPTY=8078029,SOLANA_ERROR__CODECS__UNEXPECTED_ZERO_FIXED_SIZE_ITEM_FOR_ARRAY_LIKE_SIZE_STRATEGY=8078030,SOLANA_ERROR__FIXED_POINTS__INVALID_TOTAL_BITS=809e4,SOLANA_ERROR__FIXED_POINTS__INVALID_FRACTIONAL_BITS=8090001,SOLANA_ERROR__FIXED_POINTS__INVALID_DECIMALS=8090002,SOLANA_ERROR__FIXED_POINTS__FRACTIONAL_BITS_EXCEED_TOTAL_BITS=8090003,SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE=8090004,SOLANA_ERROR__FIXED_POINTS__INVALID_STRING=8090005,SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO=8090006,SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW=8090007,SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH=8090008,SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO=8090009,SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS=8090010,SOLANA_ERROR__FIXED_POINTS__MALFORMED_RAW_VALUE=8090011,SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED=8090012,SOLANA_ERROR__RPC__INTEGER_OVERFLOW=81e5,SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN=8100001,SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR=8100002,SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD=8100003,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN=819e4,SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID=8190001,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED=8190002,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED=8190003,SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT=8190004,SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED=8195e3,SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR=8195001,SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS=85e5,SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE=8500001,SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION=8500002,SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE=8500003,SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL=8500004,SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_ACCOUNT_TYPE=8500005,SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT=8500006,SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_SIGNER=8500007,SOLANA_ERROR__WALLET__NOT_CONNECTED=89e5,SOLANA_ERROR__WALLET__NO_SIGNER_CONNECTED=8900001,SOLANA_ERROR__WALLET__SIGNER_NOT_AVAILABLE=8900002,SOLANA_ERROR__WALLET__ACCOUNT_NOT_AVAILABLE=8900003,SOLANA_ERROR__WALLET__INVALID_MESSAGE_SIGNATURE=8900004,SOLANA_ERROR__WALLET__INVALID_SIGN_IN_OUTPUT=8900005,SOLANA_ERROR__WALLET__INVALID_NUMBER_OF_OUTPUTS=8900006,SOLANA_ERROR__WALLET__FEATURE_VERSION_UNSUPPORTED=8900007,SOLANA_ERROR__REACT__MISSING_PROVIDER=9e6,SOLANA_ERROR__REACT__MISSING_CAPABILITY=9000001,SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR=9000002,SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING=99e5,SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE=9900001,SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING=9900002,SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE=9900003,SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED=9900004,SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND=9900005,SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND=9900006;SolanaErrorMessages={[SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]:"Account not found at address: $address",[SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]:"Expected decoded account at address: $address",[SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]:"Failed to decode account data at address: $address",[SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]:"Accounts not found at addresses: $addresses",[SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]:"Unable to find a viable program address bump seed.",[SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]:"$putativeAddress is not a base58-encoded address.",[SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]:"The `CryptoKey` must be an `Ed25519` public key.",[SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]:"Invalid seeds; point must fall off the Ed25519 curve.",[SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]:"Program address cannot end with PDA marker.",[SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]:"Expected base58-encoded blockhash string of length in the range [32, 44]. Actual length: $actualLength.",[SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]:"The network has progressed past the last block for which this transaction could have been committed.",[SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]:"Codec [$codecDescription] cannot decode empty byte arrays.",[SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]:"Encoder and decoder must either both be fixed-size or variable-size.",[SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]:"Expected a fixed-size codec, got a variable-size one.",[SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]:"Expected a variable-size codec, got a fixed-size one.",[SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[SOLANA_ERROR__CODECS__INVALID_CONSTANT]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]:"Invalid literal union variant. Expected one of [$variants], got $value.",[SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]:"Expected [$codecDescription] to have $expected items, got $actual.",[SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]:"Invalid value $value for base $base with alphabet $alphabet.",[SOLANA_ERROR__CODECS__INVALID_UTF8_BYTES]:"Invalid UTF-8 byte sequence at offset $offset.",[SOLANA_ERROR__CODECS__INVALID_UTF8_STRING]:"Invalid UTF-8 string. Found a lone surrogate at index $index.",[SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[SOLANA_ERROR__CODECS__SENTINEL_MISSING_AT_END_OF_BYTES]:"Codec [$codecDescription] expected sentinel [$hexSentinel] to terminate the collection, but reached the end of the byte array without it.",[SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[SOLANA_ERROR__CODECS__SENTINEL_MUST_NOT_BE_EMPTY]:"The sentinel must not be empty.",[SOLANA_ERROR__CODECS__UNEXPECTED_ZERO_FIXED_SIZE_ITEM_FOR_ARRAY_LIKE_SIZE_STRATEGY]:"Codec [$codecDescription] cannot use the [$sizeStrategy] size strategy: the item codec has a fixed size of zero and consumes no bytes.",[SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]:"This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?",[SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE]:"Invalid pattern match value. The provided value does not match any of the specified patterns.",[SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES]:"Invalid pattern match bytes. The provided byte array does not match any of the specified patterns.",[SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]:"No random values implementation could be found.",[SOLANA_ERROR__FAILED_TO_SEND_TRANSACTION]:"Failed to send transaction$causeMessage",[SOLANA_ERROR__FAILED_TO_SEND_TRANSACTIONS]:"Failed to send transactions$causeMessages",[SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTION]:"Failed to sign transaction$causeMessage",[SOLANA_ERROR__FAILED_TO_SIGN_TRANSACTIONS]:"Failed to sign transactions$causeMessages",[SOLANA_ERROR__FIXED_POINTS__ARITHMETIC_OVERFLOW]:"Fixed-point operation `$operation` of kind `$kind` overflowed. Expected a raw bigint in [$min, $max], got $result.",[SOLANA_ERROR__FIXED_POINTS__DIVISION_BY_ZERO]:"Fixed-point division by zero for value of kind `$kind` ($signedness, $totalBits bits).",[SOLANA_ERROR__FIXED_POINTS__FRACTIONAL_BITS_EXCEED_TOTAL_BITS]:"`fractionalBits` ($fractionalBits) must not exceed `totalBits` ($totalBits).",[SOLANA_ERROR__FIXED_POINTS__INVALID_DECIMALS]:"Invalid `decimals`. Expected a non-negative integer, got $decimals.",[SOLANA_ERROR__FIXED_POINTS__INVALID_FRACTIONAL_BITS]:"Invalid `fractionalBits`. Expected a non-negative integer, got $fractionalBits.",[SOLANA_ERROR__FIXED_POINTS__INVALID_STRING]:"Invalid string `$input` for fixed-point value of kind `$kind`.",[SOLANA_ERROR__FIXED_POINTS__INVALID_TOTAL_BITS]:"Invalid `totalBits`. Expected a positive integer, got $totalBits.",[SOLANA_ERROR__FIXED_POINTS__INVALID_ZERO_DENOMINATOR_RATIO]:"Invalid ratio $numerator/$denominator for fixed-point value of kind `$kind`. Denominator must be non-zero.",[SOLANA_ERROR__FIXED_POINTS__MALFORMED_RAW_VALUE]:"Fixed-point value of kind `$kind` has a malformed `raw` field. Expected a bigint, got `$raw`.",[SOLANA_ERROR__FIXED_POINTS__SHAPE_MISMATCH]:"Fixed-point `$operation` operation expected $expectedKind ($expectedSignedness, $expectedTotalBits bits, $expectedScale $expectedScaleLabel); got $actualKind ($actualSignedness, $actualTotalBits bits, $actualScale $actualScaleLabel).",[SOLANA_ERROR__FIXED_POINTS__STRICT_MODE_PRECISION_LOSS]:"Fixed-point operation `$operation` of kind `$kind` cannot be performed exactly; pass a rounding mode other than `strict` to allow a rounded result.",[SOLANA_ERROR__FIXED_POINTS__TOTAL_BITS_NOT_BYTE_ALIGNED]:"Fixed-point codec of kind `$kind` requires `totalBits` to be a multiple of 8; got $totalBits.",[SOLANA_ERROR__FIXED_POINTS__VALUE_OUT_OF_RANGE]:"Fixed-point value of kind `$kind` is out of range for $signedness $totalBits-bit storage. Expected a raw bigint in [$min, $max], got $raw.",[SOLANA_ERROR__FS__UNSUPPORTED_ENVIRONMENT]:"Filesystem operation `$operation` is not supported in this environment.",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]:"Instruction requires an uninitialized account",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]:"Instruction tries to borrow reference for an account which is already borrowed",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:"Instruction left account with an outstanding borrowed reference",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]:"Program other than the account's owner changed the size of the account data",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]:"Account data too small for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]:"Instruction expected an executable account",[SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]:"An account does not have enough lamports to be rent-exempt",[SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]:"Program arithmetic overflowed",[SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]:"Failed to serialize or deserialize account data",[SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]:"Builtin programs must consume compute units",[SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]:"Cross-program invocation call depth too deep",[SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]:"Computational budget exceeded",[SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]:"Custom program error: #$code",[SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]:"Instruction contains duplicate accounts",[SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]:"Instruction modifications of multiply-passed account differ",[SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]:"Executable accounts must be rent exempt",[SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]:"Instruction changed executable accounts data",[SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]:"Instruction changed the balance of an executable account",[SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]:"Instruction changed executable bit of an account",[SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]:"Instruction modified data of an account it does not own",[SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]:"Instruction spent from the balance of an account it does not own",[SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]:"Generic instruction error",[SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]:"Provided owner is not allowed",[SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]:"Account is immutable",[SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]:"Incorrect authority provided",[SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]:"Incorrect program id for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]:"Insufficient funds for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]:"Invalid account data for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]:"Invalid account owner",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]:"Invalid program argument",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]:"Program returned invalid error code",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]:"Invalid instruction data",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]:"Failed to reallocate account data",[SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]:"Provided seeds do not result in a valid address",[SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]:"Accounts data allocations exceeded the maximum allowed per transaction",[SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]:"Max accounts exceeded",[SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]:"Max instruction trace length exceeded",[SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]:"Length of the seed is too long for address generation",[SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]:"An account required by the instruction is missing",[SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]:"Missing required signature for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]:"Instruction illegally modified the program id of an account",[SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]:"Insufficient account keys for instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]:"Cross-program invocation with unauthorized signer or writable account",[SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]:"Failed to create program execution environment",[SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]:"Program failed to compile",[SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]:"Program failed to complete",[SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]:"Instruction modified data of a read-only account",[SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]:"Instruction changed the balance of a read-only account",[SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]:"Cross-program invocation reentrancy not allowed for this instruction",[SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]:"Instruction modified rent epoch of an account",[SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]:"Sum of account balances before and after instruction do not match",[SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]:"Instruction requires an initialized account",[SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]:"The instruction failed with the error: $errorName",[SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]:"Unsupported program id",[SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]:"Unsupported sysvar",[SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]:"Invalid instruction plan kind: $kind.",[SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN]:"The provided instruction plan is empty.",[SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]:"No failed transaction plan result was found in the provided transaction plan result.",[SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED]:"This transaction plan executor does not support non-divisible sequential plans. To support them, you may create your own executor such that multi-transaction atomicity is preserved \u2014 e.g. by targetting RPCs that support transaction bundles.",[SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]:"The provided transaction plan failed to execute. See the `transactionPlanResult` attribute for more details. Note that the `cause` property is deprecated, and a future version will not set it.",[SOLANA_ERROR__INSTRUCTION_PLANS__INVALID_MAX_INSTRUCTIONS_PER_TRANSACTION]:"The configured maximum of $maxInstructions instructions per transaction is invalid. It must be a positive integer no greater than the transaction format limit of $transactionInstructionLimit instructions per transaction. Provide a `maxInstructionsPerTransaction` (on the transaction planner) or `maxInstructions` (on the message packer) value between 1 and $transactionInstructionLimit.",[SOLANA_ERROR__INSTRUCTION_PLANS__MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED]:"Planning this transaction message would require $numInstructions instructions, which exceeds the configured maximum of $maxInstructions instructions per transaction. This limit is configurable, and intended to leave headroom for inner instructions which are included in the maximum instruction limit for transactions. Increase `maxInstructionsPerTransaction` on the transaction planner (or `maxInstructions` on the message packer) to allow more instructions per transaction.",[SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]:"The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).",[SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]:"Invalid transaction plan kind: $kind.",[SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE]:"No more instructions to pack; the message packer has completed the instruction plan.",[SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_REJECTED_BY_PACKER]:"The message packer rejected the provided transaction message: $reason.",[SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]:"Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.",[SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]:"Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.",[SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]:"Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.",[SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]:"Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.",[SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]:"The instruction does not have any accounts.",[SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]:"The instruction does not have any data.",[SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[SOLANA_ERROR__INVALID_NONCE]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]:"Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]:"Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]:"Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]:"Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[SOLANA_ERROR__JSON_RPC__PARSE_ERROR]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[SOLANA_ERROR__JSON_RPC__SCAN_ERROR]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]:"Epoch rewards period still active at slot $slot",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_FILTER_TRANSACTION_NOT_FOUND]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE]:"Failed to query long-term storage; please try again",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]:"Minimum context slot has not been reached",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]:"Node is unhealthy; behind by $numSlotsBehind slots",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SLOT_HISTORY]:"No slot history",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]:"No snapshot",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]:"Transaction simulation failed",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]:"Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]:"Transaction history is not available from this node",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]:"$__serverMessage",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]:"Transaction signature length mismatch",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]:"Transaction signature verification failure",[SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]:"$__serverMessage",[SOLANA_ERROR__KEYS__INVALID_BASE58_IN_GRIND_REGEX]:"The grind regex `/$source/` contains the character `$character`, which is not in the base58 alphabet and can never match a Solana address.",[SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]:"Key pair bytes must be of length 64, got $byteLength.",[SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]:"Expected private key bytes with length 32. Actual length: $actualLength.",[SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]:"The provided private key does not match the provided public key.",[SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[SOLANA_ERROR__KEYS__VERIFICATION_REQUIRES_EXTRACTABLE_PUBLIC_KEY]:"Signatures can only be verified using an extractable public key. The bytes of the public key must be readable. If you imported the public key yourself, set `extractable` to `true`.",[SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT]:"Writing a key pair to disk is not supported in this environment.",[SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]:"Lamports value must be in the range [0, 2e64-1]",[SOLANA_ERROR__MALFORMED_BIGINT_STRING]:"`$value` cannot be parsed as a `BigInt`",[SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]:"$message",[SOLANA_ERROR__MALFORMED_NUMBER_STRING]:"`$value` cannot be parsed as a `Number`",[SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]:"No nonce account could be found at address `$nonceAccountAddress`",[SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]:"Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]:"Attempted to sign an offchain message with an address that is not a signer for it",[SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]:"Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__CONTENT_DOES_NOT_MATCH_EXPECTED]:"The content of the offchain message does not match the content that was expected. Expected content with a byte-length of $expectedBytes; got content with a byte-length of $actualBytes. The signer may have signed different data than was requested; do not trust its signature.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]:"The signer addresses in this offchain message envelope do not match the list of required signers in the message preamble. These unexpected signers were present in the envelope: `[$unexpectedSigners]`. These required signers were missing from the envelope `[$missingSigners]`.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]:"The message body provided has a byte-length of $actualBytes. The maximum allowable byte-length is $maxBytes",[SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]:"Expected message format $expectedMessageFormat, got $actualMessageFormat",[SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]:"The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY]:"Offchain message content must be non-empty",[SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO]:"Offchain message must specify the address of at least one required signer",[SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO]:"Offchain message envelope must reserve space for at least one signature",[SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]:"The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__REQUIRED_SIGNATORIES_DO_NOT_MATCH_EXPECTED]:"The offchain message lists different required signatories than was expected. Expected [$expectedAddresses]. Got [$actualAddresses]. The signer may have signed different data than was requested; do not trust its signature.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED]:"The signatories of this offchain message must be listed in lexicographical order",[SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE]:"An address must be listed no more than once among the signatories of an offchain message",[SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]:"Offchain message is missing signatures for addresses: $addresses.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]:"Offchain message signature verification failed. Signature mismatch for required signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories [$signatoriesWithMissingSignatures]",[SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE]:"The message body provided contains characters whose codes fall outside the allowed range. In order to ensure clear-signing compatiblity with hardware wallets, the message may only contain line feeds and characters in the range [\\x20-\\x7e].",[SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]:"Expected offchain message version $expectedVersion. Got $actualVersion.",[SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]:"This version of Kit does not support decoding offchain messages with version $unsupportedVersion. The current max supported version is 0.",[SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT]:"The provided account could not be identified as an account from the $programName program.",[SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION]:"The provided instruction could not be identified as an instruction from the $programName program.",[SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS]:"The provided instruction is missing some accounts. Expected at least $expectedAccountMetas account(s), got $actualAccountMetas.",[SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_NON_NULL]:"Expected resolved instruction input '$inputName' to be non-null.",[SOLANA_ERROR__PROGRAM_CLIENTS__RESOLVED_INSTRUCTION_INPUT_MUST_BE_SIGNER]:"Expected resolved instruction input '$inputName' to be a `TransactionSigner` because the instruction requires this account to sign the transaction. If its signature is provided by other means, use `createNoopSigner()` from `@solana/signers` to satisfy this requirement.",[SOLANA_ERROR__PROGRAM_CLIENTS__UNEXPECTED_RESOLVED_INSTRUCTION_INPUT_TYPE]:"Expected resolved instruction input '$inputName' to be of type `$expectedType`.",[SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_ACCOUNT_TYPE]:"Unrecognized account type '$accountType' for the $programName program.",[SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE]:"Unrecognized instruction type '$instructionType' for the $programName program.",[SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]:"WebSocket was closed before payload could be added to the send buffer",[SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]:"WebSocket connection closed",[SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]:"WebSocket failed to connect",[SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]:"Failed to obtain a subscription id from the server",[SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]:"Could not find an API plan for RPC method: `$method`",[SOLANA_ERROR__RPC__INTEGER_OVERFLOW]:"The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",[SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]:"HTTP error ($statusCode): $message",[SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]:"The provided value does not implement the `KeyPairSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]:"The provided value does not implement the `MessageModifyingSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]:"The provided value does not implement the `MessagePartialSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]:"The provided value does not implement any of the `MessageSigner` interfaces",[SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]:"The provided value does not implement the `TransactionModifyingSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]:"The provided value does not implement the `TransactionPartialSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]:"The provided value does not implement the `TransactionSendingSigner` interface",[SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]:"The provided value does not implement any of the `TransactionSigner` interfaces",[SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]:"More than one `TransactionSendingSigner` was identified.",[SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION]:"The wallet account $address cannot be used to create a transaction signer because it does not implement either the `solana:signTransaction` or `solana:signAndSendTransaction` feature. At least one of these features is required. The account supports the following features: $supportedFeatures.",[SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED]:"This `ReactiveStreamStore` does not support retry. Use `createReactiveStoreFromDataPublisherFactory` to construct a retryable store.",[SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR]:"The stream store closed in an error state but did not report an error.",[SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]:"Cannot export a non-extractable key.",[SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]:"No digest implementation could be found.",[SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]:`This runtime does not support the generation of Ed25519 key pairs.
|
|
2176
2176
|
|
|
2177
2177
|
Install @solana/webcrypto-ed25519-polyfill and call its \`install\` function before generating keys in environments that do not support Ed25519.
|
|
2178
2178
|
|
|
@@ -2472,11 +2472,11 @@ ${captureLines}`:capture.stack}module.exports.fetch=function(init2,options=void
|
|
|
2472
2472
|
`)).join(`
|
|
2473
2473
|
|
|
2474
2474
|
`)}function applyFeishu(text){let s3=text;return s3=s3.replace(/^(#{1,6}) +(.+)$/gm,(_,_h,body)=>`**${body.trim()}**`),s3=s3.replace(/^[ \t]*-{3,}[ \t]*$/gm,""),s3}function applySlackText(text){let s3=text;s3=s3.replace(/&/g,"&");let linkPlaceholders=[];s3=s3.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(_,txt,url3)=>{let i=linkPlaceholders.length;return linkPlaceholders.push(`<${url3}|${txt}>`),`${PH_LINK}${i}${PH_END}`}),s3=s3.replace(/</g,"<").replace(/>/g,">"),s3=s3.replace(/^(#{1,6}) +(.+)$/gm,(_,_h,body)=>`**${body.trim()}**`);let boldPlaceholders=[];s3=s3.replace(/\*\*([^*\n]+)\*\*/g,(_,inner)=>{let i=boldPlaceholders.length;return boldPlaceholders.push(inner),`${PH_BOLD}${i}${PH_END}`}),s3=s3.replace(/(?<![\w*])\*([^*\n]+)\*(?![\w*])/g,"_$1_"),s3=s3.replace(/~~([^~\n]+)~~/g,"~$1~");let boldRestoreRe=new RegExp(PH_BOLD.replace(/_/g,"\\_")+"(\\d+)"+PH_END.replace(/_/g,"\\_"),"g");s3=s3.replace(boldRestoreRe,(_,i)=>`*${boldPlaceholders[parseInt(i,10)]}*`);let linkRestoreRe=new RegExp(PH_LINK.replace(/_/g,"\\_")+"(\\d+)"+PH_END.replace(/_/g,"\\_"),"g");return s3=s3.replace(linkRestoreRe,(_,i)=>linkPlaceholders[parseInt(i,10)]),s3=s3.replace(/^([ \t]*)-([ \t]+)/gm,"$1\u2022$2"),s3}function escapeTelegramText(s3){let out="";for(let ch of s3)TELEGRAM_ESCAPE_CHARS.includes(ch)?out+="\\"+ch:out+=ch;return out}function applyTelegramText(text){let tokens=[],i=0,len=text.length,peek=s3=>text.startsWith(s3,i);for(;i<len;){if(peek("**")){let end=text.indexOf("**",i+2);if(end!==-1){tokens.push({kind:"bold",raw:text.slice(i,end+2),inner:text.slice(i+2,end)}),i=end+2;continue}}if(peek("~~")){let end=text.indexOf("~~",i+2);if(end!==-1){tokens.push({kind:"strike",raw:text.slice(i,end+2),inner:text.slice(i+2,end)}),i=end+2;continue}}if(peek("`")){let end=text.indexOf("`",i+1);if(end!==-1){tokens.push({kind:"code",raw:text.slice(i,end+1),inner:text.slice(i+1,end)}),i=end+1;continue}}if(peek("[")){let close2=text.indexOf("](",i+1);if(close2!==-1){let end=text.indexOf(")",close2+2);if(end!==-1){tokens.push({kind:"link",raw:text.slice(i,end+1),inner:text.slice(i+1,close2),url:text.slice(close2+2,end)}),i=end+1;continue}}}if(text[i]==="*"&&text[i+1]!=="*"){let end=text.indexOf("*",i+1);if(end!==-1&&!text.slice(i+1,end).includes(`
|
|
2475
|
-
`)){tokens.push({kind:"italic",raw:text.slice(i,end+1),inner:text.slice(i+1,end)}),i=end+1;continue}}let j=i;for(;j<len&&!text.startsWith("**",j)&&!text.startsWith("~~",j)&&text[j]!=="`"&&text[j]!=="["&&!(text[j]==="*"&&text[j+1]!=="*");)j++;tokens.push({kind:"text",raw:text.slice(i,j)}),i=j}let out="";for(let tok of tokens)switch(tok.kind){case"text":out+=escapeTelegramText(tok.raw);break;case"bold":out+="*"+escapeTelegramText(tok.inner??"")+"*";break;case"italic":out+="_"+escapeTelegramText(tok.inner??"")+"_";break;case"strike":out+="~"+escapeTelegramText(tok.inner??"")+"~";break;case"code":out+="`"+(tok.inner??"").replace(/\\/g,"\\\\").replace(/`/g,"\\`")+"`";break;case"link":out+="["+escapeTelegramText(tok.inner??"")+"]("+(tok.url??"").replace(/\\/g,"\\\\").replace(/\)/g,"\\)")+")";break}return out}function preProcessTelegram(text){return text.replace(/^(#{1,6}) +(.+)$/gm,(_,_h,body)=>`**${body.trim()}**`)}function applyWhatsappText(text){let s3=text;s3=s3.replace(/^(#{1,6}) +(.+)$/gm,(_,_h,body)=>`**${body.trim()}**`);let boldPlaceholders=[];s3=s3.replace(/\*\*([^*\n]+)\*\*/g,(_,inner)=>{let i=boldPlaceholders.length;return boldPlaceholders.push(inner),`${PH_BOLD}${i}${PH_END}`}),s3=s3.replace(/(?<![\w*])\*([^*\n]+)\*(?![\w*])/g,"_$1_"),s3=s3.replace(/~~([^~\n]+)~~/g,"~$1~");let boldRestoreRe=new RegExp(PH_BOLD.replace(/_/g,"\\_")+"(\\d+)"+PH_END.replace(/_/g,"\\_"),"g");return s3=s3.replace(boldRestoreRe,(_,i)=>`*${boldPlaceholders[parseInt(i,10)]}*`),s3=s3.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`$1
|
|
2475
|
+
`)){tokens.push({kind:"italic",raw:text.slice(i,end+1),inner:text.slice(i+1,end)}),i=end+1;continue}}let j=peek("**")||peek("~~")?i+2:i+1;for(;j<len&&!text.startsWith("**",j)&&!text.startsWith("~~",j)&&text[j]!=="`"&&text[j]!=="["&&!(text[j]==="*"&&text[j+1]!=="*");)j++;tokens.push({kind:"text",raw:text.slice(i,j)}),i=j}let out="";for(let tok of tokens)switch(tok.kind){case"text":out+=escapeTelegramText(tok.raw);break;case"bold":out+="*"+escapeTelegramText(tok.inner??"")+"*";break;case"italic":out+="_"+escapeTelegramText(tok.inner??"")+"_";break;case"strike":out+="~"+escapeTelegramText(tok.inner??"")+"~";break;case"code":out+="`"+(tok.inner??"").replace(/\\/g,"\\\\").replace(/`/g,"\\`")+"`";break;case"link":out+="["+escapeTelegramText(tok.inner??"")+"]("+(tok.url??"").replace(/\\/g,"\\\\").replace(/\)/g,"\\)")+")";break}return out}function preProcessTelegram(text){return text.replace(/^(#{1,6}) +(.+)$/gm,(_,_h,body)=>`**${body.trim()}**`)}function applyWhatsappText(text){let s3=text;s3=s3.replace(/^(#{1,6}) +(.+)$/gm,(_,_h,body)=>`**${body.trim()}**`);let boldPlaceholders=[];s3=s3.replace(/\*\*([^*\n]+)\*\*/g,(_,inner)=>{let i=boldPlaceholders.length;return boldPlaceholders.push(inner),`${PH_BOLD}${i}${PH_END}`}),s3=s3.replace(/(?<![\w*])\*([^*\n]+)\*(?![\w*])/g,"_$1_"),s3=s3.replace(/~~([^~\n]+)~~/g,"~$1~");let boldRestoreRe=new RegExp(PH_BOLD.replace(/_/g,"\\_")+"(\\d+)"+PH_END.replace(/_/g,"\\_"),"g");return s3=s3.replace(boldRestoreRe,(_,i)=>`*${boldPlaceholders[parseInt(i,10)]}*`),s3=s3.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`$1
|
|
2476
2476
|
$2`),s3}function applyPlainText(text){let s3=text;return s3=s3.replace(/^[ \t]*-{3,}[ \t]*$/gm,""),s3=s3.replace(/^# +(.+)$/gm,(_,body)=>`${body.trim()}
|
|
2477
2477
|
${"=".repeat(visibleWidth(body.trim()))}`),s3=s3.replace(/^## +(.+)$/gm,(_,body)=>`${body.trim()}
|
|
2478
2478
|
${"-".repeat(visibleWidth(body.trim()))}`),s3=s3.replace(/^#{3,6} +(.+)$/gm,(_,body)=>body.trim()),s3=s3.replace(/\*\*([^*\n]+)\*\*/g,"$1"),s3=s3.replace(/(?<![*\w])\*([^*\n]+)\*(?!\*)/g,"$1"),s3=s3.replace(/(?<![_\w])_([^_\n]+)_(?!_)/g,"$1"),s3=s3.replace(/~~([^~\n]+)~~/g,"$1"),s3=s3.replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1 ($2)"),s3=s3.replace(/`([^`\n]+)`/g,"$1"),s3}function transformTablesInProse(text,preset){return preset==="feishu"?text:text.replace(TABLE_BLOCK_REGEX,(whole,lead,block)=>{let table=parseTable(block);if(!table)return whole;if(preset==="plain")return lead+renderTableKeyValue(table);let monospace=renderTableMonospace(table);return lead+"```\n"+monospace+"\n```\n"})}function transformFenceForPreset(seg,preset){if(preset==="plain")return fenceInner(seg.content);if(preset==="telegram"){let inner=fenceInner(seg.content).replace(/\\/g,"\\\\").replace(/`/g,"\\`");return"```"+(seg.fenceLang?seg.fenceLang:"")+`
|
|
2479
|
-
`+inner+"\n```"}return seg.content}function applyTextRulesPerPreset(text,preset){switch(preset){case"feishu":return applyFeishu(text);case"slack":return applySlackText(text);case"discord":return text;case"telegram":return applyTelegramText(preProcessTelegram(text));case"whatsapp":return applyWhatsappText(text);case"plain":return applyPlainText(text)}}function transform2(md,preset){let afterTables=splitByFences(md).map(seg=>seg.isFence?seg.content:transformTablesInProse(seg.content,preset)).join("");return splitByFences(afterTables).map(seg=>seg.isFence?transformFenceForPreset(seg,preset):applyTextRulesPerPreset(seg.content,preset)).join("")}var SHARE_PRESETS,TELEGRAM_MAX_LEN,TELEGRAM_SUFFIX_RESERVE,TELEGRAM_CHUNK_CONTENT_LIMIT,PH_BOLD,PH_LINK,PH_END,TABLE_BLOCK_REGEX,TELEGRAM_ESCAPE_CHARS,init_share_formatters=__esm({"src/share-formatters.ts"(){"use strict";SHARE_PRESETS=["feishu","slack","discord","telegram","whatsapp","plain"];TELEGRAM_MAX_LEN=4096,TELEGRAM_SUFFIX_RESERVE=24,TELEGRAM_CHUNK_CONTENT_LIMIT=TELEGRAM_MAX_LEN-TELEGRAM_SUFFIX_RESERVE,PH_BOLD="__CR_PH_BOLD_",PH_LINK="__CR_PH_LINK_",PH_END="__";TABLE_BLOCK_REGEX=/(^|\n)((?:[ \t]*\|.*\|[ \t]*\n)(?:[ \t]*\|[\s:|-]+\|[ \t]*\n)(?:[ \t]*\|.*\|[ \t]*\n?)*)/g;TELEGRAM_ESCAPE_CHARS="_*[]()~`>#+-=|{}.!"}});var solana_balance_exports={};__export(solana_balance_exports,{SolanaBalanceMonitor:()=>SolanaBalanceMonitor});var SOLANA_USDC_MINT,SOLANA_DEFAULT_RPC,BALANCE_TIMEOUT_MS,CACHE_TTL_MS2,SolanaBalanceMonitor,init_solana_balance=__esm({"src/solana-balance.ts"(){"use strict";init_index_node39();SOLANA_USDC_MINT="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",SOLANA_DEFAULT_RPC="https://api.mainnet-beta.solana.com",BALANCE_TIMEOUT_MS=1e4,CACHE_TTL_MS2=3e4,SolanaBalanceMonitor=class{rpc;walletAddress;cachedBalance=null;cachedAt=0;constructor(walletAddress,rpcUrl){this.walletAddress=walletAddress;let url3=rpcUrl||process.env.CLAWROUTER_SOLANA_RPC_URL||SOLANA_DEFAULT_RPC;this.rpc=createSolanaRpc(url3)}async checkBalance(){let now2=Date.now();if(this.cachedBalance!==null&&this.cachedBalance>0n&&now2-this.cachedAt<CACHE_TTL_MS2)return this.buildInfo(this.cachedBalance);let balance=await this.fetchBalance();return balance>0n&&(this.cachedBalance=balance,this.cachedAt=now2),this.buildInfo(balance)}deductEstimated(amountMicros){this.cachedBalance!==null&&this.cachedBalance>=amountMicros&&(this.cachedBalance-=amountMicros)}invalidate(){this.cachedBalance=null,this.cachedAt=0}async refresh(){return this.invalidate(),this.checkBalance()}async checkSufficient(estimatedCostMicros){let info=await this.checkBalance();if(info.balance>=estimatedCostMicros)return{sufficient:!0,info};let shortfall=estimatedCostMicros-info.balance;return{sufficient:!1,info,shortfall:this.formatUSDC(shortfall)}}formatUSDC(amountMicros){return`$${(Number(amountMicros)/1e6).toFixed(2)}`}getWalletAddress(){return this.walletAddress}async checkSolBalance(){let controller=new AbortController,timer2=setTimeout(()=>controller.abort(),BALANCE_TIMEOUT_MS);try{let owner=address2(this.walletAddress),response=await this.rpc.getBalance(owner).send({abortSignal:controller.signal});return BigInt(response.value)}catch{return 0n}finally{clearTimeout(timer2)}}async fetchBalance(){let owner=address2(this.walletAddress),mint4=address2(SOLANA_USDC_MINT),MAX_ATTEMPTS=3,lastError;for(let attempt=0;attempt<MAX_ATTEMPTS;attempt++)try{let result=await this.fetchBalanceOnce(owner,mint4);if(result>0n)return result;attempt<MAX_ATTEMPTS-1&&await new Promise(r2=>setTimeout(r2,1500*(attempt+1)))}catch(err){lastError=err,attempt<MAX_ATTEMPTS-1&&await new Promise(r2=>setTimeout(r2,1500*(attempt+1)))}if(lastError!==void 0)throw lastError;return 0n}async fetchBalanceOnce(owner,mint4){let controller=new AbortController,timer2=setTimeout(()=>controller.abort(),BALANCE_TIMEOUT_MS);try{let response=await this.rpc.getTokenAccountsByOwner(owner,{mint:mint4},{encoding:"jsonParsed"}).send({abortSignal:controller.signal});if(response.value.length===0)return 0n;let total=0n;for(let account of response.value){let parsed=account.account.data;total+=BigInt(parsed.parsed.info.tokenAmount.amount)}return total}catch(err){throw new Error(`Failed to fetch Solana USDC balance: ${err instanceof Error?err.message:String(err)}`,{cause:err})}finally{clearTimeout(timer2)}}buildInfo(balance){let dollars=Number(balance)/1e6;return{balance,balanceUSD:`$${dollars.toFixed(2)}`,isLow:balance<1000000n,isEmpty:balance<100n,walletAddress:this.walletAddress}}}}});var NETWORKS2,init_chunk_WWACQNRQ=__esm({"node_modules/@x402/svm/dist/esm/chunk-WWACQNRQ.mjs"(){"use strict";NETWORKS2=["solana","solana-devnet","solana-testnet"]}});var ExactSvmSchemeV1,init_chunk_PQ2KWLVO=__esm({"node_modules/@x402/svm/dist/esm/chunk-PQ2KWLVO.mjs"(){"use strict";init_chunk_WIPN332D();init_chunk_RZ6M7L3U();init_chunk_DAIKIZVB();init_src2();init_src3();init_index_node39();ExactSvmSchemeV1=class{constructor(signer,config2){this.signer=signer,this.config=config2,this.scheme="exact",this.findDefaultAsset=findDefaultAsset2,this.mintCache=new Map}async createPaymentPayload(x402Version2,paymentRequirements){let selectedV1=paymentRequirements,transactionVersion=resolveTransactionVersion(paymentRequirements.extra,this.config?.transactionVersions),rpc=createRpcClient(selectedV1.network,this.config?.rpcUrl),mintMetadata=await getCachedMintMetadata(rpc,selectedV1.network,selectedV1.asset,this.mintCache),tokenProgramAddress=mintMetadata.programAddress;if(tokenProgramAddress.toString()!==TOKEN_PROGRAM_ADDRESS.toString()&&tokenProgramAddress.toString()!==TOKEN_2022_PROGRAM_ADDRESS.toString())throw new Error("Asset was not created by a known token program");let[sourceATA]=await findAssociatedTokenPda({mint:selectedV1.asset,owner:this.signer.address,tokenProgram:tokenProgramAddress}),[destinationATA]=await findAssociatedTokenPda({mint:selectedV1.asset,owner:selectedV1.payTo,tokenProgram:tokenProgramAddress}),transferIx=getTransferCheckedInstruction({source:sourceATA,mint:selectedV1.asset,destination:destinationATA,authority:this.signer,amount:BigInt(selectedV1.maxAmountRequired),decimals:mintMetadata.decimals},{programAddress:tokenProgramAddress}),feePayer=selectedV1.extra?.feePayer;if(!feePayer)throw new Error("feePayer is required in paymentRequirements.extra for SVM transactions");let{value:latestBlockhash}=await rpc.getLatestBlockhash().send(),sellerMemo=selectedV1.extra?.memo,memoData;if(sellerMemo){if(memoData=new TextEncoder().encode(sellerMemo),memoData.byteLength>MAX_MEMO_BYTES)throw new Error(`extra.memo exceeds maximum ${MAX_MEMO_BYTES} bytes`)}else{let nonce2=crypto.getRandomValues(new Uint8Array(16));memoData=new TextEncoder().encode(Array.from(nonce2).map(b=>b.toString(16).padStart(2,"0")).join(""))}let memoIx={programAddress:MEMO_PROGRAM_ADDRESS,accounts:[],data:memoData},budget={computeUnitLimit:DEFAULT_COMPUTE_UNIT_LIMIT,computeUnitPriceMicroLamports:DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS},tx=pipe2(createTransactionMessage({version:transactionVersion}),tx2=>applyTransactionV1Config(transactionVersion,budget,tx2),tx2=>setTransactionMessageFeePayer(feePayer,tx2),tx2=>appendTransactionMessageInstructions([...computeBudgetInstructions(transactionVersion,budget),transferIx,memoIx],tx2),tx2=>setTransactionMessageLifetimeUsingBlockhash(latestBlockhash,tx2)),signedTransaction=await partiallySignTransactionMessageWithSigners(tx),payload={transaction:getBase64EncodedWireTransaction(signedTransaction)};return{x402Version:x402Version2,scheme:selectedV1.scheme,network:selectedV1.network,payload}}}}});var PENDING_SETTLEMENT_TTL_MS,init_facilitator=__esm({"node_modules/@x402/core/dist/esm/facilitator/index.mjs"(){"use strict";init_chunk_VE37GDG2();init_chunk_XW2CWVLZ();PENDING_SETTLEMENT_TTL_MS=300*1e3}});var addressEncoder,compiledMessageDecoder,compiledMessageDecoder2,init_chunk_RCDWMK2L=__esm({"node_modules/@x402/svm/dist/esm/chunk-RCDWMK2L.mjs"(){"use strict";init_chunk_7TSGYOB2();init_chunk_L56Y5KBE();init_chunk_RZ6M7L3U();init_chunk_DAIKIZVB();init_index_node39();init_facilitator();init_index_node39();init_index_node39();addressEncoder=getAddressEncoder(),compiledMessageDecoder=getCompiledTransactionMessageDecoder(),compiledMessageDecoder2=getCompiledTransactionMessageDecoder()}});var client_exports3={};__export(client_exports3,{ExactSvmScheme:()=>ExactSvmScheme,registerExactSvmScheme:()=>registerExactSvmScheme});function registerExactSvmScheme(client,config2){return config2.networks&&config2.networks.length>0?config2.networks.forEach(network=>{client.register(network,new ExactSvmScheme(config2.signer))}):client.register("solana:*",new ExactSvmScheme(config2.signer)),(config2.networks&&config2.networks.length>0?NETWORKS2.filter(name=>{let v2Network=V1_TO_V2_NETWORK_MAP[name];return v2Network?config2.networks.some(pattern=>networkMatchesPattern(pattern,v2Network)):!1}):NETWORKS2).forEach(network=>{client.registerV1(network,new ExactSvmSchemeV1(config2.signer))}),config2.policies&&config2.policies.forEach(policy=>{client.registerPolicy(policy)}),client}var init_client4=__esm({"node_modules/@x402/svm/dist/esm/exact/client/index.mjs"(){"use strict";init_chunk_2P7IHAQJ();init_chunk_WWACQNRQ();init_chunk_PQ2KWLVO();init_chunk_WIPN332D();init_chunk_RCDWMK2L();init_chunk_7TSGYOB2();init_chunk_L56Y5KBE();init_chunk_RZ6M7L3U();init_chunk_DAIKIZVB();init_utils14()}});var v1_exports={};__export(v1_exports,{ExactSvmSchemeV1:()=>ExactSvmSchemeV1,NETWORKS:()=>NETWORKS2});var init_v1=__esm({"node_modules/@x402/svm/dist/esm/v1/index.mjs"(){"use strict";init_chunk_WWACQNRQ();init_chunk_PQ2KWLVO();init_chunk_WIPN332D();init_chunk_RCDWMK2L();init_chunk_7TSGYOB2();init_chunk_L56Y5KBE();init_chunk_RZ6M7L3U();init_chunk_DAIKIZVB()}});import{AsyncLocalStorage as AsyncLocalStorage2}from"async_hooks";import{createHmac}from"crypto";import{createServer}from"http";import{finished,Readable as Readable2,Transform}from"stream";import{pipeline}from"stream/promises";import{homedir as homedir13}from"os";import{join as join17}from"path";import{mkdir as mkdir6,writeFile as writeFile4,readFile as readFile3,stat as fsStat}from"fs/promises";import{readFileSync as readFileSync8}from"fs";function describePaymentNetwork(network){return network===CAIP2_ARC?`${PAYMENT_CHAIN_LABELS.arc} (EVM)`:network.startsWith("eip155")?`${PAYMENT_CHAIN_LABELS.base} (EVM)`:network.startsWith("solana")?PAYMENT_CHAIN_LABELS.solana:network}function stampsBuilderCode(network){return network.startsWith("eip155")&&network!==CAIP2_ARC}function walletGatewayFor(chain3,hasSolanaKey){return chain3==="solana"?hasSolanaKey?BLOCKRUN_SOLANA_API:BLOCKRUN_API:chain3==="arc"?BLOCKRUN_ARC_API:BLOCKRUN_API}function evmBalanceChain(chain3){return chain3==="arc"?"arc":"base"}async function loadGatewayCatalog(apiBase,apiKey){try{let controller=new AbortController,timer2=setTimeout(()=>controller.abort(),GATEWAY_CATALOG_TIMEOUT_MS),res=await(apiKey?createApiKeyFetch(apiKey,fetch,apiBase):fetch)(`${apiBase}/v1/models`,{signal:controller.signal});if(clearTimeout(timer2),!res.ok)return;let ids=((await res.json()).data??[]).map(m=>m.id).filter(id2=>!!id2);if(ids.length===0)return;gatewayModelIds=new Set(ids);let unserved=[...FREE_MODELS].filter(m=>!gatewayModelIds.has(toUpstreamModelId(m)));unserved.length>0&&console.log(`[ClawRouter] Free models not served by this gateway (skipped in the cascade): ${unserved.join(", ")}`)}catch{}}function isServedByGateway(modelId){return gatewayModelIds?gatewayModelIds.has(toUpstreamModelId(modelId)):!0}function pickFreeModel(excludeList){for(let m of FREE_MODELS)if(!excludeList?.has(m)&&isServedByGateway(m))return m;for(let m of FREE_MODELS)if(!excludeList?.has(m))return m}function toUpstreamModelId(modelId){let override=FREE_UPSTREAM_OVERRIDES[modelId];return override||(modelId.startsWith("free/")?"nvidia/"+modelId.slice(5):modelId)}function timeoutForModel(modelId,models){return models.get(modelId)?.reasoning?REASONING_MODEL_TIMEOUT_MS:PER_MODEL_TIMEOUT_MS}function isClientAbortError(err,res){return err instanceof ClientDisconnectedError?!0:err instanceof Error?res.destroyed&&!res.writableEnded&&(err.name==="AbortError"||err.message.includes("aborted")):!1}async function readBodyWithTimeout(body,timeoutMs=MODEL_BODY_READ_TIMEOUT_MS,signal,abortError=()=>new ClientDisconnectedError){if(!body)return[];if(signal?.aborted)throw await body.cancel().catch(()=>{}),abortError();let reader=body.getReader(),chunks=[],timer2,abortHandler;try{for(;;){if(signal?.aborted)throw abortError();let abortPromise=signal?new Promise((_,reject)=>{abortHandler=()=>reject(abortError()),signal.addEventListener("abort",abortHandler,{once:!0})}):null,result=await Promise.race([reader.read(),new Promise((_,reject)=>{timer2=setTimeout(()=>reject(new Error("Body read timeout")),timeoutMs)}),...abortPromise?[abortPromise]:[]]);if(clearTimeout(timer2),signal&&abortHandler&&(signal.removeEventListener("abort",abortHandler),abortHandler=void 0),result.done)break;chunks.push(result.value)}}catch(err){throw await reader.cancel().catch(()=>{}),err}finally{clearTimeout(timer2),signal&&abortHandler&&signal.removeEventListener("abort",abortHandler),reader.releaseLock()}return chunks}function transformPaymentError(errorBody,evmChain="Base"){try{let parsed=JSON.parse(errorBody);if(parsed.error==="Payment verification failed"&&parsed.details){let match=parsed.details.match(/Verification failed:\s*(\{.*\})/s);if(match){let innerJson=JSON.parse(match[1]);if(innerJson.invalidReason==="insufficient_funds"&&innerJson.invalidMessage){let balanceMatch=innerJson.invalidMessage.match(/insufficient balance:\s*(\d+)\s*<\s*(\d+)/i);if(balanceMatch){let currentMicros=parseInt(balanceMatch[1],10),requiredMicros=parseInt(balanceMatch[2],10),currentUSD=(currentMicros/1e6).toFixed(6),requiredUSD=(requiredMicros/1e6).toFixed(6),wallet=innerJson.payer||"unknown",shortWallet=wallet.length>12?`${wallet.slice(0,6)}...${wallet.slice(-4)}`:wallet;return JSON.stringify({error:{message:`Insufficient USDC balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`,type:"insufficient_funds",wallet,current_balance_usd:currentUSD,required_usd:requiredUSD,help:`Fund wallet ${shortWallet} with USDC on ${evmChain}, or use free model: /model free`}})}}if(innerJson.invalidReason==="invalid_payload")return JSON.stringify({error:{message:"Payment signature invalid. This may be a temporary issue.",type:"invalid_payload",help:"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash"}});if(innerJson.invalidReason==="transaction_simulation_failed")return console.error(`[ClawRouter] Solana transaction simulation failed: ${innerJson.invalidMessage||"unknown"}`),JSON.stringify({error:{message:"Solana payment simulation failed. Retrying with a different model.",type:"transaction_simulation_failed",help:"This is usually temporary. If it persists, check your Solana USDC balance or try: /model free"}})}}if(parsed.error==="Payment verification failed"&&parsed.code==="PAYMENT_INVALID"&&parsed.debug){let debugLower=parsed.debug.toLowerCase(),wallet=parsed.payer||"unknown",shortWallet=wallet.length>12?`${wallet.slice(0,6)}...${wallet.slice(-4)}`:wallet,chain3=wallet.startsWith("0x")?evmChain:"Solana";return debugLower.includes("insufficient")?JSON.stringify({error:{message:`Insufficient ${chain3} USDC balance.`,type:"insufficient_funds",wallet,help:chain3==="Solana"?`Fund wallet ${shortWallet} with USDC on Solana, or switch to Base: /wallet base`:`Fund wallet ${shortWallet} with USDC on ${chain3}, or use free model: /model free`}}):debugLower.includes("transaction_simulation_failed")||debugLower.includes("simulation")?(console.error(`[ClawRouter] ${chain3} transaction simulation failed: ${parsed.debug}`),JSON.stringify({error:{message:`${chain3} payment simulation failed. Retrying with a different model.`,type:"transaction_simulation_failed",help:"This is usually temporary. If it persists, try: /model free"}})):debugLower.includes("invalid signature")||debugLower.includes("invalid_signature")?JSON.stringify({error:{message:`${chain3} payment signature invalid.`,type:"invalid_payload",help:"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash"}}):debugLower.includes("expired")?JSON.stringify({error:{message:`${chain3} payment expired. Retrying.`,type:"expired",help:"This is usually temporary."}}):(console.error(`[ClawRouter] ${chain3} payment verification failed: ${parsed.debug} payer=${wallet}`),JSON.stringify({error:{message:`${chain3} payment verification failed: ${parsed.debug}`,type:"payment_invalid",wallet,help:chain3==="Solana"?"Try again or switch to Base: /wallet base":"Try again. If this persists, try: /model free"}}))}if(parsed.error==="Settlement failed"||parsed.error==="Payment settlement failed"||parsed.details?.includes("Settlement failed")||parsed.details?.includes("transaction_simulation_failed")){let gasError=(parsed.details||"").includes("unable to estimate gas");return JSON.stringify({error:{message:gasError?"Payment failed: network congestion or gas issue. Try again.":"Payment settlement failed. Try again in a moment.",type:"settlement_failed",help:"This is usually temporary. If it persists, try: /model free"}})}}catch{}return errorBody}function categorizeError(status2,body){return status2===401?"auth_failure":status2===402?"payment_error":status2===403?/plan.*limit|quota.*exceeded|subscription|allowance/i.test(body)?"quota_exceeded":"auth_failure":status2===429?"rate_limited":status2===529||status2===503&&/overload|capacity|too.*many.*request/i.test(body)?"overloaded":status2>=500?"server_error":(status2===400||status2===413)&&PROVIDER_ERROR_PATTERNS.some(p=>p.test(body))?"config_error":null}function recordProviderError(modelId,category){perProviderErrors.has(modelId)||perProviderErrors.set(modelId,{auth_failure:0,quota_exceeded:0,rate_limited:0,overloaded:0,server_error:0,payment_error:0,config_error:0}),perProviderErrors.get(modelId)[category]++}function isRateLimited(modelId){let hitTime=rateLimitedModels.get(modelId);return hitTime?Date.now()-hitTime>=RATE_LIMIT_COOLDOWN_MS?(rateLimitedModels.delete(modelId),!1):!0:!1}function markRateLimited(modelId){rateLimitedModels.set(modelId,Date.now()),console.log(`[ClawRouter] Model ${modelId} rate-limited, will deprioritize for 60s`)}function markOverloaded(modelId){overloadedModels.set(modelId,Date.now()),console.log(`[ClawRouter] Model ${modelId} overloaded, will deprioritize for 15s`)}function isOverloaded(modelId){let hitTime=overloadedModels.get(modelId);return hitTime?Date.now()-hitTime>=OVERLOAD_COOLDOWN_MS?(overloadedModels.delete(modelId),!1):!0:!1}function prioritizeNonRateLimited(models){let available=[],degraded=[];for(let model of models)isRateLimited(model)||isOverloaded(model)?degraded.push(model):available.push(model);return[...available,...degraded]}function canWrite(res){return!res.writableEnded&&!res.destroyed&&res.socket!==null&&!res.socket.destroyed&&res.socket.writable}function safeWrite(res,data){if(!canWrite(res)){let bytes=typeof data=="string"?Buffer.byteLength(data):data.length;return console.warn(`[ClawRouter] safeWrite: socket not writable, dropping ${bytes} bytes`),!1}return res.write(data)}function sanitizeHeaderValue(value){return value.replace(/[^\t\x20-\x7E]/gu,c=>{try{return encodeURIComponent(c)}catch{return"?"}})}function debugHeadersEnabledFromEnv(env=process.env){let value=(env.CLAWROUTER_DEBUG_HEADERS??"").toLowerCase();return value!=="0"&&value!=="false"&&value!=="off"}function getProxyPort(){return PROXY_PORT}async function checkExistingProxy(port){let controller=new AbortController,timeoutId=setTimeout(()=>controller.abort(),HEALTH_CHECK_TIMEOUT_MS);try{let response=await fetch(`http://127.0.0.1:${port}/health`,{signal:controller.signal});if(clearTimeout(timeoutId),response.ok){let data=await response.json(),authMode=data.authMode==="api-key"?"api-key":"wallet";if(data.status==="ok"&&(data.wallet||authMode==="api-key"))return{wallet:data.wallet??"",paymentChain:data.paymentChain,authMode,apiKeyLabel:typeof data.apiKey=="string"?data.apiKey:void 0}}return}catch{clearTimeout(timeoutId);return}}function extractAssistantContent(payload){if(!payload||typeof payload!="object")return;let choices=payload.choices;if(!Array.isArray(choices)||choices.length===0)return;let firstChoice=choices[0];if(!firstChoice||typeof firstChoice!="object")return;let message=firstChoice.message;if(!message||typeof message!="object")return;let content=message.content;return typeof content=="string"?content:void 0}function hasKnownLoopSignature(text){if(DEGRADED_LOOP_PATTERNS.reduce((count,pattern)=>pattern.test(text)?count+1:count,0)>=2)return!0;let lines=text.split(/\r?\n/).map(line=>line.trim()).filter(Boolean);if(lines.length<8)return!1;let counts=new Map;for(let line of lines)counts.set(line,(counts.get(line)??0)+1);let maxRepeat=Math.max(...counts.values()),uniqueRatio=counts.size/lines.length;return maxRepeat>=3&&uniqueRatio<=.45}function detectDegradedSuccessResponse(body){let trimmed=body.trim();if(trimmed){if(DEGRADED_RESPONSE_PATTERNS.some(pattern=>pattern.test(trimmed)))return"degraded response: overloaded placeholder";if(hasKnownLoopSignature(trimmed))return"degraded response: repetitive loop output";try{let parsed=JSON.parse(trimmed),errorField=parsed.error,errorText="";if(typeof errorField=="string")errorText=errorField;else if(errorField&&typeof errorField=="object"){let errObj=errorField;errorText=[typeof errObj.message=="string"?errObj.message:"",typeof errObj.type=="string"?errObj.type:"",typeof errObj.code=="string"?errObj.code:""].filter(Boolean).join(" ")}if(errorText&&PROVIDER_ERROR_PATTERNS.some(pattern=>pattern.test(errorText)))return`degraded response: ${errorText.slice(0,120)}`;let choices=parsed.choices;if(Array.isArray(choices)&&choices.length===0)return"degraded response: no choices returned";if(Array.isArray(choices)&&choices.length>0){let choice=choices[0],msg=choice.message??choice.delta;if(msg){let content=msg.content,toolCalls=msg.tool_calls,hasContent=typeof content=="string"&&content.trim().length>0,hasToolCalls=Array.isArray(toolCalls)&&toolCalls.length>0,finishReason=choice.finish_reason;if(!hasContent&&!hasToolCalls&&finishReason==="stop")return"degraded response: empty turn (no content or tool calls)"}}let assistantContent=extractAssistantContent(parsed);if(!assistantContent)return;if(DEGRADED_RESPONSE_PATTERNS.some(pattern=>pattern.test(assistantContent)))return"degraded response: overloaded assistant content";if(hasKnownLoopSignature(assistantContent))return"degraded response: repetitive assistant loop"}catch{}}}function sanitizeToolId(id2){return!id2||typeof id2!="string"||VALID_TOOL_ID_PATTERN.test(id2)?id2:id2.replace(/[^a-zA-Z0-9_-]/g,"_")}function sanitizeToolIds(messages3){if(!messages3||messages3.length===0)return messages3;let hasChanges=!1,sanitized=messages3.map(msg=>{let typedMsg=msg,msgChanged=!1,newMsg={...msg};if(typedMsg.tool_calls&&Array.isArray(typedMsg.tool_calls)){let newToolCalls=typedMsg.tool_calls.map(tc=>{if(tc.id&&typeof tc.id=="string"){let sanitized2=sanitizeToolId(tc.id);if(sanitized2!==tc.id)return msgChanged=!0,{...tc,id:sanitized2}}return tc});msgChanged&&(newMsg={...newMsg,tool_calls:newToolCalls})}if(typedMsg.tool_call_id&&typeof typedMsg.tool_call_id=="string"){let sanitized2=sanitizeToolId(typedMsg.tool_call_id);sanitized2!==typedMsg.tool_call_id&&(msgChanged=!0,newMsg={...newMsg,tool_call_id:sanitized2})}if(Array.isArray(typedMsg.content)){let newContent=typedMsg.content.map(block=>{if(!block||typeof block!="object")return block;let blockChanged=!1,newBlock={...block};if(block.type==="tool_use"&&block.id&&typeof block.id=="string"){let sanitized2=sanitizeToolId(block.id);sanitized2!==block.id&&(blockChanged=!0,newBlock={...newBlock,id:sanitized2})}if(block.type==="tool_result"&&block.tool_use_id&&typeof block.tool_use_id=="string"){let sanitized2=sanitizeToolId(block.tool_use_id);sanitized2!==block.tool_use_id&&(blockChanged=!0,newBlock={...newBlock,tool_use_id:sanitized2})}return blockChanged?(msgChanged=!0,newBlock):block});msgChanged&&(newMsg={...newMsg,content:newContent})}return msgChanged?(hasChanges=!0,newMsg):msg});return hasChanges?sanitized:messages3}function normalizeMessageRoles(messages3){if(!messages3||messages3.length===0)return messages3;let hasChanges=!1,normalized=messages3.map(msg=>{if(VALID_ROLES.has(msg.role))return msg;let mappedRole=ROLE_MAPPINGS[msg.role];return mappedRole?(hasChanges=!0,{...msg,role:mappedRole}):(hasChanges=!0,{...msg,role:"user"})});return hasChanges?normalized:messages3}function normalizeMessagesForGoogle(messages3){if(!messages3||messages3.length===0)return messages3;let firstNonSystemIdx=-1;for(let i=0;i<messages3.length;i++)if(messages3[i].role!=="system"){firstNonSystemIdx=i;break}if(firstNonSystemIdx===-1)return messages3;let firstRole=messages3[firstNonSystemIdx].role;if(firstRole==="user")return messages3;if(firstRole==="assistant"||firstRole==="model"){let normalized=[...messages3];return normalized.splice(firstNonSystemIdx,0,{role:"user",content:"(continuing conversation)"}),normalized}return messages3}function isGoogleModel(modelId){return modelId.startsWith("google/")||modelId.startsWith("gemini")}function normalizeMessagesForThinking(messages3){if(!messages3||messages3.length===0)return messages3;let hasChanges=!1,normalized=messages3.map(msg=>msg.role!=="assistant"||msg.reasoning_content!==void 0?msg:(hasChanges=!0,{...msg,reasoning_content:""}));return hasChanges?normalized:messages3}function debrandSystemMessages(messages3,resolvedModel){let PROFILE_NAMES=["auto","free","eco","premium"],profilePattern=new RegExp(`\\bblockrun/(${PROFILE_NAMES.join("|")})\\b`,"gi"),prefixPattern=/\bblockrun\/(?=[a-z])/gi,hasChanges=!1,result=messages3.map(msg=>{if(msg.role!=="system"||typeof msg.content!="string")return msg;let content=msg.content,afterPrefix=content.replace(profilePattern,resolvedModel).replace(prefixPattern,"");return afterPrefix!==content&&(hasChanges=!0,content=afterPrefix),content!==msg.content?{...msg,content}:msg});return hasChanges?result:messages3}function isToolResultMessage(msg){return msg.role==="tool"?!0:Array.isArray(msg.content)?msg.content.some(b=>b&&typeof b=="object"&&b.type==="tool_result"):!1}function truncateMessages(messages3){if(!messages3||messages3.length<=MAX_MESSAGES)return{messages:messages3,wasTruncated:!1,originalCount:messages3?.length??0,truncatedCount:messages3?.length??0};let systemMsgs=messages3.filter(m=>m.role==="system"),conversationMsgs=messages3.filter(m=>m.role!=="system"),maxConversation=MAX_MESSAGES-systemMsgs.length,start=Math.max(0,conversationMsgs.length-maxConversation);for(;start<conversationMsgs.length&&isToolResultMessage(conversationMsgs[start]);)start++;let truncatedConversation=conversationMsgs.slice(start),result=[...systemMsgs,...truncatedConversation];return console.log(`[ClawRouter] Truncated messages: ${messages3.length} \u2192 ${result.length} (kept ${systemMsgs.length} system + ${truncatedConversation.length} recent)`),{messages:result,wasTruncated:!0,originalCount:messages3.length,truncatedCount:result.length}}function stripThinkingTokens(content){if(!content)return content;let cleaned=content.replace(KIMI_BLOCK_RE,"");return cleaned=cleaned.replace(KIMI_TOKEN_RE,""),cleaned=cleaned.replace(THINKING_BLOCK_RE,""),cleaned=cleaned.replace(THINKING_TAG_RE,""),cleaned}function forwardToolCallProse(){return process.env.CLAWROUTER_TOOL_CALL_PROSE?.trim().toLowerCase()!=="off"}function buildModelPricing(models=BLOCKRUN_MODELS){let map2=new Map;for(let m of models){if(m.id===AUTO_MODEL)continue;let promoPrice=getActivePromoPrice(m);map2.set(m.id,{inputPrice:m.inputPrice,outputPrice:m.outputPrice,...promoPrice!==void 0&&{flatPrice:promoPrice}})}return map2}function buildModelCapabilities(models=BLOCKRUN_MODELS){return Object.fromEntries(models.map(model=>[model.id,{contextWindow:model.contextWindow,maxOutputTokens:model.maxOutput,supportsTools:model.toolCalling===!0,supportsVision:model.vision===!0}]))}function buildProxyModelList(createdAt=Math.floor(Date.now()/1e3),catalog=fallbackCatalog()){let seen=new Set;return catalog.openclaw.filter(model=>seen.has(model.id)?!1:(seen.add(model.id),!0)).map(model=>{let targetId=MODEL_ALIASES[model.id]??model.id,canonical=catalog.models.find(entry=>entry.id===targetId);return{id:model.id,object:"model",created:createdAt,owned_by:targetId.includes("/")?targetId.split("/")[0]??"blockrun":"blockrun",name:model.name,context_window:model.contextWindow,max_output:model.maxTokens,input_price:model.cost.input,output_price:model.cost.output,reasoning:model.reasoning,vision:model.input.includes("image"),agentic:canonical?.agentic??!1,tool_calling:canonical?.toolCalling??!1}})}function mergeRoutingConfig(overrides){if(!overrides)return DEFAULT_ROUTING_CONFIG;let mergeTiers=(defaults2,user)=>user===null?null:user===void 0?defaults2??null:{...defaults2??{},...user};return{...DEFAULT_ROUTING_CONFIG,...overrides,classifier:{...DEFAULT_ROUTING_CONFIG.classifier,...overrides.classifier},scoring:{...DEFAULT_ROUTING_CONFIG.scoring,...overrides.scoring},tiers:mergeTiers(DEFAULT_ROUTING_CONFIG.tiers,overrides.tiers)??DEFAULT_ROUTING_CONFIG.tiers,agenticTiers:mergeTiers(DEFAULT_ROUTING_CONFIG.agenticTiers,overrides.agenticTiers),ecoTiers:mergeTiers(DEFAULT_ROUTING_CONFIG.ecoTiers,overrides.ecoTiers),premiumTiers:mergeTiers(DEFAULT_ROUTING_CONFIG.premiumTiers,overrides.premiumTiers),overrides:{...DEFAULT_ROUTING_CONFIG.overrides,...overrides.overrides}}}function buildCostBreakdown(params){let{actualModelUsed,routingProfile,modelPricing,inputTokens,outputTokens,tier}=params;if(typeof inputTokens!="number"||typeof outputTokens!="number"||inputTokens<0||outputTokens<0)return;let pricing=modelPricing.get(actualModelUsed),inputPrice=pricing?.inputPrice??0,outputPrice=pricing?.outputPrice??0,input2=inputTokens/1e6*inputPrice,output2=outputTokens/1e6*outputPrice,costs=calculateModelCost(actualModelUsed,modelPricing,inputTokens,outputTokens,routingProfile),total=costs.costEstimate,baseline=costs.baselineCost,savingsPct=routingProfile==="premium"||baseline<=0?void 0:Math.max(0,Math.min(100,Math.round(costs.savings*100)));return{total,input:input2,output:output2,baseline,...savingsPct!==void 0?{savings_pct:savingsPct}:{},model:actualModelUsed,...tier?{tier}:{}}}function estimateAmount(modelId,bodyLength,maxTokens,models=BLOCKRUN_MODEL_BY_ID){let model=models.get(modelId);if(!model)return;let costUsd,promoPrice=getActivePromoPrice(model);if(promoPrice!==void 0)costUsd=promoPrice;else{let estimatedInputTokens=Math.ceil(bodyLength/4),estimatedOutputTokens=maxTokens||model.maxOutput||4096;costUsd=withPlatformFee(estimatedInputTokens/1e6*model.inputPrice+estimatedOutputTokens/1e6*model.outputPrice,model.platformFeePercent)}return costUsd>0&&(costUsd+=.001),Math.max(1e3,Math.ceil(costUsd*1.2*1e6)).toString()}function estimateBalancePreflightAmount(modelId,bodyLength,maxTokens,models=BLOCKRUN_MODEL_BY_ID){let preflightMaxTokens=Math.min(maxTokens||BALANCE_PREFLIGHT_OUTPUT_TOKEN_CAP,BALANCE_PREFLIGHT_OUTPUT_TOKEN_CAP);return estimateAmount(modelId,bodyLength,preflightMaxTokens,models)}function estimatePhoneCost(urlPath){let op=urlPath.replace(/^\/v1\//,"").split("?")[0];for(let key3 of Object.keys(PHONE_PRICING).sort((a,b)=>b.length-a.length))if(op===key3||op.startsWith(`${key3}/`))return PHONE_PRICING[key3];return .05}function resolvePhoneTelemetryCost(args){if(args.paidAmount>0)return args.paidAmount;let upstreamSucceeded=args.upstreamStatus>=200&&args.upstreamStatus<300,isPostRequest=(args.method??"").toUpperCase()==="POST";return args.isPhone&&upstreamSucceeded&&isPostRequest?estimatePhoneCost(args.urlPath):args.paidAmount}function estimateVideoCost(model,durationSeconds,hasImageInput){let p=VIDEO_PRICING[model];if(!p)return .4*1.05;let dur=durationSeconds??p.defaultDurationSeconds;return(hasImageInput&&p.pricePerSecondImageInput?p.pricePerSecondImageInput:p.pricePerSecond)*dur*1.05}function estimateImageCost(model,size4,n=1){let pricing=IMAGE_PRICING[model];return pricing?((size4&&pricing.sizes?pricing.sizes[size4]:void 0)??pricing.default)*n*1.05:.04*n*1.05}function blockrunRequestId(response){if(response)for(let name of["x-blockrun-request-id","x-request-id","request-id"]){let value=response.headers.get(name)?.trim();if(value)return value}}function gatewayRemainingCreditUsd(response){let raw=response?.headers.get("x-blockrun-credit-remaining-usd");if(raw==null)return;let trimmed=raw.trim();if(trimmed==="")return;let value=Number(trimmed);if(!(!Number.isFinite(value)||value<0))return value}function settledMediaCostUsd(upstream,body,x402AmountUsd,estimate){let header=gatewaySettledCostUsd(upstream);if(header!==void 0)return header;let price=body?.price?.amount;if(typeof price=="string"||typeof price=="number"){let parsed=Number(price);if(Number.isFinite(parsed)&&parsed>=0)return parsed}return typeof x402AmountUsd=="number"&&x402AmountUsd>0?x402AmountUsd:estimate}function publishDispatchCost(usd2){let store=paymentStore.getStore();store&&(store.estimatedUsd=Number.isFinite(usd2)&&usd2>0?usd2:0)}function noteRemainingCredit(response){let remaining=gatewayRemainingCreditUsd(response);if(remaining!==void 0){if(remaining>LOW_CREDIT_USD){lowCreditWarned=!1;return}lowCreditWarned||(lowCreditWarned=!0,console.warn(remaining<=0?`[ClawRouter] \u26A0 BlockRun account credit is exhausted \u2014 calls will fail with 402. Top up: ${PORTAL_CREDITS_URL}`:`[ClawRouter] \u26A0 BlockRun account credit low: $${remaining.toFixed(2)} remaining. Top up: ${PORTAL_CREDITS_URL}`))}}function gatewaySettledCostUsd(response){let raw=response?.headers.get("x-blockrun-cost-usd");if(raw==null)return;let trimmed=raw.trim();if(trimmed==="")return;let value=Number(trimmed);if(!(!Number.isFinite(value)||value<0))return value}function refuseOverCostCap(res,err){return!(err instanceof CostCapError)||res.headersSent?!1:(res.writeHead(429,{"Content-Type":"application/json","X-ClawRouter-Cost-Cap-Exceeded":"1",...err.budgetExhausted?{"X-ClawRouter-Budget-Mode":"blocked"}:{}}),res.end(JSON.stringify({error:{message:err.message,type:"cost_cap_exceeded",code:err.budgetExhausted?"budget_exhausted":"cost_cap_exceeded"}})),!0)}function capMessagesRequest(body,headers,cap){let parsed={};try{let value=JSON.parse(body.toString());value&&typeof value=="object"&&!Array.isArray(value)&&(parsed=value)}catch{}let messages3=Array.isArray(parsed.messages)?parsed.messages.filter(m=>typeof m?.role=="string"&&m.content!==void 0):[],sessionId=getSessionId(headers)??deriveSessionId(messages3)??NO_SESSION_ID,store=paymentStore.getStore(),track=()=>{let spend2=SessionSpend.track(cap.sessions,sessionId);return store&&(store.sessionSpend=spend2),spend2},model=typeof parsed.model=="string"?parsed.model:void 0;if(model!==void 0&&cap.isFree(model))return track(),{recordSuccess:()=>{}};let estimate=parseMicros(model===void 0?void 0:estimateAmount(resolveModelAlias(model),body.length,resolveMaxTokens(parsed),new Map(cap.models.map(m=>[m.id,m])))),spend;if(cap.mode==="strict"){let admission=SessionSpend.admit(cap.sessions,sessionId,usdToMicros(cap.usd),estimate??(cap.authMode==="api-key"?1n:0n));if(!admission.admitted){let projected=admission.spentMicros+admission.heldMicros+admission.estimateMicros;throw new CostCapError(`ClawRouter cost cap exceeded: projected spend $${microsToUsd(projected).toFixed(4)} would exceed limit $${cap.usd}`)}spend=admission.spend,store&&(store.sessionSpend=spend)}else{let remainingUsd=cap.usd-cap.sessions.getSessionCostUsd(sessionId);if(!(estimate!==void 0?microsToUsd(estimate)<=remainingUsd:remainingUsd>0))throw new CostCapError(`ClawRouter budget exhausted: $${Math.max(0,remainingUsd).toFixed(4)} remaining (limit: $${cap.usd}). Increase maxCostPerRun to continue.`,!0);spend=track()}return{recordSuccess:()=>{estimate!==void 0&&spend.recordSuccess(estimate)}}}function withZeroCapGuard(inner,isFree){return async(input2,init2)=>{let{pathname}=new URL(input2 instanceof Request?input2.url:String(input2)),path8=pathname.slice(Math.max(pathname.indexOf("/v1/"),0)),method=(init2?.method??"GET").toUpperCase(),allowed;if(/^\/v1\/(?:chat\/completions|messages)$/.test(path8)){let body=init2?.body,model;try{let text=typeof body=="string"?body:body instanceof Uint8Array?Buffer.from(body).toString():"";model=JSON.parse(text).model}catch{model=void 0}allowed=typeof model=="string"&&isFree(model)}else allowed=ZERO_CAP_FREE_READ.test(path8)&&(method==="GET"||method==="HEAD");if(!allowed)throw new CostCapError(ZERO_CAP_REFUSAL);return inner(input2,init2)}}function withSessionCostCap(inner){return async(input2,init2)=>{let store=paymentStore.getStore(),spend=store?.sessionSpend,published=store?.estimatedUsd;if(spend?.isStrict&&published!==void 0){let attemptMicros=usdToMicros(published);if(!spend.coverPayment(attemptMicros))throw new CostCapError(`ClawRouter cost cap exceeded: dispatching an estimated $${microsToUsd(attemptMicros).toFixed(6)} would push this session past its maxCostPerRun limit`)}published!==void 0&&spend?.beginDispatch();let response=await inner(input2,init2),charged=gatewaySettledCostUsd(response);return spend&&charged!==void 0&&spend.recordCharged(usdToMicros(charged)),response}}function isMessagesPath(url3){return url3==="/v1/messages"||(url3?.startsWith("/v1/messages?")??!1)}async function relayWithIdleTimeout(source,destination,idleMs,signal){let timer2,arm=()=>{clearTimeout(timer2),timer2=setTimeout(()=>watchdog.destroy(new Error("Body read timeout")),idleMs)},watchdog=new Transform({transform(chunk,_encoding,done){arm(),done(null,chunk)}});arm();try{await pipeline(source,watchdog,destination,{signal})}finally{clearTimeout(timer2)}}async function proxyPaidApiRequest(req,res,apiBase,payFetch,getActualPaymentUsd,accountPassthrough=!1,authMode="wallet",capRequest){let startTime=Date.now(),upstreamUrl=`${apiBase}${req.url}`,isMessages=isMessagesPath(req.url),isBlockrunExa=req.url?.startsWith("/v1/exa/")??!1,isModalSandbox=req.url?.startsWith("/v1/modal/")??!1,isPhone=(req.url?.startsWith("/v1/phone/")??!1)||(req.url?.startsWith("/v1/voice/")??!1),requestLabel=isBlockrunExa?"BlockRun Exa":isModalSandbox?"Modal Sandbox":isPhone?"Phone/Voice":"Partner",bodyChunks=[];for await(let chunk of req)bodyChunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let body=Buffer.concat(bodyChunks),capped=capRequest?.(body),headers={};for(let[key3,value]of Object.entries(req.headers))key3==="host"||key3==="connection"||key3==="transfer-encoding"||key3==="content-length"||key3.startsWith("x-stainless-")||key3.startsWith("anthropic-")||typeof value=="string"&&(headers[key3]=value);headers["content-type"]||(headers["content-type"]="application/json"),headers["user-agent"]=USER_AGENT,console.log(`[ClawRouter] ${requestLabel} request: ${req.method} ${req.url}`);let clientAbort=new AbortController,onClientDisconnect=()=>{!res.writableEnded&&!clientAbort.signal.aborted&&clientAbort.abort()};res.on("close",onClientDisconnect),(res.destroyed||req.socket?.destroyed)&&!res.writableEnded&&onClientDisconnect(),publishDispatchCost(0);let upstream=await payFetch(upstreamUrl,{method:req.method??"POST",headers,body:body.length>0?new Uint8Array(body):void 0,signal:clientAbort.signal});upstream.ok&&capped?.recordSuccess();let responseHeaders={};if(upstream.headers.forEach((value,key3)=>{key3==="transfer-encoding"||key3==="connection"||key3==="content-encoding"||key3==="content-length"||(responseHeaders[key3]=value)}),(accountPassthrough||authMode==="api-key")&&(responseHeaders["cache-control"]="no-store"),accountPassthrough)res.writeHead(upstream.status,responseHeaders),upstream.body?await pipeline(Readable2.fromWeb(upstream.body),res,{signal:clientAbort.signal}):res.end();else if(isMessages)res.writeHead(upstream.status,responseHeaders),upstream.body?await relayWithIdleTimeout(Readable2.fromWeb(upstream.body),res,MODEL_BODY_READ_TIMEOUT_MS,clientAbort.signal):res.end();else{let chunks=upstream.body?await readBodyWithTimeout(upstream.body,ERROR_BODY_READ_TIMEOUT_MS,clientAbort.signal):[];res.writeHead(upstream.status,responseHeaders);for(let chunk of chunks)safeWrite(res,Buffer.from(chunk));res.end()}let latencyMs=Date.now()-startTime;console.log(`[ClawRouter] ${requestLabel} response: ${upstream.status} (${latencyMs}ms)`),noteRemainingCredit(upstream);let settledCostUsd=gatewaySettledCostUsd(upstream),paidAmount=settledCostUsd??getActualPaymentUsd(),requestCost=settledCostUsd!==void 0?settledCostUsd:resolvePhoneTelemetryCost({paidAmount,isPhone,upstreamStatus:upstream.status,method:req.method,urlPath:req.url??""});logUsage({timestamp:new Date().toISOString(),...blockrunRequestId(upstream)?{requestId:blockrunRequestId(upstream)}:{},model:isBlockrunExa?"blockrun-exa":isModalSandbox?"modal-sandbox":isPhone?(req.url??"").replace(/^\/v1\//,"").split("?")[0]:"partner",tier:isPhone?"PHONE":"PARTNER",cost:requestCost,baselineCost:requestCost,savings:0,latencyMs,partnerId:(req.url?.split("?")[0]??"").replace(/^\/v1\//,"").replace(/\//g,"_")||"unknown",service:isBlockrunExa?"web_search":isModalSandbox?"modal":isPhone?"phone":"partner"}).catch(()=>{})}async function uploadDataUriToHost(dataUri){let match=dataUri.match(/^data:(image\/\w+);base64,(.+)$/);if(!match)throw new Error("Invalid data URI format");let[,mimeType,b64Data]=match,ext=mimeType==="image/jpeg"?"jpg":mimeType.split("/")[1]??"png",buffer2=Buffer.from(b64Data,"base64"),blob=new Blob([buffer2],{type:mimeType}),form2=new FormData;form2.append("reqtype","fileupload"),form2.append("fileToUpload",blob,`image.${ext}`);let uploadController=new AbortController,uploadTimeout=setTimeout(()=>uploadController.abort(),3e4);try{let resp=await fetch("https://catbox.moe/user/api.php",{method:"POST",body:form2,signal:uploadController.signal});if(!resp.ok)throw new Error(`catbox.moe upload failed: HTTP ${resp.status}`);let result=await resp.text();if(result.startsWith("https://"))return result.trim();throw new Error(`catbox.moe upload failed: ${result}`)}finally{clearTimeout(uploadTimeout)}}function warnIfSpendLimitsUnenforced(spendControl){let configured;try{let limits=(spendControl??new SpendControl).getStatus().limits;configured=POLICY_LISTS.filter(list=>(limits[list]?.length??0)>0)}catch{return}configured.length!==0&&(console.warn(`[ClawRouter] \u26A0 Counterparty policy (${configured.join(", ")}) does not apply in API-key mode \u2014 there is one counterparty and no on-chain asset.`),console.warn("[ClawRouter] Your perRequest/hourly/daily/session limits DO apply here and are enforced per call."))}function assertExistingProxyBillsUs(existing,requested){let{listenPort}=requested,describe3=mode2=>mode2==="api-key"?"a BlockRun API key":"a wallet";if(existing.authMode!==requested.authMode)throw new Error(`Existing proxy on port ${listenPort} is authenticating with ${describe3(existing.authMode)} but ${describe3(requested.authMode)} was requested. Stop the existing proxy first or use a different port.`);if(requested.authMode==="api-key"){if(existing.apiKeyLabel!==requested.apiKeyLabel)throw new Error(`Existing proxy on port ${listenPort} is billing ${existing.apiKeyLabel??"an unidentified BlockRun account"}, but this process is configured for ${requested.apiKeyLabel}. Reusing it would charge the other account. Stop that proxy first, or use a different port.`);return}if(existing.paymentChain){if(existing.paymentChain!==requested.paymentChain)throw new Error(`Existing proxy on port ${listenPort} is using ${existing.paymentChain} but ${requested.paymentChain} was requested. Stop the existing proxy first or use a different port.`)}else if(requested.paymentChain!=="base")throw console.warn(`[ClawRouter] Existing proxy on port ${listenPort} does not report paymentChain (pre-v0.11 instance). Assuming Base.`),new Error(`Existing proxy on port ${listenPort} is a pre-v0.11 instance (assumed Base) but ${requested.paymentChain} was requested. Stop the existing proxy first or use a different port.`)}async function startProxy(options){options.maxCostPerRunUsd!==void 0&&!Number.isFinite(options.maxCostPerRunUsd)&&(console.warn(`[ClawRouter] Ignoring maxCostPerRun: ${String(options.maxCostPerRunUsd)} is not a finite number`),options={...options,maxCostPerRunUsd:void 0});let upstreamProxy=await applyUpstreamProxy(options.upstreamProxy);upstreamProxy&&console.log(`[ClawRouter] Upstream proxy: ${upstreamProxy}`);let apiKey=options.apiKey?.trim()||void 0;if(apiKey&&!isValidApiKey(apiKey))throw new Error('BlockRun API key is malformed (expected it to start with "brk_"). Mint one at https://user.blockrun.ai/dashboard/keys');let authMode=apiKey?"api-key":"wallet";if(!apiKey&&!options.wallet)throw new Error("startProxy needs a credential: pass either a wallet (x402) or an apiKey (brk_\u2026, from https://user.blockrun.ai/dashboard/keys).");let walletKey=options.wallet===void 0?void 0:typeof options.wallet=="string"?options.wallet:options.wallet.key,solanaPrivateKeyBytes=options.wallet===void 0||typeof options.wallet=="string"?void 0:options.wallet.solanaPrivateKeyBytes,paymentChain=options.paymentChain??await resolvePaymentChain(),requestedApiBase=options.apiBase??(authMode==="api-key"?BLOCKRUN_API_KEY_API:walletGatewayFor(paymentChain,solanaPrivateKeyBytes!==void 0)),apiBase=authMode==="api-key"?normalizeApiKeyBase(requestedApiBase):requestedApiBase;authMode==="api-key"?(console.log(`[ClawRouter] Auth: BlockRun API key ${maskApiKey(apiKey)} (${apiBase})`),console.log(`[ClawRouter] Billing: account credit \u2014 top up at ${PORTAL_CREDITS_URL}`),warnIfSpendLimitsUnenforced(options.spendControl)):paymentChain==="solana"&&!solanaPrivateKeyBytes?(console.warn("[ClawRouter] \u26A0 Payment chain is Solana but no mnemonic found \u2014 falling back to Base (EVM)."),console.warn('[ClawRouter] To fix: run "npx @blockrun/clawrouter wallet recover" if your mnemonic exists,'),console.warn('[ClawRouter] or run "npx @blockrun/clawrouter chain base" to switch to EVM.')):console.log(paymentChain==="solana"?`[ClawRouter] Payment chain: Solana (${BLOCKRUN_SOLANA_API})`:paymentChain==="arc"?`[ClawRouter] Payment chain: Arc (${apiBase})`:`[ClawRouter] Payment chain: Base (${apiBase})`),loadGatewayCatalog(apiBase,apiKey);let listenPort=options.port??getProxyPort(),existingProxy=options.allowExistingProxy===!1?void 0:await checkExistingProxy(listenPort),ourApiKeyLabel=apiKey?maskApiKey(apiKey):void 0;if(existingProxy){let baseUrl2=`http://127.0.0.1:${listenPort}`;if(assertExistingProxyBillsUs(existingProxy,{listenPort,authMode,apiKeyLabel:ourApiKeyLabel,paymentChain}),authMode==="api-key")return options.onReady?.(listenPort),{port:listenPort,baseUrl:baseUrl2,walletAddress:"",authMode,apiKeyLabel:ourApiKeyLabel,balanceMonitor:new ApiKeyBalanceMonitor,close:async()=>{}};let account2=privateKeyToAccount(walletKey);existingProxy.wallet!==account2.address&&console.warn(`[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxy.wallet}, but current config uses ${account2.address}. Reusing existing proxy.`);let reuseSolanaAddress;if(solanaPrivateKeyBytes){let{createKeyPairSignerFromPrivateKeyBytes:createKeyPairSignerFromPrivateKeyBytes2}=await Promise.resolve().then(()=>(init_index_node39(),index_node_exports));reuseSolanaAddress=(await createKeyPairSignerFromPrivateKeyBytes2(solanaPrivateKeyBytes)).address}let balanceMonitor2;if(paymentChain==="solana"&&reuseSolanaAddress){let{SolanaBalanceMonitor:SolanaBalanceMonitor2}=await Promise.resolve().then(()=>(init_solana_balance(),solana_balance_exports));balanceMonitor2=new SolanaBalanceMonitor2(reuseSolanaAddress)}else balanceMonitor2=new BalanceMonitor(account2.address,evmBalanceChain(paymentChain));return options.onReady?.(listenPort),{port:listenPort,baseUrl:baseUrl2,walletAddress:existingProxy.wallet,solanaAddress:reuseSolanaAddress,authMode,balanceMonitor:balanceMonitor2,close:async()=>{}}}let account=walletKey?privateKeyToAccount(walletKey):void 0,x402=authMode==="wallet"?new x402Client().setSpendControls(!1):void 0,registerCostCapHook=client=>client.onBeforePaymentCreation(async context=>{if(options.maxCostPerRunUsd===0)throw new CostCapError(ZERO_CAP_REFUSAL);let spend=paymentStore.getStore()?.sessionSpend;if(!spend?.isStrict)return;let quote=parseQuotedAmountMicros(context.selectedRequirements);if(quote===void 0)throw new CostCapError("ClawRouter cost cap: unreadable payment amount in the 402 quote");if(!spend.coverPayment(quote))throw new CostCapError(`ClawRouter cost cap exceeded: signing $${microsToUsd(quote).toFixed(6)} would push this session past its maxCostPerRun limit`)});x402&®isterCostCapHook(x402);let spendControl=x402&&account?options.spendControl??getSharedSpendControl():void 0;if(x402&&account&&spendControl){let evmPublicClient=createPublicClient({chain:base,transport:http()}),evmSigner=toClientEvmSigner(account,evmPublicClient);registerSpendPolicyHook(x402,spendControl),registerExactEvmScheme(x402,{signer:evmSigner})}let solanaAddress;if(x402&&solanaPrivateKeyBytes){let{registerExactSvmScheme:registerExactSvmScheme2}=await Promise.resolve().then(()=>(init_client4(),client_exports3)),{createKeyPairSignerFromPrivateKeyBytes:createKeyPairSignerFromPrivateKeyBytes2}=await Promise.resolve().then(()=>(init_index_node39(),index_node_exports)),solanaSigner=await createKeyPairSignerFromPrivateKeyBytes2(solanaPrivateKeyBytes);solanaAddress=solanaSigner.address;let solanaRpcUrl=process.env.CLAWROUTER_SOLANA_RPC_URL;if(registerExactSvmScheme2(x402,{signer:solanaSigner}),solanaRpcUrl){let{ExactSvmScheme:ExactSvmScheme2}=await Promise.resolve().then(()=>(init_client4(),client_exports3)),{ExactSvmSchemeV1:ExactSvmSchemeV12,NETWORKS:SVM_V1_NETWORKS}=await Promise.resolve().then(()=>(init_v1(),v1_exports));x402.register("solana:*",new ExactSvmScheme2(solanaSigner,{rpcUrl:solanaRpcUrl}));for(let network of SVM_V1_NETWORKS)x402.registerV1(network,new ExactSvmSchemeV12(solanaSigner,{rpcUrl:solanaRpcUrl}))}console.log(`[ClawRouter] Solana wallet: ${solanaAddress}`),solanaRpcUrl&&console.log(`[ClawRouter] Solana RPC (payment signing + balance): ${solanaRpcUrl}`)}x402?.onAfterPaymentCreation(async context=>{if(!stampsBuilderCode(context.selectedRequirements.network))return;let payload=context.paymentPayload;payload.extensions=withBuilderCodeServiceCode(payload.extensions)});let registerSigningRecorders=client=>{client.onAfterPaymentCreation(async context=>{let network=context.selectedRequirements.network,chain3=describePaymentNetwork(network),amountUsd=parseInt(context.selectedRequirements.amount||"0",10)/1e6,store=paymentStore.getStore();store&&(store.amountUsd=amountUsd),console.log(`[ClawRouter] Payment signed on ${chain3} (${network}) \u2014 $${amountUsd.toFixed(6)}`)}),client.onAfterPaymentCreation(async context=>{let spend=paymentStore.getStore()?.sessionSpend,amount=parseQuotedAmountMicros(context.selectedRequirements);spend&&amount!==void 0&&spend.recordSigned(amount)})};x402&®isterSigningRecorders(x402);let solanaBatchSettings=x402&&paymentChain==="solana"&&solanaPrivateKeyBytes&&solanaAddress?resolveSolanaBatchSettings(options.solanaBatch,SOLANA_BATCH_ENV):void 0,solanaBatch;solanaBatchSettings&&solanaPrivateKeyBytes&&solanaAddress&&(solanaBatch={payer:await createSolanaBatchPayer({seed:solanaPrivateKeyBytes,address:solanaAddress,rpcUrl:process.env.CLAWROUTER_SOLANA_RPC_URL||SOLANA_PUBLIC_RPC,settings:solanaBatchSettings,configureClient:client=>{let hooks=client;hooks.onBeforePaymentCreation(async()=>{let store=paymentStore.getStore();store?.batchMark!==void 0&&store.sessionSpend?.voidSignedSince(store.batchMark,!1)}),registerCostCapHook(hooks),spendControl&®isterSpendPolicyHook(client,spendControl),registerSigningRecorders(hooks)}}),begin:()=>{let store=paymentStore.getStore(),mark=store?.sessionSpend?.signatureMark();return store&&(store.batchMark=mark),mark},settle:(mark,outcome)=>{let store=paymentStore.getStore();store&&(store.batchMark=void 0);let spend=store?.sessionSpend;outcome.kind==="paid"?(store&&outcome.chargedMicros!==void 0&&(store.amountUsd=microsToUsd(outcome.chargedMicros)),spend&&mark!==void 0&&spend.signatureMark()>mark&&(spend.voidSignedSince(mark,!0),outcome.chargedMicros!==void 0&&spend.settleLastSigned(outcome.chargedMicros))):outcome.kind==="not_charged"?(store&&(store.amountUsd=0),spend&&mark!==void 0&&spend.voidSignedSince(mark,!1)):spend&&mark!==void 0&&spend.voidSignedSince(mark,!0)}},console.log(`[ClawRouter] Solana batch-settlement on (BlockRun operator, max deposit ${solanaBatchSettings.maxDeposit??"$1"})`));let requestOptions=solanaBatch?{...options,_solanaBatchActive:!0}:options,keyFetch=apiKey?createApiKeyFetch(apiKey,fetch,apiBase):void 0,isFreeForCap=model=>{let{freeIds}=catalog.current();return freeIds.has(resolveModelAlias(model))||[...freeIds].some(id2=>toUpstreamModelId(id2)===model)},payFetch=authMode==="api-key"?withSessionCostCap(withSpendPolicy(options.maxCostPerRunUsd===0?withZeroCapGuard(keyFetch,isFreeForCap):keyFetch,options.spendControl??getSharedSpendControl(),()=>{let store=paymentStore.getStore(),published=store?.estimatedUsd;return store&&(store.estimatedUsd=void 0),published})):createPayFetchWithPreAuth(fetch,x402,void 0,{skipPreAuth:paymentChain==="solana",estimateAmount,onPayment:options.onPayment,onPaymentDeclined:()=>paymentStore.getStore()?.sessionSpend?.voidLastSigned(),solanaBatch}),balanceMonitor;if(options._balanceMonitorOverride)balanceMonitor=options._balanceMonitorOverride;else if(authMode==="api-key")balanceMonitor=new ApiKeyBalanceMonitor;else if(paymentChain==="solana"&&solanaAddress){let{SolanaBalanceMonitor:SolanaBalanceMonitor2}=await Promise.resolve().then(()=>(init_solana_balance(),solana_balance_exports));balanceMonitor=new SolanaBalanceMonitor2(solanaAddress)}else balanceMonitor=new BalanceMonitor(account.address,evmBalanceChain(paymentChain));let routingConfig=mergeRoutingConfig(options.routingConfig),modelPricing=buildModelPricing(),routerOpts={config:routingConfig,modelPricing,modelCapabilities:buildModelCapabilities()},catalog=createClawCatalog({network:paymentChain==="solana"&&(apiKey||solanaPrivateKeyBytes)?"solana":"base",apiBase,apiKey}),catalogClosed=!1,refreshCatalog=async()=>{let previous=catalog.current(),view=await catalog.refresh();if(!(catalogClosed||view===previous)){routerOpts={...routerOpts,modelPricing:buildModelPricing(view.models),modelCapabilities:buildModelCapabilities(view.models)};try{options.onCatalogUpdated?.(view.visible)}catch{}}},deduplicator=new RequestDeduplicator,responseCache2=new ResponseCache(options.cacheConfig),sessionStore=new SessionStore(options.sessionConfig),sessionJournal=new SessionJournal,connections=new Set,server=createServer((req,res)=>{paymentStore.run({amountUsd:0},async()=>{req.on("error",err=>{console.error(`[ClawRouter] Request stream error: ${err.message}`)}),res.on("error",err=>{console.error(`[ClawRouter] Response stream error: ${err.message}`)}),finished(res,err=>{err&&err.code!=="ERR_STREAM_DESTROYED"&&console.error(`[ClawRouter] Response finished with error: ${err.message}`)}),finished(req,err=>{err&&err.code!=="ERR_STREAM_DESTROYED"&&console.error(`[ClawRouter] Request finished with error: ${err.message}`)});let untrusted=untrustedRequestReason(req);if(untrusted){console.warn(`[ClawRouter] Refused request to ${req.url}: ${untrusted}`),res.writeHead(403,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"forbidden",details:untrusted}));return}if(req.url==="/health"||req.url?.startsWith("/health?")){let full=new URL(req.url,"http://localhost").searchParams.get("full")==="true",response={status:"ok",authMode};if(authMode==="api-key"?(response.apiKey=maskApiKey(apiKey),response.gateway=apiBase):(response.wallet=account.address,response.paymentChain=paymentChain,response.gateway=apiBase,solanaAddress&&(response.solana=solanaAddress)),upstreamProxy&&(response.upstreamProxy=upstreamProxy),full)try{let balanceInfo=await Promise.race([balanceMonitor.checkBalance(),new Promise((_,reject)=>setTimeout(()=>reject(new Error("balance check timed out")),BALANCE_CHECK_TIMEOUT_MS).unref())]);if(authMode==="api-key"){let credit=await fetchCreditBalance(apiKey,BALANCE_CHECK_TIMEOUT_MS);response.balance=credit?.remainingUsd??null,response.creditSpent=credit?.spentUsd??null,response.creditGranted=credit?.grantedUsd??null,response.billingMode=credit?.billingMode??null,response.creditSummary=credit?formatCreditBalance(credit):null,response.blocked=credit?.blocked??!1,credit?.blockedReason&&(response.blockedReason=credit.blockedReason),response.isEmpty=credit?.remainingUsd!==null&&(credit?.remainingUsd??1)<=0,response.billing="BlockRun account credit",response.topUpUrl=PORTAL_CREDITS_URL}else response.balance=balanceInfo.balanceUSD,response.isLow=balanceInfo.isLow,response.isEmpty=balanceInfo.isEmpty}catch{response.balanceError="Could not fetch balance"}let headers={"Content-Type":"application/json","Cache-Control":"no-store"},challengeValue=req.headers["x-clawrouter-challenge"],challenge2=Array.isArray(challengeValue)?challengeValue[0]:challengeValue;if(challenge2&&/^[a-f0-9]{64}$/i.test(challenge2))try{let token=readFileSync8(DESKTOP_SERVICE_TOKEN_FILE,"utf8").trim();/^[a-f0-9]{64}$/i.test(token)&&(headers["X-ClawRouter-Proof"]=createHmac("sha256",token).update(challenge2).digest("hex"))}catch{}res.writeHead(200,headers),res.end(JSON.stringify(response));return}if(req.url==="/cache"||req.url?.startsWith("/cache?")){let stats=responseCache2.getStats();res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),res.end(JSON.stringify(stats,null,2));return}if(req.url==="/stats"&&req.method==="DELETE"){try{let result=await clearStats();res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({cleared:!0,deletedFiles:result.deletedFiles}))}catch(err){res.writeHead(500,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:`Failed to clear stats: ${err instanceof Error?err.message:String(err)}`}))}return}if(req.url==="/stats"||req.url?.startsWith("/stats?")){try{let url3=new URL(req.url,"http://localhost"),days=resolveStatsDays(url3.searchParams.get("days")),stats=await getStats(days);res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),res.end(JSON.stringify({...stats,providerErrors:Object.fromEntries(perProviderErrors)},null,2))}catch(err){res.writeHead(500,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:`Failed to get stats: ${err instanceof Error?err.message:String(err)}`}))}return}if(req.url==="/v1/models"&&req.method==="GET"){let models=buildProxyModelList(void 0,catalog.current());res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({object:"list",data:models}));return}if(req.url?.startsWith("/share")&&req.method==="GET"){try{let url3=new URL(req.url,"http://localhost"),path8=url3.pathname;if(path8==="/share/list"){let limit=Math.min(parseInt(url3.searchParams.get("limit")||"20",10),100),entries=await listRecent(limit);res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(entries.map(e7=>({id:e7.id,timestamp:e7.timestamp,model:e7.model,sessionId:e7.sessionId,requestSummary:e7.requestSummary,responseLength:e7.responseText.length}))));return}if(path8==="/share/last"){let sessionId=url3.searchParams.get("sessionId")||void 0,entry=await getLast(sessionId);if(!entry){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"no responses yet"}));return}let preset=url3.searchParams.get("as");if(preset&&isSharePreset(preset)){res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),res.end(JSON.stringify({id:entry.id,timestamp:entry.timestamp,model:entry.model,preset,rendered:transform2(entry.responseText,preset)}));return}res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(entry));return}let idMatch=path8.match(/^\/share\/(resp_[A-Za-z0-9_]+)(?:\/render)?$/);if(idMatch){let id2=idMatch[1],entry=await getById(id2);if(!entry){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:`no response with id ${id2}`}));return}let preset=url3.searchParams.get("as");if(preset&&isSharePreset(preset)){res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({id:entry.id,timestamp:entry.timestamp,model:entry.model,preset,rendered:transform2(entry.responseText,preset)}));return}res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(entry));return}res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"unknown share endpoint"}))}catch(err){res.writeHead(500,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:`share failed: ${err instanceof Error?err.message:String(err)}`}))}return}if(req.url?.startsWith("/images/")&&req.method==="GET"){let filename=req.url.slice(8).split("?")[0].replace(/[^a-zA-Z0-9._-]/g,"");if(!filename){res.writeHead(400),res.end("Bad request");return}let filePath=join17(IMAGE_DIR,filename);try{if(!(await fsStat(filePath)).isFile())throw new Error("not a file");let ext=filename.split(".").pop()?.toLowerCase()??"png",mime={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif"},data=await readFile3(filePath);res.writeHead(200,{"Content-Type":mime[ext]??"application/octet-stream","Content-Length":data.length}),res.end(data)}catch{res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Image not found"}))}return}if(req.url?.startsWith("/audio/")&&req.method==="GET"){let filename=req.url.slice(7).split("?")[0].replace(/[^a-zA-Z0-9._-]/g,"");if(!filename){res.writeHead(400),res.end("Bad request");return}let filePath=join17(AUDIO_DIR,filename);try{if(!(await fsStat(filePath)).isFile())throw new Error("not a file");let ext=filename.split(".").pop()?.toLowerCase()??"mp3",mime={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",m4a:"audio/mp4"},data=await readFile3(filePath);res.writeHead(200,{"Content-Type":mime[ext]??"audio/mpeg","Content-Length":data.length}),res.end(data)}catch{res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Audio not found"}))}return}if(req.url?.startsWith("/videos/")&&req.method==="GET"){let filename=req.url.slice(8).split("?")[0].replace(/[^a-zA-Z0-9._-]/g,"");if(!filename){res.writeHead(400),res.end("Bad request");return}let filePath=join17(VIDEO_DIR,filename);try{if(!(await fsStat(filePath)).isFile())throw new Error("not a file");let ext=filename.split(".").pop()?.toLowerCase()??"mp4",mime={mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime"},data=await readFile3(filePath);res.writeHead(200,{"Content-Type":mime[ext]??"video/mp4","Content-Length":data.length}),res.end(data)}catch{res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Video not found"}))}return}if(req.url==="/v1/images/generations"&&req.method==="POST"){let imgStartTime=Date.now(),clientAbort=new AbortController;res.on("close",()=>{res.writableEnded||clientAbort.abort()});let chunks=[];for await(let chunk of req)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let reqBody=Buffer.concat(chunks),imgModel="unknown",imgCost=0;try{let parsed=JSON.parse(reqBody.toString());imgModel=parsed.model||"google/nano-banana";let n=parsed.n||1;imgCost=estimateImageCost(imgModel,parsed.size,n)}catch{}try{publishDispatchCost(imgCost);let upstream=await payFetch(`${apiBase}/v1/images/generations`,{method:"POST",headers:{"content-type":"application/json","user-agent":USER_AGENT},body:reqBody,signal:clientAbort.signal}),text=await upstream.text();if(!upstream.ok&&upstream.status!==202){res.writeHead(upstream.status,{"Content-Type":"application/json"}),res.end(text);return}let result;try{result=JSON.parse(text)}catch{res.writeHead(200,{"Content-Type":"application/json"}),res.end(text);return}if(result.poll_url&&result.id&&!result.data?.length){let apiOrigin=new URL(apiBase).origin,pollUrl=result.poll_url.startsWith("http")?result.poll_url:`${apiOrigin}${result.poll_url}`;console.log(`[ClawRouter] Image job submitted (id=${result.id}), polling upstream \u2014 typical 30\u2013120s...`);let pollDeadline=Date.now()+3e5,pollInterval=3e3;await new Promise(r2=>setTimeout(r2,2e3));let pollError,completed=!1;for(;Date.now()<pollDeadline;){if(clientAbort.signal.aborted){console.log(`[ClawRouter] Client disconnected \u2014 abandoning image poll (id=${result.id})`);return}let pollResp=await payFetch(pollUrl,{method:"GET",headers:{"user-agent":USER_AGENT},signal:clientAbort.signal}),pollText=await pollResp.text(),pollBody={};try{pollBody=JSON.parse(pollText)}catch{pollError=`Non-JSON poll response (${pollResp.status}): ${pollText.slice(0,200)}`;break}if(pollResp.status===202||pollBody.status==="queued"||pollBody.status==="in_progress"){await new Promise(r2=>setTimeout(r2,pollInterval));continue}if(pollBody.status==="failed"){pollError=pollBody.error??"Upstream image generation failed";break}if(pollResp.ok&&pollBody.status==="completed"){result=pollBody,completed=!0;break}if(!pollResp.ok){res.writeHead(pollResp.status,{"Content-Type":"application/json"}),res.end(pollText);return}result=pollBody,completed=!0;break}if(pollError){res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Image generation failed",details:pollError}));return}if(!completed){res.writeHead(504,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Image generation timed out",details:`Upstream did not complete within 5 minutes (job id=${result.id}). No payment has been settled.`}));return}}if(result.data?.length){await mkdir6(IMAGE_DIR,{recursive:!0});let port2=server.address()?.port??8402;for(let img of result.data){let dataUriMatch=img.url?.match(/^data:(image\/\w+);base64,(.+)$/);if(dataUriMatch){let[,mimeType,b64]=dataUriMatch,ext=mimeType==="image/jpeg"?"jpg":mimeType.split("/")[1]??"png",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`;await writeFile4(join17(IMAGE_DIR,filename),Buffer.from(b64,"base64")),img.url=`http://localhost:${port2}/images/${filename}`,console.log(`[ClawRouter] Image saved \u2192 ${img.url}`)}else if(img.url?.startsWith("https://")||img.url?.startsWith("http://"))try{let imgResp=await fetch(img.url,{signal:clientAbort.signal});if(imgResp.ok){let contentType=imgResp.headers.get("content-type")??"image/png",ext=contentType.includes("jpeg")||contentType.includes("jpg")?"jpg":contentType.includes("webp")?"webp":"png",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`,buf=Buffer.from(await imgResp.arrayBuffer());await writeFile4(join17(IMAGE_DIR,filename),buf),img.url=`http://localhost:${port2}/images/${filename}`,console.log(`[ClawRouter] Image downloaded & saved \u2192 ${img.url}`)}}catch(downloadErr){console.warn(`[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error?downloadErr.message:String(downloadErr)}`)}}}let imgActualCost=settledMediaCostUsd(upstream,result,paymentStore.getStore()?.amountUsd,imgCost);logUsage({timestamp:new Date().toISOString(),...blockrunRequestId(upstream)?{requestId:blockrunRequestId(upstream)}:{},model:imgModel,tier:"IMAGE",cost:imgActualCost,baselineCost:imgActualCost,savings:0,latencyMs:Date.now()-imgStartTime}).catch(()=>{}),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(result))}catch(err){if(clientAbort.signal.aborted||refuseOverCostCap(res,err))return;let msg=err instanceof Error?err.message:String(err);console.error(`[ClawRouter] Image generation error: ${msg}`),res.headersSent||(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Image generation failed",details:msg})))}return}if(req.url==="/v1/images/image2image"&&req.method==="POST"){let img2imgStartTime=Date.now(),clientAbort=new AbortController;res.on("close",()=>{res.writableEnded||clientAbort.abort()});let chunks=[];for await(let chunk of req)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let rawBody=Buffer.concat(chunks),reqBody,img2imgModel="openai/gpt-image-1",img2imgCost=0;try{let parsed=JSON.parse(rawBody.toString());for(let field of["image","mask"]){let val=parsed[field];if(!(typeof val!="string"||!val)&&!val.startsWith("data:"))if(val.startsWith("https://")||val.startsWith("http://")){let imgResp=await ssrfSafeFetch(val,{signal:clientAbort.signal,allowPrivate:process.env.CLAWROUTER_ALLOW_PRIVATE_FETCH==="1",viaUpstreamProxy:!!upstreamProxy});if(!imgResp.ok)throw new Error(`Failed to download ${field} from ${val}: HTTP ${imgResp.status}`);let contentType=imgResp.headers.get("content-type")??"image/png",buf=Buffer.from(await imgResp.arrayBuffer());parsed[field]=`data:${contentType};base64,${buf.toString("base64")}`,console.log(`[ClawRouter] img2img: downloaded ${field} URL \u2192 data URI (${buf.length} bytes)`)}else parsed[field]=readLocalImageAsDataUri(val),console.log(`[ClawRouter] img2img: read ${field} file \u2192 data URI`)}parsed.model||(parsed.model="openai/gpt-image-1"),img2imgModel=parsed.model,img2imgCost=estimateImageCost(img2imgModel,parsed.size,parsed.n||1),reqBody=JSON.stringify(parsed)}catch(parseErr){if(clientAbort.signal.aborted)return;let msg=parseErr instanceof Error?parseErr.message:String(parseErr);res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid request",details:msg}));return}try{publishDispatchCost(img2imgCost);let upstream=await payFetch(`${apiBase}/v1/images/image2image`,{method:"POST",headers:{"content-type":"application/json","user-agent":USER_AGENT},body:reqBody,signal:clientAbort.signal});authMode==="api-key"&&(upstream=await pollApiKeyJob(upstream,payFetch,apiBase,clientAbort.signal));let text=await upstream.text();if(!upstream.ok){res.writeHead(upstream.status,{"Content-Type":"application/json"}),res.end(text);return}let result;try{result=JSON.parse(text)}catch{res.writeHead(200,{"Content-Type":"application/json"}),res.end(text);return}if(result.data?.length){await mkdir6(IMAGE_DIR,{recursive:!0});let port2=server.address()?.port??8402;for(let img of result.data){let dataUriMatch=img.url?.match(/^data:(image\/\w+);base64,(.+)$/);if(dataUriMatch){let[,mimeType,b64]=dataUriMatch,ext=mimeType==="image/jpeg"?"jpg":mimeType.split("/")[1]??"png",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`;await writeFile4(join17(IMAGE_DIR,filename),Buffer.from(b64,"base64")),img.url=`http://localhost:${port2}/images/${filename}`,console.log(`[ClawRouter] Image saved \u2192 ${img.url}`)}else if(img.url?.startsWith("https://")||img.url?.startsWith("http://"))try{let imgResp=await fetch(img.url,{signal:clientAbort.signal});if(imgResp.ok){let contentType=imgResp.headers.get("content-type")??"image/png",ext=contentType.includes("jpeg")||contentType.includes("jpg")?"jpg":contentType.includes("webp")?"webp":"png",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`,buf=Buffer.from(await imgResp.arrayBuffer());await writeFile4(join17(IMAGE_DIR,filename),buf),img.url=`http://localhost:${port2}/images/${filename}`,console.log(`[ClawRouter] Image downloaded & saved \u2192 ${img.url}`)}}catch(downloadErr){console.warn(`[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error?downloadErr.message:String(downloadErr)}`)}}}let img2imgActualCost=settledMediaCostUsd(upstream,result,paymentStore.getStore()?.amountUsd,img2imgCost);logUsage({timestamp:new Date().toISOString(),...blockrunRequestId(upstream)?{requestId:blockrunRequestId(upstream)}:{},model:img2imgModel,tier:"IMAGE",cost:img2imgActualCost,baselineCost:img2imgActualCost,savings:0,latencyMs:Date.now()-img2imgStartTime}).catch(()=>{}),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(result))}catch(err){if(clientAbort.signal.aborted||refuseOverCostCap(res,err))return;let msg=err instanceof Error?err.message:String(err);console.error(`[ClawRouter] Image editing error: ${msg}`),res.headersSent||(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Image editing failed",details:msg})))}return}if(req.url==="/v1/audio/generations"&&req.method==="POST"){let audioStartTime=Date.now(),clientAbort=new AbortController;res.on("close",()=>{res.writableEnded||clientAbort.abort()});let chunks=[];for await(let chunk of req)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let reqBody=Buffer.concat(chunks),audioModel="minimax/music-2.5+";try{audioModel=JSON.parse(reqBody.toString()).model||audioModel}catch{}try{publishDispatchCost(.15);let upstream=await payFetch(`${apiBase}/v1/audio/generations`,{method:"POST",headers:{"content-type":"application/json","user-agent":USER_AGENT},body:reqBody,signal:clientAbort.signal});authMode==="api-key"&&(upstream=await pollApiKeyJob(upstream,payFetch,apiBase,clientAbort.signal));let text=await upstream.text();if(!upstream.ok){res.writeHead(upstream.status,{"Content-Type":"application/json"}),res.end(text);return}let result;try{result=JSON.parse(text)}catch{res.writeHead(200,{"Content-Type":"application/json"}),res.end(text);return}if(result.data?.length){await mkdir6(AUDIO_DIR,{recursive:!0});let port2=server.address()?.port??8402;for(let track of result.data)if(track.url?.startsWith("https://")||track.url?.startsWith("http://"))try{let audioResp=await fetch(track.url,{signal:clientAbort.signal});if(audioResp.ok){let ext=(audioResp.headers.get("content-type")??"audio/mpeg").includes("wav")?"wav":"mp3",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`,buf=Buffer.from(await audioResp.arrayBuffer());await writeFile4(join17(AUDIO_DIR,filename),buf),track.url=`http://localhost:${port2}/audio/${filename}`,console.log(`[ClawRouter] Audio saved \u2192 ${track.url}`)}}catch(downloadErr){console.warn(`[ClawRouter] Failed to download audio, using original URL: ${downloadErr instanceof Error?downloadErr.message:String(downloadErr)}`)}}let audioActualCost=settledMediaCostUsd(upstream,result,paymentStore.getStore()?.amountUsd,.15);logUsage({timestamp:new Date().toISOString(),...blockrunRequestId(upstream)?{requestId:blockrunRequestId(upstream)}:{},model:audioModel,tier:"AUDIO",cost:audioActualCost,baselineCost:audioActualCost,savings:0,latencyMs:Date.now()-audioStartTime}).catch(()=>{}),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(result))}catch(err){if(clientAbort.signal.aborted||refuseOverCostCap(res,err))return;let msg=err instanceof Error?err.message:String(err);console.error(`[ClawRouter] Audio generation error: ${msg}`),res.headersSent||(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Audio generation failed",details:msg})))}return}if(req.url==="/v1/videos/generations"&&req.method==="POST"){let videoStartTime=Date.now(),clientAbort=new AbortController;res.on("close",()=>{res.writableEnded||clientAbort.abort()});let chunks=[];for await(let chunk of req)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let reqBody=Buffer.concat(chunks),videoModel="xai/grok-imagine-video",videoDuration,videoHasImageInput=!1;try{let parsed=JSON.parse(reqBody.toString());videoModel=parsed.model||videoModel,videoDuration=typeof parsed.duration_seconds=="number"?parsed.duration_seconds:void 0,videoHasImageInput=typeof parsed.image_url=="string"&&parsed.image_url.length>0}catch{}try{publishDispatchCost(estimateVideoCost(videoModel,videoDuration,videoHasImageInput));let submitResp=await payFetch(`${apiBase}/v1/videos/generations`,{method:"POST",headers:{"content-type":"application/json","user-agent":USER_AGENT},body:reqBody,signal:clientAbort.signal}),submitText=await submitResp.text();if(!submitResp.ok&&submitResp.status!==202){res.writeHead(submitResp.status,{"Content-Type":"application/json"}),res.end(submitText);return}let submitResult;try{submitResult=JSON.parse(submitText)}catch{res.writeHead(200,{"Content-Type":"application/json"}),res.end(submitText);return}let finalResult=submitResult;if(submitResult.poll_url&&submitResult.id){let apiOrigin=new URL(apiBase).origin,pollUrl=submitResult.poll_url.startsWith("http")?submitResult.poll_url:`${apiOrigin}${submitResult.poll_url}`;console.log(`[ClawRouter] Video job submitted (id=${submitResult.id}), polling upstream \u2014 typical 60\u2013180s...`);let pollDeadline=Date.now()+3e5,pollInterval=5e3;await new Promise(r2=>setTimeout(r2,3e3));let pollError,videoCompleted=!1;for(;Date.now()<pollDeadline;){if(clientAbort.signal.aborted){console.log(`[ClawRouter] Client disconnected \u2014 abandoning video poll (id=${submitResult.id})`);return}let pollResp=await payFetch(pollUrl,{method:"GET",headers:{"user-agent":USER_AGENT},signal:clientAbort.signal}),pollText=await pollResp.text(),pollBody={};try{pollBody=JSON.parse(pollText)}catch{pollError=`Non-JSON poll response (${pollResp.status}): ${pollText.slice(0,200)}`;break}if(pollResp.status===202||pollBody.status==="queued"||pollBody.status==="in_progress"){await new Promise(r2=>setTimeout(r2,pollInterval));continue}if(pollBody.status==="failed"){pollError=pollBody.error??"Upstream video generation failed";break}if(pollResp.ok&&pollBody.status==="completed"){finalResult=pollBody,videoCompleted=!0;break}if(!pollResp.ok){res.writeHead(pollResp.status,{"Content-Type":"application/json"}),res.end(pollText);return}finalResult=pollBody,videoCompleted=!0;break}if(pollError){res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Video generation failed",details:pollError}));return}if(!videoCompleted){res.writeHead(504,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Video generation timed out",details:`Upstream did not complete within 5 minutes (job id=${submitResult.id}). No payment has been settled.`}));return}}if(finalResult.data?.length){await mkdir6(VIDEO_DIR,{recursive:!0});let port2=server.address()?.port??8402;for(let clip of finalResult.data)if(clip.url?.startsWith("https://")||clip.url?.startsWith("http://"))try{let videoResp=await fetch(clip.url,{signal:clientAbort.signal});if(videoResp.ok){let contentType=videoResp.headers.get("content-type")??"video/mp4",ext=contentType.includes("webm")?"webm":contentType.includes("quicktime")?"mov":"mp4",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`,buf=Buffer.from(await videoResp.arrayBuffer());await writeFile4(join17(VIDEO_DIR,filename),buf),clip.url=`http://localhost:${port2}/videos/${filename}`,console.log(`[ClawRouter] Video saved \u2192 ${clip.url}`)}}catch(downloadErr){console.warn(`[ClawRouter] Failed to download video, using original URL: ${downloadErr instanceof Error?downloadErr.message:String(downloadErr)}`)}}let videoActualCost=settledMediaCostUsd(void 0,submitResult,paymentStore.getStore()?.amountUsd,estimateVideoCost(videoModel,videoDuration,videoHasImageInput));logUsage({timestamp:new Date().toISOString(),model:videoModel,tier:"VIDEO",cost:videoActualCost,baselineCost:videoActualCost,savings:0,latencyMs:Date.now()-videoStartTime}).catch(()=>{}),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(finalResult))}catch(err){if(clientAbort.signal.aborted||refuseOverCostCap(res,err))return;let msg=err instanceof Error?err.message:String(err);console.error(`[ClawRouter] Video generation error: ${msg}`),res.headersSent||(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Video generation failed",details:msg})))}return}let isMessages=isMessagesPath(req.url);if(isMessages||req.url==="/v1/audio/speech"||(req.url?.startsWith("/v1/audio/speech?")??!1)||req.url?.match(PAID_API_PATH)){try{await proxyPaidApiRequest(req,res,apiBase,payFetch,()=>paymentStore.getStore()?.amountUsd??0,!1,authMode,isMessages&&options.maxCostPerRunUsd!==void 0&&options.maxCostPerRunUsd!==0?body=>capMessagesRequest(body,req.headers,{usd:options.maxCostPerRunUsd,mode:options.maxCostPerRunMode??"graceful",authMode,sessions:sessionStore,models:catalog.current().models,isFree:isFreeForCap}):void 0)}catch(err){if(refuseOverCostCap(res,err))return;let clientGone=isClientAbortError(err,res);clientGone||options.onError?.(err instanceof Error?err:new Error(String(err))),clientGone?res.writableEnded||res.destroy():res.headersSent?res.writableEnded||res.end():(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:{message:`Partner proxy error: ${err instanceof Error?err.message:String(err)}`,type:"partner_error"}})))}finally{paymentStore.getStore()?.sessionSpend?.release()}return}if(!req.url?.startsWith("/v1")){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Not found"}));return}if(authMode==="api-key"&&/^\/v1\//.test(req.url??"")&&!/^\/v1\/(?:chat\/completions|messages)(?:\?|$)/.test(req.url??"")){try{await proxyPaidApiRequest(req,res,apiBase,payFetch,()=>paymentStore.getStore()?.amountUsd??0,!0,authMode)}catch(err){if(refuseOverCostCap(res,err))return;let clientGone=isClientAbortError(err,res);clientGone||options.onError?.(err instanceof Error?err:new Error(String(err))),clientGone?res.writableEnded||res.destroy():res.headersSent?res.writableEnded||res.end():(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:{message:`Account API error: ${err instanceof Error?err.message:String(err)}`,type:"account_error"}})))}finally{paymentStore.getStore()?.sessionSpend?.release()}return}if(!req.url.includes("/chat/completions")){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:{message:`ClawRouter does not proxy ${req.url}. It serves /v1/chat/completions, /v1/messages, /v1/models, /v1/images/generations, /v1/images/image2image, /v1/videos/generations, /v1/audio/generations, /v1/audio/speech, and the partner prefixes /v1/{partner,pm,exa,modal,stocks,usstock,crypto,fx,commodity,phone,voice}/. If BlockRun serves this endpoint, call it directly against the gateway.`,type:"invalid_request_error",code:"unsupported_endpoint"}}));return}try{await proxyRequest(req,res,apiBase,payFetch,requestOptions,routerOpts,deduplicator,balanceMonitor,sessionStore,responseCache2,sessionJournal,catalog.current())}catch(err){let error62=err instanceof Error?err:new Error(String(err));options.onError?.(error62),res.headersSent?res.writableEnded||(res.write(`data: ${JSON.stringify({error:{message:error62.message,type:"proxy_error"}})}
|
|
2479
|
+
`+inner+"\n```"}return seg.content}function applyTextRulesPerPreset(text,preset){switch(preset){case"feishu":return applyFeishu(text);case"slack":return applySlackText(text);case"discord":return text;case"telegram":return applyTelegramText(preProcessTelegram(text));case"whatsapp":return applyWhatsappText(text);case"plain":return applyPlainText(text)}}function transform2(md,preset){let afterTables=splitByFences(md).map(seg=>seg.isFence?seg.content:transformTablesInProse(seg.content,preset)).join("");return splitByFences(afterTables).map(seg=>seg.isFence?transformFenceForPreset(seg,preset):applyTextRulesPerPreset(seg.content,preset)).join("")}var SHARE_PRESETS,TELEGRAM_MAX_LEN,TELEGRAM_SUFFIX_RESERVE,TELEGRAM_CHUNK_CONTENT_LIMIT,PH_BOLD,PH_LINK,PH_END,TABLE_BLOCK_REGEX,TELEGRAM_ESCAPE_CHARS,init_share_formatters=__esm({"src/share-formatters.ts"(){"use strict";SHARE_PRESETS=["feishu","slack","discord","telegram","whatsapp","plain"];TELEGRAM_MAX_LEN=4096,TELEGRAM_SUFFIX_RESERVE=24,TELEGRAM_CHUNK_CONTENT_LIMIT=TELEGRAM_MAX_LEN-TELEGRAM_SUFFIX_RESERVE,PH_BOLD="__CR_PH_BOLD_",PH_LINK="__CR_PH_LINK_",PH_END="__";TABLE_BLOCK_REGEX=/(^|\n)((?:[ \t]*\|.*\|[ \t]*\n)(?:[ \t]*\|[\s:|-]+\|[ \t]*\n)(?:[ \t]*\|.*\|[ \t]*\n?)*)/g;TELEGRAM_ESCAPE_CHARS="_*[]()~`>#+-=|{}.!"}});var solana_balance_exports={};__export(solana_balance_exports,{SolanaBalanceMonitor:()=>SolanaBalanceMonitor});var SOLANA_USDC_MINT,SOLANA_DEFAULT_RPC,BALANCE_TIMEOUT_MS,CACHE_TTL_MS2,SolanaBalanceMonitor,init_solana_balance=__esm({"src/solana-balance.ts"(){"use strict";init_index_node39();SOLANA_USDC_MINT="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",SOLANA_DEFAULT_RPC="https://api.mainnet-beta.solana.com",BALANCE_TIMEOUT_MS=1e4,CACHE_TTL_MS2=3e4,SolanaBalanceMonitor=class{rpc;walletAddress;cachedBalance=null;cachedAt=0;inflightFetch=null;cacheEpoch=0;constructor(walletAddress,rpcUrl){this.walletAddress=walletAddress;let url3=rpcUrl||process.env.CLAWROUTER_SOLANA_RPC_URL||SOLANA_DEFAULT_RPC;this.rpc=createSolanaRpc(url3)}async checkBalance(){let now2=Date.now();if(this.cachedBalance!==null&&this.cachedBalance>0n&&now2-this.cachedAt<CACHE_TTL_MS2)return this.buildInfo(this.cachedBalance);let pending=this.inflightFetch;if(!pending){let epoch=this.cacheEpoch;pending=this.fetchBalance().then(balance2=>(this.cacheEpoch===epoch&&(balance2>0n?(this.cachedBalance=balance2,this.cachedAt=Date.now()):(this.cachedBalance=null,this.cachedAt=0)),balance2)).finally(()=>{this.inflightFetch===pending&&(this.inflightFetch=null)}),this.inflightFetch=pending}let balance=await pending;return this.buildInfo(balance)}deductEstimated(amountMicros){this.cachedBalance!==null&&this.cachedBalance>=amountMicros&&(this.cachedBalance-=amountMicros)}invalidate(){this.cacheEpoch++,this.cachedBalance=null,this.cachedAt=0,this.inflightFetch=null}async refresh(){return this.invalidate(),this.checkBalance()}async checkSufficient(estimatedCostMicros){let info=await this.checkBalance();if(info.balance>=estimatedCostMicros)return{sufficient:!0,info};let shortfall=estimatedCostMicros-info.balance;return{sufficient:!1,info,shortfall:this.formatUSDC(shortfall)}}formatUSDC(amountMicros){return`$${(Number(amountMicros)/1e6).toFixed(2)}`}getWalletAddress(){return this.walletAddress}async checkSolBalance(){let controller=new AbortController,timer2=setTimeout(()=>controller.abort(),BALANCE_TIMEOUT_MS);try{let owner=address2(this.walletAddress),response=await this.rpc.getBalance(owner).send({abortSignal:controller.signal});return BigInt(response.value)}catch{return 0n}finally{clearTimeout(timer2)}}async fetchBalance(){let owner=address2(this.walletAddress),mint4=address2(SOLANA_USDC_MINT),MAX_ATTEMPTS=3,lastError;for(let attempt=0;attempt<MAX_ATTEMPTS;attempt++)try{let result=await this.fetchBalanceOnce(owner,mint4);if(result>0n)return result;attempt<MAX_ATTEMPTS-1&&await new Promise(r2=>setTimeout(r2,1500*(attempt+1)))}catch(err){lastError=err,attempt<MAX_ATTEMPTS-1&&await new Promise(r2=>setTimeout(r2,1500*(attempt+1)))}if(lastError!==void 0)throw lastError;return 0n}async fetchBalanceOnce(owner,mint4){let controller=new AbortController,timer2=setTimeout(()=>controller.abort(),BALANCE_TIMEOUT_MS);try{let response=await this.rpc.getTokenAccountsByOwner(owner,{mint:mint4},{encoding:"jsonParsed"}).send({abortSignal:controller.signal});if(response.value.length===0)return 0n;let total=0n;for(let account of response.value){let parsed=account.account.data;total+=BigInt(parsed.parsed.info.tokenAmount.amount)}return total}catch(err){throw new Error(`Failed to fetch Solana USDC balance: ${err instanceof Error?err.message:String(err)}`,{cause:err})}finally{clearTimeout(timer2)}}buildInfo(balance){let dollars=Number(balance)/1e6;return{balance,balanceUSD:`$${dollars.toFixed(2)}`,isLow:balance<1000000n,isEmpty:balance<100n,walletAddress:this.walletAddress}}}}});var NETWORKS2,init_chunk_WWACQNRQ=__esm({"node_modules/@x402/svm/dist/esm/chunk-WWACQNRQ.mjs"(){"use strict";NETWORKS2=["solana","solana-devnet","solana-testnet"]}});var ExactSvmSchemeV1,init_chunk_PQ2KWLVO=__esm({"node_modules/@x402/svm/dist/esm/chunk-PQ2KWLVO.mjs"(){"use strict";init_chunk_WIPN332D();init_chunk_RZ6M7L3U();init_chunk_DAIKIZVB();init_src2();init_src3();init_index_node39();ExactSvmSchemeV1=class{constructor(signer,config2){this.signer=signer,this.config=config2,this.scheme="exact",this.findDefaultAsset=findDefaultAsset2,this.mintCache=new Map}async createPaymentPayload(x402Version2,paymentRequirements){let selectedV1=paymentRequirements,transactionVersion=resolveTransactionVersion(paymentRequirements.extra,this.config?.transactionVersions),rpc=createRpcClient(selectedV1.network,this.config?.rpcUrl),mintMetadata=await getCachedMintMetadata(rpc,selectedV1.network,selectedV1.asset,this.mintCache),tokenProgramAddress=mintMetadata.programAddress;if(tokenProgramAddress.toString()!==TOKEN_PROGRAM_ADDRESS.toString()&&tokenProgramAddress.toString()!==TOKEN_2022_PROGRAM_ADDRESS.toString())throw new Error("Asset was not created by a known token program");let[sourceATA]=await findAssociatedTokenPda({mint:selectedV1.asset,owner:this.signer.address,tokenProgram:tokenProgramAddress}),[destinationATA]=await findAssociatedTokenPda({mint:selectedV1.asset,owner:selectedV1.payTo,tokenProgram:tokenProgramAddress}),transferIx=getTransferCheckedInstruction({source:sourceATA,mint:selectedV1.asset,destination:destinationATA,authority:this.signer,amount:BigInt(selectedV1.maxAmountRequired),decimals:mintMetadata.decimals},{programAddress:tokenProgramAddress}),feePayer=selectedV1.extra?.feePayer;if(!feePayer)throw new Error("feePayer is required in paymentRequirements.extra for SVM transactions");let{value:latestBlockhash}=await rpc.getLatestBlockhash().send(),sellerMemo=selectedV1.extra?.memo,memoData;if(sellerMemo){if(memoData=new TextEncoder().encode(sellerMemo),memoData.byteLength>MAX_MEMO_BYTES)throw new Error(`extra.memo exceeds maximum ${MAX_MEMO_BYTES} bytes`)}else{let nonce2=crypto.getRandomValues(new Uint8Array(16));memoData=new TextEncoder().encode(Array.from(nonce2).map(b=>b.toString(16).padStart(2,"0")).join(""))}let memoIx={programAddress:MEMO_PROGRAM_ADDRESS,accounts:[],data:memoData},budget={computeUnitLimit:DEFAULT_COMPUTE_UNIT_LIMIT,computeUnitPriceMicroLamports:DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS},tx=pipe2(createTransactionMessage({version:transactionVersion}),tx2=>applyTransactionV1Config(transactionVersion,budget,tx2),tx2=>setTransactionMessageFeePayer(feePayer,tx2),tx2=>appendTransactionMessageInstructions([...computeBudgetInstructions(transactionVersion,budget),transferIx,memoIx],tx2),tx2=>setTransactionMessageLifetimeUsingBlockhash(latestBlockhash,tx2)),signedTransaction=await partiallySignTransactionMessageWithSigners(tx),payload={transaction:getBase64EncodedWireTransaction(signedTransaction)};return{x402Version:x402Version2,scheme:selectedV1.scheme,network:selectedV1.network,payload}}}}});var PENDING_SETTLEMENT_TTL_MS,init_facilitator=__esm({"node_modules/@x402/core/dist/esm/facilitator/index.mjs"(){"use strict";init_chunk_VE37GDG2();init_chunk_XW2CWVLZ();PENDING_SETTLEMENT_TTL_MS=300*1e3}});var addressEncoder,compiledMessageDecoder,compiledMessageDecoder2,init_chunk_RCDWMK2L=__esm({"node_modules/@x402/svm/dist/esm/chunk-RCDWMK2L.mjs"(){"use strict";init_chunk_7TSGYOB2();init_chunk_L56Y5KBE();init_chunk_RZ6M7L3U();init_chunk_DAIKIZVB();init_index_node39();init_facilitator();init_index_node39();init_index_node39();addressEncoder=getAddressEncoder(),compiledMessageDecoder=getCompiledTransactionMessageDecoder(),compiledMessageDecoder2=getCompiledTransactionMessageDecoder()}});var client_exports3={};__export(client_exports3,{ExactSvmScheme:()=>ExactSvmScheme,registerExactSvmScheme:()=>registerExactSvmScheme});function registerExactSvmScheme(client,config2){return config2.networks&&config2.networks.length>0?config2.networks.forEach(network=>{client.register(network,new ExactSvmScheme(config2.signer))}):client.register("solana:*",new ExactSvmScheme(config2.signer)),(config2.networks&&config2.networks.length>0?NETWORKS2.filter(name=>{let v2Network=V1_TO_V2_NETWORK_MAP[name];return v2Network?config2.networks.some(pattern=>networkMatchesPattern(pattern,v2Network)):!1}):NETWORKS2).forEach(network=>{client.registerV1(network,new ExactSvmSchemeV1(config2.signer))}),config2.policies&&config2.policies.forEach(policy=>{client.registerPolicy(policy)}),client}var init_client4=__esm({"node_modules/@x402/svm/dist/esm/exact/client/index.mjs"(){"use strict";init_chunk_2P7IHAQJ();init_chunk_WWACQNRQ();init_chunk_PQ2KWLVO();init_chunk_WIPN332D();init_chunk_RCDWMK2L();init_chunk_7TSGYOB2();init_chunk_L56Y5KBE();init_chunk_RZ6M7L3U();init_chunk_DAIKIZVB();init_utils14()}});var v1_exports={};__export(v1_exports,{ExactSvmSchemeV1:()=>ExactSvmSchemeV1,NETWORKS:()=>NETWORKS2});var init_v1=__esm({"node_modules/@x402/svm/dist/esm/v1/index.mjs"(){"use strict";init_chunk_WWACQNRQ();init_chunk_PQ2KWLVO();init_chunk_WIPN332D();init_chunk_RCDWMK2L();init_chunk_7TSGYOB2();init_chunk_L56Y5KBE();init_chunk_RZ6M7L3U();init_chunk_DAIKIZVB()}});import{AsyncLocalStorage as AsyncLocalStorage2}from"async_hooks";import{createHmac}from"crypto";import{createServer}from"http";import{finished,Readable as Readable2,Transform}from"stream";import{pipeline}from"stream/promises";import{homedir as homedir13}from"os";import{join as join17}from"path";import{mkdir as mkdir6,writeFile as writeFile4,readFile as readFile3,stat as fsStat}from"fs/promises";import{readFileSync as readFileSync8}from"fs";function describePaymentNetwork(network){return network===CAIP2_ARC?`${PAYMENT_CHAIN_LABELS.arc} (EVM)`:network.startsWith("eip155")?`${PAYMENT_CHAIN_LABELS.base} (EVM)`:network.startsWith("solana")?PAYMENT_CHAIN_LABELS.solana:network}function stampsBuilderCode(network){return network.startsWith("eip155")&&network!==CAIP2_ARC}function walletGatewayFor(chain3,hasSolanaKey){return chain3==="solana"?hasSolanaKey?BLOCKRUN_SOLANA_API:BLOCKRUN_API:chain3==="arc"?BLOCKRUN_ARC_API:BLOCKRUN_API}function evmBalanceChain(chain3){return chain3==="arc"?"arc":"base"}async function loadGatewayCatalog(apiBase,apiKey){try{let controller=new AbortController,timer2=setTimeout(()=>controller.abort(),GATEWAY_CATALOG_TIMEOUT_MS),res=await(apiKey?createApiKeyFetch(apiKey,fetch,apiBase):fetch)(`${apiBase}/v1/models`,{signal:controller.signal});if(clearTimeout(timer2),!res.ok)return;let ids=((await res.json()).data??[]).map(m=>m.id).filter(id2=>!!id2);if(ids.length===0)return;gatewayModelIds=new Set(ids);let unserved=[...FREE_MODELS].filter(m=>!gatewayModelIds.has(toUpstreamModelId(m)));unserved.length>0&&console.log(`[ClawRouter] Free models not served by this gateway (skipped in the cascade): ${unserved.join(", ")}`)}catch{}}function isServedByGateway(modelId){return gatewayModelIds?gatewayModelIds.has(toUpstreamModelId(modelId)):!0}function pickFreeModel(excludeList){for(let m of FREE_MODELS)if(!excludeList?.has(m)&&isServedByGateway(m))return m;for(let m of FREE_MODELS)if(!excludeList?.has(m))return m}function toUpstreamModelId(modelId){let override=FREE_UPSTREAM_OVERRIDES[modelId];return override||(modelId.startsWith("free/")?"nvidia/"+modelId.slice(5):modelId)}function timeoutForModel(modelId,models){return models.get(modelId)?.reasoning?REASONING_MODEL_TIMEOUT_MS:PER_MODEL_TIMEOUT_MS}function isClientAbortError(err,res){return err instanceof ClientDisconnectedError?!0:err instanceof Error?res.destroyed&&!res.writableEnded&&(err.name==="AbortError"||err.message.includes("aborted")):!1}async function readBodyWithTimeout(body,timeoutMs=MODEL_BODY_READ_TIMEOUT_MS,signal,abortError=()=>new ClientDisconnectedError){if(!body)return[];if(signal?.aborted)throw await body.cancel().catch(()=>{}),abortError();let reader=body.getReader(),chunks=[],timer2,abortHandler;try{for(;;){if(signal?.aborted)throw abortError();let abortPromise=signal?new Promise((_,reject)=>{abortHandler=()=>reject(abortError()),signal.addEventListener("abort",abortHandler,{once:!0})}):null,result=await Promise.race([reader.read(),new Promise((_,reject)=>{timer2=setTimeout(()=>reject(new Error("Body read timeout")),timeoutMs)}),...abortPromise?[abortPromise]:[]]);if(clearTimeout(timer2),signal&&abortHandler&&(signal.removeEventListener("abort",abortHandler),abortHandler=void 0),result.done)break;chunks.push(result.value)}}catch(err){throw await reader.cancel().catch(()=>{}),err}finally{clearTimeout(timer2),signal&&abortHandler&&signal.removeEventListener("abort",abortHandler),reader.releaseLock()}return chunks}function transformPaymentError(errorBody,evmChain="Base"){try{let parsed=JSON.parse(errorBody);if(parsed.error==="Payment verification failed"&&parsed.details){let match=parsed.details.match(/Verification failed:\s*(\{.*\})/s);if(match){let innerJson=JSON.parse(match[1]);if(innerJson.invalidReason==="insufficient_funds"&&innerJson.invalidMessage){let balanceMatch=innerJson.invalidMessage.match(/insufficient balance:\s*(\d+)\s*<\s*(\d+)/i);if(balanceMatch){let currentMicros=parseInt(balanceMatch[1],10),requiredMicros=parseInt(balanceMatch[2],10),currentUSD=(currentMicros/1e6).toFixed(6),requiredUSD=(requiredMicros/1e6).toFixed(6),wallet=innerJson.payer||"unknown",shortWallet=wallet.length>12?`${wallet.slice(0,6)}...${wallet.slice(-4)}`:wallet;return JSON.stringify({error:{message:`Insufficient USDC balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`,type:"insufficient_funds",wallet,current_balance_usd:currentUSD,required_usd:requiredUSD,help:`Fund wallet ${shortWallet} with USDC on ${evmChain}, or use free model: /model free`}})}}if(innerJson.invalidReason==="invalid_payload")return JSON.stringify({error:{message:"Payment signature invalid. This may be a temporary issue.",type:"invalid_payload",help:"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash"}});if(innerJson.invalidReason==="transaction_simulation_failed")return console.error(`[ClawRouter] Solana transaction simulation failed: ${innerJson.invalidMessage||"unknown"}`),JSON.stringify({error:{message:"Solana payment simulation failed. Retrying with a different model.",type:"transaction_simulation_failed",help:"This is usually temporary. If it persists, check your Solana USDC balance or try: /model free"}})}}if(parsed.error==="Payment verification failed"&&parsed.code==="PAYMENT_INVALID"&&parsed.debug){let debugLower=parsed.debug.toLowerCase(),wallet=parsed.payer||"unknown",shortWallet=wallet.length>12?`${wallet.slice(0,6)}...${wallet.slice(-4)}`:wallet,chain3=wallet.startsWith("0x")?evmChain:"Solana";return debugLower.includes("insufficient")?JSON.stringify({error:{message:`Insufficient ${chain3} USDC balance.`,type:"insufficient_funds",wallet,help:chain3==="Solana"?`Fund wallet ${shortWallet} with USDC on Solana, or switch to Base: /wallet base`:`Fund wallet ${shortWallet} with USDC on ${chain3}, or use free model: /model free`}}):debugLower.includes("transaction_simulation_failed")||debugLower.includes("simulation")?(console.error(`[ClawRouter] ${chain3} transaction simulation failed: ${parsed.debug}`),JSON.stringify({error:{message:`${chain3} payment simulation failed. Retrying with a different model.`,type:"transaction_simulation_failed",help:"This is usually temporary. If it persists, try: /model free"}})):debugLower.includes("invalid signature")||debugLower.includes("invalid_signature")?JSON.stringify({error:{message:`${chain3} payment signature invalid.`,type:"invalid_payload",help:"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash"}}):debugLower.includes("expired")?JSON.stringify({error:{message:`${chain3} payment expired. Retrying.`,type:"expired",help:"This is usually temporary."}}):(console.error(`[ClawRouter] ${chain3} payment verification failed: ${parsed.debug} payer=${wallet}`),JSON.stringify({error:{message:`${chain3} payment verification failed: ${parsed.debug}`,type:"payment_invalid",wallet,help:chain3==="Solana"?"Try again or switch to Base: /wallet base":"Try again. If this persists, try: /model free"}}))}if(parsed.error==="Settlement failed"||parsed.error==="Payment settlement failed"||parsed.details?.includes("Settlement failed")||parsed.details?.includes("transaction_simulation_failed")){let gasError=(parsed.details||"").includes("unable to estimate gas");return JSON.stringify({error:{message:gasError?"Payment failed: network congestion or gas issue. Try again.":"Payment settlement failed. Try again in a moment.",type:"settlement_failed",help:"This is usually temporary. If it persists, try: /model free"}})}}catch{}return errorBody}function categorizeError(status2,body){return status2===401?"auth_failure":status2===402?"payment_error":status2===403?/plan.*limit|quota.*exceeded|subscription|allowance/i.test(body)?"quota_exceeded":"auth_failure":status2===429?"rate_limited":status2===529||status2===503&&/overload|capacity|too.*many.*request/i.test(body)?"overloaded":status2>=500?"server_error":(status2===400||status2===413)&&PROVIDER_ERROR_PATTERNS.some(p=>p.test(body))?"config_error":null}function recordProviderError(modelId,category){perProviderErrors.has(modelId)||perProviderErrors.set(modelId,{auth_failure:0,quota_exceeded:0,rate_limited:0,overloaded:0,server_error:0,payment_error:0,config_error:0}),perProviderErrors.get(modelId)[category]++}function isRateLimited(modelId){let hitTime=rateLimitedModels.get(modelId);return hitTime?Date.now()-hitTime>=RATE_LIMIT_COOLDOWN_MS?(rateLimitedModels.delete(modelId),!1):!0:!1}function markRateLimited(modelId){rateLimitedModels.set(modelId,Date.now()),console.log(`[ClawRouter] Model ${modelId} rate-limited, will deprioritize for 60s`)}function markOverloaded(modelId){overloadedModels.set(modelId,Date.now()),console.log(`[ClawRouter] Model ${modelId} overloaded, will deprioritize for 15s`)}function isOverloaded(modelId){let hitTime=overloadedModels.get(modelId);return hitTime?Date.now()-hitTime>=OVERLOAD_COOLDOWN_MS?(overloadedModels.delete(modelId),!1):!0:!1}function prioritizeNonRateLimited(models){let available=[],degraded=[];for(let model of models)isRateLimited(model)||isOverloaded(model)?degraded.push(model):available.push(model);return[...available,...degraded]}function canWrite(res){return!res.writableEnded&&!res.destroyed&&res.socket!==null&&!res.socket.destroyed&&res.socket.writable}function safeWrite(res,data){if(!canWrite(res)){let bytes=typeof data=="string"?Buffer.byteLength(data):data.length;return console.warn(`[ClawRouter] safeWrite: socket not writable, dropping ${bytes} bytes`),!1}return res.write(data)}function sanitizeHeaderValue(value){return value.replace(/[^\t\x20-\x7E]/gu,c=>{try{return encodeURIComponent(c)}catch{return"?"}})}function debugHeadersEnabledFromEnv(env=process.env){let value=(env.CLAWROUTER_DEBUG_HEADERS??"").toLowerCase();return value!=="0"&&value!=="false"&&value!=="off"}function getProxyPort(){return PROXY_PORT}async function checkExistingProxy(port){let controller=new AbortController,timeoutId=setTimeout(()=>controller.abort(),HEALTH_CHECK_TIMEOUT_MS);try{let response=await fetch(`http://127.0.0.1:${port}/health`,{signal:controller.signal});if(clearTimeout(timeoutId),response.ok){let data=await response.json(),authMode=data.authMode==="api-key"?"api-key":"wallet";if(data.status==="ok"&&(data.wallet||authMode==="api-key"))return{wallet:data.wallet??"",paymentChain:data.paymentChain,authMode,apiKeyLabel:typeof data.apiKey=="string"?data.apiKey:void 0}}return}catch{clearTimeout(timeoutId);return}}function extractAssistantContent(payload){if(!payload||typeof payload!="object")return;let choices=payload.choices;if(!Array.isArray(choices)||choices.length===0)return;let firstChoice=choices[0];if(!firstChoice||typeof firstChoice!="object")return;let message=firstChoice.message;if(!message||typeof message!="object")return;let content=message.content;return typeof content=="string"?content:void 0}function hasKnownLoopSignature(text){if(DEGRADED_LOOP_PATTERNS.reduce((count,pattern)=>pattern.test(text)?count+1:count,0)>=2)return!0;let lines=text.split(/\r?\n/).map(line=>line.trim()).filter(Boolean);if(lines.length<8)return!1;let counts=new Map;for(let line of lines)counts.set(line,(counts.get(line)??0)+1);let maxRepeat=Math.max(...counts.values()),uniqueRatio=counts.size/lines.length;return maxRepeat>=3&&uniqueRatio<=.45}function detectDegradedSuccessResponse(body){let trimmed=body.trim();if(trimmed){if(DEGRADED_RESPONSE_PATTERNS.some(pattern=>pattern.test(trimmed)))return"degraded response: overloaded placeholder";if(hasKnownLoopSignature(trimmed))return"degraded response: repetitive loop output";try{let parsed=JSON.parse(trimmed),errorField=parsed.error,errorText="";if(typeof errorField=="string")errorText=errorField;else if(errorField&&typeof errorField=="object"){let errObj=errorField;errorText=[typeof errObj.message=="string"?errObj.message:"",typeof errObj.type=="string"?errObj.type:"",typeof errObj.code=="string"?errObj.code:""].filter(Boolean).join(" ")}if(errorText&&PROVIDER_ERROR_PATTERNS.some(pattern=>pattern.test(errorText)))return`degraded response: ${errorText.slice(0,120)}`;let choices=parsed.choices;if(Array.isArray(choices)&&choices.length===0)return"degraded response: no choices returned";if(Array.isArray(choices)&&choices.length>0){let choice=choices[0],msg=choice.message??choice.delta;if(msg){let content=msg.content,toolCalls=msg.tool_calls,hasContent=typeof content=="string"&&content.trim().length>0,hasToolCalls=Array.isArray(toolCalls)&&toolCalls.length>0,finishReason=choice.finish_reason;if(!hasContent&&!hasToolCalls&&finishReason==="stop")return"degraded response: empty turn (no content or tool calls)"}}let assistantContent=extractAssistantContent(parsed);if(!assistantContent)return;if(DEGRADED_RESPONSE_PATTERNS.some(pattern=>pattern.test(assistantContent)))return"degraded response: overloaded assistant content";if(hasKnownLoopSignature(assistantContent))return"degraded response: repetitive assistant loop"}catch{}}}function sanitizeToolId(id2){return!id2||typeof id2!="string"||VALID_TOOL_ID_PATTERN.test(id2)?id2:id2.replace(/[^a-zA-Z0-9_-]/g,"_")}function sanitizeToolIds(messages3){if(!messages3||messages3.length===0)return messages3;let hasChanges=!1,sanitized=messages3.map(msg=>{let typedMsg=msg,msgChanged=!1,newMsg={...msg};if(typedMsg.tool_calls&&Array.isArray(typedMsg.tool_calls)){let newToolCalls=typedMsg.tool_calls.map(tc=>{if(tc.id&&typeof tc.id=="string"){let sanitized2=sanitizeToolId(tc.id);if(sanitized2!==tc.id)return msgChanged=!0,{...tc,id:sanitized2}}return tc});msgChanged&&(newMsg={...newMsg,tool_calls:newToolCalls})}if(typedMsg.tool_call_id&&typeof typedMsg.tool_call_id=="string"){let sanitized2=sanitizeToolId(typedMsg.tool_call_id);sanitized2!==typedMsg.tool_call_id&&(msgChanged=!0,newMsg={...newMsg,tool_call_id:sanitized2})}if(Array.isArray(typedMsg.content)){let newContent=typedMsg.content.map(block=>{if(!block||typeof block!="object")return block;let blockChanged=!1,newBlock={...block};if(block.type==="tool_use"&&block.id&&typeof block.id=="string"){let sanitized2=sanitizeToolId(block.id);sanitized2!==block.id&&(blockChanged=!0,newBlock={...newBlock,id:sanitized2})}if(block.type==="tool_result"&&block.tool_use_id&&typeof block.tool_use_id=="string"){let sanitized2=sanitizeToolId(block.tool_use_id);sanitized2!==block.tool_use_id&&(blockChanged=!0,newBlock={...newBlock,tool_use_id:sanitized2})}return blockChanged?(msgChanged=!0,newBlock):block});msgChanged&&(newMsg={...newMsg,content:newContent})}return msgChanged?(hasChanges=!0,newMsg):msg});return hasChanges?sanitized:messages3}function normalizeMessageRoles(messages3){if(!messages3||messages3.length===0)return messages3;let hasChanges=!1,normalized=messages3.map(msg=>{if(VALID_ROLES.has(msg.role))return msg;let mappedRole=ROLE_MAPPINGS[msg.role];return mappedRole?(hasChanges=!0,{...msg,role:mappedRole}):(hasChanges=!0,{...msg,role:"user"})});return hasChanges?normalized:messages3}function normalizeMessagesForGoogle(messages3){if(!messages3||messages3.length===0)return messages3;let firstNonSystemIdx=-1;for(let i=0;i<messages3.length;i++)if(messages3[i].role!=="system"){firstNonSystemIdx=i;break}if(firstNonSystemIdx===-1)return messages3;let firstRole=messages3[firstNonSystemIdx].role;if(firstRole==="user")return messages3;if(firstRole==="assistant"||firstRole==="model"){let normalized=[...messages3];return normalized.splice(firstNonSystemIdx,0,{role:"user",content:"(continuing conversation)"}),normalized}return messages3}function isGoogleModel(modelId){return modelId.startsWith("google/")||modelId.startsWith("gemini")}function normalizeMessagesForThinking(messages3){if(!messages3||messages3.length===0)return messages3;let hasChanges=!1,normalized=messages3.map(msg=>msg.role!=="assistant"||msg.reasoning_content!==void 0?msg:(hasChanges=!0,{...msg,reasoning_content:""}));return hasChanges?normalized:messages3}function debrandSystemMessages(messages3,resolvedModel){let PROFILE_NAMES=["auto","free","eco","premium"],profilePattern=new RegExp(`\\bblockrun/(${PROFILE_NAMES.join("|")})\\b`,"gi"),prefixPattern=/\bblockrun\/(?=[a-z])/gi,hasChanges=!1,result=messages3.map(msg=>{if(msg.role!=="system"||typeof msg.content!="string")return msg;let content=msg.content,afterPrefix=content.replace(profilePattern,resolvedModel).replace(prefixPattern,"");return afterPrefix!==content&&(hasChanges=!0,content=afterPrefix),content!==msg.content?{...msg,content}:msg});return hasChanges?result:messages3}function isToolResultMessage(msg){return msg.role==="tool"?!0:Array.isArray(msg.content)?msg.content.some(b=>b&&typeof b=="object"&&b.type==="tool_result"):!1}function truncateMessages(messages3){if(!messages3||messages3.length<=MAX_MESSAGES)return{messages:messages3,wasTruncated:!1,originalCount:messages3?.length??0,truncatedCount:messages3?.length??0};let systemMsgs=messages3.filter(m=>m.role==="system"),conversationMsgs=messages3.filter(m=>m.role!=="system"),maxConversation=MAX_MESSAGES-systemMsgs.length,start=Math.max(0,conversationMsgs.length-maxConversation);for(;start<conversationMsgs.length&&isToolResultMessage(conversationMsgs[start]);)start++;let truncatedConversation=conversationMsgs.slice(start),result=[...systemMsgs,...truncatedConversation];return console.log(`[ClawRouter] Truncated messages: ${messages3.length} \u2192 ${result.length} (kept ${systemMsgs.length} system + ${truncatedConversation.length} recent)`),{messages:result,wasTruncated:!0,originalCount:messages3.length,truncatedCount:result.length}}function stripThinkingTokens(content){if(!content)return content;let cleaned=content.replace(KIMI_BLOCK_RE,"");return cleaned=cleaned.replace(KIMI_TOKEN_RE,""),cleaned=cleaned.replace(THINKING_BLOCK_RE,""),cleaned=cleaned.replace(THINKING_TAG_RE,""),cleaned}function forwardToolCallProse(){return process.env.CLAWROUTER_TOOL_CALL_PROSE?.trim().toLowerCase()!=="off"}function buildModelPricing(models=BLOCKRUN_MODELS){let map2=new Map;for(let m of models){if(m.id===AUTO_MODEL)continue;let promoPrice=getActivePromoPrice(m);map2.set(m.id,{inputPrice:m.inputPrice,outputPrice:m.outputPrice,...promoPrice!==void 0&&{flatPrice:promoPrice}})}return map2}function buildModelCapabilities(models=BLOCKRUN_MODELS){return Object.fromEntries(models.map(model=>[model.id,{contextWindow:model.contextWindow,maxOutputTokens:model.maxOutput,supportsTools:model.toolCalling===!0,supportsVision:model.vision===!0}]))}function buildProxyModelList(createdAt=Math.floor(Date.now()/1e3),catalog=fallbackCatalog()){let seen=new Set;return catalog.openclaw.filter(model=>seen.has(model.id)?!1:(seen.add(model.id),!0)).map(model=>{let targetId=MODEL_ALIASES[model.id]??model.id,canonical=catalog.models.find(entry=>entry.id===targetId);return{id:model.id,object:"model",created:createdAt,owned_by:targetId.includes("/")?targetId.split("/")[0]??"blockrun":"blockrun",name:model.name,context_window:model.contextWindow,max_output:model.maxTokens,input_price:model.cost.input,output_price:model.cost.output,reasoning:model.reasoning,vision:model.input.includes("image"),agentic:canonical?.agentic??!1,tool_calling:canonical?.toolCalling??!1}})}function mergeRoutingConfig(overrides){if(!overrides)return DEFAULT_ROUTING_CONFIG;let mergeTiers=(defaults2,user)=>user===null?null:user===void 0?defaults2??null:{...defaults2??{},...user};return{...DEFAULT_ROUTING_CONFIG,...overrides,classifier:{...DEFAULT_ROUTING_CONFIG.classifier,...overrides.classifier},scoring:{...DEFAULT_ROUTING_CONFIG.scoring,...overrides.scoring},tiers:mergeTiers(DEFAULT_ROUTING_CONFIG.tiers,overrides.tiers)??DEFAULT_ROUTING_CONFIG.tiers,agenticTiers:mergeTiers(DEFAULT_ROUTING_CONFIG.agenticTiers,overrides.agenticTiers),ecoTiers:mergeTiers(DEFAULT_ROUTING_CONFIG.ecoTiers,overrides.ecoTiers),premiumTiers:mergeTiers(DEFAULT_ROUTING_CONFIG.premiumTiers,overrides.premiumTiers),overrides:{...DEFAULT_ROUTING_CONFIG.overrides,...overrides.overrides}}}function buildCostBreakdown(params){let{actualModelUsed,routingProfile,modelPricing,inputTokens,outputTokens,tier}=params;if(typeof inputTokens!="number"||typeof outputTokens!="number"||inputTokens<0||outputTokens<0)return;let pricing=modelPricing.get(actualModelUsed),inputPrice=pricing?.inputPrice??0,outputPrice=pricing?.outputPrice??0,input2=inputTokens/1e6*inputPrice,output2=outputTokens/1e6*outputPrice,costs=calculateModelCost(actualModelUsed,modelPricing,inputTokens,outputTokens,routingProfile),total=costs.costEstimate,baseline=costs.baselineCost,savingsPct=routingProfile==="premium"||baseline<=0?void 0:Math.max(0,Math.min(100,Math.round(costs.savings*100)));return{total,input:input2,output:output2,baseline,...savingsPct!==void 0?{savings_pct:savingsPct}:{},model:actualModelUsed,...tier?{tier}:{}}}function estimateAmount(modelId,bodyLength,maxTokens,models=BLOCKRUN_MODEL_BY_ID){let model=models.get(modelId);if(!model)return;let costUsd,promoPrice=getActivePromoPrice(model);if(promoPrice!==void 0)costUsd=promoPrice;else{let estimatedInputTokens=Math.ceil(bodyLength/4),estimatedOutputTokens=maxTokens||model.maxOutput||4096;costUsd=withPlatformFee(estimatedInputTokens/1e6*model.inputPrice+estimatedOutputTokens/1e6*model.outputPrice,model.platformFeePercent)}return costUsd>0&&(costUsd+=.001),Math.max(1e3,Math.ceil(costUsd*1.2*1e6)).toString()}function estimateBalancePreflightAmount(modelId,bodyLength,maxTokens,models=BLOCKRUN_MODEL_BY_ID){let preflightMaxTokens=Math.min(maxTokens||BALANCE_PREFLIGHT_OUTPUT_TOKEN_CAP,BALANCE_PREFLIGHT_OUTPUT_TOKEN_CAP);return estimateAmount(modelId,bodyLength,preflightMaxTokens,models)}function estimatePhoneCost(urlPath){let op=urlPath.replace(/^\/v1\//,"").split("?")[0];for(let key3 of Object.keys(PHONE_PRICING).sort((a,b)=>b.length-a.length))if(op===key3||op.startsWith(`${key3}/`))return PHONE_PRICING[key3];return .05}function resolvePhoneTelemetryCost(args){if(args.paidAmount>0)return args.paidAmount;let upstreamSucceeded=args.upstreamStatus>=200&&args.upstreamStatus<300,isPostRequest=(args.method??"").toUpperCase()==="POST";return args.isPhone&&upstreamSucceeded&&isPostRequest?estimatePhoneCost(args.urlPath):args.paidAmount}function estimateVideoCost(model,durationSeconds,hasImageInput){let p=VIDEO_PRICING[model];if(!p)return .4*1.05;let dur=durationSeconds??p.defaultDurationSeconds;return(hasImageInput&&p.pricePerSecondImageInput?p.pricePerSecondImageInput:p.pricePerSecond)*dur*1.05}function estimateImageCost(model,size4,n=1){let pricing=IMAGE_PRICING[model];return pricing?((size4&&pricing.sizes?pricing.sizes[size4]:void 0)??pricing.default)*n*1.05:.04*n*1.05}function blockrunRequestId(response){if(response)for(let name of["x-blockrun-request-id","x-request-id","request-id"]){let value=response.headers.get(name)?.trim();if(value)return value}}function gatewayRemainingCreditUsd(response){let raw=response?.headers.get("x-blockrun-credit-remaining-usd");if(raw==null)return;let trimmed=raw.trim();if(trimmed==="")return;let value=Number(trimmed);if(!(!Number.isFinite(value)||value<0))return value}function settledMediaCostUsd(upstream,body,x402AmountUsd,estimate){let header=gatewaySettledCostUsd(upstream);if(header!==void 0)return header;let price=body?.price?.amount;if(typeof price=="string"||typeof price=="number"){let parsed=Number(price);if(Number.isFinite(parsed)&&parsed>=0)return parsed}return typeof x402AmountUsd=="number"&&x402AmountUsd>0?x402AmountUsd:estimate}function publishDispatchCost(usd2){let store=paymentStore.getStore();store&&(store.estimatedUsd=Number.isFinite(usd2)&&usd2>0?usd2:0)}function noteRemainingCredit(response){let remaining=gatewayRemainingCreditUsd(response);if(remaining!==void 0){if(remaining>LOW_CREDIT_USD){lowCreditWarned=!1;return}lowCreditWarned||(lowCreditWarned=!0,console.warn(remaining<=0?`[ClawRouter] \u26A0 BlockRun account credit is exhausted \u2014 calls will fail with 402. Top up: ${PORTAL_CREDITS_URL}`:`[ClawRouter] \u26A0 BlockRun account credit low: $${remaining.toFixed(2)} remaining. Top up: ${PORTAL_CREDITS_URL}`))}}function gatewaySettledCostUsd(response){let raw=response?.headers.get("x-blockrun-cost-usd");if(raw==null)return;let trimmed=raw.trim();if(trimmed==="")return;let value=Number(trimmed);if(!(!Number.isFinite(value)||value<0))return value}function refuseOverCostCap(res,err){return!(err instanceof CostCapError)||res.headersSent?!1:(res.writeHead(429,{"Content-Type":"application/json","X-ClawRouter-Cost-Cap-Exceeded":"1",...err.budgetExhausted?{"X-ClawRouter-Budget-Mode":"blocked"}:{}}),res.end(JSON.stringify({error:{message:err.message,type:"cost_cap_exceeded",code:err.budgetExhausted?"budget_exhausted":"cost_cap_exceeded"}})),!0)}function capMessagesRequest(body,headers,cap){let parsed={};try{let value=JSON.parse(body.toString());value&&typeof value=="object"&&!Array.isArray(value)&&(parsed=value)}catch{}let messages3=Array.isArray(parsed.messages)?parsed.messages.filter(m=>typeof m?.role=="string"&&m.content!==void 0):[],sessionId=getSessionId(headers)??deriveSessionId(messages3)??NO_SESSION_ID,store=paymentStore.getStore(),track=()=>{let spend2=SessionSpend.track(cap.sessions,sessionId);return store&&(store.sessionSpend=spend2),spend2},model=typeof parsed.model=="string"?parsed.model:void 0;if(model!==void 0&&cap.isFree(model))return track(),{recordSuccess:()=>{}};let estimate=parseMicros(model===void 0?void 0:estimateAmount(resolveModelAlias(model),body.length,resolveMaxTokens(parsed),new Map(cap.models.map(m=>[m.id,m])))),spend;if(cap.mode==="strict"){let admission=SessionSpend.admit(cap.sessions,sessionId,usdToMicros(cap.usd),estimate??(cap.authMode==="api-key"?1n:0n));if(!admission.admitted){let projected=admission.spentMicros+admission.heldMicros+admission.estimateMicros;throw new CostCapError(`ClawRouter cost cap exceeded: projected spend $${microsToUsd(projected).toFixed(4)} would exceed limit $${cap.usd}`)}spend=admission.spend,store&&(store.sessionSpend=spend)}else{let remainingUsd=cap.usd-cap.sessions.getSessionCostUsd(sessionId);if(!(estimate!==void 0?microsToUsd(estimate)<=remainingUsd:remainingUsd>0))throw new CostCapError(`ClawRouter budget exhausted: $${Math.max(0,remainingUsd).toFixed(4)} remaining (limit: $${cap.usd}). Increase maxCostPerRun to continue.`,!0);spend=track()}return{recordSuccess:()=>{estimate!==void 0&&spend.recordSuccess(estimate)}}}function withZeroCapGuard(inner,isFree){return async(input2,init2)=>{let{pathname}=new URL(input2 instanceof Request?input2.url:String(input2)),path8=pathname.slice(Math.max(pathname.indexOf("/v1/"),0)),method=(init2?.method??"GET").toUpperCase(),allowed;if(/^\/v1\/(?:chat\/completions|messages)$/.test(path8)){let body=init2?.body,model;try{let text=typeof body=="string"?body:body instanceof Uint8Array?Buffer.from(body).toString():"";model=JSON.parse(text).model}catch{model=void 0}allowed=typeof model=="string"&&isFree(model)}else allowed=ZERO_CAP_FREE_READ.test(path8)&&(method==="GET"||method==="HEAD");if(!allowed)throw new CostCapError(ZERO_CAP_REFUSAL);return inner(input2,init2)}}function withSessionCostCap(inner){return async(input2,init2)=>{let store=paymentStore.getStore(),spend=store?.sessionSpend,published=store?.estimatedUsd;if(spend?.isStrict&&published!==void 0){let attemptMicros=usdToMicros(published);if(!spend.coverPayment(attemptMicros))throw new CostCapError(`ClawRouter cost cap exceeded: dispatching an estimated $${microsToUsd(attemptMicros).toFixed(6)} would push this session past its maxCostPerRun limit`)}published!==void 0&&spend?.beginDispatch();let response=await inner(input2,init2),charged=gatewaySettledCostUsd(response);return spend&&charged!==void 0&&spend.recordCharged(usdToMicros(charged)),response}}function isMessagesPath(url3){return url3==="/v1/messages"||(url3?.startsWith("/v1/messages?")??!1)}async function relayWithIdleTimeout(source,destination,idleMs,signal){let timer2,arm=()=>{clearTimeout(timer2),timer2=setTimeout(()=>watchdog.destroy(new Error("Body read timeout")),idleMs)},watchdog=new Transform({transform(chunk,_encoding,done){arm(),done(null,chunk)}});arm();try{await pipeline(source,watchdog,destination,{signal})}finally{clearTimeout(timer2)}}async function proxyPaidApiRequest(req,res,apiBase,payFetch,getActualPaymentUsd,accountPassthrough=!1,authMode="wallet",capRequest){let startTime=Date.now(),upstreamUrl=`${apiBase}${req.url}`,isMessages=isMessagesPath(req.url),isBlockrunExa=req.url?.startsWith("/v1/exa/")??!1,isModalSandbox=req.url?.startsWith("/v1/modal/")??!1,isPhone=(req.url?.startsWith("/v1/phone/")??!1)||(req.url?.startsWith("/v1/voice/")??!1),requestLabel=isBlockrunExa?"BlockRun Exa":isModalSandbox?"Modal Sandbox":isPhone?"Phone/Voice":"Partner",bodyChunks=[];for await(let chunk of req)bodyChunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let body=Buffer.concat(bodyChunks),capped=capRequest?.(body),headers={};for(let[key3,value]of Object.entries(req.headers))key3==="host"||key3==="connection"||key3==="transfer-encoding"||key3==="content-length"||key3.startsWith("x-stainless-")||key3.startsWith("anthropic-")||typeof value=="string"&&(headers[key3]=value);headers["content-type"]||(headers["content-type"]="application/json"),headers["user-agent"]=USER_AGENT,console.log(`[ClawRouter] ${requestLabel} request: ${req.method} ${req.url}`);let clientAbort=new AbortController,onClientDisconnect=()=>{!res.writableEnded&&!clientAbort.signal.aborted&&clientAbort.abort()};res.on("close",onClientDisconnect),(res.destroyed||req.socket?.destroyed)&&!res.writableEnded&&onClientDisconnect(),publishDispatchCost(0);let upstream=await payFetch(upstreamUrl,{method:req.method??"POST",headers,body:body.length>0?new Uint8Array(body):void 0,signal:clientAbort.signal});upstream.ok&&capped?.recordSuccess();let responseHeaders={};if(upstream.headers.forEach((value,key3)=>{key3==="transfer-encoding"||key3==="connection"||key3==="content-encoding"||key3==="content-length"||(responseHeaders[key3]=value)}),(accountPassthrough||authMode==="api-key")&&(responseHeaders["cache-control"]="no-store"),accountPassthrough)res.writeHead(upstream.status,responseHeaders),upstream.body?await pipeline(Readable2.fromWeb(upstream.body),res,{signal:clientAbort.signal}):res.end();else if(isMessages)res.writeHead(upstream.status,responseHeaders),upstream.body?await relayWithIdleTimeout(Readable2.fromWeb(upstream.body),res,MODEL_BODY_READ_TIMEOUT_MS,clientAbort.signal):res.end();else{let chunks=upstream.body?await readBodyWithTimeout(upstream.body,ERROR_BODY_READ_TIMEOUT_MS,clientAbort.signal):[];res.writeHead(upstream.status,responseHeaders);for(let chunk of chunks)safeWrite(res,Buffer.from(chunk));res.end()}let latencyMs=Date.now()-startTime;console.log(`[ClawRouter] ${requestLabel} response: ${upstream.status} (${latencyMs}ms)`),noteRemainingCredit(upstream);let settledCostUsd=gatewaySettledCostUsd(upstream),paidAmount=settledCostUsd??getActualPaymentUsd(),requestCost=settledCostUsd!==void 0?settledCostUsd:resolvePhoneTelemetryCost({paidAmount,isPhone,upstreamStatus:upstream.status,method:req.method,urlPath:req.url??""});logUsage({timestamp:new Date().toISOString(),...blockrunRequestId(upstream)?{requestId:blockrunRequestId(upstream)}:{},model:isBlockrunExa?"blockrun-exa":isModalSandbox?"modal-sandbox":isPhone?(req.url??"").replace(/^\/v1\//,"").split("?")[0]:"partner",tier:isPhone?"PHONE":"PARTNER",cost:requestCost,baselineCost:requestCost,savings:0,latencyMs,partnerId:(req.url?.split("?")[0]??"").replace(/^\/v1\//,"").replace(/\//g,"_")||"unknown",service:isBlockrunExa?"web_search":isModalSandbox?"modal":isPhone?"phone":"partner"}).catch(()=>{})}async function uploadDataUriToHost(dataUri){let match=dataUri.match(/^data:(image\/\w+);base64,(.+)$/);if(!match)throw new Error("Invalid data URI format");let[,mimeType,b64Data]=match,ext=mimeType==="image/jpeg"?"jpg":mimeType.split("/")[1]??"png",buffer2=Buffer.from(b64Data,"base64"),blob=new Blob([buffer2],{type:mimeType}),form2=new FormData;form2.append("reqtype","fileupload"),form2.append("fileToUpload",blob,`image.${ext}`);let uploadController=new AbortController,uploadTimeout=setTimeout(()=>uploadController.abort(),3e4);try{let resp=await fetch("https://catbox.moe/user/api.php",{method:"POST",body:form2,signal:uploadController.signal});if(!resp.ok)throw new Error(`catbox.moe upload failed: HTTP ${resp.status}`);let result=await resp.text();if(result.startsWith("https://"))return result.trim();throw new Error(`catbox.moe upload failed: ${result}`)}finally{clearTimeout(uploadTimeout)}}function warnIfSpendLimitsUnenforced(spendControl){let configured;try{let limits=(spendControl??new SpendControl).getStatus().limits;configured=POLICY_LISTS.filter(list=>(limits[list]?.length??0)>0)}catch{return}configured.length!==0&&(console.warn(`[ClawRouter] \u26A0 Counterparty policy (${configured.join(", ")}) does not apply in API-key mode \u2014 there is one counterparty and no on-chain asset.`),console.warn("[ClawRouter] Your perRequest/hourly/daily/session limits DO apply here and are enforced per call."))}function assertExistingProxyBillsUs(existing,requested){let{listenPort}=requested,describe3=mode2=>mode2==="api-key"?"a BlockRun API key":"a wallet";if(existing.authMode!==requested.authMode)throw new Error(`Existing proxy on port ${listenPort} is authenticating with ${describe3(existing.authMode)} but ${describe3(requested.authMode)} was requested. Stop the existing proxy first or use a different port.`);if(requested.authMode==="api-key"){if(existing.apiKeyLabel!==requested.apiKeyLabel)throw new Error(`Existing proxy on port ${listenPort} is billing ${existing.apiKeyLabel??"an unidentified BlockRun account"}, but this process is configured for ${requested.apiKeyLabel}. Reusing it would charge the other account. Stop that proxy first, or use a different port.`);return}if(existing.paymentChain){if(existing.paymentChain!==requested.paymentChain)throw new Error(`Existing proxy on port ${listenPort} is using ${existing.paymentChain} but ${requested.paymentChain} was requested. Stop the existing proxy first or use a different port.`)}else if(requested.paymentChain!=="base")throw console.warn(`[ClawRouter] Existing proxy on port ${listenPort} does not report paymentChain (pre-v0.11 instance). Assuming Base.`),new Error(`Existing proxy on port ${listenPort} is a pre-v0.11 instance (assumed Base) but ${requested.paymentChain} was requested. Stop the existing proxy first or use a different port.`)}async function startProxy(options){options.maxCostPerRunUsd!==void 0&&!Number.isFinite(options.maxCostPerRunUsd)&&(console.warn(`[ClawRouter] Ignoring maxCostPerRun: ${String(options.maxCostPerRunUsd)} is not a finite number`),options={...options,maxCostPerRunUsd:void 0});let upstreamProxy=await applyUpstreamProxy(options.upstreamProxy);upstreamProxy&&console.log(`[ClawRouter] Upstream proxy: ${upstreamProxy}`);let apiKey=options.apiKey?.trim()||void 0;if(apiKey&&!isValidApiKey(apiKey))throw new Error('BlockRun API key is malformed (expected it to start with "brk_"). Mint one at https://user.blockrun.ai/dashboard/keys');let authMode=apiKey?"api-key":"wallet";if(!apiKey&&!options.wallet)throw new Error("startProxy needs a credential: pass either a wallet (x402) or an apiKey (brk_\u2026, from https://user.blockrun.ai/dashboard/keys).");let walletKey=options.wallet===void 0?void 0:typeof options.wallet=="string"?options.wallet:options.wallet.key,solanaPrivateKeyBytes=options.wallet===void 0||typeof options.wallet=="string"?void 0:options.wallet.solanaPrivateKeyBytes,paymentChain=options.paymentChain??await resolvePaymentChain(),requestedApiBase=options.apiBase??(authMode==="api-key"?BLOCKRUN_API_KEY_API:walletGatewayFor(paymentChain,solanaPrivateKeyBytes!==void 0)),apiBase=authMode==="api-key"?normalizeApiKeyBase(requestedApiBase):requestedApiBase;authMode==="api-key"?(console.log(`[ClawRouter] Auth: BlockRun API key ${maskApiKey(apiKey)} (${apiBase})`),console.log(`[ClawRouter] Billing: account credit \u2014 top up at ${PORTAL_CREDITS_URL}`),warnIfSpendLimitsUnenforced(options.spendControl)):paymentChain==="solana"&&!solanaPrivateKeyBytes?(console.warn("[ClawRouter] \u26A0 Payment chain is Solana but no mnemonic found \u2014 falling back to Base (EVM)."),console.warn('[ClawRouter] To fix: run "npx @blockrun/clawrouter wallet recover" if your mnemonic exists,'),console.warn('[ClawRouter] or run "npx @blockrun/clawrouter chain base" to switch to EVM.')):console.log(paymentChain==="solana"?`[ClawRouter] Payment chain: Solana (${BLOCKRUN_SOLANA_API})`:paymentChain==="arc"?`[ClawRouter] Payment chain: Arc (${apiBase})`:`[ClawRouter] Payment chain: Base (${apiBase})`),loadGatewayCatalog(apiBase,apiKey);let listenPort=options.port??getProxyPort(),existingProxy=options.allowExistingProxy===!1?void 0:await checkExistingProxy(listenPort),ourApiKeyLabel=apiKey?maskApiKey(apiKey):void 0;if(existingProxy){let baseUrl2=`http://127.0.0.1:${listenPort}`;if(assertExistingProxyBillsUs(existingProxy,{listenPort,authMode,apiKeyLabel:ourApiKeyLabel,paymentChain}),authMode==="api-key")return options.onReady?.(listenPort),{port:listenPort,baseUrl:baseUrl2,walletAddress:"",authMode,apiKeyLabel:ourApiKeyLabel,balanceMonitor:new ApiKeyBalanceMonitor,close:async()=>{}};let account2=privateKeyToAccount(walletKey);existingProxy.wallet!==account2.address&&console.warn(`[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxy.wallet}, but current config uses ${account2.address}. Reusing existing proxy.`);let reuseSolanaAddress;if(solanaPrivateKeyBytes){let{createKeyPairSignerFromPrivateKeyBytes:createKeyPairSignerFromPrivateKeyBytes2}=await Promise.resolve().then(()=>(init_index_node39(),index_node_exports));reuseSolanaAddress=(await createKeyPairSignerFromPrivateKeyBytes2(solanaPrivateKeyBytes)).address}let balanceMonitor2;if(paymentChain==="solana"&&reuseSolanaAddress){let{SolanaBalanceMonitor:SolanaBalanceMonitor2}=await Promise.resolve().then(()=>(init_solana_balance(),solana_balance_exports));balanceMonitor2=new SolanaBalanceMonitor2(reuseSolanaAddress)}else balanceMonitor2=new BalanceMonitor(account2.address,evmBalanceChain(paymentChain));return options.onReady?.(listenPort),{port:listenPort,baseUrl:baseUrl2,walletAddress:existingProxy.wallet,solanaAddress:reuseSolanaAddress,authMode,balanceMonitor:balanceMonitor2,close:async()=>{}}}let account=walletKey?privateKeyToAccount(walletKey):void 0,x402=authMode==="wallet"?new x402Client().setSpendControls(!1):void 0,registerCostCapHook=client=>client.onBeforePaymentCreation(async context=>{if(options.maxCostPerRunUsd===0)throw new CostCapError(ZERO_CAP_REFUSAL);let spend=paymentStore.getStore()?.sessionSpend;if(!spend?.isStrict)return;let quote=parseQuotedAmountMicros(context.selectedRequirements);if(quote===void 0)throw new CostCapError("ClawRouter cost cap: unreadable payment amount in the 402 quote");if(!spend.coverPayment(quote))throw new CostCapError(`ClawRouter cost cap exceeded: signing $${microsToUsd(quote).toFixed(6)} would push this session past its maxCostPerRun limit`)});x402&®isterCostCapHook(x402);let spendControl=x402&&account?options.spendControl??getSharedSpendControl():void 0;if(x402&&account&&spendControl){let evmPublicClient=createPublicClient({chain:base,transport:http()}),evmSigner=toClientEvmSigner(account,evmPublicClient);registerSpendPolicyHook(x402,spendControl),registerExactEvmScheme(x402,{signer:evmSigner})}let solanaAddress;if(x402&&solanaPrivateKeyBytes){let{registerExactSvmScheme:registerExactSvmScheme2}=await Promise.resolve().then(()=>(init_client4(),client_exports3)),{createKeyPairSignerFromPrivateKeyBytes:createKeyPairSignerFromPrivateKeyBytes2}=await Promise.resolve().then(()=>(init_index_node39(),index_node_exports)),solanaSigner=await createKeyPairSignerFromPrivateKeyBytes2(solanaPrivateKeyBytes);solanaAddress=solanaSigner.address;let solanaRpcUrl=process.env.CLAWROUTER_SOLANA_RPC_URL;if(registerExactSvmScheme2(x402,{signer:solanaSigner}),solanaRpcUrl){let{ExactSvmScheme:ExactSvmScheme2}=await Promise.resolve().then(()=>(init_client4(),client_exports3)),{ExactSvmSchemeV1:ExactSvmSchemeV12,NETWORKS:SVM_V1_NETWORKS}=await Promise.resolve().then(()=>(init_v1(),v1_exports));x402.register("solana:*",new ExactSvmScheme2(solanaSigner,{rpcUrl:solanaRpcUrl}));for(let network of SVM_V1_NETWORKS)x402.registerV1(network,new ExactSvmSchemeV12(solanaSigner,{rpcUrl:solanaRpcUrl}))}console.log(`[ClawRouter] Solana wallet: ${solanaAddress}`),solanaRpcUrl&&console.log(`[ClawRouter] Solana RPC (payment signing + balance): ${solanaRpcUrl}`)}x402?.onAfterPaymentCreation(async context=>{if(!stampsBuilderCode(context.selectedRequirements.network))return;let payload=context.paymentPayload;payload.extensions=withBuilderCodeServiceCode(payload.extensions)});let registerSigningRecorders=client=>{client.onAfterPaymentCreation(async context=>{let network=context.selectedRequirements.network,chain3=describePaymentNetwork(network),amountUsd=parseInt(context.selectedRequirements.amount||"0",10)/1e6,store=paymentStore.getStore();store&&(store.amountUsd=amountUsd),console.log(`[ClawRouter] Payment signed on ${chain3} (${network}) \u2014 $${amountUsd.toFixed(6)}`)}),client.onAfterPaymentCreation(async context=>{let spend=paymentStore.getStore()?.sessionSpend,amount=parseQuotedAmountMicros(context.selectedRequirements);spend&&amount!==void 0&&spend.recordSigned(amount)})};x402&®isterSigningRecorders(x402);let solanaBatchSettings=x402&&paymentChain==="solana"&&solanaPrivateKeyBytes&&solanaAddress?resolveSolanaBatchSettings(options.solanaBatch,SOLANA_BATCH_ENV):void 0,solanaBatch;solanaBatchSettings&&solanaPrivateKeyBytes&&solanaAddress&&(solanaBatch={payer:await createSolanaBatchPayer({seed:solanaPrivateKeyBytes,address:solanaAddress,rpcUrl:process.env.CLAWROUTER_SOLANA_RPC_URL||SOLANA_PUBLIC_RPC,settings:solanaBatchSettings,configureClient:client=>{let hooks=client;hooks.onBeforePaymentCreation(async()=>{let store=paymentStore.getStore();store?.batchMark!==void 0&&store.sessionSpend?.voidSignedSince(store.batchMark,!1)}),registerCostCapHook(hooks),spendControl&®isterSpendPolicyHook(client,spendControl),registerSigningRecorders(hooks)}}),begin:()=>{let store=paymentStore.getStore(),mark=store?.sessionSpend?.signatureMark();return store&&(store.batchMark=mark),mark},settle:(mark,outcome)=>{let store=paymentStore.getStore();store&&(store.batchMark=void 0);let spend=store?.sessionSpend;outcome.kind==="paid"?(store&&outcome.chargedMicros!==void 0&&(store.amountUsd=microsToUsd(outcome.chargedMicros)),spend&&mark!==void 0&&spend.signatureMark()>mark&&(spend.voidSignedSince(mark,!0),outcome.chargedMicros!==void 0&&spend.settleLastSigned(outcome.chargedMicros))):outcome.kind==="not_charged"?(store&&(store.amountUsd=0),spend&&mark!==void 0&&spend.voidSignedSince(mark,!1)):spend&&mark!==void 0&&spend.voidSignedSince(mark,!0)}},console.log(`[ClawRouter] Solana batch-settlement on (BlockRun operator, max deposit ${solanaBatchSettings.maxDeposit??"$1"})`));let requestOptions=solanaBatch?{...options,_solanaBatchActive:!0}:options,keyFetch=apiKey?createApiKeyFetch(apiKey,fetch,apiBase):void 0,isFreeForCap=model=>{let{freeIds}=catalog.current();return freeIds.has(resolveModelAlias(model))||[...freeIds].some(id2=>toUpstreamModelId(id2)===model)},payFetch=authMode==="api-key"?withSessionCostCap(withSpendPolicy(options.maxCostPerRunUsd===0?withZeroCapGuard(keyFetch,isFreeForCap):keyFetch,options.spendControl??getSharedSpendControl(),()=>{let store=paymentStore.getStore(),published=store?.estimatedUsd;return store&&(store.estimatedUsd=void 0),published})):createPayFetchWithPreAuth(fetch,x402,void 0,{skipPreAuth:paymentChain==="solana",estimateAmount,onPayment:options.onPayment,onPaymentDeclined:()=>paymentStore.getStore()?.sessionSpend?.voidLastSigned(),solanaBatch}),balanceMonitor;if(options._balanceMonitorOverride)balanceMonitor=options._balanceMonitorOverride;else if(authMode==="api-key")balanceMonitor=new ApiKeyBalanceMonitor;else if(paymentChain==="solana"&&solanaAddress){let{SolanaBalanceMonitor:SolanaBalanceMonitor2}=await Promise.resolve().then(()=>(init_solana_balance(),solana_balance_exports));balanceMonitor=new SolanaBalanceMonitor2(solanaAddress)}else balanceMonitor=new BalanceMonitor(account.address,evmBalanceChain(paymentChain));let routingConfig=mergeRoutingConfig(options.routingConfig),modelPricing=buildModelPricing(),routerOpts={config:routingConfig,modelPricing,modelCapabilities:buildModelCapabilities()},catalog=createClawCatalog({network:paymentChain==="solana"&&(apiKey||solanaPrivateKeyBytes)?"solana":"base",apiBase,apiKey}),catalogClosed=!1,refreshCatalog=async()=>{let previous=catalog.current(),view=await catalog.refresh();if(!(catalogClosed||view===previous)){routerOpts={...routerOpts,modelPricing:buildModelPricing(view.models),modelCapabilities:buildModelCapabilities(view.models)};try{options.onCatalogUpdated?.(view.visible)}catch{}}},deduplicator=new RequestDeduplicator,responseCache2=new ResponseCache(options.cacheConfig),sessionStore=new SessionStore(options.sessionConfig),sessionJournal=new SessionJournal,connections=new Set,server=createServer((req,res)=>{paymentStore.run({amountUsd:0},async()=>{req.on("error",err=>{console.error(`[ClawRouter] Request stream error: ${err.message}`)}),res.on("error",err=>{console.error(`[ClawRouter] Response stream error: ${err.message}`)}),finished(res,err=>{err&&err.code!=="ERR_STREAM_DESTROYED"&&console.error(`[ClawRouter] Response finished with error: ${err.message}`)}),finished(req,err=>{err&&err.code!=="ERR_STREAM_DESTROYED"&&console.error(`[ClawRouter] Request finished with error: ${err.message}`)});let untrusted=untrustedRequestReason(req);if(untrusted){console.warn(`[ClawRouter] Refused request to ${req.url}: ${untrusted}`),res.writeHead(403,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"forbidden",details:untrusted}));return}if(req.url==="/health"||req.url?.startsWith("/health?")){let full=new URL(req.url,"http://localhost").searchParams.get("full")==="true",response={status:"ok",authMode};if(authMode==="api-key"?(response.apiKey=maskApiKey(apiKey),response.gateway=apiBase):(response.wallet=account.address,response.paymentChain=paymentChain,response.gateway=apiBase,solanaAddress&&(response.solana=solanaAddress)),upstreamProxy&&(response.upstreamProxy=upstreamProxy),full)try{let balanceInfo=await Promise.race([balanceMonitor.checkBalance(),new Promise((_,reject)=>setTimeout(()=>reject(new Error("balance check timed out")),BALANCE_CHECK_TIMEOUT_MS).unref())]);if(authMode==="api-key"){let credit=await fetchCreditBalance(apiKey,BALANCE_CHECK_TIMEOUT_MS);response.balance=credit?.remainingUsd??null,response.creditSpent=credit?.spentUsd??null,response.creditGranted=credit?.grantedUsd??null,response.billingMode=credit?.billingMode??null,response.creditSummary=credit?formatCreditBalance(credit):null,response.blocked=credit?.blocked??!1,credit?.blockedReason&&(response.blockedReason=credit.blockedReason),response.isEmpty=credit?.remainingUsd!==null&&(credit?.remainingUsd??1)<=0,response.billing="BlockRun account credit",response.topUpUrl=PORTAL_CREDITS_URL}else response.balance=balanceInfo.balanceUSD,response.isLow=balanceInfo.isLow,response.isEmpty=balanceInfo.isEmpty}catch{response.balanceError="Could not fetch balance"}let headers={"Content-Type":"application/json","Cache-Control":"no-store"},challengeValue=req.headers["x-clawrouter-challenge"],challenge2=Array.isArray(challengeValue)?challengeValue[0]:challengeValue;if(challenge2&&/^[a-f0-9]{64}$/i.test(challenge2))try{let token=readFileSync8(DESKTOP_SERVICE_TOKEN_FILE,"utf8").trim();/^[a-f0-9]{64}$/i.test(token)&&(headers["X-ClawRouter-Proof"]=createHmac("sha256",token).update(challenge2).digest("hex"))}catch{}res.writeHead(200,headers),res.end(JSON.stringify(response));return}if(req.url==="/cache"||req.url?.startsWith("/cache?")){let stats=responseCache2.getStats();res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),res.end(JSON.stringify(stats,null,2));return}if(req.url==="/stats"&&req.method==="DELETE"){try{let result=await clearStats();res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({cleared:!0,deletedFiles:result.deletedFiles}))}catch(err){res.writeHead(500,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:`Failed to clear stats: ${err instanceof Error?err.message:String(err)}`}))}return}if(req.url==="/stats"||req.url?.startsWith("/stats?")){try{let url3=new URL(req.url,"http://localhost"),days=resolveStatsDays(url3.searchParams.get("days")),stats=await getStats(days);res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),res.end(JSON.stringify({...stats,providerErrors:Object.fromEntries(perProviderErrors)},null,2))}catch(err){res.writeHead(500,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:`Failed to get stats: ${err instanceof Error?err.message:String(err)}`}))}return}if(req.url==="/v1/models"&&req.method==="GET"){let models=buildProxyModelList(void 0,catalog.current());res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({object:"list",data:models}));return}if(req.url?.startsWith("/share")&&req.method==="GET"){try{let url3=new URL(req.url,"http://localhost"),path8=url3.pathname;if(path8==="/share/list"){let limit=Math.min(parseInt(url3.searchParams.get("limit")||"20",10),100),entries=await listRecent(limit);res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(entries.map(e7=>({id:e7.id,timestamp:e7.timestamp,model:e7.model,sessionId:e7.sessionId,requestSummary:e7.requestSummary,responseLength:e7.responseText.length}))));return}if(path8==="/share/last"){let sessionId=url3.searchParams.get("sessionId")||void 0,entry=await getLast(sessionId);if(!entry){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"no responses yet"}));return}let preset=url3.searchParams.get("as");if(preset&&isSharePreset(preset)){res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),res.end(JSON.stringify({id:entry.id,timestamp:entry.timestamp,model:entry.model,preset,rendered:transform2(entry.responseText,preset)}));return}res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(entry));return}let idMatch=path8.match(/^\/share\/(resp_[A-Za-z0-9_]+)(?:\/render)?$/);if(idMatch){let id2=idMatch[1],entry=await getById(id2);if(!entry){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:`no response with id ${id2}`}));return}let preset=url3.searchParams.get("as");if(preset&&isSharePreset(preset)){res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({id:entry.id,timestamp:entry.timestamp,model:entry.model,preset,rendered:transform2(entry.responseText,preset)}));return}res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(entry));return}res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"unknown share endpoint"}))}catch(err){res.writeHead(500,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:`share failed: ${err instanceof Error?err.message:String(err)}`}))}return}if(req.url?.startsWith("/images/")&&req.method==="GET"){let filename=req.url.slice(8).split("?")[0].replace(/[^a-zA-Z0-9._-]/g,"");if(!filename){res.writeHead(400),res.end("Bad request");return}let filePath=join17(IMAGE_DIR,filename);try{if(!(await fsStat(filePath)).isFile())throw new Error("not a file");let ext=filename.split(".").pop()?.toLowerCase()??"png",mime={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif"},data=await readFile3(filePath);res.writeHead(200,{"Content-Type":mime[ext]??"application/octet-stream","Content-Length":data.length}),res.end(data)}catch{res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Image not found"}))}return}if(req.url?.startsWith("/audio/")&&req.method==="GET"){let filename=req.url.slice(7).split("?")[0].replace(/[^a-zA-Z0-9._-]/g,"");if(!filename){res.writeHead(400),res.end("Bad request");return}let filePath=join17(AUDIO_DIR,filename);try{if(!(await fsStat(filePath)).isFile())throw new Error("not a file");let ext=filename.split(".").pop()?.toLowerCase()??"mp3",mime={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",m4a:"audio/mp4"},data=await readFile3(filePath);res.writeHead(200,{"Content-Type":mime[ext]??"audio/mpeg","Content-Length":data.length}),res.end(data)}catch{res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Audio not found"}))}return}if(req.url?.startsWith("/videos/")&&req.method==="GET"){let filename=req.url.slice(8).split("?")[0].replace(/[^a-zA-Z0-9._-]/g,"");if(!filename){res.writeHead(400),res.end("Bad request");return}let filePath=join17(VIDEO_DIR,filename);try{if(!(await fsStat(filePath)).isFile())throw new Error("not a file");let ext=filename.split(".").pop()?.toLowerCase()??"mp4",mime={mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime"},data=await readFile3(filePath);res.writeHead(200,{"Content-Type":mime[ext]??"video/mp4","Content-Length":data.length}),res.end(data)}catch{res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Video not found"}))}return}if(req.url==="/v1/images/generations"&&req.method==="POST"){let imgStartTime=Date.now(),clientAbort=new AbortController;res.on("close",()=>{res.writableEnded||clientAbort.abort()});let chunks=[];for await(let chunk of req)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let reqBody=Buffer.concat(chunks),imgModel="unknown",imgCost=0;try{let parsed=JSON.parse(reqBody.toString());imgModel=parsed.model||"google/nano-banana";let n=parsed.n||1;imgCost=estimateImageCost(imgModel,parsed.size,n)}catch{}try{publishDispatchCost(imgCost);let upstream=await payFetch(`${apiBase}/v1/images/generations`,{method:"POST",headers:{"content-type":"application/json","user-agent":USER_AGENT},body:reqBody,signal:clientAbort.signal}),text=await upstream.text();if(!upstream.ok&&upstream.status!==202){res.writeHead(upstream.status,{"Content-Type":"application/json"}),res.end(text);return}let result;try{result=JSON.parse(text)}catch{res.writeHead(200,{"Content-Type":"application/json"}),res.end(text);return}if(result.poll_url&&result.id&&!result.data?.length){let apiOrigin=new URL(apiBase).origin,pollUrl=result.poll_url.startsWith("http")?result.poll_url:`${apiOrigin}${result.poll_url}`;console.log(`[ClawRouter] Image job submitted (id=${result.id}), polling upstream \u2014 typical 30\u2013120s...`);let pollDeadline=Date.now()+3e5,pollInterval=3e3;await new Promise(r2=>setTimeout(r2,2e3));let pollError,completed=!1;for(;Date.now()<pollDeadline;){if(clientAbort.signal.aborted){console.log(`[ClawRouter] Client disconnected \u2014 abandoning image poll (id=${result.id})`);return}let pollResp=await payFetch(pollUrl,{method:"GET",headers:{"user-agent":USER_AGENT},signal:clientAbort.signal}),pollText=await pollResp.text(),pollBody={};try{pollBody=JSON.parse(pollText)}catch{pollError=`Non-JSON poll response (${pollResp.status}): ${pollText.slice(0,200)}`;break}if(pollResp.status===202||pollBody.status==="queued"||pollBody.status==="in_progress"){await new Promise(r2=>setTimeout(r2,pollInterval));continue}if(pollBody.status==="failed"){pollError=pollBody.error??"Upstream image generation failed";break}if(pollResp.ok&&pollBody.status==="completed"){result=pollBody,completed=!0;break}if(!pollResp.ok){res.writeHead(pollResp.status,{"Content-Type":"application/json"}),res.end(pollText);return}result=pollBody,completed=!0;break}if(pollError){res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Image generation failed",details:pollError}));return}if(!completed){res.writeHead(504,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Image generation timed out",details:`Upstream did not complete within 5 minutes (job id=${result.id}). No payment has been settled.`}));return}}if(result.data?.length){await mkdir6(IMAGE_DIR,{recursive:!0});let port2=server.address()?.port??8402;for(let img of result.data){let dataUriMatch=img.url?.match(/^data:(image\/\w+);base64,(.+)$/);if(dataUriMatch){let[,mimeType,b64]=dataUriMatch,ext=mimeType==="image/jpeg"?"jpg":mimeType.split("/")[1]??"png",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`;await writeFile4(join17(IMAGE_DIR,filename),Buffer.from(b64,"base64")),img.url=`http://localhost:${port2}/images/${filename}`,console.log(`[ClawRouter] Image saved \u2192 ${img.url}`)}else if(img.url?.startsWith("https://")||img.url?.startsWith("http://"))try{let imgResp=await fetch(img.url,{signal:clientAbort.signal});if(imgResp.ok){let contentType=imgResp.headers.get("content-type")??"image/png",ext=contentType.includes("jpeg")||contentType.includes("jpg")?"jpg":contentType.includes("webp")?"webp":"png",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`,buf=Buffer.from(await imgResp.arrayBuffer());await writeFile4(join17(IMAGE_DIR,filename),buf),img.url=`http://localhost:${port2}/images/${filename}`,console.log(`[ClawRouter] Image downloaded & saved \u2192 ${img.url}`)}}catch(downloadErr){console.warn(`[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error?downloadErr.message:String(downloadErr)}`)}}}let imgActualCost=settledMediaCostUsd(upstream,result,paymentStore.getStore()?.amountUsd,imgCost);logUsage({timestamp:new Date().toISOString(),...blockrunRequestId(upstream)?{requestId:blockrunRequestId(upstream)}:{},model:imgModel,tier:"IMAGE",cost:imgActualCost,baselineCost:imgActualCost,savings:0,latencyMs:Date.now()-imgStartTime}).catch(()=>{}),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(result))}catch(err){if(clientAbort.signal.aborted||refuseOverCostCap(res,err))return;let msg=err instanceof Error?err.message:String(err);console.error(`[ClawRouter] Image generation error: ${msg}`),res.headersSent||(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Image generation failed",details:msg})))}return}if(req.url==="/v1/images/image2image"&&req.method==="POST"){let img2imgStartTime=Date.now(),clientAbort=new AbortController;res.on("close",()=>{res.writableEnded||clientAbort.abort()});let chunks=[];for await(let chunk of req)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let rawBody=Buffer.concat(chunks),reqBody,img2imgModel="openai/gpt-image-1",img2imgCost=0;try{let parsed=JSON.parse(rawBody.toString());for(let field of["image","mask"]){let val=parsed[field];if(!(typeof val!="string"||!val)&&!val.startsWith("data:"))if(val.startsWith("https://")||val.startsWith("http://")){let imgResp=await ssrfSafeFetch(val,{signal:clientAbort.signal,allowPrivate:process.env.CLAWROUTER_ALLOW_PRIVATE_FETCH==="1",viaUpstreamProxy:!!upstreamProxy});if(!imgResp.ok)throw new Error(`Failed to download ${field} from ${val}: HTTP ${imgResp.status}`);let contentType=imgResp.headers.get("content-type")??"image/png",buf=Buffer.from(await imgResp.arrayBuffer());parsed[field]=`data:${contentType};base64,${buf.toString("base64")}`,console.log(`[ClawRouter] img2img: downloaded ${field} URL \u2192 data URI (${buf.length} bytes)`)}else parsed[field]=readLocalImageAsDataUri(val),console.log(`[ClawRouter] img2img: read ${field} file \u2192 data URI`)}parsed.model||(parsed.model="openai/gpt-image-1"),img2imgModel=parsed.model,img2imgCost=estimateImageCost(img2imgModel,parsed.size,parsed.n||1),reqBody=JSON.stringify(parsed)}catch(parseErr){if(clientAbort.signal.aborted)return;let msg=parseErr instanceof Error?parseErr.message:String(parseErr);res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid request",details:msg}));return}try{publishDispatchCost(img2imgCost);let upstream=await payFetch(`${apiBase}/v1/images/image2image`,{method:"POST",headers:{"content-type":"application/json","user-agent":USER_AGENT},body:reqBody,signal:clientAbort.signal});authMode==="api-key"&&(upstream=await pollApiKeyJob(upstream,payFetch,apiBase,clientAbort.signal));let text=await upstream.text();if(!upstream.ok){res.writeHead(upstream.status,{"Content-Type":"application/json"}),res.end(text);return}let result;try{result=JSON.parse(text)}catch{res.writeHead(200,{"Content-Type":"application/json"}),res.end(text);return}if(result.data?.length){await mkdir6(IMAGE_DIR,{recursive:!0});let port2=server.address()?.port??8402;for(let img of result.data){let dataUriMatch=img.url?.match(/^data:(image\/\w+);base64,(.+)$/);if(dataUriMatch){let[,mimeType,b64]=dataUriMatch,ext=mimeType==="image/jpeg"?"jpg":mimeType.split("/")[1]??"png",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`;await writeFile4(join17(IMAGE_DIR,filename),Buffer.from(b64,"base64")),img.url=`http://localhost:${port2}/images/${filename}`,console.log(`[ClawRouter] Image saved \u2192 ${img.url}`)}else if(img.url?.startsWith("https://")||img.url?.startsWith("http://"))try{let imgResp=await fetch(img.url,{signal:clientAbort.signal});if(imgResp.ok){let contentType=imgResp.headers.get("content-type")??"image/png",ext=contentType.includes("jpeg")||contentType.includes("jpg")?"jpg":contentType.includes("webp")?"webp":"png",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`,buf=Buffer.from(await imgResp.arrayBuffer());await writeFile4(join17(IMAGE_DIR,filename),buf),img.url=`http://localhost:${port2}/images/${filename}`,console.log(`[ClawRouter] Image downloaded & saved \u2192 ${img.url}`)}}catch(downloadErr){console.warn(`[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error?downloadErr.message:String(downloadErr)}`)}}}let img2imgActualCost=settledMediaCostUsd(upstream,result,paymentStore.getStore()?.amountUsd,img2imgCost);logUsage({timestamp:new Date().toISOString(),...blockrunRequestId(upstream)?{requestId:blockrunRequestId(upstream)}:{},model:img2imgModel,tier:"IMAGE",cost:img2imgActualCost,baselineCost:img2imgActualCost,savings:0,latencyMs:Date.now()-img2imgStartTime}).catch(()=>{}),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(result))}catch(err){if(clientAbort.signal.aborted||refuseOverCostCap(res,err))return;let msg=err instanceof Error?err.message:String(err);console.error(`[ClawRouter] Image editing error: ${msg}`),res.headersSent||(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Image editing failed",details:msg})))}return}if(req.url==="/v1/audio/generations"&&req.method==="POST"){let audioStartTime=Date.now(),clientAbort=new AbortController;res.on("close",()=>{res.writableEnded||clientAbort.abort()});let chunks=[];for await(let chunk of req)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let reqBody=Buffer.concat(chunks),audioModel="minimax/music-2.5+";try{audioModel=JSON.parse(reqBody.toString()).model||audioModel}catch{}try{publishDispatchCost(.15);let upstream=await payFetch(`${apiBase}/v1/audio/generations`,{method:"POST",headers:{"content-type":"application/json","user-agent":USER_AGENT},body:reqBody,signal:clientAbort.signal});authMode==="api-key"&&(upstream=await pollApiKeyJob(upstream,payFetch,apiBase,clientAbort.signal));let text=await upstream.text();if(!upstream.ok){res.writeHead(upstream.status,{"Content-Type":"application/json"}),res.end(text);return}let result;try{result=JSON.parse(text)}catch{res.writeHead(200,{"Content-Type":"application/json"}),res.end(text);return}if(result.data?.length){await mkdir6(AUDIO_DIR,{recursive:!0});let port2=server.address()?.port??8402;for(let track of result.data)if(track.url?.startsWith("https://")||track.url?.startsWith("http://"))try{let audioResp=await fetch(track.url,{signal:clientAbort.signal});if(audioResp.ok){let ext=(audioResp.headers.get("content-type")??"audio/mpeg").includes("wav")?"wav":"mp3",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`,buf=Buffer.from(await audioResp.arrayBuffer());await writeFile4(join17(AUDIO_DIR,filename),buf),track.url=`http://localhost:${port2}/audio/${filename}`,console.log(`[ClawRouter] Audio saved \u2192 ${track.url}`)}}catch(downloadErr){console.warn(`[ClawRouter] Failed to download audio, using original URL: ${downloadErr instanceof Error?downloadErr.message:String(downloadErr)}`)}}let audioActualCost=settledMediaCostUsd(upstream,result,paymentStore.getStore()?.amountUsd,.15);logUsage({timestamp:new Date().toISOString(),...blockrunRequestId(upstream)?{requestId:blockrunRequestId(upstream)}:{},model:audioModel,tier:"AUDIO",cost:audioActualCost,baselineCost:audioActualCost,savings:0,latencyMs:Date.now()-audioStartTime}).catch(()=>{}),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(result))}catch(err){if(clientAbort.signal.aborted||refuseOverCostCap(res,err))return;let msg=err instanceof Error?err.message:String(err);console.error(`[ClawRouter] Audio generation error: ${msg}`),res.headersSent||(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Audio generation failed",details:msg})))}return}if(req.url==="/v1/videos/generations"&&req.method==="POST"){let videoStartTime=Date.now(),clientAbort=new AbortController;res.on("close",()=>{res.writableEnded||clientAbort.abort()});let chunks=[];for await(let chunk of req)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let reqBody=Buffer.concat(chunks),videoModel="xai/grok-imagine-video",videoDuration,videoHasImageInput=!1;try{let parsed=JSON.parse(reqBody.toString());videoModel=parsed.model||videoModel,videoDuration=typeof parsed.duration_seconds=="number"?parsed.duration_seconds:void 0,videoHasImageInput=typeof parsed.image_url=="string"&&parsed.image_url.length>0}catch{}try{publishDispatchCost(estimateVideoCost(videoModel,videoDuration,videoHasImageInput));let submitResp=await payFetch(`${apiBase}/v1/videos/generations`,{method:"POST",headers:{"content-type":"application/json","user-agent":USER_AGENT},body:reqBody,signal:clientAbort.signal}),submitText=await submitResp.text();if(!submitResp.ok&&submitResp.status!==202){res.writeHead(submitResp.status,{"Content-Type":"application/json"}),res.end(submitText);return}let submitResult;try{submitResult=JSON.parse(submitText)}catch{res.writeHead(200,{"Content-Type":"application/json"}),res.end(submitText);return}let finalResult=submitResult;if(submitResult.poll_url&&submitResult.id){let apiOrigin=new URL(apiBase).origin,pollUrl=submitResult.poll_url.startsWith("http")?submitResult.poll_url:`${apiOrigin}${submitResult.poll_url}`;console.log(`[ClawRouter] Video job submitted (id=${submitResult.id}), polling upstream \u2014 typical 60\u2013180s...`);let pollDeadline=Date.now()+3e5,pollInterval=5e3;await new Promise(r2=>setTimeout(r2,3e3));let pollError,videoCompleted=!1;for(;Date.now()<pollDeadline;){if(clientAbort.signal.aborted){console.log(`[ClawRouter] Client disconnected \u2014 abandoning video poll (id=${submitResult.id})`);return}let pollResp=await payFetch(pollUrl,{method:"GET",headers:{"user-agent":USER_AGENT},signal:clientAbort.signal}),pollText=await pollResp.text(),pollBody={};try{pollBody=JSON.parse(pollText)}catch{pollError=`Non-JSON poll response (${pollResp.status}): ${pollText.slice(0,200)}`;break}if(pollResp.status===202||pollBody.status==="queued"||pollBody.status==="in_progress"){await new Promise(r2=>setTimeout(r2,pollInterval));continue}if(pollBody.status==="failed"){pollError=pollBody.error??"Upstream video generation failed";break}if(pollResp.ok&&pollBody.status==="completed"){finalResult=pollBody,videoCompleted=!0;break}if(!pollResp.ok){res.writeHead(pollResp.status,{"Content-Type":"application/json"}),res.end(pollText);return}finalResult=pollBody,videoCompleted=!0;break}if(pollError){res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Video generation failed",details:pollError}));return}if(!videoCompleted){res.writeHead(504,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Video generation timed out",details:`Upstream did not complete within 5 minutes (job id=${submitResult.id}). No payment has been settled.`}));return}}if(finalResult.data?.length){await mkdir6(VIDEO_DIR,{recursive:!0});let port2=server.address()?.port??8402;for(let clip of finalResult.data)if(clip.url?.startsWith("https://")||clip.url?.startsWith("http://"))try{let videoResp=await fetch(clip.url,{signal:clientAbort.signal});if(videoResp.ok){let contentType=videoResp.headers.get("content-type")??"video/mp4",ext=contentType.includes("webm")?"webm":contentType.includes("quicktime")?"mov":"mp4",filename=`${Date.now()}-${Math.random().toString(36).slice(2,10)}.${ext}`,buf=Buffer.from(await videoResp.arrayBuffer());await writeFile4(join17(VIDEO_DIR,filename),buf),clip.url=`http://localhost:${port2}/videos/${filename}`,console.log(`[ClawRouter] Video saved \u2192 ${clip.url}`)}}catch(downloadErr){console.warn(`[ClawRouter] Failed to download video, using original URL: ${downloadErr instanceof Error?downloadErr.message:String(downloadErr)}`)}}let videoActualCost=settledMediaCostUsd(void 0,submitResult,paymentStore.getStore()?.amountUsd,estimateVideoCost(videoModel,videoDuration,videoHasImageInput));logUsage({timestamp:new Date().toISOString(),model:videoModel,tier:"VIDEO",cost:videoActualCost,baselineCost:videoActualCost,savings:0,latencyMs:Date.now()-videoStartTime}).catch(()=>{}),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify(finalResult))}catch(err){if(clientAbort.signal.aborted||refuseOverCostCap(res,err))return;let msg=err instanceof Error?err.message:String(err);console.error(`[ClawRouter] Video generation error: ${msg}`),res.headersSent||(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Video generation failed",details:msg})))}return}let isMessages=isMessagesPath(req.url);if(isMessages||req.url==="/v1/audio/speech"||(req.url?.startsWith("/v1/audio/speech?")??!1)||req.url?.match(PAID_API_PATH)){try{await proxyPaidApiRequest(req,res,apiBase,payFetch,()=>paymentStore.getStore()?.amountUsd??0,!1,authMode,isMessages&&options.maxCostPerRunUsd!==void 0&&options.maxCostPerRunUsd!==0?body=>capMessagesRequest(body,req.headers,{usd:options.maxCostPerRunUsd,mode:options.maxCostPerRunMode??"graceful",authMode,sessions:sessionStore,models:catalog.current().models,isFree:isFreeForCap}):void 0)}catch(err){if(refuseOverCostCap(res,err))return;let clientGone=isClientAbortError(err,res);clientGone||options.onError?.(err instanceof Error?err:new Error(String(err))),clientGone?res.writableEnded||res.destroy():res.headersSent?res.writableEnded||res.end():(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:{message:`Partner proxy error: ${err instanceof Error?err.message:String(err)}`,type:"partner_error"}})))}finally{paymentStore.getStore()?.sessionSpend?.release()}return}if(!req.url?.startsWith("/v1")){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Not found"}));return}if(authMode==="api-key"&&/^\/v1\//.test(req.url??"")&&!/^\/v1\/(?:chat\/completions|messages)(?:\?|$)/.test(req.url??"")){try{await proxyPaidApiRequest(req,res,apiBase,payFetch,()=>paymentStore.getStore()?.amountUsd??0,!0,authMode)}catch(err){if(refuseOverCostCap(res,err))return;let clientGone=isClientAbortError(err,res);clientGone||options.onError?.(err instanceof Error?err:new Error(String(err))),clientGone?res.writableEnded||res.destroy():res.headersSent?res.writableEnded||res.end():(res.writeHead(502,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:{message:`Account API error: ${err instanceof Error?err.message:String(err)}`,type:"account_error"}})))}finally{paymentStore.getStore()?.sessionSpend?.release()}return}if(!req.url.includes("/chat/completions")){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:{message:`ClawRouter does not proxy ${req.url}. It serves /v1/chat/completions, /v1/messages, /v1/models, /v1/images/generations, /v1/images/image2image, /v1/videos/generations, /v1/audio/generations, /v1/audio/speech, and the partner prefixes /v1/{partner,pm,exa,modal,stocks,usstock,crypto,fx,commodity,phone,voice}/. If BlockRun serves this endpoint, call it directly against the gateway.`,type:"invalid_request_error",code:"unsupported_endpoint"}}));return}try{await proxyRequest(req,res,apiBase,payFetch,requestOptions,routerOpts,deduplicator,balanceMonitor,sessionStore,responseCache2,sessionJournal,catalog.current())}catch(err){let error62=err instanceof Error?err:new Error(String(err));options.onError?.(error62),res.headersSent?res.writableEnded||(res.write(`data: ${JSON.stringify({error:{message:error62.message,type:"proxy_error"}})}
|
|
2480
2480
|
|
|
2481
2481
|
`),res.write(`data: [DONE]
|
|
2482
2482
|
|